answer
stringlengths 17
10.2M
|
|---|
package nom.bdezonia.zorbage.algorithm;
import nom.bdezonia.zorbage.basic.procedure.Procedure;
import nom.bdezonia.zorbage.basic.procedure.Procedure1;
import nom.bdezonia.zorbage.type.algebra.Group;
import nom.bdezonia.zorbage.type.storage.linear.LinearStorage;
/**
*
* @author Barry DeZonia
*
*/
public class Fill {
// do not instantiate
private Fill() {}
/**
*
* @param group
* @param storage
* @param value
*/
public static <T extends Group<T,U>,U>
void compute(T group, LinearStorage<?,U> storage, U value)
{
compute(group, storage, value, 0, storage.size());
}
/**
*
* @param group
* @param storage
* @param value
* @param start
* @param count
*/
public static <T extends Group<T,U>,U>
void compute(T group, LinearStorage<?,U> storage, U value, long start, long count)
{
for (long i = 0; i < count; i++) {
storage.set(start+i, value);
}
}
/**
*
* @param group
* @param proc
* @param storage
*/
public static <T extends Group<T,U>,U>
void compute(T group, Procedure1<U> proc, LinearStorage<?,U> storage)
{
compute(group, proc, 0, storage.size(), storage);
}
/**
*
* @param group
* @param proc
* @param start
* @param count
* @param storage
*/
public static <T extends Group<T,U>,U>
void compute(T group, Procedure1<U> proc, long start, long count, LinearStorage<?,U> storage)
{
U value = group.construct();
for (long i = 0; i < count; i++) {
proc.call(value);
storage.set(start+i, value);
}
}
/**
*
* @param group
* @param proc
* @param storage
* @param inputs
*/
public static <T extends Group<T,U>,U>
void compute(T group, Procedure<U> proc, LinearStorage<?,U> storage, U... inputs)
{
compute(group, proc, 0, storage.size(), storage, inputs);
}
/**
*
* @param group
* @param proc
* @param start
* @param count
* @param storage
* @param inputs
*/
public static <T extends Group<T,U>,U>
void compute(T group, Procedure<U> proc, long start, long count, LinearStorage<?,U> storage, U... inputs)
{
U value = group.construct();
for (long i = 0; i < count; i++) {
proc.call(value, inputs);
storage.set(start+i, value);
}
}
}
|
package nuclibook.entity_utils;
import nuclibook.models.ActionLog;
import nuclibook.models.Staff;
import org.joda.time.DateTime;
import java.util.HashMap;
import java.util.Map;
/**
* This class records user logging. Types of actions are stored as static final integers.
* There is a static HashMap for associating the actionID (integer) with the action description.
* Logging an action can be done by calling the static method logAction
*/
public class ActionLogger {
public static final int VIEW_PATIENT_LIST = 1;
public static final int CREATE_PATIENT = 2;
public static final int VIEW_PATIENT = 3;
public static final int UPDATE_PATIENT = 4;
public static final int DELETE_PATIENT = 5;
public static final int ATTEMPT_VIEW_PATIENT_LIST = 6;
public static final int ATTEMPT_CREATE_PATIENT = 7;
public static final int ATTEMPT_VIEW_PATIENT = 8;
public static final int ATTEMPT_UPDATE_PATIENT = 9;
public static final int ATTEMPT_DELETE_PATIENT = 10;
public static final int CREATE_TRACER = 11;
public static final int VIEW_TRACER = 12;
public static final int UPDATE_TRACER = 13;
public static final int DELETE_TRACER = 14;
public static final int ATTEMPT_CREATE_TRACER = 15;
public static final int ATTEMPT_VIEW_TRACER = 16;
public static final int ATTEMPT_UPDATE_TRACER = 17;
public static final int ATTEMPT_DELETE_TRACER = 18;
public static final int CREATE_CAMERA_TYPE = 19;
public static final int VIEW_CAMERA_TYPE = 20;
public static final int UPDATE_CAMERA_TYPE = 21;
public static final int DELETE_CAMERA_TYPE = 22;
public static final int ATTEMPT_CREATE_CAMERA_TYPE = 23;
public static final int ATTEMPT_VIEW_CAMERA_TYPE = 24;
public static final int ATTEMPT_UPDATE_CAMERA_TYPE = 25;
public static final int ATTEMPT_DELETE_CAMERA_TYPE = 26;
public static final int CREATE_CAMERA = 27;
public static final int VIEW_CAMERA = 28;
public static final int UPDATE_CAMERA = 29;
public static final int DELETE_CAMERA = 30;
public static final int ATTEMPT_CREATE_CAMERA = 31;
public static final int ATTEMPT_VIEW_CAMERA = 32;
public static final int ATTEMPT_UPDATE_CAMERA = 33;
public static final int ATTEMPT_DELETE_CAMERA = 34;
public static final int CREATE_THERAPY = 35;
public static final int VIEW_THERAPY = 36;
public static final int UPDATE_THERAPY = 37;
public static final int DELETE_THERAPY = 38;
public static final int ATTEMPT_CREATE_THERAPY = 39;
public static final int ATTEMPT_VIEW_THERAPY = 40;
public static final int ATTEMPT_UPDATE_THERAPY = 41;
public static final int ATTEMPT_DELETE_THERAPY = 42;
public static final int CREATE_STAFF_ROLE = 43;
public static final int VIEW_STAFF_ROLE = 44;
public static final int UPDATE_STAFF_ROLE = 45;
public static final int DELETE_STAFF_ROLE = 46;
public static final int ATTEMPT_CREATE_STAFF_ROLE = 47;
public static final int ATTEMPT_VIEW_STAFF_ROLE = 48;
public static final int ATTEMPT_UPDATE_STAFF_ROLE = 49;
public static final int ATTEMPT_DELETE_STAFF_ROLE = 50;
public static final int CREATE_STAFF = 51;
public static final int VIEW_STAFF = 52;
public static final int UPDATE_STAFF = 53;
public static final int DELETE_STAFF = 54;
public static final int ATTEMPT_CREATE_STAFF = 55;
public static final int ATTEMPT_CREATE_STAFF_PASSWORD = 56;
public static final int ATTEMPT_VIEW_STAFF = 57;
public static final int ATTEMPT_UPDATE_STAFF = 58;
public static final int ATTEMPT_DELETE_STAFF = 59;
public static final int CREATE_STAFF_ABSENCE = 60;
public static final int VIEW_STAFF_ABSENCE = 61;
public static final int UPDATE_STAFF_ABSENCE = 62;
public static final int DELETE_STAFF_ABSENCE = 63;
public static final int ATTEMPT_CREATE_STAFF_ABSENCE = 64;
public static final int ATTEMPT_VIEW_STAFF_ABSENCE = 65;
public static final int ATTEMPT_UPDATE_STAFF_ABSENCE = 66;
public static final int ATTEMPT_DELETE_STAFF_ABSENCE = 67;
public static final int CREATE_STAFF_AVAILABILITY = 68;
public static final int VIEW_STAFF_AVAILABILITY = 69;
public static final int UPDATE_STAFF_AVAILABILITY = 70;
public static final int DELETE_STAFF_AVAILABILITY = 71;
public static final int ATTEMPT_CREATE_STAFF_AVAILABILITY = 72;
public static final int ATTEMPT_VIEW_STAFF_AVAILABILITY = 73;
public static final int ATTEMPT_UPDATE_STAFF_AVAILABILITY = 74;
public static final int ATTEMPT_DELETE_STAFF_AVAILABILITY = 75;
public static final int VIEW_BOOKING_CALENDAR = 76;
public static final int CREATE_BOOKING = 77;
public static final int VIEW_BOOKING = 78;
public static final int UPDATE_BOOKING = 79;
public static final int DELETE_BOOKING = 80;
public static final int ATTEMPT_VIEW_BOOKING_CALENDAR = 81;
public static final int ATTEMPT_CREATE_BOOKING = 82;
public static final int ATTEMPT_VIEW_BOOKING = 83;
public static final int ATTEMPT_UPDATE_BOOKING = 84;
public static final int ATTEMPT_DELETE_BOOKING = 85;
public static final int LOG_IN = 86;
public static final int ATTEMPT_LOG_IN_PASSWORD = 87;
public static final int ATTEMPT_LOG_IN_STAFF_ID = 88;
public static final int ATTEMPT_LOG_IN_STAFF_ID_DISABLED = 89;
public static final int LOG_OUT = 90;
public static final int UPDATE_STAFF_PASSWORD = 91;
public static final int ATTEMPT_UPDATE_STAFF_PASSWORD = 92;
public static Map actionDescription = new HashMap<Integer, String>() {{
put(VIEW_PATIENT_LIST, "Viewed patient log");
put(CREATE_PATIENT, "Created a new patient");
put(VIEW_PATIENT, "Viewed patient");
put(UPDATE_PATIENT, "Updated patient");
put(DELETE_PATIENT, "Deleted patient");
put(ATTEMPT_VIEW_PATIENT_LIST, "Attempted to view patient log");
put(ATTEMPT_CREATE_PATIENT, "Attempted to create a new patient");
put(ATTEMPT_VIEW_PATIENT, "Attempted to view patient");
put(ATTEMPT_UPDATE_PATIENT, "Attempted to update patient");
put(ATTEMPT_DELETE_PATIENT, "Attempted to delete patient");
put(CREATE_TRACER, "Created tracer");
put(VIEW_TRACER, "Viewed tracer ");
put(UPDATE_TRACER, "Updated tracer");
put(DELETE_TRACER, "Deleted tracer");
put(ATTEMPT_CREATE_TRACER, "Attempted to create tracer");
put(ATTEMPT_VIEW_TRACER, "Attempted to view tracer ");
put(ATTEMPT_UPDATE_TRACER, "Attempted to update tracer");
put(ATTEMPT_DELETE_TRACER, "Attempted to delete tracer");
put(CREATE_CAMERA_TYPE, "Created camera type");
put(VIEW_CAMERA_TYPE, "Viewed camera type");
put(UPDATE_CAMERA_TYPE, "Updated camera type");
put(DELETE_CAMERA_TYPE, "Deleted camera type");
put(ATTEMPT_CREATE_CAMERA_TYPE, "Attempted to create camera type");
put(ATTEMPT_VIEW_CAMERA_TYPE, "Attempted to view camera type");
put(ATTEMPT_UPDATE_CAMERA_TYPE, "Attempted to update camera type");
put(ATTEMPT_DELETE_CAMERA_TYPE, "Attempted to delete camera type");
put(CREATE_CAMERA, "Created camera");
put(VIEW_CAMERA, "Viewed camera");
put(UPDATE_CAMERA, "Updated camera");
put(DELETE_CAMERA, "Deleted camera");
put(ATTEMPT_CREATE_CAMERA, "Attempted to create camera");
put(ATTEMPT_VIEW_CAMERA, "Attempted to view camera");
put(ATTEMPT_UPDATE_CAMERA, "Attempted to update camera");
put(ATTEMPT_DELETE_CAMERA, "Attempted to delete camera");
put(CREATE_THERAPY, "Created therapy");
put(VIEW_THERAPY, "Viewed therapy");
put(UPDATE_THERAPY, "Updated therapy");
put(DELETE_THERAPY, "Deleted therapy");
put(ATTEMPT_CREATE_THERAPY, "Attempted to create therapy");
put(ATTEMPT_VIEW_THERAPY, "Attempted to view therapy");
put(ATTEMPT_UPDATE_THERAPY, "Attempted to update therapy");
put(ATTEMPT_DELETE_THERAPY, "Attempted to delete therapy");
put(CREATE_STAFF_ROLE, "Created staff role");
put(VIEW_STAFF_ROLE, "Viewed staff role");
put(UPDATE_STAFF_ROLE, "Updated staff role");
put(DELETE_STAFF_ROLE, "Deleted staff role");
put(ATTEMPT_CREATE_STAFF_ROLE, "Attempted to create staff role");
put(ATTEMPT_VIEW_STAFF_ROLE, "Attempted to view staff role");
put(ATTEMPT_UPDATE_STAFF_ROLE, "Attempted to update staff role");
put(ATTEMPT_DELETE_STAFF_ROLE, "Attempted to delete staff role");
put(CREATE_STAFF, "Created staff member");
put(VIEW_STAFF, "Viewed staff member");
put(UPDATE_STAFF, "Updated staff member");
put(DELETE_STAFF, "Deleted staff member");
put(ATTEMPT_CREATE_STAFF, "Attempted to create staff member");
put(ATTEMPT_CREATE_STAFF_PASSWORD, "Attempted to create staff member with invalid password");
put(ATTEMPT_VIEW_STAFF, "Attempted to view staff member");
put(ATTEMPT_UPDATE_STAFF, "Attempted to update staff member");
put(ATTEMPT_DELETE_STAFF, "Attempted to delete staff member");
put(CREATE_STAFF_ABSENCE, "Created staff absence");
put(VIEW_STAFF_ABSENCE, "Viewed staff absence");
put(UPDATE_STAFF_ABSENCE, "Updated staff absence");
put(DELETE_STAFF_ABSENCE, "Deleted staff absence");
put(ATTEMPT_CREATE_STAFF_ABSENCE, "Attempted to create staff absence");
put(ATTEMPT_VIEW_STAFF_ABSENCE, "Attempted to view staff absence");
put(ATTEMPT_UPDATE_STAFF_ABSENCE, "Attempted to update staff absence");
put(ATTEMPT_DELETE_STAFF_ABSENCE, "Attempted to delete staff absence");
put(CREATE_STAFF_AVAILABILITY, "Created staff availability");
put(VIEW_STAFF_AVAILABILITY, "Viewed staff availability");
put(UPDATE_STAFF_AVAILABILITY, "Updated staff availability");
put(DELETE_STAFF_AVAILABILITY, "Deleted staff availability");
put(ATTEMPT_CREATE_STAFF_AVAILABILITY, "Attempted to create staff availability");
put(ATTEMPT_VIEW_STAFF_AVAILABILITY, "Attempted to view staff availability");
put(ATTEMPT_UPDATE_STAFF_AVAILABILITY, "Attempted to update staff availability");
put(ATTEMPT_DELETE_STAFF_AVAILABILITY, "Attempted to delete staff availability");
put(VIEW_BOOKING_CALENDAR, "Viewed booking calendar");
put(ATTEMPT_VIEW_BOOKING_CALENDAR, "Attempted to view booking calendar");
put(CREATE_BOOKING, "Created booking");
put(VIEW_BOOKING, "Viewed booking");
put(UPDATE_BOOKING, "Updated booking");
put(DELETE_BOOKING, "Deleted booking");
put(ATTEMPT_CREATE_BOOKING, "Attempted to create booking");
put(ATTEMPT_VIEW_BOOKING, "Attempted to view booking");
put(ATTEMPT_UPDATE_BOOKING, "Attempted to update booking");
put(ATTEMPT_DELETE_BOOKING, "Attempted to delete booking");
put(LOG_IN, "Logged in");
put(ATTEMPT_LOG_IN_PASSWORD, "Attempted to log in with wrong password");
put(ATTEMPT_LOG_IN_STAFF_ID, "Attempted to log in with staff ID that doesn't exist");
put(ATTEMPT_LOG_IN_STAFF_ID_DISABLED, "Attempted to log in with a disabled staff ID");
put(LOG_OUT, "Logged out");
put(UPDATE_STAFF_PASSWORD, "Changed staff password");
put(ATTEMPT_UPDATE_STAFF_PASSWORD, "Attempted to change staff password");
}};
/**
* A method for recording staff action. Date/Time of the action are generated in the database. Requires
* an integer for the type of action performed and an id of the object to which it is applied to.
* E.g. for deleting a patient with id = 4356, actionPerformed would be 5 amd objectID - 4356.
*
* @param actionPerformed the type of action performed (e.g. deleted patient)
* @param objectID the objectID on which the action was performed
*/
public static void logAction(int actionPerformed, int objectID) {
Staff loggedIn = SecurityUtils.getCurrentUser();
ActionLog entity = new ActionLog(loggedIn, new DateTime(), actionPerformed, objectID);
AbstractEntityUtils.createEntity(ActionLog.class, entity);
}
/**
* A method for recording staff action. Date/Time of the action are generated in the database. Requires
* an integer for the type of action performed and an id of the object to which it is applied to.
* E.g. for deleting a patient with id = 4356, actionPerformed would be 5 amd objectID - 4356.
*
* @param actionPerformed the type of action performed (e.g. deleted patient)
* @param objectID the objectID on which the action was performed
* @param note the note about the action when it occurred
*/
public static void logAction(int actionPerformed, int objectID, String note) {
Staff loggedIn = SecurityUtils.getCurrentUser();
ActionLog entity = new ActionLog(loggedIn, new DateTime(), actionPerformed, objectID, note);
AbstractEntityUtils.createEntity(ActionLog.class, entity);
}
}
|
package org.exist.xquery.modules.sort;
import org.exist.EXistException;
import org.exist.dom.QName;
import org.exist.indexing.sort.SortIndex;
import org.exist.indexing.sort.SortIndexWorker;
import org.exist.util.LockException;
import org.exist.xquery.*;
import org.exist.xquery.value.*;
public class HasIndex extends BasicFunction {
public final static FunctionSignature signature =
new FunctionSignature(
new QName("has-index", SortModule.NAMESPACE_URI, SortModule.PREFIX),
"Check if the sort index, $id, exists.",
new SequenceType[] {
new FunctionParameterSequenceType("id", Type.STRING, Cardinality.EXACTLY_ONE, "The name of the index.")
},
new FunctionReturnSequenceType(Type.BOOLEAN, Cardinality.EXACTLY_ONE, "true() if the sort index, $id, exists, false() otherwise."));
public HasIndex(XQueryContext context) {
super(context, signature);
}
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
String id = args[0].getStringValue();
SortIndexWorker index = (SortIndexWorker)
context.getBroker().getIndexController().getWorkerByIndexId(SortIndex.ID);
try {
return BooleanValue.valueOf(index.hasIndex(id));
} catch (EXistException e) {
throw new XPathException(this, e.getMessage(), e);
} catch (LockException e) {
throw new XPathException(this, "Caught lock error while searching index. Giving up.", e);
}
}
}
|
package org.fakekoji.xmlrpc.server.core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.sshd.server.SshServer;
import org.fakekoji.xmlrpc.server.SshUploadService;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestSshApi {
private static final String IDS_RSA = "
+ "MIISKQIBAAKCBAEA6DOkXJ7K89Ai3E+XTvFjefNmXRrYVIxx8TFonXGfUvSdNISD\n"
+ "uZW+tC9FbFNBJWZUFludQdHAczLCKLOoUq7mTBe/wPOreSyIDI1iNnawV/KsX7Ok\n"
+ "yThsDolKxgRA+we8JuUYAes2y94FKaw4kAY/Ob16WSf7AP9Y8Oa4/PcK6KCIkzQx\n"
+ "iqL+SGG3mLy+XhTU/pJYnEC8c1lw+Gah8oPWG1vx5W578iWixgTbNp0TTXNr1+jU\n"
+ "xVRg1SitC4WP8g67af6f5rhcJZt5Dz/gWajHqKkK97nmPSDttso56ueeUW3L8lM3\n"
+ "scFjGQu3QbpLmFpMZeTpePOn7CjVjfBZnocNzDdqkgE+ivEB7nWWNbgEwALX4NR4\n"
+ "DzkGGoFPUKdsIdEBC5D73XC6NJxHKWOO9L+KyUxoeA8hUHBuWc3pVSi7NyG04Pvq\n"
+ "EfO0Ea1p4Tn2nb2CreEgOyCQ/nLJJrPEDef+8GUKKs3tVawbOn6tLFyi7aFY9u35\n"
+ "KX3fgt5t8TiIqmcIxs7oC16ny/97pe7gBRZuLU4AxK76m6Nxr1lGw7wJOXllhoKb\n"
+ "Zys676qlIG6VvSw/dAUekY/Vk9duIm9BHHLVZetv/LL4hWNy7xMvlpl8V141azJw\n"
+ "BE10V1GuvJnRtsf57ZqSOjiezTewavteJLwTZlRTV7QwsVpUGM7YyYJacv1GkFzz\n"
+ "00UWg+/Pf1gyLHf+JgsWx1ftUU9WlnVgBSfZpWKHexjcKrJzk4n96HWFL4ihCfxd\n"
+ "895ZkBsbTyuRAsC3Tw+k/FC6j0bbM5eE9weBH9b3Ap6tZFlIwEwXCvU28i0SbxEq\n"
+ "PXpnxpK33XRHz3byu8QtX4BulVrwa0P/ZeY0fvooUJo+tUqHbE7Pf5DlzylZarXQ\n"
+ "BSHjPcG+bs37LA2ar/1o6hRXJ5Z3b8f4YH3HumGuiYY3NjDvq++P5RTnasWFN7+f\n"
+ "1xYexB3HZE9RXxCTTVIn09fVHnaloNCnvhl6fn40TfsmS10qN1hwh55nzvpUjqGz\n"
+ "qyC+9Z/F+RpqIIAVKyijyMy2PiJRBy8sPZa1qf9+xDCZsRYdUPebr8t38sPEYYtR\n"
+ "8wMfY1iq0qXn1Pi/G+ghmTn+/UIdubn/m7Iu/F0GSyN6cjz4fskpS5bAb1oJhoWD\n"
+ "yrx6EAf96OoVIrMQcaBkLVcd7MW59rSDK0gNK7DE3ZXa85VwcMj/Y9HCybY/Xlf5\n"
+ "v7Csi38E+ybHP2R3YEPMduLg3hrs0UVfQaZoirA/yVtvVF3mv5Nh/RfCvCvGGR2s\n"
+ "PNgnq7ZKia5/nXqV4/l2Yrrg2QPYtAYwuv2Sf6GK5MqhqBtWb8qZRZVH7df4IroJ\n"
+ "orWmi2obRqdU5+w2F+OaL7OOs8GIwLb9iGeswwIDAQABAoIEAQC9ZPnoLgEeMyNs\n"
+ "DWM+GbfozXYt9OqEs/VwJLvOx9GLaUgcgQWsRw7Ai1oVzCZz6e4mOl2fRQWzMLCb\n"
+ "YEaoAk6HvEtEh7vSX1cs3dlA0Thu09pzSOTc16+Tf7pEn02dM6btFqmpTwBn8tTF\n"
+ "M9sC5oWFhB4aQHkETEJwY9B5TMtSCTa80rKiAOZlhYaqBzFDLby5VAcAk/DiKQ7z\n"
+ "HUt0ssHdmPZKC/7++GG3IFjpR99pqf5JoniB55v/4Wib4DoT1p5ZCz3Dg5Ztek2Y\n"
+ "+aH1n6wSzqbKfo/kRkp+cJ4jEv7YLjVOlz/zNeitkhfMfbaRMv3jkn44kIzkHD5r\n"
+ "wqJmooPHkV/UbT1lOMU5iiGV+V2ue+M3WDYBPKLU1aorABQ71O0EUSKOcRcAOIP2\n"
+ "p2UADoeWP0NqwfSLVtk7WK+8LTfe9RhC9lbqg5vZW1fkRFH6QYwoZVrTv3FkiZ22\n"
+ "eqQsL5GK5O8RENxHp9ShtpdrerfOGW+mIV680BWR+fk06sbWLqpC9prgQzmcM+vX\n"
+ "4WpJ3AzL2TbZNlvkvMDKpIgKuQHRJkqAF2HIGcO9nrOHK4vpPAEZkd9oHSi4qNwF\n"
+ "LDewi52xvwKd3CDHM+GYTU7giJqZ7JantAEYEVEWs+JRpSkf7CbX/d7NrEci3gyA\n"
+ "hj04u0sbiSZdf/TDhAjaH0VFv5Qk+xEf4NbGvL+UZse/WYCINYQNSbLZCH3ZmnFn\n"
+ "3JG/vlAB1ojpAHJb2Eg2zTIcPw//ocig27ZvzZG1fwebLB0dwPoMOtaeh66hzSv/\n"
+ "TTduDJsiLg/x/I9Fbw/uJd6DSypndSCq+BNUy3g32umnsmj4x3XTnfn56d2E5n2w\n"
+ "ivMxYaFlyMTJ3ilJJEpk2ioLzlWYVhZFMielmrpsE8EM4Rnv+lVfPzu7VDSIyMDI\n"
+ "L6VPLRG4+wakSajacwKBGfVB/wEWrhGxQb9uHdFcXbzNmx2m/70S5LEiOTmTv47g\n"
+ "rSD7bPxQ9ghx9XcXnoFjts+Crz9Pl0NbmMCJQ2KTPmAXCMJNBC0Xof3yrP0+ZKM+\n"
+ "ZNXTAhCPesDTgOmYtMnyKZa0XxzCf5DgBYa6zzT484w0qZcMRYewFLJEv0oD2cwC\n"
+ "WSbjvvCmBJLHxp9+L3H5uE4hMLuZhdIV7+KrwTetylRNxjM7wi8w0uUUE9/6uHK4\n"
+ "Wy4DA7kfjPmvGhbbv/63baVQRRCs7M8Sk6rUD+JZ+ZKzVK31+j8WwNT7zbXte2qs\n"
+ "NCnEPrGvJRKb3arq6VMJXzLlknFUbOiO6S8EvgeglunPtqyadMIhNQdk7cW+4hzq\n"
+ "tY4aNtT4zdozmji/WzDBSPMhIYh0CV7zSgVuFS/SsWyAWDHX4IvZCoHLlg+bROaE\n"
+ "NdnX6B6JAoICAQD9V6GdwcUsgbH0jJb3dhQ0Zpqcrrl8U496msYkg+b6MyqX55Ev\n"
+ "YItv16grvhl7QupK93pD256zGm+83e6Jxox4ZxLLmgx6fH3ubkRC7CbpRWtb7R1o\n"
+ "3YENjo8wmbjjcs38tUG5LEHFsZOeyVWkkW+/PCuOUl4m/3m7BOiwEYIA6vYdC42F\n"
+ "kBH8FaRi2zZ+kiHX2vHIbdpb7H013gSZt8ieKrLJh6FESFSINuW4ISGbCgn9nEw7\n"
+ "uAG7EMwQliCe66SIx+aYxaaxJL0q0tJkX/glzO//9Fu5LX+n5nCgqcTv2TB5IANi\n"
+ "fyi/YrbaX1hUxJFYyh39a1rIpjk4wSZwXZIC6ZHc3CKu5mNhML4a809W5siKXR/9\n"
+ "hQqiSeCIXuBq96E+s9kGNp9hLBUgQGooZwMZdVgOX0dSf4E6KoVz5c4PTEuJO7K8\n"
+ "wxlTfegUxzKzYi+A29lNHiYJF51CSJGr7Z1VFWpVUa7Ts953SgsfIYqB1Yrflgtn\n"
+ "vJi3+FDuNLPIMeVJLDdp8tXBUDnDzZL4eRdQEIzmYJuExEj3g3i8Vmd1fJ5yhtEd\n"
+ "7N93KVstqp8mGvYYnfCfXZUiwn1ivRgzfeYR+siTKuTXmwhsXBcy6Z5cLZOatjUC\n"
+ "uBME4We4ra9AoXc6iU9Zrn8zAEMeEtl8QSiIk2OJkqTIaWck1Li6RpRJVwKCAgEA\n"
+ "6qM8dzcv6naHOSJmbdZT8c8yVVAEbhkgj22mdfHJa437o0dqXm8oKyDhucDhG1kx\n"
+ "Uj4lBlx7vH5uDJJ3YbrsLQcQhf1r7ol84VAlJmm9OF6horLKRWc2Eke8LbtRw3VV\n"
+ "9M9fOP4b5gwJFeVOYHK61iKRwDw+qs1GX/5jOQLPdDC+BSzLFCGvDCFk6BrAadcn\n"
+ "IVfJ+7Sid9v30kpUPGpDiJzZ0Ofb6+1ppcW/YlZE6OPBJMD0cIcd3ogMFPBA+ZuQ\n"
+ "zLPf3PVbEUxDNLOCjTvLie5jvGvBTXrGSvXXTRt+rpBkkrd6GqM3jKBEOPMxWiFm\n"
+ "Uiw8WqOKKC46FpiUAD82uJddnd1R/dM1cbtJiF3QX5CEGbaKdAWzoG0CODw5tyX1\n"
+ "Cxgy43PCQafz/AOKAecNp6eCWkyEbjCBsCrJg3lKfQWyJ0MqToadSA+iDUYRA6PB\n"
+ "sEJWiy8UtnbwgDtTtUNKxWhbGOLxGRQnnSo7USE93ew8tuWa9oW9S/BEF7AiCk+S\n"
+ "HCINMB7ek2QXzFqS3h7WBSzDn+ZsSOo3EH5I5NV0EfgeGfAnC9mKLc9wM6XiuBOY\n"
+ "eLiFPc6nLlB8jJpEFioK44oQl4qV8NCP4Dwz2r+iLUt8E8vQAypYNZrZTLEktIL9\n"
+ "Egl+3+bUPgMJOVqwI4YCkICnJjnlVDkBL2xpFmsOGHUCggIAEvUDuvJM9s+dqVb7\n"
+ "1PiY+nLTDvZkGtGF4v7B5OmZ1w8NGODTFGB9DplslBldfsO7FHEATSOZ9Hz973wL\n"
+ "5XNd/4R2+5VDacb3BWhq4zcYkkwHhJFxqe8pQQJx5IkcNKjakRZfHKQbJ9fp2+/k\n"
+ "4LOhUQYHnFa9hN2JFl1/q+0jdT4fvHyo0l29eseDzYHpyf7VWXmgrgbKWCaSF/3N\n"
+ "ClOeR3eaeUoU3y8qZCb3eZfBFADkTn3rlmxmdMEFBBi3yCyJ21JaBwSDPK4rGZE8\n"
+ "/RXRU8LKErUOSAUHkGDF/L+3ZNszrVyf5DbvraKNXDnWOkGbPrGhHN1zpaAKmByb\n"
+ "67yUuHMR3xz522yR8yvajdm3DiGmz/O3+RiDezFcA9hVoqt0/WQn0Tc1JehOjGNF\n"
+ "jlBnAvis5iZrB9lSqi+UXN/NU4e5/0LgVQ+kTYMWYrelK5clRtcso4CmB/gkZFlZ\n"
+ "zSuyojNACbJbCqxi8ToxKtsvqhd4lNJ9d/28z8ddBvYandhd9+O/IcZyCE0ghW5U\n"
+ "mRM2k18pq/N+r6igbSUBW9Z7V2dD0/4Sl9KpxhjqIbiqwAc0cxMedk5iYn97MnBD\n"
+ "51Z8aMwDRj/nb9rB/pnFgqHIn80pRmJsBRARHERhpogYnRV3/oFX1rYf/oj+fLmc\n"
+ "XJfjmJSu1hSLEBQTC8Z/LDEr13ECggIBAOlnB7bvRtLMpSbIeWu5UDeyDDehKUb7\n"
+ "58/FG1kn81zyF+cMG1tk52g/hUrp+wLhbpaJCvuQ8+VFPuNyrx6gel8wL9eZh8v5\n"
+ "KChZORtFA90XBWJ6x4rSaI82nJJBS8xK4/5qaiafX9EvF7qYJ6b5ebGZIbNAOnZd\n"
+ "TCwhOUJ08Th7ZApxzHFyMFa4wU/BjLW8OEiKs3mW7iacwaCGH9UZP6Sdom6Utcey\n"
+ "mu00EHUZq+Ke7HpLFtz5C1VZr+sEMx4ZCakXJRD/YF+MpS2/g5ZKbOYAJWZBKkCQ\n"
+ "aMAYXNtvBk1PhTwNF4F36sIQisy73dPydX44UrE3DS97DH19uXulZiGpMI7gobcE\n"
+ "ap1/2F22NJlbgIyzcHaJVW24AgU+o4r0TxWCNNzdQddd4u5F9vp9hK/JiXmZtAKI\n"
+ "bfl4FoyaEubay6USwvrqHXqZUnIxyKr+MqXK15wMcWYwWny0h0hAcBh+/l97IKn5\n"
+ "yo4kfGzvzEL9xEeLjuK7ltn7X0DRDIuFK6qglM3RZ0bmwmWdk4sw0WTEarSc2gqO\n"
+ "MchOVuSLELLvRcI3ih/XfgSj3NEDqsvBcmJj6ubYsqT3m22h5yjFGZ/Or0KPsSej\n"
+ "z/sW594p0oGMHRj0HS+I58YrCw2nCQQnaOaQW40OaQJmsr5C4AP2QobL83mrDd0B\n"
+ "95PdG4wZYiQhAoICAAEQjP1dbHOT/4oycWukZIayEN3rGJbwjLJcM5n+VVMMprDE\n"
+ "2Bx9YmjijOMRHqCZY7rDr6OMhnuI1E2gkAbTfHfLWM3OpnagdL73uAjYWoU8QIZl\n"
+ "8NS3u8lNbDQby4WIbmtvIbPbKrnV47illLfdfcMvp16E+zXpgBERZfA5kjdvL2Zs\n"
+ "CoKitgJmes6Cw7gpxq04wuuq5xJ856rPmwiFTJCJGoN5yXQYZsqNsz1iWvjTVUen\n"
+ "JjNj5aveSb1a34JEqlLxk2NoYrT47A54iMJQSqXQQDwbW2U0vOZMv9FtwjJti9EO\n"
+ "aIma8wcoQhLGqt9/yQ66BzLCCQfnxMDgGUK7RD85Jcq7WghgSJv8iRQ4Hu8J7tTO\n"
+ "SZJOJy9IDmSp/Yh5R/9KMEdgvUQRo4JFqORyguokkKTa2EYYPpoDfCv1uEg8rr+4\n"
+ "xtKBxoiw+UJZGnEbUGJw2Yt2ynbV4dUlUkgMOBrznYdtmivaF544DD8Tgk8elNdT\n"
+ "WowvdHlPa9HCY7VNWo80vaOUXUSo6ftUkTVhyd9EI84g1JyFGPcpd624NsAhQrSm\n"
+ "kg8qubbQM3Tij5oGYewJ2PzeweosiQ4AVlq3+mVGnkNLPLyABHOgGmoUPpyR297R\n"
+ "nDe3iQJfqKGHQck94dCtx7mlbcgBwWiM1SCdZcJ8H06gBWA99hNqcwWS9kSv\n"
+ "
private static final String IDS_RSA_PUB = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAEAQDoM6Rcnsrz0CLcT5dO8WN582ZdGthUjHHxMWidcZ9S9J00hIO5lb60L0VsU0ElZlQWW51B0cBzMsIos6hSruZMF7/A86t5LIgMjWI2drBX8qxfs6TJOGwOiUrGBED7B7wm5RgB6zbL3gUprDiQBj85vXpZJ/sA/1jw5rj89wrooIiTNDGKov5IYbeYvL5eFNT+klicQLxzWXD4ZqHyg9YbW/HlbnvyJaLGBNs2nRNNc2vX6NTFVGDVKK0LhY/yDrtp/p/muFwlm3kPP+BZqMeoqQr3ueY9IO22yjnq555RbcvyUzexwWMZC7dBukuYWkxl5Ol486fsKNWN8Fmehw3MN2qSAT6K8QHudZY1uATAAtfg1HgPOQYagU9Qp2wh0QELkPvdcLo0nEcpY470v4rJTGh4DyFQcG5ZzelVKLs3IbTg++oR87QRrWnhOfadvYKt4SA7IJD+cskms8QN5/7wZQoqze1VrBs6fq0sXKLtoVj27fkpfd+C3m3xOIiqZwjGzugLXqfL/3ul7uAFFm4tTgDErvqbo3GvWUbDvAk5eWWGgptnKzrvqqUgbpW9LD90BR6Rj9WT124ib0EcctVl62/8sviFY3LvEy+WmXxXXjVrMnAETXRXUa68mdG2x/ntmpI6OJ7NN7Bq+14kvBNmVFNXtDCxWlQYztjJglpy/UaQXPPTRRaD789/WDIsd/4mCxbHV+1RT1aWdWAFJ9mlYod7GNwqsnOTif3odYUviKEJ/F3z3lmQGxtPK5ECwLdPD6T8ULqPRtszl4T3B4Ef1vcCnq1kWUjATBcK9TbyLRJvESo9emfGkrfddEfPdvK7xC1fgG6VWvBrQ/9l5jR++ihQmj61SodsTs9/kOXPKVlqtdAFIeM9wb5uzfssDZqv/WjqFFcnlndvx/hgfce6Ya6Jhjc2MO+r74/lFOdqxYU3v5/XFh7EHcdkT1FfEJNNUifT19UedqWg0Ke+GXp+fjRN+yZLXSo3WHCHnmfO+lSOobOrIL71n8X5GmoggBUrKKPIzLY+IlEHLyw9lrWp/37EMJmxFh1Q95uvy3fyw8Rhi1HzAx9jWKrSpefU+L8b6CGZOf79Qh25uf+bsi78XQZLI3pyPPh+ySlLlsBvWgmGhYPKvHoQB/3o6hUisxBxoGQtVx3sxbn2tIMrSA0rsMTdldrzlXBwyP9j0cLJtj9eV/m/sKyLfwT7Jsc/ZHdgQ8x24uDeGuzRRV9BpmiKsD/JW29UXea/k2H9F8K8K8YZHaw82CertkqJrn+depXj+XZiuuDZA9i0BjC6/ZJ/oYrkyqGoG1ZvyplFlUft1/giugmitaaLahtGp1Tn7DYX45ovs46zwYjAtv2IZ6zD tester";
private static File kojiDb;
private static File sources;
private static File secondDir;
private static File priv;
private static File pub;
private static int port;
private static SshServer sshd;
private static final boolean debug = true;
@BeforeClass
public static void startSshdServer() throws IOException, GeneralSecurityException {
ServerSocket s = new ServerSocket(0);
port = s.getLocalPort();
final File keys = File.createTempFile("ssh-fake-koji.", ".TestKeys");
keys.delete();
keys.mkdir();
priv = new File(keys, "id_rsa");
pub = new File(keys, "id_rsa.pub");
createFile(priv, IDS_RSA);
createFile(pub, IDS_RSA_PUB);
Set<PosixFilePermission> perms = new HashSet<>();
Files.setPosixFilePermissions(pub.toPath(), perms);
Files.setPosixFilePermissions(priv.toPath(), perms);
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
Files.setPosixFilePermissions(pub.toPath(), perms);
Files.setPosixFilePermissions(priv.toPath(), perms);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
priv.delete();
pub.delete();
keys.delete();
}
});
s.close();
SshUploadService server = new SshUploadService();
kojiDb = File.createTempFile("ssh-fake-koji.", ".root");
kojiDb.delete();
kojiDb.mkdir();
kojiDb.deleteOnExit();
sshd = server.setup(port, kojiDb, "tester=" + pub.getAbsolutePath());
sources = File.createTempFile("ssh-fake-koji.", ".sources");
sources.delete();
sources.mkdir();
sources.deleteOnExit();
secondDir = File.createTempFile("ssh-fake-koji.", ".secondDir");
secondDir.delete();
secondDir.mkdir();
secondDir.deleteOnExit();
}
@AfterClass
public static void stopSshd() throws IOException {
sshd.stop(true);
}
private static void createFile(File path, String content) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
bw.write(content);
}
}
private static String readFile(File path) {
try {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
} catch (Exception ex) {
ex.printStackTrace();
return "impossible";
}
}
private static int scpTo(String target, String... source) throws InterruptedException, IOException {
return scpTo(new String[0], target, null, source);
}
private static int scpToCwd(String target, File cwd, String... source) throws InterruptedException, IOException {
return scpTo(new String[0], target, cwd, source);
}
private static int scpTo(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException {
String fullTarget = "tester@localhost:" + target;
return scpRaw(params, fullTarget, cwd, source);
}
private static int scpFrom(String target, String source) throws InterruptedException, IOException {
return scpFrom(new String[0], target, null, source);
}
private static int scpFromCwd(String target, File cwd, String source) throws InterruptedException, IOException {
return scpFrom(new String[0], target, cwd, source);
}
private static int scpFrom(String[] params, String target, File cwd, String source) throws InterruptedException, IOException {
String fullSource = "tester@localhost:" + source;
return scpRaw(params, target, cwd, fullSource);
}
private static int scpRaw(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException {
title(3);
List<String> cmd = new ArrayList<>(params.length + source.length + 9);
cmd.add("scp");
//cmd.add("-v"); //verbose
cmd.add("-o");
cmd.add("StrictHostKeyChecking=no");
cmd.add("-i");
cmd.add(priv.getAbsolutePath());
cmd.add("-P");
cmd.add("" + port);
cmd.addAll(Arrays.asList(params));
cmd.addAll(Arrays.asList(source));
cmd.add(target);
if (debug) {
for (int i = 0; i < source.length; i++) {
String string = source[i];
System.out.println(i + ". scp from " + string);
System.out.println(" scp to " + target);
}
}
ProcessBuilder pb = new ProcessBuilder(cmd);
if (cwd != null) {
pb.directory(cwd);
}
Process p = pb.start();
if (debug) {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while (true) {
String s = br.readLine();
if (s == null) {
break;
}
System.out.println(s);
}
}
int i = p.waitFor();
if (debug) {
System.out.println(" === scpEnd === ");
}
return i;
}
@After
public void cleanSecondDir() {
clean(secondDir);
}
@After
public void cleanSources() {
clean(sources);
}
@After
public void cleanKojiDb() {
clean(kojiDb);
}
private void clean(File f) {
File[] content = f.listFiles();
for (File file : content) {
deleteRecursively(file);
}
Assert.assertTrue(f.isDirectory());
Assert.assertTrue(f.listFiles().length == 0);
}
private void deleteRecursively(File file) {
if (file.isDirectory()) {
File[] content = file.listFiles();
for (File f : content) {
deleteRecursively(f);
}
}
file.delete();
}
private static void checkFileExists(File f) {
if (debug) {
System.out.println(f + " is supposed to exists. f.exists() is: " + f.exists());
if (f.exists()) {
System.out.println("content: '" + readFile(f) + "'");
}
}
Assert.assertTrue(f + " was supposed to exists. was not", f.exists());
}
private static void checkFileNotExists(File f) {
if (debug) {
System.out.println(f + " is supposed to NOT exists. f.exists() is: " + f.exists());
if (f.exists()) {
System.out.println("content: '" + readFile(f) + "'");
}
}
Assert.assertFalse(f + " was supposed to NOT exists. was", f.exists());
}
private static void title(int i) {
if (debug) {
String s = "method-unknow";
if (Thread.currentThread().getStackTrace().length > i) {
s = Thread.currentThread().getStackTrace()[i].getMethodName();
}
System.out.println(" ==" + i + "== " + s + " ==" + i + "== ");
}
}
private class NvraTarballPathsHelper {
private final String vid;
private final String rid;
private final String aid;
public NvraTarballPathsHelper(String id) {
this(id, id, id);
}
public NvraTarballPathsHelper(String vid, String rid, String aid) {
this.vid = vid;
this.rid = rid;
this.aid = aid;
}
public String getName() {
return "terrible-x-name-version" + vid + "-release" + rid + ".arch" + aid + ".suffix";
}
public String getStub() {
return "terrible-x-name/version" + vid + "/release" + rid + "/arch" + aid;
}
public String getContent() {
return "nvra - " + vid + ":" + rid + ":" + ":" + aid;
}
public String getStubWithName() {
return getStub() + "/" + getName();
}
public File getLocalFile() {
return new File(sources, getName());
}
public File getSecondaryLocalFile() {
return new File(secondDir, getName());
}
public void createLocal() throws IOException {
createFile(getLocalFile(), getContent());
checkFileExists(getLocalFile());
}
public void createSecondaryLocal() throws IOException {
createFile(getSecondaryLocalFile(), getContent());
checkFileExists(getSecondaryLocalFile());
}
public void createRemote() throws IOException {
getRemoteFile().getParentFile().mkdirs();
createFile(getRemoteFile(), getContent());
checkFileExists(getRemoteFile());
}
public File getRemoteFile() {
return new File(kojiDb, getStubWithName());
}
}
@Test
/*
* scp /abs/path/nvra tester@localhost:
*/
public void scpNvraAbsPathsTo() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1t1");
nvra.createLocal();
int r = scpTo("", nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
*scp tester@localhost:nvra /abs/path/
*/
public void scpNvraAbsPathsFrom1() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f1");
nvra.createRemote();
int r2 = scpFrom(nvra.getLocalFile().getParent(), nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
*scp tester@localhost:/nvra /abs/path
*/
public void scpNvraAbsPathsFrom2() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f2");
nvra.createRemote();
int r3 = scpFrom(nvra.getLocalFile().getParent(), "/" + nvra.getName());
Assert.assertTrue(r3 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp /abs/path/nvra tester@localhost:/nvra
*/
public void scpNvraAbsPathsRenameLikeTo() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1");
nvra.createLocal();
int r = scpTo("/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:nvra /abs/path/nvra
*/
public void scpNvraAbsPathsRenameLikeFrom1() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1");
nvra.createRemote();
int r1 = scpFrom(nvra.getLocalFile().getAbsolutePath(), nvra.getName());
Assert.assertTrue(r1 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp tester@localhost:nvra /abs/path/nvra2
*/
public void scpNvraAbsPathsRenameLikeFrom2() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t2");
nvra.createRemote();
int r2 = scpFrom(new File(nvra.getLocalFile().getParent(), "nvra2").getAbsolutePath(), nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(new File(nvra.getLocalFile().getParent(), "nvra2"));
}
@Test
/*
* scp nvra tester@localhost:
*/
public void scpNvraAllRelativeToNoTarget() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1");
nvra.createLocal();
int r = scpToCwd("", sources, nvra.getLocalFile().getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp nvra tester@localhost:nvra
*/
public void scpNvraAllRelativeTo() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1");
nvra.createLocal();
int r = scpToCwd("", sources, nvra.getLocalFile().getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp nvra tester@localhost:/nvra
*/
public void scpNvraAllRelativeToPseudoAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t2");
nvra.createLocal();
int r = scpToCwd("/", sources, nvra.getLocalFile().getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:nvra .
*/
public void scpNvraAbsPathsFromNameToCwd() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f1");
nvra.createRemote();
int r2 = scpFromCwd(".", sources, nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp tester@localhost:nvra ./nvra2
*/
public void scpNvraAbsPathsFromNameToCwdrenamed() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f2");
nvra.createRemote();
int r2 = scpFromCwd("./renamed", sources, nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(new File(nvra.getLocalFile().getParentFile(), "renamed"));
}
@Test
/*
* scp /abs/path/nvra tester@localhost:/some/garbage
*/
public void scpNvraAbsToAbsGarbage() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t1");
nvra.createLocal();
int r = scpTo("/some/garbage", nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
scp /abs/path/nvra tester@localhost:/some/garbage/nvra
*/
public void scpNvraAbsToAbsGarbageRenameLike() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t2");
nvra.createLocal();
int r = scpTo("/some/garbage/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp nvra tester@localhost:some/garbage
*/
public void scpNvraRelToRelGarbage() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3");
nvra.createLocal();
int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/* scp nvra tester@localhost:some/garbage/nvra
*/
public void scpNvraRelToRelGarbageRenameLike() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3");
nvra.createLocal();
int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:/some/garbage/nvra /abs/path/
*/
public void scpAbsGarbagedNvraToAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f1");
nvra.createRemote();
int r2 = scpFrom(nvra.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nvra some/path/
*/
public void scpRelGarbagedNvraToRel() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f2");
nvra.createRemote();
int r2 = scpFromCwd(nvra.getName(), sources, "some/garbage/" + nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/* scp /some/path/nvra2 tester@localhost:some/garbage/nvra1
*/
public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraRel() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t1x1");
NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t1x2");
nvraSource.createLocal();
checkFileNotExists(nvraTarget.getLocalFile());
int r = scpTo("some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvraTarget.getRemoteFile());
checkFileNotExists(nvraSource.getRemoteFile());
}
@Test
/* scp /some/path/nvra2 tester@localhost:/some/garbage/nvra1
*/
public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1");
NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2");
nvraSource.createLocal();
checkFileNotExists(nvraTarget.getLocalFile());
int r = scpTo("/some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvraTarget.getRemoteFile());
checkFileNotExists(nvraSource.getRemoteFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nvra1 /some/path/nvra2
*/
public void scpNvrFromAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1");
NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2");
nvraSource.createRemote();
checkFileNotExists(nvraTarget.getRemoteFile());
int r = scpFrom(nvraTarget.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvraSource.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvraTarget.getLocalFile());
checkFileNotExists(nvraSource.getLocalFile());
}
@Test
/*
* scp some/path/nonNvra tester@localhost:some/garbage/nvra
*/
public void scpSomeFileToGarbagedNvra() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5t3");
nvra.createLocal();
File renamed = new File(nvra.getLocalFile().getParentFile(), "renamed");
nvra.getLocalFile().renameTo(renamed);
checkFileNotExists(nvra.getLocalFile());
checkFileExists(renamed);
nvra.getLocalFile().renameTo(renamed);
int r = scpTo("some/garbage/" + nvra.getName(), renamed.getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nvra /some/path/nonNvra
*/
public void scpSomeFileFromGarbagedNvra() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5f3");
nvra.createRemote();
File nwFile = new File(nvra.getLocalFile().getParent(), "renamed");
int r = scpFrom(nwFile.getAbsolutePath(), "some/garbage/" + nvra.getName());
Assert.assertTrue(r == 0);
checkFileNotExists(nvra.getLocalFile());
checkFileExists(nwFile);
}
@Test
/*
* scp some/path/nvra tester@localhost:some/garbage/NonNvra
*/
public void scpNvraToMoreGarbaged() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6t2");
nvra.createLocal();
int r2 = scpTo("/some/garbage/someFile", nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nonNvra some/path/nvra
*/
public void scpNonsenseToNvra() throws IOException, InterruptedException {
//inccorect case
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6f1");
nvra.createRemote();
int r = scpFrom(nvra.getLocalFile().getAbsolutePath(), "some/garbage/notExisting");
Assert.assertTrue(r != 0);
checkFileNotExists(nvra.getLocalFile());
}
//data
//logs
//data/logs
//genereic/path
// -r version
}
|
package org.fakekoji.xmlrpc.server.core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFilePermission;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.sshd.server.SshServer;
import org.fakekoji.xmlrpc.server.SshApiService;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class TestSshApi {
private static final String IDS_RSA = "
+ "MIISKQIBAAKCBAEA6DOkXJ7K89Ai3E+XTvFjefNmXRrYVIxx8TFonXGfUvSdNISD\n"
+ "uZW+tC9FbFNBJWZUFludQdHAczLCKLOoUq7mTBe/wPOreSyIDI1iNnawV/KsX7Ok\n"
+ "yThsDolKxgRA+we8JuUYAes2y94FKaw4kAY/Ob16WSf7AP9Y8Oa4/PcK6KCIkzQx\n"
+ "iqL+SGG3mLy+XhTU/pJYnEC8c1lw+Gah8oPWG1vx5W578iWixgTbNp0TTXNr1+jU\n"
+ "xVRg1SitC4WP8g67af6f5rhcJZt5Dz/gWajHqKkK97nmPSDttso56ueeUW3L8lM3\n"
+ "scFjGQu3QbpLmFpMZeTpePOn7CjVjfBZnocNzDdqkgE+ivEB7nWWNbgEwALX4NR4\n"
+ "DzkGGoFPUKdsIdEBC5D73XC6NJxHKWOO9L+KyUxoeA8hUHBuWc3pVSi7NyG04Pvq\n"
+ "EfO0Ea1p4Tn2nb2CreEgOyCQ/nLJJrPEDef+8GUKKs3tVawbOn6tLFyi7aFY9u35\n"
+ "KX3fgt5t8TiIqmcIxs7oC16ny/97pe7gBRZuLU4AxK76m6Nxr1lGw7wJOXllhoKb\n"
+ "Zys676qlIG6VvSw/dAUekY/Vk9duIm9BHHLVZetv/LL4hWNy7xMvlpl8V141azJw\n"
+ "BE10V1GuvJnRtsf57ZqSOjiezTewavteJLwTZlRTV7QwsVpUGM7YyYJacv1GkFzz\n"
+ "00UWg+/Pf1gyLHf+JgsWx1ftUU9WlnVgBSfZpWKHexjcKrJzk4n96HWFL4ihCfxd\n"
+ "895ZkBsbTyuRAsC3Tw+k/FC6j0bbM5eE9weBH9b3Ap6tZFlIwEwXCvU28i0SbxEq\n"
+ "PXpnxpK33XRHz3byu8QtX4BulVrwa0P/ZeY0fvooUJo+tUqHbE7Pf5DlzylZarXQ\n"
+ "BSHjPcG+bs37LA2ar/1o6hRXJ5Z3b8f4YH3HumGuiYY3NjDvq++P5RTnasWFN7+f\n"
+ "1xYexB3HZE9RXxCTTVIn09fVHnaloNCnvhl6fn40TfsmS10qN1hwh55nzvpUjqGz\n"
+ "qyC+9Z/F+RpqIIAVKyijyMy2PiJRBy8sPZa1qf9+xDCZsRYdUPebr8t38sPEYYtR\n"
+ "8wMfY1iq0qXn1Pi/G+ghmTn+/UIdubn/m7Iu/F0GSyN6cjz4fskpS5bAb1oJhoWD\n"
+ "yrx6EAf96OoVIrMQcaBkLVcd7MW59rSDK0gNK7DE3ZXa85VwcMj/Y9HCybY/Xlf5\n"
+ "v7Csi38E+ybHP2R3YEPMduLg3hrs0UVfQaZoirA/yVtvVF3mv5Nh/RfCvCvGGR2s\n"
+ "PNgnq7ZKia5/nXqV4/l2Yrrg2QPYtAYwuv2Sf6GK5MqhqBtWb8qZRZVH7df4IroJ\n"
+ "orWmi2obRqdU5+w2F+OaL7OOs8GIwLb9iGeswwIDAQABAoIEAQC9ZPnoLgEeMyNs\n"
+ "DWM+GbfozXYt9OqEs/VwJLvOx9GLaUgcgQWsRw7Ai1oVzCZz6e4mOl2fRQWzMLCb\n"
+ "YEaoAk6HvEtEh7vSX1cs3dlA0Thu09pzSOTc16+Tf7pEn02dM6btFqmpTwBn8tTF\n"
+ "M9sC5oWFhB4aQHkETEJwY9B5TMtSCTa80rKiAOZlhYaqBzFDLby5VAcAk/DiKQ7z\n"
+ "HUt0ssHdmPZKC/7++GG3IFjpR99pqf5JoniB55v/4Wib4DoT1p5ZCz3Dg5Ztek2Y\n"
+ "+aH1n6wSzqbKfo/kRkp+cJ4jEv7YLjVOlz/zNeitkhfMfbaRMv3jkn44kIzkHD5r\n"
+ "wqJmooPHkV/UbT1lOMU5iiGV+V2ue+M3WDYBPKLU1aorABQ71O0EUSKOcRcAOIP2\n"
+ "p2UADoeWP0NqwfSLVtk7WK+8LTfe9RhC9lbqg5vZW1fkRFH6QYwoZVrTv3FkiZ22\n"
+ "eqQsL5GK5O8RENxHp9ShtpdrerfOGW+mIV680BWR+fk06sbWLqpC9prgQzmcM+vX\n"
+ "4WpJ3AzL2TbZNlvkvMDKpIgKuQHRJkqAF2HIGcO9nrOHK4vpPAEZkd9oHSi4qNwF\n"
+ "LDewi52xvwKd3CDHM+GYTU7giJqZ7JantAEYEVEWs+JRpSkf7CbX/d7NrEci3gyA\n"
+ "hj04u0sbiSZdf/TDhAjaH0VFv5Qk+xEf4NbGvL+UZse/WYCINYQNSbLZCH3ZmnFn\n"
+ "3JG/vlAB1ojpAHJb2Eg2zTIcPw//ocig27ZvzZG1fwebLB0dwPoMOtaeh66hzSv/\n"
+ "TTduDJsiLg/x/I9Fbw/uJd6DSypndSCq+BNUy3g32umnsmj4x3XTnfn56d2E5n2w\n"
+ "ivMxYaFlyMTJ3ilJJEpk2ioLzlWYVhZFMielmrpsE8EM4Rnv+lVfPzu7VDSIyMDI\n"
+ "L6VPLRG4+wakSajacwKBGfVB/wEWrhGxQb9uHdFcXbzNmx2m/70S5LEiOTmTv47g\n"
+ "rSD7bPxQ9ghx9XcXnoFjts+Crz9Pl0NbmMCJQ2KTPmAXCMJNBC0Xof3yrP0+ZKM+\n"
+ "ZNXTAhCPesDTgOmYtMnyKZa0XxzCf5DgBYa6zzT484w0qZcMRYewFLJEv0oD2cwC\n"
+ "WSbjvvCmBJLHxp9+L3H5uE4hMLuZhdIV7+KrwTetylRNxjM7wi8w0uUUE9/6uHK4\n"
+ "Wy4DA7kfjPmvGhbbv/63baVQRRCs7M8Sk6rUD+JZ+ZKzVK31+j8WwNT7zbXte2qs\n"
+ "NCnEPrGvJRKb3arq6VMJXzLlknFUbOiO6S8EvgeglunPtqyadMIhNQdk7cW+4hzq\n"
+ "tY4aNtT4zdozmji/WzDBSPMhIYh0CV7zSgVuFS/SsWyAWDHX4IvZCoHLlg+bROaE\n"
+ "NdnX6B6JAoICAQD9V6GdwcUsgbH0jJb3dhQ0Zpqcrrl8U496msYkg+b6MyqX55Ev\n"
+ "YItv16grvhl7QupK93pD256zGm+83e6Jxox4ZxLLmgx6fH3ubkRC7CbpRWtb7R1o\n"
+ "3YENjo8wmbjjcs38tUG5LEHFsZOeyVWkkW+/PCuOUl4m/3m7BOiwEYIA6vYdC42F\n"
+ "kBH8FaRi2zZ+kiHX2vHIbdpb7H013gSZt8ieKrLJh6FESFSINuW4ISGbCgn9nEw7\n"
+ "uAG7EMwQliCe66SIx+aYxaaxJL0q0tJkX/glzO//9Fu5LX+n5nCgqcTv2TB5IANi\n"
+ "fyi/YrbaX1hUxJFYyh39a1rIpjk4wSZwXZIC6ZHc3CKu5mNhML4a809W5siKXR/9\n"
+ "hQqiSeCIXuBq96E+s9kGNp9hLBUgQGooZwMZdVgOX0dSf4E6KoVz5c4PTEuJO7K8\n"
+ "wxlTfegUxzKzYi+A29lNHiYJF51CSJGr7Z1VFWpVUa7Ts953SgsfIYqB1Yrflgtn\n"
+ "vJi3+FDuNLPIMeVJLDdp8tXBUDnDzZL4eRdQEIzmYJuExEj3g3i8Vmd1fJ5yhtEd\n"
+ "7N93KVstqp8mGvYYnfCfXZUiwn1ivRgzfeYR+siTKuTXmwhsXBcy6Z5cLZOatjUC\n"
+ "uBME4We4ra9AoXc6iU9Zrn8zAEMeEtl8QSiIk2OJkqTIaWck1Li6RpRJVwKCAgEA\n"
+ "6qM8dzcv6naHOSJmbdZT8c8yVVAEbhkgj22mdfHJa437o0dqXm8oKyDhucDhG1kx\n"
+ "Uj4lBlx7vH5uDJJ3YbrsLQcQhf1r7ol84VAlJmm9OF6horLKRWc2Eke8LbtRw3VV\n"
+ "9M9fOP4b5gwJFeVOYHK61iKRwDw+qs1GX/5jOQLPdDC+BSzLFCGvDCFk6BrAadcn\n"
+ "IVfJ+7Sid9v30kpUPGpDiJzZ0Ofb6+1ppcW/YlZE6OPBJMD0cIcd3ogMFPBA+ZuQ\n"
+ "zLPf3PVbEUxDNLOCjTvLie5jvGvBTXrGSvXXTRt+rpBkkrd6GqM3jKBEOPMxWiFm\n"
+ "Uiw8WqOKKC46FpiUAD82uJddnd1R/dM1cbtJiF3QX5CEGbaKdAWzoG0CODw5tyX1\n"
+ "Cxgy43PCQafz/AOKAecNp6eCWkyEbjCBsCrJg3lKfQWyJ0MqToadSA+iDUYRA6PB\n"
+ "sEJWiy8UtnbwgDtTtUNKxWhbGOLxGRQnnSo7USE93ew8tuWa9oW9S/BEF7AiCk+S\n"
+ "HCINMB7ek2QXzFqS3h7WBSzDn+ZsSOo3EH5I5NV0EfgeGfAnC9mKLc9wM6XiuBOY\n"
+ "eLiFPc6nLlB8jJpEFioK44oQl4qV8NCP4Dwz2r+iLUt8E8vQAypYNZrZTLEktIL9\n"
+ "Egl+3+bUPgMJOVqwI4YCkICnJjnlVDkBL2xpFmsOGHUCggIAEvUDuvJM9s+dqVb7\n"
+ "1PiY+nLTDvZkGtGF4v7B5OmZ1w8NGODTFGB9DplslBldfsO7FHEATSOZ9Hz973wL\n"
+ "5XNd/4R2+5VDacb3BWhq4zcYkkwHhJFxqe8pQQJx5IkcNKjakRZfHKQbJ9fp2+/k\n"
+ "4LOhUQYHnFa9hN2JFl1/q+0jdT4fvHyo0l29eseDzYHpyf7VWXmgrgbKWCaSF/3N\n"
+ "ClOeR3eaeUoU3y8qZCb3eZfBFADkTn3rlmxmdMEFBBi3yCyJ21JaBwSDPK4rGZE8\n"
+ "/RXRU8LKErUOSAUHkGDF/L+3ZNszrVyf5DbvraKNXDnWOkGbPrGhHN1zpaAKmByb\n"
+ "67yUuHMR3xz522yR8yvajdm3DiGmz/O3+RiDezFcA9hVoqt0/WQn0Tc1JehOjGNF\n"
+ "jlBnAvis5iZrB9lSqi+UXN/NU4e5/0LgVQ+kTYMWYrelK5clRtcso4CmB/gkZFlZ\n"
+ "zSuyojNACbJbCqxi8ToxKtsvqhd4lNJ9d/28z8ddBvYandhd9+O/IcZyCE0ghW5U\n"
+ "mRM2k18pq/N+r6igbSUBW9Z7V2dD0/4Sl9KpxhjqIbiqwAc0cxMedk5iYn97MnBD\n"
+ "51Z8aMwDRj/nb9rB/pnFgqHIn80pRmJsBRARHERhpogYnRV3/oFX1rYf/oj+fLmc\n"
+ "XJfjmJSu1hSLEBQTC8Z/LDEr13ECggIBAOlnB7bvRtLMpSbIeWu5UDeyDDehKUb7\n"
+ "58/FG1kn81zyF+cMG1tk52g/hUrp+wLhbpaJCvuQ8+VFPuNyrx6gel8wL9eZh8v5\n"
+ "KChZORtFA90XBWJ6x4rSaI82nJJBS8xK4/5qaiafX9EvF7qYJ6b5ebGZIbNAOnZd\n"
+ "TCwhOUJ08Th7ZApxzHFyMFa4wU/BjLW8OEiKs3mW7iacwaCGH9UZP6Sdom6Utcey\n"
+ "mu00EHUZq+Ke7HpLFtz5C1VZr+sEMx4ZCakXJRD/YF+MpS2/g5ZKbOYAJWZBKkCQ\n"
+ "aMAYXNtvBk1PhTwNF4F36sIQisy73dPydX44UrE3DS97DH19uXulZiGpMI7gobcE\n"
+ "ap1/2F22NJlbgIyzcHaJVW24AgU+o4r0TxWCNNzdQddd4u5F9vp9hK/JiXmZtAKI\n"
+ "bfl4FoyaEubay6USwvrqHXqZUnIxyKr+MqXK15wMcWYwWny0h0hAcBh+/l97IKn5\n"
+ "yo4kfGzvzEL9xEeLjuK7ltn7X0DRDIuFK6qglM3RZ0bmwmWdk4sw0WTEarSc2gqO\n"
+ "MchOVuSLELLvRcI3ih/XfgSj3NEDqsvBcmJj6ubYsqT3m22h5yjFGZ/Or0KPsSej\n"
+ "z/sW594p0oGMHRj0HS+I58YrCw2nCQQnaOaQW40OaQJmsr5C4AP2QobL83mrDd0B\n"
+ "95PdG4wZYiQhAoICAAEQjP1dbHOT/4oycWukZIayEN3rGJbwjLJcM5n+VVMMprDE\n"
+ "2Bx9YmjijOMRHqCZY7rDr6OMhnuI1E2gkAbTfHfLWM3OpnagdL73uAjYWoU8QIZl\n"
+ "8NS3u8lNbDQby4WIbmtvIbPbKrnV47illLfdfcMvp16E+zXpgBERZfA5kjdvL2Zs\n"
+ "CoKitgJmes6Cw7gpxq04wuuq5xJ856rPmwiFTJCJGoN5yXQYZsqNsz1iWvjTVUen\n"
+ "JjNj5aveSb1a34JEqlLxk2NoYrT47A54iMJQSqXQQDwbW2U0vOZMv9FtwjJti9EO\n"
+ "aIma8wcoQhLGqt9/yQ66BzLCCQfnxMDgGUK7RD85Jcq7WghgSJv8iRQ4Hu8J7tTO\n"
+ "SZJOJy9IDmSp/Yh5R/9KMEdgvUQRo4JFqORyguokkKTa2EYYPpoDfCv1uEg8rr+4\n"
+ "xtKBxoiw+UJZGnEbUGJw2Yt2ynbV4dUlUkgMOBrznYdtmivaF544DD8Tgk8elNdT\n"
+ "WowvdHlPa9HCY7VNWo80vaOUXUSo6ftUkTVhyd9EI84g1JyFGPcpd624NsAhQrSm\n"
+ "kg8qubbQM3Tij5oGYewJ2PzeweosiQ4AVlq3+mVGnkNLPLyABHOgGmoUPpyR297R\n"
+ "nDe3iQJfqKGHQck94dCtx7mlbcgBwWiM1SCdZcJ8H06gBWA99hNqcwWS9kSv\n"
+ "
private static final String IDS_RSA_PUB = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAEAQDoM6Rcnsrz0CLcT5dO8WN582ZdGthUjHHxMWidcZ9S9J00hIO5lb60L0VsU0ElZlQWW51B0cBzMsIos6hSruZMF7/A86t5LIgMjWI2drBX8qxfs6TJOGwOiUrGBED7B7wm5RgB6zbL3gUprDiQBj85vXpZJ/sA/1jw5rj89wrooIiTNDGKov5IYbeYvL5eFNT+klicQLxzWXD4ZqHyg9YbW/HlbnvyJaLGBNs2nRNNc2vX6NTFVGDVKK0LhY/yDrtp/p/muFwlm3kPP+BZqMeoqQr3ueY9IO22yjnq555RbcvyUzexwWMZC7dBukuYWkxl5Ol486fsKNWN8Fmehw3MN2qSAT6K8QHudZY1uATAAtfg1HgPOQYagU9Qp2wh0QELkPvdcLo0nEcpY470v4rJTGh4DyFQcG5ZzelVKLs3IbTg++oR87QRrWnhOfadvYKt4SA7IJD+cskms8QN5/7wZQoqze1VrBs6fq0sXKLtoVj27fkpfd+C3m3xOIiqZwjGzugLXqfL/3ul7uAFFm4tTgDErvqbo3GvWUbDvAk5eWWGgptnKzrvqqUgbpW9LD90BR6Rj9WT124ib0EcctVl62/8sviFY3LvEy+WmXxXXjVrMnAETXRXUa68mdG2x/ntmpI6OJ7NN7Bq+14kvBNmVFNXtDCxWlQYztjJglpy/UaQXPPTRRaD789/WDIsd/4mCxbHV+1RT1aWdWAFJ9mlYod7GNwqsnOTif3odYUviKEJ/F3z3lmQGxtPK5ECwLdPD6T8ULqPRtszl4T3B4Ef1vcCnq1kWUjATBcK9TbyLRJvESo9emfGkrfddEfPdvK7xC1fgG6VWvBrQ/9l5jR++ihQmj61SodsTs9/kOXPKVlqtdAFIeM9wb5uzfssDZqv/WjqFFcnlndvx/hgfce6Ya6Jhjc2MO+r74/lFOdqxYU3v5/XFh7EHcdkT1FfEJNNUifT19UedqWg0Ke+GXp+fjRN+yZLXSo3WHCHnmfO+lSOobOrIL71n8X5GmoggBUrKKPIzLY+IlEHLyw9lrWp/37EMJmxFh1Q95uvy3fyw8Rhi1HzAx9jWKrSpefU+L8b6CGZOf79Qh25uf+bsi78XQZLI3pyPPh+ySlLlsBvWgmGhYPKvHoQB/3o6hUisxBxoGQtVx3sxbn2tIMrSA0rsMTdldrzlXBwyP9j0cLJtj9eV/m/sKyLfwT7Jsc/ZHdgQ8x24uDeGuzRRV9BpmiKsD/JW29UXea/k2H9F8K8K8YZHaw82CertkqJrn+depXj+XZiuuDZA9i0BjC6/ZJ/oYrkyqGoG1ZvyplFlUft1/giugmitaaLahtGp1Tn7DYX45ovs46zwYjAtv2IZ6zD tester";
private static File kojiDb;
private static File sources;
private static File secondDir;
private static File priv;
private static File pub;
private static int port;
private static SshServer sshd;
private static final boolean debug = true;
@BeforeClass
public static void startSshdServer() throws IOException, GeneralSecurityException {
ServerSocket s = new ServerSocket(0);
port = s.getLocalPort();
final File keys = File.createTempFile("ssh-fake-koji.", ".TestKeys");
keys.delete();
keys.mkdir();
priv = new File(keys, "id_rsa");
pub = new File(keys, "id_rsa.pub");
createFile(priv, IDS_RSA);
createFile(pub, IDS_RSA_PUB);
Set<PosixFilePermission> perms = new HashSet<>();
Files.setPosixFilePermissions(pub.toPath(), perms);
Files.setPosixFilePermissions(priv.toPath(), perms);
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
Files.setPosixFilePermissions(pub.toPath(), perms);
Files.setPosixFilePermissions(priv.toPath(), perms);
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
priv.delete();
pub.delete();
keys.delete();
}
});
s.close();
SshApiService server = new SshApiService();
kojiDb = File.createTempFile("ssh-fake-koji.", ".root");
kojiDb.delete();
kojiDb.mkdir();
kojiDb.deleteOnExit();
sshd = server.setup(port, kojiDb, "tester=" + pub.getAbsolutePath());
sources = File.createTempFile("ssh-fake-koji.", ".sources");
sources.delete();
sources.mkdir();
sources.deleteOnExit();
secondDir = File.createTempFile("ssh-fake-koji.", ".secondDir");
secondDir.delete();
secondDir.mkdir();
secondDir.deleteOnExit();
}
@AfterClass
public static void stopSshd() throws IOException {
sshd.stop(true);
}
private static void createFile(File path, String content) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(path))) {
bw.write(content);
}
}
private static String readFile(File path) {
try {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine();
}
} catch (Exception ex) {
ex.printStackTrace();
return "impossible";
}
}
private static int scpTo(String target, String... source) throws InterruptedException, IOException {
return scpTo(new String[0], target, null, source);
}
private static int scpToCwd(String target, File cwd, String... source) throws InterruptedException, IOException {
return scpTo(new String[0], target, cwd, source);
}
private static final String TESTERatLOCALHOSTscp = "tester@localhost:";
private static int scpTo(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException {
String fullTarget = TESTERatLOCALHOSTscp + target;
return scpRaw(params, fullTarget, cwd, source);
}
private static int scpFrom(String target, String... source) throws InterruptedException, IOException {
return scpFrom(new String[0], target, null, source);
}
private static int scpFromCwd(String target, File cwd, String... source) throws InterruptedException, IOException {
return scpFrom(new String[0], target, cwd, source);
}
private static int scpFrom(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException {
for (int i = 0; i < source.length; i++) {
source[i] = TESTERatLOCALHOSTscp + source[i];
}
return scpRaw(params, target, cwd, source);
}
private static int scpRaw(String[] params, String target, File cwd, String... source) throws InterruptedException, IOException {
title(3);
List<String> cmd = new ArrayList<>(params.length + source.length + 9);
cmd.add("scp");
//cmd.add("-v"); //verbose
cmd.add("-o");
cmd.add("StrictHostKeyChecking=no");
cmd.add("-i");
cmd.add(priv.getAbsolutePath());
cmd.add("-P");
cmd.add("" + port);
cmd.addAll(Arrays.asList(params));
cmd.addAll(Arrays.asList(source));
cmd.add(target);
if (debug) {
for (int i = 0; i < source.length; i++) {
String string = source[i];
System.out.println(i + ". scp from " + string);
System.out.println(" scp to " + target);
}
}
ProcessBuilder pb = new ProcessBuilder(cmd);
if (cwd != null) {
pb.directory(cwd);
}
Process p = pb.start();
if (debug) {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while (true) {
String s = br.readLine();
if (s == null) {
break;
}
System.out.println(s);
}
}
int i = p.waitFor();
if (debug) {
System.out.println(" === scpEnd === ");
}
return i;
}
@After
public void cleanSecondDir() {
clean(secondDir);
}
@After
public void cleanSources() {
clean(sources);
}
@After
public void cleanKojiDb() {
clean(kojiDb);
}
private void clean(File f) {
File[] content = f.listFiles();
for (File file : content) {
deleteRecursively(file);
}
Assert.assertTrue(f.isDirectory());
Assert.assertTrue(f.listFiles().length == 0);
}
private void deleteRecursively(File file) {
if (file.isDirectory()) {
File[] content = file.listFiles();
for (File f : content) {
deleteRecursively(f);
}
}
file.delete();
}
private static void checkFileExists(File f) {
if (debug) {
System.out.println(f + " is supposed to exists. f.exists() is: " + f.exists());
if (f.exists()) {
System.out.println("content: '" + readFile(f) + "'");
}
}
Assert.assertTrue(f + " was supposed to exists. was not", f.exists());
}
private static void checkFileNotExists(File f) {
if (debug) {
System.out.println(f + " is supposed to NOT exists. f.exists() is: " + f.exists());
if (f.exists()) {
System.out.println("content: '" + readFile(f) + "'");
}
}
Assert.assertFalse(f + " was supposed to NOT exists. was", f.exists());
}
private static void title(int i) {
if (debug) {
String s = "method-unknow";
if (Thread.currentThread().getStackTrace().length > i) {
s = Thread.currentThread().getStackTrace()[i].getMethodName();
}
System.out.println(" ==" + i + "== " + s + " ==" + i + "== ");
}
}
private class NvraTarballPathsHelper {
private final String vid;
private final String rid;
private final String aid;
public NvraTarballPathsHelper(String id) {
this(id, id, id);
}
public NvraTarballPathsHelper(String vid, String rid, String aid) {
this.vid = vid;
this.rid = rid;
this.aid = aid;
}
public String getName() {
return "terrible-x-name-version" + vid + "-release" + rid + ".arch" + aid + ".suffix";
}
public String getLocalName() {
return getName();
}
public String getRemoteName() {
return getName();
}
public String getNVRstub() {
return "terrible-x-name/version" + vid + "/release" + rid;
}
public String getStub() {
return getNVRstub() + "/arch" + aid;
}
public String getContent() {
return "nvra - " + vid + ":" + rid + ":" + ":" + aid;
}
public String getStubWithName() {
return getStub() + "/" + getRemoteName();
}
public File getLocalFile() {
return new File(sources, getLocalName());
}
public File getSecondaryLocalFile() {
return new File(secondDir, getLocalName());
}
public void createLocal() throws IOException {
createFile(getLocalFile(), getContent());
checkFileExists(getLocalFile());
}
public void createSecondaryLocal() throws IOException {
createFile(getSecondaryLocalFile(), getContent());
checkFileExists(getSecondaryLocalFile());
}
public void createRemote() throws IOException {
getRemoteFile().getParentFile().mkdirs();
createFile(getRemoteFile(), getContent());
checkFileExists(getRemoteFile());
}
public File getRemoteFile() {
return new File(kojiDb, getStubWithName());
}
}
@Test
/*
* scp /abs/path/nvra tester@localhost:
*/
public void scpNvraAbsPathsTo() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1t1");
nvra.createLocal();
int r = scpTo("", nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
*scp tester@localhost:nvra /abs/path/
*/
public void scpNvraAbsPathsFrom1() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f1");
nvra.createRemote();
int r2 = scpFrom(nvra.getLocalFile().getParent(), nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
*scp tester@localhost:/nvra /abs/path
*/
public void scpNvraAbsPathsFrom2() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("1f2");
nvra.createRemote();
int r3 = scpFrom(nvra.getLocalFile().getParent(), "/" + nvra.getName());
Assert.assertTrue(r3 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp /abs/path/nvra tester@localhost:/nvra
*/
public void scpNvraAbsPathsRenameLikeTo() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1");
nvra.createLocal();
int r = scpTo("/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:nvra /abs/path/nvra
*/
public void scpNvraAbsPathsRenameLikeFrom1() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t1");
nvra.createRemote();
int r1 = scpFrom(nvra.getLocalFile().getAbsolutePath(), nvra.getName());
Assert.assertTrue(r1 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp tester@localhost:nvra /abs/path/nvra2
*/
public void scpNvraAbsPathsRenameLikeFrom2() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("2t2");
nvra.createRemote();
int r2 = scpFrom(new File(nvra.getLocalFile().getParent(), "nvra2").getAbsolutePath(), nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(new File(nvra.getLocalFile().getParent(), "nvra2"));
}
@Test
/*
* scp nvra tester@localhost:
*/
public void scpNvraAllRelativeToNoTarget() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1");
nvra.createLocal();
int r = scpToCwd("", sources, nvra.getLocalFile().getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp nvra tester@localhost:nvra
*/
public void scpNvraAllRelativeTo() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t1");
nvra.createLocal();
int r = scpToCwd("", sources, nvra.getLocalFile().getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp nvra tester@localhost:/nvra
*/
public void scpNvraAllRelativeToPseudoAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3t2");
nvra.createLocal();
int r = scpToCwd("/", sources, nvra.getLocalFile().getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:nvra .
*/
public void scpNvraAbsPathsFromNameToCwd() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f1");
nvra.createRemote();
int r2 = scpFromCwd(".", sources, nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp tester@localhost:nvra ./nvra2
*/
public void scpNvraAbsPathsFromNameToCwdrenamed() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("3f2");
nvra.createRemote();
int r2 = scpFromCwd("./renamed", sources, nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(new File(nvra.getLocalFile().getParentFile(), "renamed"));
}
@Test
/*
* scp /abs/path/nvra tester@localhost:/some/garbage
*/
public void scpNvraAbsToAbsGarbage() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t1");
nvra.createLocal();
int r = scpTo("/some/garbage", nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
scp /abs/path/nvra tester@localhost:/some/garbage/nvra
*/
public void scpNvraAbsToAbsGarbageRenameLike() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t2");
nvra.createLocal();
int r = scpTo("/some/garbage/" + nvra.getName(), nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp nvra tester@localhost:some/garbage
*/
public void scpNvraRelToRelGarbage() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3");
nvra.createLocal();
int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/* scp nvra tester@localhost:some/garbage/nvra
*/
public void scpNvraRelToRelGarbageRenameLike() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4t3");
nvra.createLocal();
int r = scpToCwd("some/garbage/" + nvra.getName(), nvra.getLocalFile().getParentFile(), nvra.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:/some/garbage/nvra /abs/path/
*/
public void scpAbsGarbagedNvraToAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f1");
nvra.createRemote();
int r2 = scpFrom(nvra.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nvra some/path/
*/
public void scpRelGarbagedNvraToRel() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("4f2");
nvra.createRemote();
int r2 = scpFromCwd(nvra.getName(), sources, "some/garbage/" + nvra.getName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getLocalFile());
}
@Test
/* scp /some/path/nvra2 tester@localhost:some/garbage/nvra1
*/
public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraRel() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t1x1");
NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t1x2");
nvraSource.createLocal();
checkFileNotExists(nvraTarget.getLocalFile());
int r = scpTo("some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvraTarget.getRemoteFile());
checkFileNotExists(nvraSource.getRemoteFile());
}
@Test
/* scp /some/path/nvra2 tester@localhost:/some/garbage/nvra1
*/
public void scpNvraAbsToAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1");
NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2");
nvraSource.createLocal();
checkFileNotExists(nvraTarget.getLocalFile());
int r = scpTo("/some/garbage/" + nvraTarget.getName(), nvraSource.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvraTarget.getRemoteFile());
checkFileNotExists(nvraSource.getRemoteFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nvra1 /some/path/nvra2
*/
public void scpNvrFromAbsGarbageRenameLikeAnotherNvraAbs() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvraSource = new NvraTarballPathsHelper("5t2x1");
NvraTarballPathsHelper nvraTarget = new NvraTarballPathsHelper("5t2x2");
nvraSource.createRemote();
checkFileNotExists(nvraTarget.getRemoteFile());
int r = scpFrom(nvraTarget.getLocalFile().getAbsolutePath(), "/some/garbage/" + nvraSource.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvraTarget.getLocalFile());
checkFileNotExists(nvraSource.getLocalFile());
}
@Test
/*
* scp some/path/nonNvra tester@localhost:some/garbage/nvra
*/
public void scpSomeFileToGarbagedNvra() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5t3");
nvra.createLocal();
File renamed = new File(nvra.getLocalFile().getParentFile(), "renamed");
nvra.getLocalFile().renameTo(renamed);
checkFileNotExists(nvra.getLocalFile());
checkFileExists(renamed);
nvra.getLocalFile().renameTo(renamed);
int r = scpTo("some/garbage/" + nvra.getName(), renamed.getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nvra /some/path/nonNvra
*/
public void scpSomeFileFromGarbagedNvra() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("5f3");
nvra.createRemote();
File nwFile = new File(nvra.getLocalFile().getParent(), "renamed");
int r = scpFrom(nwFile.getAbsolutePath(), "some/garbage/" + nvra.getName());
Assert.assertTrue(r == 0);
checkFileNotExists(nvra.getLocalFile());
checkFileExists(nwFile);
}
@Test
/*
* scp some/path/nvra tester@localhost:some/garbage/NonNvra
*/
public void scpNvraToMoreGarbaged() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6t2");
nvra.createLocal();
int r2 = scpTo("/some/garbage/someFile", nvra.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvra.getRemoteFile());
}
@Test
/*
* scp tester@localhost:some/garbage/nonNvra some/path/nvra
*/
public void scpNonsenseToNvra() throws IOException, InterruptedException {
//inccorect case
title(2);
NvraTarballPathsHelper nvra = new NvraTarballPathsHelper("6f1");
nvra.createRemote();
int r = scpFrom(nvra.getLocalFile().getAbsolutePath(), "some/garbage/notExisting");
Assert.assertTrue(r != 0);
checkFileNotExists(nvra.getLocalFile());
}
@Test
/*
* scp some/path/nvra1 some/path/nvra1 tester@localhost:
*/
public void scpMultipleFilesToRelNothing() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7t3");
NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8t3");
nvra1.createLocal();
nvra2.createLocal();
int r = scpTo("", nvra1.getLocalFile().getAbsolutePath(), nvra2.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra1.getRemoteFile());
checkFileExists(nvra2.getRemoteFile());
}
@Test
/*
* scp some/path/nvra1 some/path/nvra1 tester@localhost:
*/
public void scpMultipleFilesToAbsGarbage() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7t4");
NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8t4");
nvra1.createLocal();
nvra2.createLocal();
int r = scpTo("/some/path/", nvra1.getLocalFile().getAbsolutePath(), nvra2.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra1.getRemoteFile());
checkFileExists(nvra2.getRemoteFile());
}
@Test
/*
* scp tester@localhost:/seome/garbage/nvra1 tester@localhost:/another/garbage/nvra2 .
*/
public void scpMultipleFilesFromAbsGarbage() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7f3");
NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8f3");
nvra1.createRemote();
nvra2.createRemote();
int r = scpFrom(sources.getAbsolutePath(), "some/garbage/" + nvra1.getName(), "/another/garbage/" + nvra2.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra1.getLocalFile());
checkFileExists(nvra2.getLocalFile());
}
@Test
/*
* scp tester@localhost:nvra1 tester@localhost:nvra2 dir
*/
public void scpMultipleFilesFrom() throws IOException, InterruptedException {
title(2);
NvraTarballPathsHelper nvra1 = new NvraTarballPathsHelper("7f4");
NvraTarballPathsHelper nvra2 = new NvraTarballPathsHelper("8f4");
nvra1.createRemote();
nvra2.createRemote();
int r = scpFrom(sources.getAbsolutePath(), nvra1.getName(), nvra2.getName());
Assert.assertTrue(r == 0);
checkFileExists(nvra1.getLocalFile());
checkFileExists(nvra2.getLocalFile());
}
/*
DATA
*/
private class NvraDataPathsHelper extends NvraTarballPathsHelper {
private final String localName;
private final String remoteName;
public NvraDataPathsHelper(String id, String name) {
this(id, name, name);
}
public NvraDataPathsHelper(String id, String localName, String remoteName) {
super(id);
this.localName = localName;
this.remoteName = remoteName;
}
@Override
public String getRemoteName() {
return remoteName;
}
@Override
public String getLocalName() {
return localName;
}
@Override
public String getStub() {
//no arch!
return super.getNVRstub() + "/data";
}
}
// scp /some/path/logname tester@localhost:nvra/data
@Test
public void scpDataToRelativeNvraDataNoSlash() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data1To", "dataFile");
nvraDataFile.createLocal();
int r2 = scpTo(nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:nvra/data/
@Test
public void scpDataToRelativeNvraDataSlash() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data2To", "dataFile");
nvraDataFile.createLocal();
int r2 = scpTo(nvraDataFile.getName() + "/data/", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:some/garbage/nvra/data
@Test
public void scpDataToRelGarbageNvraDataNoSlash() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data3To", "dataFile");
nvraDataFile.createLocal();
int r2 = scpTo("some/garbage/" + nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:some/garbage/nvra/data/
@Test
public void scpDataToRelGarbageNvraDataSlash() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data4To", "dataFile");
nvraDataFile.createLocal();
int r2 = scpTo("some/garbage/" + nvraDataFile.getName() + "/data/", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:/some/garbage/nvra/data
@Test
public void scpDataToAbsGarbageNvraDataNoSlash() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data5To", "dataFile");
nvraDataFile.createLocal();
int r2 = scpTo("/some/garbage/" + nvraDataFile.getName() + "/data", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:nvra/data/renamedLog
@Test
public void scpDataToRelNvraDataRenamed() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data6To", "dataFile", "newName");
nvraDataFile.createLocal();
int r2 = scpTo(nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:some/garbage/nvra/data/renamedLog
@Test
public void scpDataToRelGarbageNvraDataRenamed() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data7To", "dataFile", "newName");
nvraDataFile.createLocal();
int r2 = scpTo("some/garabge/" + nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:/some/garbage/nvra/data/renamedLog
@Test
public void scpDataToAbsGarbageNvraDataRenamed() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data8To", "dataFile", "newName");
nvraDataFile.createLocal();
int r2 = scpTo("/some/garabge/" + nvraDataFile.getName() + "/data/newName", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:data
@Test
public void scpDataToRelDataWrong() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data9To", "dataFile");
nvraDataFile.createLocal();
int r2 = scpTo("data", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertFalse(r2 == 0);
checkFileNotExists(nvraDataFile.getRemoteFile());
}
// scp /some/path/logname tester@localhost:/
@Test
public void scpDataToNothing() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data10To", "dataFile", "newName");
nvraDataFile.createLocal();
int r2 = scpTo("/", nvraDataFile.getLocalFile().getAbsolutePath());
Assert.assertFalse(r2 == 0);
checkFileNotExists(nvraDataFile.getRemoteFile());
}
// scp tester@localhost:nvra/data/name /some/path/
@Test
public void scpDataFromRelToDir() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data1f1", "dataFile");
nvraDataFile.createRemote();
int r2 = scpFrom(sources.getAbsolutePath(), nvraDataFile.getName() + "/data/" + nvraDataFile.getRemoteName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getLocalFile());
}
// scp tester@localhost:/nvra/data/name /some/path/
@Test
public void scpDataFromAbsToDir() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data2f1", "dataFile");
nvraDataFile.createRemote();
int r2 = scpFrom(sources.getAbsolutePath(), "/" + nvraDataFile.getName() + "/data/" + nvraDataFile.getRemoteName());
Assert.assertTrue(r2 == 0);
checkFileExists(nvraDataFile.getLocalFile());
}
// scp tester@localhost:garbage/nvra/data/name /some/path/rename
@Test
public void scpDataFromRelGarbageToDirFile() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data3f1", "dataFile");
nvraDataFile.createRemote();
File rename = new File(sources.getAbsolutePath(), "renamed");
checkFileNotExists(rename);
int r2 = scpFrom(rename.getAbsolutePath(), "some/garbage/" + nvraDataFile.getName() + "/data/" + nvraDataFile.getRemoteName());
Assert.assertTrue(r2 == 0);
checkFileExists(rename);
}
// scp tester@localhost:/another/garbagenvra/data/name /some/path/rename
@Test
public void scpDataFromAbsGarbageToDirFile() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvraDataFile = new NvraDataPathsHelper("data4f1", "dataFile");
nvraDataFile.createRemote();
File rename = new File(sources.getAbsolutePath(), "renamed");
checkFileNotExists(rename);
int r2 = scpFrom(rename.getAbsolutePath(), "/some/garbage/" + nvraDataFile.getName() + "/data/" + nvraDataFile.getRemoteName());
Assert.assertTrue(r2 == 0);
checkFileExists(rename);
}
@Test
/*
* scp some/path/file1 some/path/file2 tester@localhost:nvra/data
*/
public void scpMultipleDataFilesTo() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvra1 = new NvraDataPathsHelper("d1tt1", "f1");
NvraDataPathsHelper nvra2 = new NvraDataPathsHelper("d1tt1", "f2");
nvra1.createLocal();
nvra2.createLocal();
int r = scpTo(nvra1.getName() + "/data", nvra1.getLocalFile().getAbsolutePath(), nvra2.getLocalFile().getAbsolutePath());
Assert.assertTrue(r == 0);
checkFileExists(nvra1.getRemoteFile());
checkFileExists(nvra2.getRemoteFile());
}
@Test
/*
* scp tester@localhost:nvra1/data/f1 tester@localhost:nvra2/data/f2 dir
*/
public void scpMultipleDataFilesFrom() throws IOException, InterruptedException {
title(2);
NvraDataPathsHelper nvra1 = new NvraDataPathsHelper("d1ff1", "f1");
NvraDataPathsHelper nvra2 = new NvraDataPathsHelper("d1ff1", "f2");
nvra1.createRemote();
nvra2.createRemote();
int r = scpFrom(sources.getAbsolutePath(), "some/garbage/" + nvra1.getName() + "/data/" + nvra1.getRemoteName(), "/another/garbage/" + nvra2.getName() + "/data/" + nvra2.getRemoteName());
Assert.assertTrue(r == 0);
checkFileExists(nvra1.getLocalFile());
checkFileExists(nvra2.getLocalFile());
}
// -r uploads
// -r may need logs implementation
// scp -r tester@localhost:nvra/data .
// scp -r tester@localhost:nvra/data/ /some/path/
// scp -r tester@localhost:nvra/data .
// scp -r tester@localhost:nvra/data/ /some/path/
// scp -r tester@localhost:nvra/data/name .
// scp -r tester@localhost:nvra/data/name /some/path/
// scp -r tester@localhost:nvra/data/name .
// scp -r tester@localhost:nvra/data/name /some/path/
// scp -r tester@localhost:nvra/data/name rename
// scp -r tester@localhost:nvra/data/name /some/path/rename
// scp -r tester@localhost:nvra/data/name rename
// scp -r tester@localhost:nvra/data/name /some/path/rename
//logs
//data/logs
//genereic/path
// -r version
}
|
import java.util.Random;
/**
* @author Thomas Werner
* @date Mar 18, 2014
* @brief Allows an 'Easy' AI to generate moves in a game of Othello
* @details An AI that generates moves by generating 2 numbers at random and checking
* if it is a valid move
*
*/
public class OthEasyAI {
// Class Constants
private static final int BOARD_ROWS = 8;
private static final int BOARD_COLS = 8;
private static final int PLAYER_TWO = 1;
private static final int MOVE_SELECT_VALUE = 2;
// Misc Variables
private Random m_rand;
private int[] m_selectedMoves;
private int m_selectedRow;
private int m_selectedCol;
private boolean m_validMove;
/**
* Randomly selects a column and row using an object of the Random class until a valid move is selected
*
* @param PC Allows the current game to be accessed
* @return int[] array containing 2 indexes representing the selected x,y values
*/
public int[] selectMove(ProgramController PC) {
m_selectedMoves = new int[MOVE_SELECT_VALUE];
m_rand = new Random();
m_validMove = false;
while(m_validMove == false) {
m_selectedRow = m_rand.nextInt(BOARD_ROWS);
m_selectedCol = m_rand.nextInt(BOARD_COLS);
if(PC.getGame().checkValid(m_selectedRow, m_selectedCol, PC.getGame().getPlayer(PLAYER_TWO)) == true) {
m_validMove = true;
}
}
m_selectedMoves[0] = m_selectedRow;
m_selectedMoves[1] = m_selectedCol;
return m_selectedMoves;
}
/**
* Main method for class tests on OthEasyAI
* Takes no arguments
*/
public static void main(String[] args) {
/*
* Test One
* Calling OthEasyAI.selectCol on an Oth Board with default starting state.
*/
ProgramController testPC = new ProgramController();
C4AndOthelloBoardStore testBoard = new C4AndOthelloBoardStore();
OthEasyAI testAI = new OthEasyAI();
testPC.setIsC4(1);
testPC.setGame("player1", "player2");
testBoard.setBoardWidth(BOARD_ROWS);
testBoard.setBoardHeight(BOARD_COLS);
testBoard.setBoard(BOARD_ROWS, BOARD_COLS);
testPC.setBoard(testBoard);
int[] selectedMoves = new int[2];
selectedMoves = testAI.selectMove(testPC);
int testRow = selectedMoves[0];
int testCol = selectedMoves[1];
if(testPC.getGame().checkValid(testRow, testCol, testPC.getGame().getPlayer(PLAYER_TWO)) == true) {
System.out.println("C4EasyAI.selectCol Evaluated: Correct");
}
else {
System.out.println("C4EasyAI.selectCol Evaluated: Incorrect");
}
}
}
|
package aeronicamc.mods.mxtune.gui;
import aeronicamc.mods.mxtune.gui.widget.MXButton;
import aeronicamc.mods.mxtune.gui.widget.label.MXLabel;
import aeronicamc.mods.mxtune.gui.widget.list.SoundFontList;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Items;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Objects;
import static aeronicamc.mods.mxtune.init.ModItems.INSTRUMENT_ITEMS;
public class TestScreen extends Screen
{
private static final Logger LOGGER = LogManager.getLogger();
private final SoundFontList sfpWidget = new SoundFontList();
private TextFieldWidget titleTextWidget;
private TextFieldWidget musicTextWidget;
private MXLabel labelTitle;
private boolean initialized;
private final MXButton buttonOpen = new MXButton((open) -> onButtonOpen());
public TestScreen()
{
super(new TranslationTextComponent("screen.mxtune.test.title"));
}
@Override
public void init()
{
super.init();
labelTitle = new MXLabel(font, width / 2 , 5, font.width(title.getString()) + 4, font.lineHeight + 4, title, TextColorFg.WHITE);
labelTitle.setBackground(false);
labelTitle.setBorder(1);
labelTitle.setCentered(true);
labelTitle.setUlColor(TextColorBg.WHITE);
labelTitle.setBrColor(TextColorBg.DARK_GRAY);
labelTitle.setBackColor(TextColorBg.BLUE);
Objects.requireNonNull(this.minecraft).keyboardHandler.setSendRepeatsToGui(true);
buttonOpen.setLayout(this.width - 65, (this.height / 6 + 168) - 20, 50, 20);
buttonOpen.setMessage(new TranslationTextComponent("gui.mxtune.open"));
addButton(buttonOpen);
this.addButton(new MXButton(buttonOpen.getLeft(), buttonOpen.getBottom(), 50, 20, new TranslationTextComponent("gui.done"), (done) -> {
minecraft.popGuiLayer();
}));
sfpWidget.setLayout(128, height - 30 , 15, height - 15, 15);
sfpWidget.setCallBack((entry)-> {
LOGGER.info("Selected {}", entry.getId());
});
if (!initialized)
{
sfpWidget.init();
initialized = true;
}
titleTextWidget = new TextFieldWidget(font, sfpWidget.getRight() + 10, height / 2, (width - sfpWidget.getRight()) - 20, font.lineHeight + 4, new StringTextComponent("Title"));
musicTextWidget = new TextFieldWidget(font, sfpWidget.getRight() + 10, (height / 2) + 20, (width - sfpWidget.getRight()) - 20, font.lineHeight + 4, new StringTextComponent("MML"));
musicTextWidget.setMaxLength(10000);
addWidget(sfpWidget);
addWidget(titleTextWidget);
addWidget(musicTextWidget);
}
public void onButtonOpen()
{
Objects.requireNonNull(minecraft).setScreen(new GuiMultiInstChooser(this));
}
@Override
public void render(MatrixStack matrixStack, int pMouseX, int pMouseY, float pPartialTicks)
{
this.renderBackground(matrixStack);
labelTitle.render(matrixStack, pMouseX, pMouseY, pPartialTicks);
this.sfpWidget.render(matrixStack, pMouseX, pMouseY, pPartialTicks);
this.titleTextWidget.render(matrixStack, pMouseX, pMouseY, pPartialTicks);
this.musicTextWidget.render(matrixStack, pMouseX, pMouseY, pPartialTicks);
super.render(matrixStack, pMouseX, pMouseY, pPartialTicks);
// Render the Instrument GUI image
int relX = ((width - sfpWidget.getRight()) / 5) + sfpWidget.getRight();
int relY = height/5;
ItemStack itemStack = sfpWidget.getSelected() != null ? INSTRUMENT_ITEMS.get(sfpWidget.getSelected().getIndex()).get().getDefaultInstance() : Items.CREEPER_HEAD.getDefaultInstance();
ModGuiHelper.RenderGuiItemScaled(Objects.requireNonNull(minecraft).getItemRenderer(), itemStack, relX, relY, 3, true);
}
@Override
public boolean keyPressed(int p_keyPressed_1_, int p_keyPressed_2_, int p_keyPressed_3_)
{
return super.keyPressed(p_keyPressed_1_, p_keyPressed_2_, p_keyPressed_3_);
}
@Override
public boolean shouldCloseOnEsc()
{
return false;
}
// Call on ESC key force close! Ignores chained GUI's?
// Override "shouldCloseOnEsc and return false" to prevent closing on ESC.
@Override
public void removed()
{
Objects.requireNonNull(this.minecraft).keyboardHandler.setSendRepeatsToGui(false);
super.removed();
}
// Called on ESC key and minecraft.displayGuiScreen(this.lastScreen);
@Override
public void onClose()
{
super.onClose();
}
@Override
public boolean isPauseScreen()
{
return false;
}
}
|
package org.apdplat.jsearch.search;
/**
*
* @author
*/
public interface Searcher {
Hits search(String keyword);
Hits search(String keyword, SearchMode searchMode);
Hits search(String keyword, int page);
Hits search(String keyword, SearchMode searchMode, int page);
}
|
package ch.eitchnet.utils.helper;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A helper class to perform different actions on {@link String}s
*
* @author Robert von Burg <eitch@eitchnet.ch>
*/
public class StringHelper {
public static final String NEW_LINE = "\n"; //$NON-NLS-1$
private static final Logger logger = LoggerFactory.getLogger(StringHelper.class);
/**
* Hex char table for fast calculating of hex value
*/
private static final byte[] HEX_CHAR_TABLE = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C',
'D', 'E', 'F' };
/**
* Converts each byte of the given byte array to a HEX value and returns the concatenation of these values
*
* @param raw
* the bytes to convert to String using numbers in hexadecimal
*
* @return the encoded string
*
* @throws RuntimeException
*/
public static String getHexString(byte[] raw) throws RuntimeException {
try {
byte[] hex = new byte[2 * raw.length];
int index = 0;
for (byte b : raw) {
int v = b & 0xFF;
hex[index++] = StringHelper.HEX_CHAR_TABLE[v >>> 4];
hex[index++] = StringHelper.HEX_CHAR_TABLE[v & 0xF];
}
return new String(hex, "ASCII");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Something went wrong while converting to HEX: " + e.getLocalizedMessage(), e);
}
}
/**
* Returns a byte array of a given string by converting each character of the string to a number base 16
*
* @param encoded
* the string to convert to a byt string
*
* @return the encoded byte stream
*/
public static byte[] fromHexString(String encoded) {
if ((encoded.length() % 2) != 0)
throw new IllegalArgumentException("Input string must contain an even number of characters.");
final byte result[] = new byte[encoded.length() / 2];
final char enc[] = encoded.toCharArray();
for (int i = 0; i < enc.length; i += 2) {
StringBuilder curr = new StringBuilder(2);
curr.append(enc[i]).append(enc[i + 1]);
result[i / 2] = (byte) Integer.parseInt(curr.toString(), 16);
}
return result;
}
/**
* Generates the MD5 Hash of a string and converts it to a HEX string
*
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static String hashMd5AsHex(String string) {
return getHexString(StringHelper.hashMd5(string.getBytes()));
}
/**
* Generates the MD5 Hash of a string. Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a
* Hex String which is printable
*
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hashMd5(String string) {
return StringHelper.hashMd5(string.getBytes());
}
/**
* Generates the MD5 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array to
* a Hex String which is printable
*
* @param bytes
* the bytes to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hashMd5(byte[] bytes) {
return StringHelper.hash("MD5", bytes);
}
/**
* Generates the SHA1 Hash of a string and converts it to a HEX String
*
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static String hashSha1AsHex(String string) {
return getHexString(StringHelper.hashSha1(string.getBytes()));
}
/**
* Generates the SHA1 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to a
* Hex String which is printable
*
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hashSha1(String string) {
return StringHelper.hashSha1(string.getBytes());
}
/**
* Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array
* to a Hex String which is printable
*
* @param bytes
* the bytes to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hashSha1(byte[] bytes) {
return StringHelper.hash("SHA-1", bytes);
}
/**
* Generates the SHA-256 Hash of a string and converts it to a HEX String
*
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static String hashSha256AsHex(String string) {
return getHexString(StringHelper.hashSha256(string.getBytes()));
}
/**
* Generates the SHA-256 Hash of a string Use {@link StringHelper#getHexString(byte[])} to convert the byte array to
* a Hex String which is printable
*
* @param string
* the string to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hashSha256(String string) {
return StringHelper.hashSha256(string.getBytes());
}
/**
* Generates the SHA1 Hash of a byte array Use {@link StringHelper#getHexString(byte[])} to convert the byte array
* to a Hex String which is printable
*
* @param bytes
* the bytes to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hashSha256(byte[] bytes) {
return StringHelper.hash("SHA-256", bytes);
}
/**
* Returns the hash of an algorithm
*
* @param algorithm
* the algorithm to use
* @param bytes
* the bytes to hash
*
* @return the hash or null, if an exception was thrown
*/
public static byte[] hash(String algorithm, byte[] bytes) {
try {
MessageDigest digest = MessageDigest.getInstance(algorithm);
byte[] hashArray = digest.digest(bytes);
return hashArray;
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Algorithm " + algorithm + " does not exist!", e);
}
}
/**
* Normalizes the length of a String. Does not shorten it when it is too long, but lengthens it, depending on the
* options set: adding the char at the beginning or appending it at the end
*
* @param value
* string to normalize
* @param length
* length string must have
* @param beginning
* add at beginning of value
* @param c
* char to append when appending
* @return the new string
*/
public static String normalizeLength(String value, int length, boolean beginning, char c) {
return StringHelper.normalizeLength(value, length, beginning, false, c);
}
/**
* Normalizes the length of a String. Shortens it when it is too long, giving out a logger warning, or lengthens it,
* depending on the options set: appending the char at the beginning or the end
*
* @param value
* string to normalize
* @param length
* length string must have
* @param beginning
* append at beginning of value
* @param shorten
* allow shortening of value
* @param c
* char to append when appending
* @return the new string
*/
public static String normalizeLength(String value, int length, boolean beginning, boolean shorten, char c) {
if (value.length() == length)
return value;
if (value.length() < length) {
String tmp = value;
while (tmp.length() != length) {
if (beginning) {
tmp = c + tmp;
} else {
tmp = tmp + c;
}
}
return tmp;
} else if (shorten) {
StringHelper.logger.warn("Shortening length of value: " + value);
StringHelper.logger.warn("Length is: " + value.length() + " max: " + length);
return value.substring(0, length);
}
return value;
}
/**
* Calls {@link #replacePropertiesIn(Properties, String)}, with {@link System#getProperties()} as input
*
* @return a new string with all defined system properties replaced or if an error occurred the original value is
* returned
*/
public static String replaceSystemPropertiesIn(String value) {
return StringHelper.replacePropertiesIn(System.getProperties(), value);
}
/**
* Traverses the given string searching for occurrences of ${...} sequences. Theses sequences are replaced with a
* {@link Properties#getProperty(String)} value if such a value exists in the properties map. If the value of the
* sequence is not in the properties, then the sequence is not replaced
*
* @param properties
* the {@link Properties} in which to get the value
* @param value
* the value in which to replace any system properties
*
* @return a new string with all defined properties replaced or if an error occurred the original value is returned
*/
public static String replacePropertiesIn(Properties properties, String alue) {
// get a copy of the value
String tmpValue = alue;
// get first occurrence of $ character
int pos = -1;
int stop = 0;
// loop on $ character positions
while ((pos = tmpValue.indexOf('$', pos + 1)) != -1) {
// if pos+1 is not { character then continue
if (tmpValue.charAt(pos + 1) != '{') {
continue;
}
// find end of sequence with } character
stop = tmpValue.indexOf('}', pos + 1);
// if no stop found, then break as another sequence should be able to start
if (stop == -1) {
StringHelper.logger.error("Sequence starts at offset " + pos + " but does not end!");
tmpValue = alue;
break;
}
// get sequence enclosed by pos and stop
String sequence = tmpValue.substring(pos + 2, stop);
// make sure sequence doesn't contain $ { } characters
if (sequence.contains("$") || sequence.contains("{") || sequence.contains("}")) {
StringHelper.logger.error("Enclosed sequence in offsets " + pos + " - " + stop
+ " contains one of the illegal chars: $ { }: " + sequence);
tmpValue = alue;
break;
}
// sequence is good, so see if we have a property for it
String property = properties.getProperty(sequence, "");
// if no property exists, then log and continue
if (property.isEmpty()) {
// logger.warn("No system property found for sequence " + sequence);
continue;
}
// property exists, so replace in value
tmpValue = tmpValue.replace("${" + sequence + "}", property);
}
return tmpValue;
}
/**
* Calls {@link #replaceProperties(Properties, Properties)} with null as the second argument. This allows for
* replacing all properties with itself
*
* @param properties
* the properties in which the values must have any ${...} replaced by values of the respective key
*/
public static void replaceProperties(Properties properties) {
StringHelper.replaceProperties(properties, null);
}
/**
* Checks every value in the {@link Properties} and then then replaces any ${...} variables with keys in this
* {@link Properties} value using {@link StringHelper#replacePropertiesIn(Properties, String)}
*
* @param properties
* the properties in which the values must have any ${...} replaced by values of the respective key
* @param altProperties
* if properties does not contain the ${...} key, then try these alternative properties
*/
public static void replaceProperties(Properties properties, Properties altProperties) {
for (Object keyObj : properties.keySet()) {
String key = (String) keyObj;
String property = properties.getProperty(key);
String newProperty = StringHelper.replacePropertiesIn(properties, property);
// try first properties
if (!property.equals(newProperty)) {
// logger.info("Key " + key + " has replaced property " + property + " with new value " + newProperty);
properties.put(key, newProperty);
} else if (altProperties != null) {
// try alternative properties
newProperty = StringHelper.replacePropertiesIn(altProperties, property);
if (!property.equals(newProperty)) {
// logger.info("Key " + key + " has replaced property " + property + " from alternative properties with new value " + newProperty);
properties.put(key, newProperty);
}
}
}
}
/**
* This is a helper method with which it is possible to print the location in the two given strings where they start
* to differ. The length of string returned is currently 40 characters, or less if either of the given strings are
* shorter. The format of the string is 3 lines. The first line has information about where in the strings the
* difference occurs, and the second and third lines contain contexts
*
* @param s1
* the first string
* @param s2
* the second string
*
* @return the string from which the strings differ with a length of 40 characters within the original strings
*/
public static String printUnequalContext(String s1, String s2) {
byte[] bytes1 = s1.getBytes();
byte[] bytes2 = s2.getBytes();
int i = 0;
for (; i < bytes1.length; i++) {
if (i > bytes2.length)
break;
if (bytes1[i] != bytes2[i])
break;
}
int maxContext = 40;
int start = Math.max(0, (i - maxContext));
int end = Math.min(i + maxContext, (Math.min(bytes1.length, bytes2.length)));
StringBuilder sb = new StringBuilder();
sb.append("Strings are not equal! Start of inequality is at " + i + ". Showing " + maxContext
+ " extra characters and start and end:\n");
sb.append("context s1: " + s1.substring(start, end) + "\n");
sb.append("context s2: " + s2.substring(start, end) + "\n");
return sb.toString();
}
/**
* Formats the given number of milliseconds to a time like 0.000s/ms
*
* @param millis
* the number of milliseconds
*
* @return format the given number of milliseconds to a time like 0.000s/ms
*/
public static String formatMillisecondsDuration(final long millis) {
if (millis > 1000) {
return String.format("%.3fs", (((double) millis) / 1000)); //$NON-NLS-1$
}
return millis + "ms"; //$NON-NLS-1$
}
/**
* Formats the given number of nanoseconds to a time like 0.000s/ms/us/ns
*
* @param nanos
* the number of nanoseconds
*
* @return format the given number of nanoseconds to a time like 0.000s/ms/us/ns
*/
public static String formatNanoDuration(final long nanos) {
if (nanos > 1000000000) {
return String.format("%.3fs", (((double) nanos) / 1000000000)); //$NON-NLS-1$
} else if (nanos > 1000000) {
return String.format("%.3fms", (((double) nanos) / 1000000)); //$NON-NLS-1$
} else if (nanos > 1000) {
return String.format("%.3fus", (((double) nanos) / 1000)); //$NON-NLS-1$
} else {
return nanos + "ns"; //$NON-NLS-1$
}
}
/**
* Simply returns true if the value is null, or empty
*
* @param value
* the value to check
*
* @return true if the value is null, or empty
*/
public static boolean isEmpty(String value) {
return value == null || value.isEmpty();
}
/**
* <p>
* Parses the given string value to a boolean. This extends the default {@link Boolean#parseBoolean(String)} as it
* throws an exception if the string value is not equal to "true" or "false" being case insensitive.
* </p>
*
* <p>
* This additional restriction is important where false should really be caught, not any random vaue for false
* </p>
*
* @param value
* the value to check
*
* @return true or false, depending on the string value
*
* @throws RuntimeException
* if the value is empty, or not equal to the case insensitive value "true" or "false"
*/
public static boolean parseBoolean(String value) throws RuntimeException {
if (isEmpty(value))
throw new RuntimeException("Value to parse to boolean is empty! Expected case insensitive true or false");
String tmp = value.toLowerCase();
if (tmp.equals(Boolean.TRUE.toString())) {
return true;
} else if (tmp.equals(Boolean.FALSE.toString())) {
return false;
} else {
throw new RuntimeException("Value " + value
+ " can not be parsed to boolean! Expected case insensitive true or false");
}
}
}
|
package org.c4sg.controller;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.c4sg.dto.SkillDTO;
import org.c4sg.dto.SkillUserCountDTO;
import org.c4sg.exception.BadRequestException;
import org.c4sg.exception.NotFoundException;
import org.c4sg.exception.SkillException;
import org.c4sg.service.SkillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/api/skills")
@Api(description = "Operations about Skills", tags = "skill")
public class SkillController {
@Autowired
private SkillService skillService;
@CrossOrigin
@RequestMapping(produces = {"application/json"}, method = RequestMethod.GET)
@ApiOperation(value = "Get all skills", notes = "Returns a collection of skills (alphabetical)")
public List<SkillDTO> getSkills() {
return skillService.findSkills();
}
@CrossOrigin
@RequestMapping(value="/userCount",produces = {"application/json"}, method = RequestMethod.GET)
@ApiOperation(value = "Get skills grouped by user count", notes = "Returns a collection of skills with user count")
public List<SkillUserCountDTO> getSkillsWithUserCount() {
return skillService.findSkillsWithUserCount();
}
@CrossOrigin
@RequestMapping(value="/user",produces = {"application/json"}, method = RequestMethod.GET)
@ApiOperation(value = "Get skills for an user by id", notes = "Returns a collection of skills for an user by id")
public List<String> getSkillsForUser(@ApiParam(value = "ID of user to return", required = true)
@RequestParam Integer id) {
return skillService.findSkillsForUser(id);
}
@CrossOrigin
@RequestMapping(value="/project",produces = {"application/json"}, method = RequestMethod.GET)
@ApiOperation(value = "Get skills for a project by id", notes = "Returns a collection of skills for a project")
public List<String> getSkillsForProject(@ApiParam(value = "ID of project to return", required = true)
@RequestParam Integer id) {
return skillService.findSkillsForProject(id);
}
@CrossOrigin
@RequestMapping(value="/user/addSkills", method = RequestMethod.POST)
@ApiOperation(value = "Add skills for a user", notes = "Adds skills for the user with display order")
public void createSkillsForUser(@ApiParam(value = "ID of user to add skills",name="id", required = true)
@RequestParam Integer id,
@ApiParam(value = "Skills in display order",name="skillsList", required = true)
@RequestParam List<String> skillsList) {
try {
skillService.saveSkillsForUser(id,skillsList);
} catch (NullPointerException e) {
throw new NotFoundException(e.getMessage());
} catch (SkillException e) {
throw new BadRequestException(e.getMessage());
}
}
@CrossOrigin
@RequestMapping(value="/project/addSkills", method = RequestMethod.POST)
@ApiOperation(value = "Add skills for a project", notes = "Adds skills for the project with display order")
public void createSkillsForProject(@ApiParam(value = "ID of project to add skills", required = true)
@RequestParam Integer id,
@ApiParam(value = "Skills in display order", required = true)
@RequestParam List<String> skillsList) {
try {
skillService.saveSkillsForProject(id,skillsList);
} catch (NullPointerException e) {
throw new NotFoundException(e.getMessage());
} catch (SkillException e) {
throw new BadRequestException(e.getMessage());
}
}
}
|
package ch.openech.transaction;
import java.util.List;
import org.minimalj.backend.Backend;
import org.minimalj.transaction.criteria.Criteria;
import org.minimalj.util.StringUtils;
import ch.openech.model.common.NamedId;
import ch.openech.model.organisation.Organisation;
import ch.openech.model.organisation.OrganisationIdentification;
import ch.openech.model.person.Person;
import ch.openech.model.person.PersonIdentification;
public class EchPersistence {
public static Person getByIdentification(Backend backend, PersonIdentification personIdentification) {
if (NamedId.OPEN_ECH_ID_CATEGORY.equals(personIdentification.technicalIds.localId.personIdCategory)) {
long id = Long.valueOf(personIdentification.technicalIds.localId.personId);
return backend.read(Person.class, id);
}
if (personIdentification.vn != null) {
List<Person> persons = backend.read(Person.class, Criteria.search(personIdentification.vn.value, Person.SEARCH_BY_VN) , 1);
if (!persons.isEmpty()) return persons.get(0);
}
List<PersonIdentification> persons = backend.read(PersonIdentification.class, Criteria.search(personIdentification.officialName), 500);
for (PersonIdentification p : persons) {
if (StringUtils.equals(p.firstName, personIdentification.firstName)) {
if (StringUtils.equals(p.officialName, personIdentification.officialName)) {
return backend.read(Person.class, p.id);
}
}
}
return null;
}
public static Organisation getByIdentification(Backend backend, OrganisationIdentification organisationIdentification) {
if (NamedId.OPEN_ECH_ID_CATEGORY.equals(organisationIdentification.technicalIds.localId.personIdCategory)) {
long id = Long.valueOf(organisationIdentification.technicalIds.localId.personId);
return backend.read(Organisation.class, id);
}
List<Organisation> organisations = backend.read(Organisation.class, Criteria.equals(Organisation.$.uid.value, organisationIdentification.uid.value), 2);
if (organisations.isEmpty()) {
organisations = backend.read(Organisation.class, Criteria.equals(Organisation.$.organisationName, organisationIdentification.organisationName), 2);
}
if (!organisations.isEmpty()) {
return organisations.get(0);
} else {
return null;
}
}
}
|
package org.dynmap.regions;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.bukkit.World;
import org.dynmap.ClientComponent;
import org.dynmap.ClientUpdateEvent;
import org.dynmap.ConfigurationNode;
import org.dynmap.DynmapPlugin;
import org.dynmap.Event;
import org.dynmap.Log;
import org.dynmap.web.Json;
public class RegionsComponent extends ClientComponent {
public RegionsComponent(final DynmapPlugin plugin, final ConfigurationNode configuration) {
super(plugin, configuration);
// For internal webserver.
String fname = configuration.getString("filename", "regions.yml");
plugin.webServer.handlers.put("/standalone/" + fname.substring(0, fname.lastIndexOf('.')) + "_*", new RegionHandler(configuration));
// For external webserver.
//Parse region file for multi world style
if (configuration.getBoolean("useworldpath", false)) {
plugin.events.addListener("clientupdatewritten", new Event.Listener<ClientUpdateEvent>() {
@Override
public void triggered(ClientUpdateEvent t) {
World world = t.world.world;
parseRegionFile(world.getName() + "/" + configuration.getString("filename", "regions.yml"), configuration.getString("filename", "regions.yml").replace(".", "_" + world.getName() + ".yml"));
}
});
} else {
plugin.events.addListener("clientupdateswritten", new Event.Listener<Object>() {
@Override
public void triggered(Object t) {
parseRegionFile(configuration.getString("filename", "regions.yml"), configuration.getString("filename", "regions.yml"));
}
});
}
}
//handles parsing and writing region json files
private void parseRegionFile(String regionFile, String outputFileName)
{
File outputFile;
org.bukkit.util.config.Configuration regionConfig = null;
if(configuration.getBoolean("useworldpath", false))
{
if(new File("plugins/"+configuration.getString("name", "WorldGuard"), regionFile).exists())
regionConfig = new org.bukkit.util.config.Configuration(new File("plugins/"+configuration.getString("name", "WorldGuard"), regionFile));
else if(new File("plugins/"+configuration.getString("name", "WorldGuard")+"/worlds", regionFile).exists())
regionConfig = new org.bukkit.util.config.Configuration(new File("plugins/"+configuration.getString("name", "WorldGuard")+"/worlds", regionFile));
}
else
regionConfig = new org.bukkit.util.config.Configuration(new File("plugins/"+configuration.getString("name", "WorldGuard"), regionFile));
//File didn't exist
if(regionConfig == null)
return;
regionConfig.load();
outputFileName = outputFileName.substring(0, outputFileName.lastIndexOf("."))+".json";
File webWorldPath = new File(plugin.getWebPath()+"/standalone/", outputFileName);
Map<?, ?> regionData = (Map<?, ?>) regionConfig.getProperty(configuration.getString("basenode", "regions"));
/* See if we have explicit list of regions to report - limit to this list if we do */
List<String> idlist = configuration.getStrings("visibleregions", null);
if(idlist != null) {
@SuppressWarnings("unchecked")
HashSet<String> ids = new HashSet<String>((Collection<? extends String>) regionData.keySet());
for(String id : ids) {
/* If not in list, remove it */
if(!idlist.contains(id)) {
regionData.remove(id);
}
}
}
if (webWorldPath.isAbsolute())
outputFile = webWorldPath;
else {
outputFile = new File(plugin.getDataFolder(), webWorldPath.toString());
}
try {
FileOutputStream fos = new FileOutputStream(outputFile);
fos.write(Json.stringifyJson(regionData).getBytes());
fos.close();
} catch (FileNotFoundException ex) {
Log.severe("Exception while writing JSON-file.", ex);
} catch (IOException ioe) {
Log.severe("Exception while writing JSON-file.", ioe);
}
}
}
|
package org.egordorichev.lasttry.mod;
import org.egordorichev.lasttry.entity.*;
import org.egordorichev.lasttry.*;
import org.egordorichev.lasttry.util.Callable;
import org.egordorichev.lasttry.world.World;
import org.newdawn.slick.Input;
import org.newdawn.slick.KeyListener;
public class ModAPI { // TODO: add more
public static Player getPlayer() {
return LastTry.player;
}
public static World getWorld() {
return LastTry.world;
}
public static Enemy createEnemy(int id) {
return Enemy.create(id);
}
public static Enemy spawnEnemy(int id, int x, int y) {
return LastTry.world.spawnEnemy(id, x, y);
}
// TODO: add methods for creating new enemies
public static void addKeyBinding(int key, Callable callable) {
LastTry.input.addKeyListener(new KeyListener() {
@Override
public void keyPressed(int i, char c) {
if(i == key) {
callable.call();
}
}
@Override
public void keyReleased(int i, char c) {
}
@Override
public void setInput(Input input) {
}
@Override
public boolean isAcceptingInput() {
return true;
}
@Override
public void inputEnded() {
}
@Override
public void inputStarted() {
}
});
}
}
|
package com.alibaba.excel.read;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.ParserConfigurationException;
import com.alibaba.excel.read.v07.RowHandler;
import com.alibaba.excel.read.v07.XmlParserFactory;
import com.alibaba.excel.read.v07.XMLTempFile;
import com.alibaba.excel.read.context.AnalysisContext;
import com.alibaba.excel.read.exception.ExcelAnalysisException;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.util.FileUtil;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.xmlbeans.XmlException;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbook;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTWorkbookPr;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.WorkbookDocument;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @author jipengfei
*/
public class SaxAnalyserV07 extends BaseSaxAnalyser {
private SharedStringsTable sharedStringsTable;
private List<String> sharedStringList = new LinkedList<String>();
private List<SheetSource> sheetSourceList = new ArrayList<SheetSource>();
private boolean use1904WindowDate = false;
private final String path;
private File tmpFile;
private String workBookXMLFilePath;
private String sharedStringXMLFilePath;
public SaxAnalyserV07(AnalysisContext analysisContext) throws Exception {
this.analysisContext = analysisContext;
this.path = XMLTempFile.createPath();
this.tmpFile = new File(XMLTempFile.getTmpFilePath(path));
this.workBookXMLFilePath = XMLTempFile.getWorkBookFilePath(path);
this.sharedStringXMLFilePath = XMLTempFile.getSharedStringFilePath(path);
start();
}
@Override
protected void execute() {
try {
Sheet sheet = analysisContext.getCurrentSheet();
if (!isAnalysisAllSheets(sheet)) {
if (this.sheetSourceList.size() < sheet.getSheetNo() || sheet.getSheetNo() == 0) {
return;
}
InputStream sheetInputStream = this.sheetSourceList.get(sheet.getSheetNo() - 1).getInputStream();
parseXmlSource(sheetInputStream);
return;
}
int i = 0;
for (SheetSource sheetSource : this.sheetSourceList) {
i++;
this.analysisContext.setCurrentSheet(new Sheet(i));
parseXmlSource(sheetSource.getInputStream());
}
} catch (Exception e) {
stop();
throw new ExcelAnalysisException(e);
} finally {
}
}
private boolean isAnalysisAllSheets(Sheet sheet) {
if (sheet == null) {
return true;
}
if (sheet.getSheetNo() < 0) {
return true;
}
return false;
}
public void stop() {
for (SheetSource sheet : sheetSourceList) {
if (sheet.getInputStream() != null) {
try {
sheet.getInputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileUtil.deletefile(path);
}
private void parseXmlSource(InputStream inputStream) {
try {
ContentHandler handler = new RowHandler(this, this.sharedStringsTable, this.analysisContext,
sharedStringList);
XmlParserFactory.parse(inputStream, handler);
inputStream.close();
} catch (Exception e) {
try {
inputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
throw new ExcelAnalysisException(e);
}
}
public List<Sheet> getSheets() {
List<Sheet> sheets = new ArrayList<Sheet>();
try {
int i = 1;
for (SheetSource sheetSource : this.sheetSourceList) {
Sheet sheet = new Sheet(i, 0);
sheet.setSheetName(sheetSource.getSheetName());
i++;
sheets.add(sheet);
}
} catch (Exception e) {
stop();
throw new ExcelAnalysisException(e);
} finally {
}
return sheets;
}
private void start() throws IOException, XmlException, ParserConfigurationException, SAXException {
createTmpFile();
unZipTempFile();
initSharedStringsTable();
initUse1904WindowDate();
initSheetSourceList();
}
private void createTmpFile() throws FileNotFoundException {
FileUtil.writeFile(tmpFile, analysisContext.getInputStream());
}
private void unZipTempFile() throws IOException {
FileUtil.doUnZip(path, tmpFile);
}
private void initSheetSourceList() throws IOException, ParserConfigurationException, SAXException {
this.sheetSourceList = new ArrayList<SheetSource>();
InputStream workbookXml = new FileInputStream(this.workBookXMLFilePath);
XmlParserFactory.parse(workbookXml, new DefaultHandler() {
private int id = 0;
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (qName.toLowerCase(Locale.US).equals("sheet")) {
String name = null;
id++;
for (int i = 0; i < attrs.getLength(); i++) {
if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("name")) {
name = attrs.getValue(i);
} else if (attrs.getLocalName(i).toLowerCase(Locale.US).equals("r:id")) {
//id = Integer.parseInt(attrs.getValue(i).replaceAll("rId", ""));
try {
InputStream inputStream = new FileInputStream(XMLTempFile.getSheetFilePath(path, id));
sheetSourceList.add(new SheetSource(id, name, inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
});
workbookXml.close();
Collections.sort(sheetSourceList);
}
private void initUse1904WindowDate() throws IOException, XmlException {
InputStream workbookXml = new FileInputStream(workBookXMLFilePath);
WorkbookDocument ctWorkbook = WorkbookDocument.Factory.parse(workbookXml);
CTWorkbook wb = ctWorkbook.getWorkbook();
CTWorkbookPr prefix = wb.getWorkbookPr();
if (prefix != null) {
this.use1904WindowDate = prefix.getDate1904();
}
this.analysisContext.setUse1904WindowDate(use1904WindowDate);
workbookXml.close();
}
private void initSharedStringsTable() throws IOException, ParserConfigurationException, SAXException {
InputStream inputStream = new FileInputStream(this.sharedStringXMLFilePath);
//this.sharedStringsTable = new SharedStringsTable();
//this.sharedStringsTable.readFrom(inputStream);
XmlParserFactory.parse(inputStream, new DefaultHandler() {
//int lastElementPosition = -1;
//int lastHandledElementPosition = -1;
String beforeQName = "";
String currentQName = "";
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
//if (hasSkippedEmptySharedString()) {
// sharedStringList.add("");
//if ("t".equals(qName)) {
// lastElementPosition++;
if ("si".equals(qName) || "t".equals(qName)) {
beforeQName = currentQName;
currentQName = qName;
}
}
//@Override
//public void endElement (String uri, String localName, String qName)
// throws SAXException
// if ("si".equals(qName) || "t".equals(qName)) {
// beforeQName = qName;
// currentQName = "";
//private boolean hasSkippedEmptySharedString() {
// return lastElementPosition > lastHandledElementPosition;
@Override
public void characters(char[] ch, int start, int length) {
if ("t".equals(currentQName) && ("t".equals(beforeQName))) {
String pre = sharedStringList.get(sharedStringList.size() - 1);
String str = pre + new String(ch, start, length);
sharedStringList.remove(sharedStringList.size() - 1);
sharedStringList.add(str);
}else if ("t".equals(currentQName) && ("si".equals(beforeQName))){
sharedStringList.add(new String(ch, start, length));
}
// lastHandledElementPosition++;
}
});
inputStream.close();
}
private class SheetSource implements Comparable<SheetSource> {
private int id;
private String sheetName;
private InputStream inputStream;
public SheetSource(int id, String sheetName, InputStream inputStream) {
this.id = id;
this.sheetName = sheetName;
this.inputStream = inputStream;
}
public String getSheetName() {
return sheetName;
}
public void setSheetName(String sheetName) {
this.sheetName = sheetName;
}
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int compareTo(SheetSource o) {
if (o.id == this.id) {
return 0;
} else if (o.id > this.id) {
return -1;
} else {
return 1;
}
}
}
}
|
package org.goldenorb.zookeeper;
import java.util.Collection;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.goldenorb.conf.OrbConfigurable;
import org.goldenorb.conf.OrbConfiguration;
import org.goldenorb.event.LeadershipChangeEvent;
import org.goldenorb.event.LostMemberEvent;
import org.goldenorb.event.NewMemberEvent;
import org.goldenorb.event.OrbCallback;
import org.goldenorb.event.OrbEvent;
import org.goldenorb.event.OrbExceptionEvent;
public class LeaderGroup<MEMBER_TYPE extends Member> implements OrbConfigurable {
private OrbConfiguration orbConf;
private OrbCallback orbCallback;
private String basePath;
private String myPath;
private MEMBER_TYPE member;
private Class<? extends Member> memberClass;
private ZooKeeper zk;
private boolean processWatchedEvents = true;
private SortedMap<String,MEMBER_TYPE> members = new TreeMap<String,MEMBER_TYPE>();
private boolean fireEvents = false;
public LeaderGroup(ZooKeeper zk,
OrbCallback orbCallback,
String path,
MEMBER_TYPE member,
Class<? extends Member> memberClass) {
this.memberClass = memberClass;
this.orbCallback = orbCallback;
this.basePath = path;
this.member = member;
this.zk = zk;
init();
}
public void init() {
try {
ZookeeperUtils.notExistCreateNode(zk, basePath);
myPath = ZookeeperUtils.tryToCreateNode(zk, basePath + "/member", member,
CreateMode.EPHEMERAL_SEQUENTIAL);
members.put(myPath, member);
updateMembers();
fireEvents = true;
} catch (OrbZKFailure e) {
fireEvent(new OrbExceptionEvent(e));
}
}
@SuppressWarnings("unchecked")
public void updateMembers() throws OrbZKFailure {
synchronized (members) {
int numOfMembers = getNumOfMembers();
MEMBER_TYPE leaderMember;
if (numOfMembers != 0) {
leaderMember = getLeader();
} else {
leaderMember = null;
}
List<String> memberList;
try {
memberList = zk.getChildren(basePath, new WatchMembers());
} catch (KeeperException e) {
e.printStackTrace();
throw new OrbZKFailure(e);
} catch (InterruptedException e) {
e.printStackTrace();
throw new OrbZKFailure(e);
}
members.clear();
for (String memberPath : memberList) {
MEMBER_TYPE memberW = (MEMBER_TYPE) ZookeeperUtils.getNodeWritable(zk, basePath + "/" + memberPath,
memberClass, orbConf);
if (memberW != null) {
members.put(memberPath, memberW);
}
}
if (numOfMembers > getNumOfMembers()) {
fireEvent(new LostMemberEvent());
} else if (numOfMembers < getNumOfMembers()) {
fireEvent(new NewMemberEvent());
}
if (numOfMembers != 0 && getNumOfMembers() != 0) {
if (!leaderMember.equals(getLeader())) {
fireEvent(new LeadershipChangeEvent());
}
}
}
}
public class WatchMembers implements Watcher {
public void process(WatchedEvent event) {
if (LeaderGroup.this.isProcessWatchedEvents()) {
try {
updateMembers();
} catch (OrbZKFailure e) {
fireEvent(new OrbExceptionEvent(e));
}
}
}
}
public Collection<MEMBER_TYPE> getMembers() {
synchronized (members) {
return members.values();
}
}
public int getNumOfMembers() {
synchronized (members) {
return members.size();
}
}
public boolean isLeader() {
synchronized (members) {
return member.equals(members.get(members.firstKey()));
}
}
public MEMBER_TYPE getLeader() {
synchronized (members) {
return members.get(members.firstKey());
}
}
public void fireEvent(OrbEvent e) {
if (fireEvents) {
orbCallback.process(e);
}
}
public void setOrbConf(OrbConfiguration orbConf) {
this.orbConf = orbConf;
}
public OrbConfiguration getOrbConf() {
return orbConf;
}
public void leave() {
this.processWatchedEvents = false;
try {
ZookeeperUtils.deleteNodeIfEmpty(zk, myPath);
} catch (OrbZKFailure e) {
fireEvent(new OrbExceptionEvent(e));
}
}
protected boolean isProcessWatchedEvents() {
return processWatchedEvents;
}
protected void setProcessWatchedEvents(boolean processWatchedEvents) {
this.processWatchedEvents = processWatchedEvents;
}
}
|
package gw.lang.parser;
import gw.config.BaseService;
import gw.config.CommonServices;
import gw.lang.GosuShop;
import gw.lang.IDimension;
import gw.lang.parser.coercers.*;
import gw.lang.parser.exceptions.ParseException;
import gw.lang.parser.resources.Res;
import gw.lang.reflect.*;
import gw.lang.reflect.features.FeatureReference;
import gw.lang.reflect.gs.IGosuArrayClass;
import gw.lang.reflect.gs.IGosuArrayClassInstance;
import gw.lang.reflect.gs.IGosuClass;
import gw.lang.reflect.gs.IGosuEnhancement;
import gw.lang.reflect.gs.IGosuObject;
import gw.lang.reflect.java.GosuTypes;
import gw.lang.reflect.java.IJavaArrayType;
import gw.lang.reflect.java.IJavaType;
import gw.lang.reflect.java.JavaTypes;
import gw.util.GosuExceptionUtil;
import gw.util.Pair;
import gw.util.concurrent.Cache;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class StandardCoercionManager extends BaseService implements ICoercionManager
{
private static final DecimalFormat BIG_DECIMAL_FORMAT = new DecimalFormat();
static {
BIG_DECIMAL_FORMAT.setParseBigDecimal( true );
}
public static final Object NO_DICE = new Object();
// LRUish cache of coercers
public final TypeSystemAwareCache<Pair<IType, IType>, ICoercer> _coercerCache =
TypeSystemAwareCache.make( "Coercer Cache", 1000,
new Cache.MissHandler<Pair<IType, IType>, ICoercer>()
{
public final ICoercer load( Pair<IType, IType> key )
{
ICoercer coercer = findCoercerImpl( key.getFirst(), key.getSecond(), false );
if( coercer == null )
{
return NullSentinalCoercer.instance();
}
else
{
return coercer;
}
}
} )/*.logEveryNSeconds( 10, new SystemOutLogger( SystemOutLogger.LoggingLevel.INFO ) )*/;
public final boolean canCoerce( IType lhsType, IType rhsType )
{
ICoercer iCoercer = findCoercer( lhsType, rhsType, false );
return iCoercer != null;
}
private Object coerce( IType intrType, IType runtimeType, Object value )
{
ICoercer coercer = findCoercer( intrType, runtimeType, true );
if( coercer != null )
{
return coercer.coerceValue( intrType, value );
}
return null;
}
private boolean hasPotentialLossOfPrecisionOrScale( IType lhsType, IType rhsType )
{
if( lhsType == JavaTypes.pBYTE() || lhsType == JavaTypes.BYTE() )
{
return rhsType != JavaTypes.pBYTE() && rhsType != JavaTypes.BYTE();
}
else if( lhsType == JavaTypes.pCHAR() || lhsType == JavaTypes.CHARACTER() )
{
return rhsType != JavaTypes.pCHAR() && rhsType != JavaTypes.CHARACTER();
}
else if( lhsType == JavaTypes.pDOUBLE() || lhsType == JavaTypes.DOUBLE() )
{
return rhsType != JavaTypes.DOUBLE() && !rhsType.isPrimitive() &&
(JavaTypes.BIG_DECIMAL().isAssignableFrom( rhsType ) || JavaTypes.BIG_INTEGER().isAssignableFrom( rhsType ));
}
else if( lhsType == JavaTypes.pFLOAT() || lhsType == JavaTypes.FLOAT() )
{
return rhsType == JavaTypes.pDOUBLE() || rhsType == JavaTypes.DOUBLE() ||
JavaTypes.BIG_DECIMAL().isAssignableFrom( rhsType ) || JavaTypes.BIG_INTEGER().isAssignableFrom( rhsType );
}
else if( lhsType == JavaTypes.pINT() || lhsType == JavaTypes.INTEGER() )
{
return rhsType != JavaTypes.pINT() && rhsType != JavaTypes.INTEGER() &&
rhsType != JavaTypes.pSHORT() && rhsType != JavaTypes.SHORT() &&
rhsType != JavaTypes.pBYTE() && rhsType != JavaTypes.BYTE() &&
rhsType != JavaTypes.pCHAR() && rhsType != JavaTypes.CHARACTER();
}
else if( lhsType == JavaTypes.pLONG() || lhsType == JavaTypes.LONG() )
{
return rhsType != JavaTypes.pLONG() && rhsType != JavaTypes.LONG() &&
rhsType != JavaTypes.pINT() && rhsType != JavaTypes.INTEGER() &&
rhsType != JavaTypes.pSHORT() && rhsType != JavaTypes.SHORT() &&
rhsType != JavaTypes.pBYTE() && rhsType != JavaTypes.BYTE() &&
rhsType != JavaTypes.pCHAR() && rhsType != JavaTypes.CHARACTER();
}
else if( lhsType == JavaTypes.pSHORT() || lhsType == JavaTypes.SHORT() )
{
return rhsType != JavaTypes.pSHORT() && rhsType != JavaTypes.SHORT() &&
rhsType != JavaTypes.pBYTE() && rhsType != JavaTypes.BYTE();
}
else if( JavaTypes.BIG_INTEGER().isAssignableFrom( lhsType ) )
{
return rhsType != JavaTypes.BIG_INTEGER() && hasPotentialLossOfPrecisionOrScale( JavaTypes.LONG(), rhsType );
}
return false;
}
public final ICoercer findCoercer( IType lhsType, IType rhsType, boolean runtime )
{
if( runtime )
{
return findCoercerImpl( lhsType, rhsType, runtime );
}
else
{
@SuppressWarnings({"unchecked"})
ICoercer iCoercer = _coercerCache.get( new Pair( lhsType, rhsType ) );
if( iCoercer == NullSentinalCoercer.instance() )
{
return null;
}
else
{
return iCoercer;
}
}
}
private ICoercer findCoercerImpl( IType lhsType, IType rhsType, boolean runtime )
{
ICoercer coercer = getCoercerInternal( lhsType, rhsType, runtime );
if( coercer != null )
{
return coercer;
}
//Look at interfaces on rhsType for coercions
IType[] interfaces = rhsType.getInterfaces();
for ( IType anInterface1 : interfaces ) {
coercer = findCoercer(lhsType, anInterface1, runtime);
if (coercer != null) {
return coercer;
}
}
//Recurse to the superclass of rhsType for coercions
if( rhsType.getSupertype() == null || isPrimitiveOrBoxed( lhsType ) )
{
return null;
}
else
{
return findCoercer( lhsType, rhsType.getSupertype(), runtime );
}
}
/**
* Returns a coercer from values of rhsType to values of lhsType if one exists.
* I tried to write a reasonable spec in the comments below that indicate exactly
* what should coerce to what.
*
* @param lhsType the type to coerce to
* @param rhsType the type to coerce from
* @param runtime true if the coercion is happening at runtime rather than compile time
* (note: This param should go away as we store the coercions on the parsed elements, rather than calling into the
* coercion manager)
*
* @return a coercer from the lhsType to the rhsType, or null if no such coercer exists or is needed
*/
protected ICoercer getCoercerInternal( IType lhsType, IType rhsType, boolean runtime )
{
// Anything can be coerced to a string
if( JavaTypes.STRING() == lhsType && !(rhsType instanceof IErrorType) )
{
if( JavaTypes.pCHAR().equals( rhsType ) || JavaTypes.CHARACTER().equals( rhsType ) )
{
return NonWarningStringCoercer.instance();
}
else
{
return StringCoercer.instance();
}
}
// All primitives and boxed types inter-coerce, except null to true primitives
if( lhsType.isPrimitive() && rhsType.equals( JavaTypes.pVOID() ) )
{
return null;
}
if( isPrimitiveOrBoxed( lhsType ) && isPrimitiveOrBoxed( rhsType ) )
{
if( TypeSystem.isBoxedTypeFor( lhsType, rhsType ) ||
TypeSystem.isBoxedTypeFor( rhsType, lhsType ) )
{
return getHighPriorityPrimitiveOrBoxedConverter( lhsType );
}
return getPrimitiveOrBoxedConverter( lhsType );
}
// Primitives coerce to things their boxed type is assignable to
if( rhsType.isPrimitive() )
{
if( lhsType.isAssignableFrom( TypeSystem.getBoxType( rhsType ) ) )
{
return getPrimitiveOrBoxedConverter( rhsType );
}
}
// IMonitorLock supports java-style synchronization
if( !rhsType.isPrimitive() && GosuTypes.IMONITORLOCK_NAME.equals(lhsType.getName()) )
{
return IMonitorLockCoercer.instance();
}
// Class<T> <- Meta<T' instanceof JavaType>
if( (JavaTypes.CLASS().equals( lhsType.getGenericType() ) &&
(rhsType instanceof IMetaType &&
(((IMetaType)rhsType).getType() instanceof IHasJavaClass ||
((IMetaType)rhsType).getType() instanceof IMetaType && ((IMetaType)((IMetaType)rhsType).getType()).getType() instanceof IHasJavaClass))) )
{
if( !lhsType.isParameterizedType() ||
lhsType.getTypeParameters()[0].isAssignableFrom( ((IMetaType)rhsType).getType() ) ||
isStructurallyAssignable( lhsType.getTypeParameters()[0], rhsType ) ||
isStructurallyAssignable( lhsType.getTypeParameters()[0], ((IMetaType)rhsType).getType() ) ||
(((IMetaType)rhsType).getType().isPrimitive() && canCoerce( lhsType.getTypeParameters()[0], ((IMetaType)rhsType).getType() )) )
{
return MetaTypeToClassCoercer.instance();
}
}
// Numeric type unification
if( TypeSystem.isNumericType( lhsType ) && TypeSystem.isNumericType( rhsType ) )
{
// All numeric values can be down-coerced to the primitives and boxed types
if( lhsType.isPrimitive() || isBoxed( lhsType ) )
{
return getPrimitiveOrBoxedConverter( lhsType );
}
// All numeric values can be coerced to BigDecimal
if( lhsType.equals( JavaTypes.BIG_DECIMAL() ))
{
return BigDecimalCoercer.instance();
}
// All numeric values can be coerced to BigInteger
if( lhsType.equals( JavaTypes.BIG_INTEGER() ))
{
if( hasPotentialLossOfPrecisionOrScale( lhsType, rhsType ) )
{
return BigIntegerCoercer.instance();
}
else
{
return BigIntegerCoercer.instance();
}
}
}
// JavaType interface <- compatible block
if( rhsType instanceof IFunctionType && lhsType.isInterface() )
{
IFunctionType rhsFunctionType = (IFunctionType)rhsType;
IFunctionType lhsFunctionType = FunctionToInterfaceCoercer.getRepresentativeFunctionType( lhsType );
if( lhsFunctionType != null )
{
if( lhsFunctionType.isAssignableFrom( rhsFunctionType ) )
{
return FunctionToInterfaceCoercer.instance();
}
else
{
if( lhsFunctionType.areParamsCompatible( rhsFunctionType ) )
{
ICoercer coercer = findCoercer( lhsFunctionType.getReturnType(), rhsFunctionType.getReturnType(), runtime );
if( coercer != null )
{
return FunctionToInterfaceCoercer.instance();
}
}
}
}
}
// JavaType interface <- block class
if( rhsType instanceof IBlockClass && lhsType.isInterface() )
{
// Note this condition is only ever called at runtime e.g., block cast to Object cast to Interface
return FunctionToInterfaceCoercer.instance();
}
// block <- compatible block
if (lhsType instanceof IFunctionType &&
TypeSystem.get(FeatureReference.class).getParameterizedType(TypeSystem.get(Object.class), lhsType).isAssignableFrom(rhsType)) {
return FeatureReferenceToBlockCoercer.instance();
}
// Coerce synthetic block classes to function types
if( lhsType instanceof IFunctionType && rhsType instanceof IBlockClass )
{
if( lhsType.isAssignableFrom( ((IBlockClass)rhsType).getBlockType() ) )
{
return IdentityCoercer.instance();
}
}
// compatible block <- JavaType interface
if( lhsType instanceof IFunctionType && rhsType.isInterface() &&
FunctionFromInterfaceCoercer.areTypesCompatible( (IFunctionType)lhsType, rhsType ) )
{
return FunctionFromInterfaceCoercer.instance();
}
// Coerce block types that are coercable in return values and contravariant in arg types
if( lhsType instanceof IBlockType && rhsType instanceof IBlockType )
{
IBlockType lBlock = (IBlockType)lhsType;
IBlockType rBlock = (IBlockType)rhsType;
if( lBlock.areParamsCompatible( rBlock ) )
{
IType leftType = lBlock.getReturnType();
IType rightType = rBlock.getReturnType();
if( rightType != JavaTypes.pVOID() )
{
ICoercer iCoercer = findCoercer( leftType, rightType, runtime );
if( iCoercer != null && !coercionRequiresWarningIfImplicit( leftType, rightType ))
{
return BlockCoercer.instance();
}
}
}
}
return null;
}
public boolean isPrimitiveOrBoxed( IType lhsType )
{
return lhsType.isPrimitive() || isBoxed( lhsType );
}
public static boolean isBoxed( IType lhsType )
{
return lhsType == JavaTypes.BOOLEAN()
|| lhsType == JavaTypes.BYTE()
|| lhsType == JavaTypes.CHARACTER()
|| lhsType == JavaTypes.DOUBLE()
|| lhsType == JavaTypes.FLOAT()
|| lhsType == JavaTypes.INTEGER()
|| lhsType == JavaTypes.LONG()
|| lhsType == JavaTypes.SHORT();
}
protected ICoercer getPrimitiveOrBoxedConverter( IType type )
{
if( type == JavaTypes.pBOOLEAN() )
{
return BasePrimitiveCoercer.BooleanPCoercer.get();
}
else if( type == JavaTypes.BOOLEAN() )
{
return BooleanCoercer.instance();
}
else if( type == JavaTypes.pBYTE() )
{
return BasePrimitiveCoercer.BytePCoercer.get();
}
else if( type == JavaTypes.BYTE() )
{
return ByteCoercer.instance();
}
else if( type == JavaTypes.pCHAR() )
{
return BasePrimitiveCoercer.CharPCoercer.get();
}
else if( type == JavaTypes.CHARACTER() )
{
return CharCoercer.instance();
}
else if( type == JavaTypes.pDOUBLE() )
{
return BasePrimitiveCoercer.DoublePCoercer.get();
}
else if( type == JavaTypes.DOUBLE() )
{
return DoubleCoercer.instance();
}
else if( type == JavaTypes.pFLOAT() )
{
return BasePrimitiveCoercer.FloatPCoercer.get();
}
else if( type == JavaTypes.FLOAT() )
{
return FloatCoercer.instance();
}
else if( type == JavaTypes.pINT() )
{
return BasePrimitiveCoercer.IntPCoercer.get();
}
else if( type == JavaTypes.INTEGER() )
{
return IntCoercer.instance();
}
else if( type == JavaTypes.pLONG() )
{
return BasePrimitiveCoercer.LongPCoercer.get();
}
else if( type == JavaTypes.LONG() )
{
return LongCoercer.instance();
}
else if( type == JavaTypes.pSHORT() )
{
return BasePrimitiveCoercer.ShortPCoercer.get();
}
else if( type == JavaTypes.SHORT() )
{
return ShortCoercer.instance();
}
else if( type == JavaTypes.pVOID() )
{
return IdentityCoercer.instance();
}
else
{
return null;
}
}
protected ICoercer getHighPriorityPrimitiveOrBoxedConverter( IType type )
{
if( type == JavaTypes.pBOOLEAN() )
{
return BooleanPHighPriorityCoercer.instance();
}
else if( type == JavaTypes.BOOLEAN() )
{
return BooleanHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pBYTE() )
{
return BytePHighPriorityCoercer.instance();
}
else if( type == JavaTypes.BYTE() )
{
return ByteHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pCHAR() )
{
return CharPHighPriorityCoercer.instance();
}
else if( type == JavaTypes.CHARACTER() )
{
return CharHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pDOUBLE() )
{
return DoublePHighPriorityCoercer.instance();
}
else if( type == JavaTypes.DOUBLE() )
{
return DoubleHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pFLOAT() )
{
return FloatPHighPriorityCoercer.instance();
}
else if( type == JavaTypes.FLOAT() )
{
return FloatHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pINT() )
{
return IntPHighPriorityCoercer.instance();
}
else if( type == JavaTypes.INTEGER() )
{
return IntHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pLONG() )
{
return LongPHighPriorityCoercer.instance();
}
else if( type == JavaTypes.LONG() )
{
return LongHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pSHORT() )
{
return ShortPHighPriorityCoercer.instance();
}
else if( type == JavaTypes.SHORT() )
{
return ShortHighPriorityCoercer.instance();
}
else if( type == JavaTypes.pVOID() )
{
return IdentityCoercer.instance();
}
else
{
return null;
}
}
public IType verifyTypesComparable( IType lhsType, IType rhsType, boolean bBiDirectional ) throws ParseException
{
return verifyTypesComparable( lhsType, rhsType, bBiDirectional, null );
}
public IType verifyTypesComparable( IType lhsType, IType rhsType, boolean bBiDirectional, IFullParserState parserState ) throws ParseException
{
IType lhsT;
IType rhsT;
if( bBiDirectional )
{
// Bi-Directional indicates comparison as opposed to assignability, therefore for comparison
// we need to test comparability between type variables' bounds
lhsT = TypeSystem.getDefaultParameterizedTypeWithTypeVars( lhsType );
rhsT = TypeSystem.getDefaultParameterizedTypeWithTypeVars( rhsType );
}
else
{
lhsT = lhsType;
rhsT = rhsType;
}
// Upcasting
if( lhsT == rhsT )
{
return lhsType;
}
if( lhsT.equals( rhsT ) )
{
return lhsType;
}
if( lhsT.isAssignableFrom( rhsT ) )
{
return lhsType;
}
if( JavaTypes.pVOID().equals( rhsT ) && !lhsT.isPrimitive() )
{
return lhsType;
}
if( JavaTypes.pVOID().equals( lhsT ) && !rhsT.isPrimitive() )
{
return rhsType;
}
// Error type handling
if( lhsT instanceof IErrorType)
{
return lhsType;
}
if( rhsT instanceof IErrorType )
{
return rhsType;
}
// IPlaceholderType type handling
if( (lhsT instanceof IPlaceholder && ((IPlaceholder)lhsT).isPlaceholder()) ||
(rhsT instanceof IPlaceholder && ((IPlaceholder)rhsT).isPlaceholder()) )
{
return lhsType;
}
//Covariant arrays
if( lhsT.isArray() && rhsT.isArray() )
{
// Note an array of primitives and an array of non-primitives are never assignable
if( lhsT.getComponentType().isPrimitive() == rhsT.getComponentType().isPrimitive() &&
lhsT.getComponentType().isAssignableFrom( rhsT.getComponentType() ) )
{
return lhsType;
}
}
// Downcasting
if( bBiDirectional )
{
if( rhsT.isAssignableFrom( lhsT ) )
{
return lhsType;
}
if( lhsT.isArray() && rhsT.isArray() )
{
if( rhsT.getComponentType().isAssignableFrom( lhsT.getComponentType() ) )
{
return lhsType;
}
}
}
// Structurally suitable (static duck typing)
if( isStructurallyAssignable( lhsT, rhsT ) )
{
return lhsType;
}
// Coercion
if( canCoerce( lhsT, rhsT ) )
{
return lhsType;
}
if( bBiDirectional )
{
if( canCoerce( rhsT, lhsT ) )
{
return rhsType;
}
}
String strLhs = TypeSystem.getNameWithQualifiedTypeVariables( lhsType );
String strRhs = TypeSystem.getNameWithQualifiedTypeVariables( rhsType );
throw new ParseException( parserState, lhsType, Res.MSG_TYPE_MISMATCH, strLhs, strRhs );
}
public static boolean isStructurallyAssignable( IType toType, IType fromType )
{
if( !(toType instanceof IGosuClass && ((IGosuClass)toType).isStructure()) )
{
return false;
}
return isStructurallyAssignable_Laxed( toType, fromType );
}
public static boolean isStructurallyAssignable_Laxed( IType toType, IType fromType )
{
// if( fromType instanceof IMetaType && ((IMetaType)fromType).getType() instanceof IGosuClass && ((IGosuClass)((IMetaType)fromType).getType()).isStructure() )
// // So that:
// // foo( MyStaticCharAtType )
// // function foo( t: Type<CharAt> ) {
// // var c = (t as CharAt).charAt( 0 )
// fromType = ((IMetaType)fromType).getType();
// else if( JavaTypes.CLASS().isAssignableFrom( fromType ) && fromType.getTypeParameters()[0] instanceof IGosuClass && ((IGosuClass)((IMetaType)fromType).getType()).isStructure() )
// // So that:
// // foo( MyStaticCharAtType )
// // function foo( t: Class<CharAt> ) {
// // var c = (t as CharAt).charAt( 0 )
// fromType = fromType.getTypeParameters()[0];
ITypeInfo fromTypeInfo = fromType.getTypeInfo();
MethodList fromMethods = fromTypeInfo instanceof IRelativeTypeInfo
? ((IRelativeTypeInfo)fromTypeInfo).getMethods( toType )
: fromTypeInfo.getMethods();
ITypeInfo toTypeInfo = toType.getTypeInfo();
MethodList toMethods = toTypeInfo instanceof IRelativeTypeInfo
? ((IRelativeTypeInfo)toTypeInfo).getMethods( fromType )
: toTypeInfo.getMethods();
for( IMethodInfo toMi : toMethods )
{
if( isObjectMethod( toMi ) ) {
continue;
}
if( toMi.getOwnersType() instanceof IGosuEnhancement ) {
continue;
}
IMethodInfo fromMi = fromMethods.findAssignableMethod( toMi, fromType instanceof IMetaType && (!(((IMetaType)fromType).getType() instanceof IGosuClass) || !((IGosuClass)((IMetaType)fromType).getType()).isStructure()) );
if( fromMi == null ) {
if( toMi.getDisplayName().startsWith( "@" ) ) {
// Find matching property/field
IPropertyInfo fromPi = fromTypeInfo.getProperty( toMi.getDisplayName().substring( 1 ) );
if( fromPi != null ) {
if( toMi.getParameters().length == 0 ) {
boolean bAssignable = toMi.getReturnType().equals( fromPi.getFeatureType() ) ||
arePrimitiveTypesAssignable( toMi.getReturnType(), fromPi.getFeatureType() );
if( bAssignable ) {
continue;
}
}
else {
boolean bAssignable = fromPi.isWritable( toType ) &&
(fromPi.getFeatureType().equals( toMi.getParameters()[0].getFeatureType() ) ||
arePrimitiveTypesAssignable( fromPi.getFeatureType(), toMi.getParameters()[0].getFeatureType() ));
if( bAssignable ) {
continue;
}
}
}
}
return false;
}
}
return true;
}
public static boolean arePrimitiveTypesAssignable( IType toType, IType fromType ) {
if( toType == null || fromType == null || !toType.isPrimitive() || !fromType.isPrimitive() ) {
return false;
}
if( toType == fromType )
{
return true;
}
if( toType == JavaTypes.pDOUBLE() ) {
return fromType == JavaTypes.pFLOAT() ||
fromType == JavaTypes.pINT() ||
fromType == JavaTypes.pCHAR() ||
fromType == JavaTypes.pSHORT() ||
fromType == JavaTypes.pBYTE();
}
if( toType == JavaTypes.pFLOAT() ) {
return fromType == JavaTypes.pCHAR() ||
fromType == JavaTypes.pSHORT() ||
fromType == JavaTypes.pBYTE();
}
if( toType == JavaTypes.pLONG() ) {
return fromType == JavaTypes.pINT() ||
fromType == JavaTypes.pCHAR() ||
fromType == JavaTypes.pSHORT() ||
fromType == JavaTypes.pBYTE();
}
if( toType == JavaTypes.pINT() ) {
return fromType == JavaTypes.pSHORT() ||
fromType == JavaTypes.pCHAR() ||
fromType == JavaTypes.pBYTE();
}
if( toType == JavaTypes.pSHORT() ) {
return fromType == JavaTypes.pBYTE();
}
return false;
}
public static boolean isObjectMethod( IMethodInfo mi )
{
IGosuClass gosuObjectType = GosuShop.getGosuClassFrom( JavaTypes.IGOSU_OBJECT() );
if( mi.getOwnersType() == gosuObjectType || mi.getDisplayName().equals( "@itype" ) )
{
// A IGosuObject method
return true;
}
IParameterInfo[] params = mi.getParameters();
IType[] paramTypes = new IType[params.length];
for( int i = 0; i < params.length; i++ )
{
paramTypes[i] = params[i].getFeatureType();
}
IRelativeTypeInfo ti = (IRelativeTypeInfo)JavaTypes.OBJECT().getTypeInfo();
IMethodInfo objMethod = ti.getMethod( JavaTypes.OBJECT(), mi.getDisplayName(), paramTypes );
return objMethod != null;
}
public boolean coercionRequiresWarningIfImplicit( IType lhsType, IType rhsType )
{
// Upcasting
if( lhsType == rhsType )
{
return false;
}
if( lhsType.equals( rhsType ) )
{
return false;
}
if( lhsType.isAssignableFrom( rhsType ) )
{
return false;
}
if ( rhsType.isPrimitive() && lhsType.isAssignableFrom( TypeSystem.getBoxType( rhsType ) ) )
{
return false;
}
if( JavaTypes.pVOID().equals(rhsType) )
{
return false;
}
// Error type handling
if( lhsType instanceof IErrorType )
{
return false;
}
if( rhsType instanceof IErrorType )
{
return false;
}
// IPlaceholderType type handling
if( (lhsType instanceof IPlaceholder && ((IPlaceholder)lhsType).isPlaceholder()) ||
(rhsType instanceof IPlaceholder && ((IPlaceholder)rhsType).isPlaceholder()) )
{
return false;
}
//Covariant arrays (java semantics, which are wrong)
// (Five years later, let me totally disagree with my former self. Java array semantics are not only right,
// we've decided to adopt them for generics. Worse is better.)
if( lhsType.isArray() && rhsType.isArray() )
{
if( lhsType.getComponentType().isAssignableFrom( rhsType.getComponentType() ) )
{
return false;
}
}
// Coercion
if( TypeSystem.isNumericType( lhsType ) &&
TypeSystem.isNumericType( rhsType ) )
{
return hasPotentialLossOfPrecisionOrScale( lhsType, rhsType );
}
else
{
if( TypeSystem.isBoxedTypeFor( lhsType, rhsType ) ||
TypeSystem.isBoxedTypeFor( rhsType, lhsType ) )
{
return false;
}
else
{
ICoercer iCoercer = findCoercer( lhsType, rhsType, false );
return iCoercer != null && iCoercer.isExplicitCoercion();
}
}
}
/**
* Given a value and a target Class, return a compatible value via the target Class.
*/
public final Object convertValue(Object value, IType intrType)
{
// Null handling
if( intrType == null )
{
return null;
}
//## todo: This is a horrible hack
//## todo: The only known case where this is necessary is when we have an array of parameterized java type e.g., List<String>[]
intrType = getBoundingTypeOfTypeVariable( intrType );
if( value == null )
{
return intrType.isPrimitive() ? convertNullAsPrimitive( intrType, true ) : null;
}
IType runtimeType = TypeSystem.getFromObject( value );
// IPlaceholder type handling
if( (intrType instanceof IPlaceholder && ((IPlaceholder)intrType).isPlaceholder()) ||
(runtimeType instanceof IPlaceholder && ((IPlaceholder)runtimeType).isPlaceholder()) )
{
return value;
}
// Runtime polymorphism (with java array semantics)
if( intrType == runtimeType )
{
return value;
}
if( intrType.equals( runtimeType ) )
{
return value;
}
if( intrType.isAssignableFrom( runtimeType ) )
{
value = extractObjectArray( intrType, value );
return value;
}
if( intrType.isArray() && runtimeType.isArray() )
{
if( intrType.getComponentType().isAssignableFrom( runtimeType.getComponentType() ) )
{
value = extractObjectArray( intrType, value );
return value;
}
else if( intrType instanceof IGosuArrayClass &&
value instanceof IGosuObject[] )
{
return value;
}
}
// Proxy coercion. The proxy class generated for Java classes is not a super type of the Gosu class.
// The following check allows coercion of the Gosu class to the Gosu proxy class needed for the super call.
if( intrType instanceof IJavaType &&
IGosuClass.ProxyUtil.isProxy( intrType ) &&
runtimeType instanceof IGosuClass &&
intrType.getSupertype() != null &&
intrType.getSupertype().isAssignableFrom( runtimeType ) )
{
return value;
}
// Check Java world types
//noinspection deprecation
if( intrType instanceof IJavaType &&
((IJavaType)intrType).getIntrinsicClass().isAssignableFrom( value.getClass() ) )
{
return value;
}
// Coercion
Object convertedValue = coerce( intrType, runtimeType, value );
if( convertedValue != null )
{
return convertedValue;
}
else
{
//If the null arose from an actual coercion, return it
if( canCoerce( intrType, runtimeType ) )
{
return convertedValue;
}
else
{
//otherwise, return the value itself uncoerced (See comment above)
if( !runtimeType.isArray() )
{
return NO_DICE;
}
return value;
}
}
}
private IType getBoundingTypeOfTypeVariable( IType intrType )
{
int i = 0;
while( intrType instanceof ITypeVariableArrayType )
{
i++;
intrType = intrType.getComponentType();
}
if( intrType instanceof ITypeVariableType )
{
intrType = ((ITypeVariableType)intrType).getBoundingType();
while( i
{
intrType = intrType.getArrayType();
}
}
return intrType;
}
private Object extractObjectArray( IType intrType, Object value )
{
if( intrType.isArray() &&
intrType instanceof IJavaArrayType &&
value instanceof IGosuArrayClassInstance )
{
value = ((IGosuArrayClassInstance)value).getObjectArray();
}
return value;
}
public Object convertNullAsPrimitive( IType intrType, boolean isForBoxing )
{
if( intrType == null )
{
return null;
}
if( !intrType.isPrimitive() )
{
throw GosuShop.createEvaluationException( intrType.getName() + " is not a primitive type." );
}
if( intrType == JavaTypes.pBYTE() )
{
return (byte) 0;
}
if( intrType == JavaTypes.pCHAR() )
{
return '\0';
}
if( intrType == JavaTypes.pDOUBLE() )
{
return isForBoxing ? IGosuParser.NaN : (double) 0;
}
if( intrType == JavaTypes.pFLOAT() )
{
return isForBoxing ? Float.NaN : (float) 0;
}
if( intrType == JavaTypes.pINT() )
{
return 0;
}
if( intrType == JavaTypes.pLONG() )
{
return (long) 0;
}
if( intrType == JavaTypes.pSHORT() )
{
return (short) 0;
}
if( intrType == JavaTypes.pBOOLEAN() )
{
return Boolean.FALSE;
}
if( intrType == JavaTypes.pVOID() )
{
return null;
}
throw GosuShop.createEvaluationException( "Unexpected primitive type: " + intrType.getName() );
}
public ICoercer resolveCoercerStatically( IType typeToCoerceTo, IType typeToCoerceFrom )
{
if( typeToCoerceTo == null || typeToCoerceFrom == null )
{
return null;
}
else if( typeToCoerceTo == typeToCoerceFrom )
{
return null;
}
else if( typeToCoerceTo.equals( typeToCoerceFrom ) )
{
return null;
}
else if( typeToCoerceTo instanceof IErrorType || typeToCoerceFrom instanceof IErrorType )
{
return null;
}
else if( typeToCoerceTo instanceof ITypeVariableArrayType )
{
return RuntimeCoercer.instance();
}
else if( typeToCoerceTo instanceof ITypeVariableType )
{
return TypeVariableCoercer.instance();
}
else if( typeToCoerceTo.isAssignableFrom( typeToCoerceFrom ) )
{
return null;
}
else
{
ICoercer coercerInternal = findCoercerImpl( typeToCoerceTo, typeToCoerceFrom, false );
if( coercerInternal == null )
{
if( typeToCoerceFrom.isAssignableFrom( typeToCoerceTo ) && !JavaTypes.pVOID().equals(typeToCoerceTo) )
{
if( areJavaClassesAndAreNotAssignable( typeToCoerceTo, typeToCoerceFrom ) )
{
return RuntimeCoercer.instance();
}
return identityOrRuntime( typeToCoerceTo, typeToCoerceFrom );
}
else if( (typeToCoerceFrom.isInterface() || typeToCoerceTo.isInterface() || TypeSystem.canCast( typeToCoerceFrom, typeToCoerceTo )) &&
!typeToCoerceFrom.isPrimitive() && !typeToCoerceTo.isPrimitive() )
{
return identityOrRuntime( typeToCoerceTo, typeToCoerceFrom );
}
else if( typeToCoerceTo.isPrimitive() && typeToCoerceFrom instanceof IPlaceholder && ((IPlaceholder)typeToCoerceFrom).isPlaceholder() )
{
return IdentityCoercer.instance();
}
}
return coercerInternal;
}
}
private boolean areJavaClassesAndAreNotAssignable( IType typeToCoerceTo, IType typeToCoerceFrom )
{
if( typeToCoerceFrom instanceof IJavaType && typeToCoerceTo instanceof IJavaType )
{
if( !((IJavaType)typeToCoerceFrom).getBackingClassInfo().isAssignableFrom( ((IJavaType)typeToCoerceTo).getBackingClassInfo() ) )
{
return true;
}
}
return false;
}
private ICoercer identityOrRuntime( IType typeToCoerceTo, IType typeToCoerceFrom )
{
if( TypeSystem.isBytecodeType( typeToCoerceFrom ) &&
TypeSystem.isBytecodeType( typeToCoerceTo ) )
{
return IdentityCoercer.instance(); // (perf) class-to-class downcast can use checkcast bytecode
}
if( typeToCoerceTo instanceof IGosuClass && ((IGosuClass)typeToCoerceTo).isStructure() &&
typeToCoerceFrom instanceof IMetaType )
{
return IdentityCoercer.instance();
}
return RuntimeCoercer.instance();
}
public Double makeDoubleFrom( Object obj )
{
if( obj == null )
{
return null;
}
if( obj instanceof IDimension)
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof Double )
{
return (Double)obj;
}
double d;
if( obj instanceof Number )
{
d = ((Number)obj).doubleValue();
}
else if( obj instanceof Boolean )
{
return (Boolean) obj ? IGosuParser.ONE : IGosuParser.ZERO;
}
else if( obj instanceof Date )
{
return (double)((Date)obj).getTime();
}
else if( obj instanceof Character )
{
return (double) ((Character) obj).charValue();
}
else if( CommonServices.getCoercionManager().canCoerce( JavaTypes.NUMBER(),
TypeSystem.getFromObject( obj ) ) )
{
Number num = (Number)CommonServices.getCoercionManager().convertValue( obj, JavaTypes.NUMBER() );
return num.doubleValue();
}
else
{
String strValue = obj.toString();
return makeDoubleFrom( parseNumber( strValue ) );
}
if( d >= 0D && d <= 9D )
{
int i = (int)d;
if( ((double)i == d) && (i >= 0 && i <= 9) )
{
return IGosuParser.DOUBLE_DIGITS[i];
}
}
return d;
}
public int makePrimitiveIntegerFrom( Object obj )
{
if( obj == null )
{
return 0;
}
else
{
return makeIntegerFrom( obj );
}
}
public Integer makeIntegerFrom( Object obj )
{
if( obj == null )
{
return null;
}
if( obj instanceof IDimension )
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof Integer )
{
return (Integer)obj;
}
if( obj instanceof Number )
{
return ( (Number) obj ).intValue();
}
else if( obj instanceof Boolean )
{
return (Boolean) obj
? IGosuParser.ONE.intValue()
: IGosuParser.ZERO.intValue();
}
else if( obj instanceof Date )
{
return (int) ((Date) obj).getTime();
}
else if( obj instanceof Character )
{
return (int) ((Character) obj).charValue();
}
else if( CommonServices.getCoercionManager().canCoerce( JavaTypes.NUMBER(),
TypeSystem.getFromObject( obj ) ) )
{
Number num = (Number)CommonServices.getCoercionManager().convertValue( obj, JavaTypes.NUMBER() );
return num.intValue();
}
else
{
String strValue = obj.toString();
return makeIntegerFrom( parseNumber( strValue ) );
}
}
public long makePrimitiveLongFrom( Object obj )
{
if( obj == null )
{
return 0;
}
else
{
return makeLongFrom( obj );
}
}
public Long makeLongFrom( Object obj )
{
if( obj == null )
{
return null;
}
if( obj instanceof IDimension )
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof Long )
{
return (Long)obj;
}
if( obj instanceof Number )
{
return ((Number)obj).longValue();
}
else if( obj instanceof Boolean )
{
return (Boolean) obj
? IGosuParser.ONE.longValue()
: IGosuParser.ZERO.longValue();
}
else if( obj instanceof Date )
{
return ((Date)obj).getTime();
}
else if( obj instanceof Character )
{
return (long)((Character)obj).charValue();
}
else if( CommonServices.getCoercionManager().canCoerce( JavaTypes.NUMBER(),
TypeSystem.getFromObject( obj ) ) )
{
Number num = (Number)CommonServices.getCoercionManager().convertValue( obj , JavaTypes.NUMBER() );
return num.longValue();
}
else
{
String strValue = obj.toString();
return makeLongFrom( parseNumber( strValue ) );
}
}
public BigDecimal makeBigDecimalFrom( Object obj )
{
if( obj == null )
{
return null;
}
if( obj instanceof IDimension )
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof BigDecimal )
{
return (BigDecimal)obj;
}
if( obj instanceof String )
{
try
{
return (BigDecimal)BIG_DECIMAL_FORMAT.parse( obj.toString() );
}
catch( java.text.ParseException e )
{
throw GosuExceptionUtil.convertToRuntimeException( e );
}
}
if( obj instanceof Integer )
{
return BigDecimal.valueOf( (Integer)obj );
}
else if( obj instanceof BigInteger )
{
return new BigDecimal( (BigInteger)obj );
}
else if( obj instanceof Long )
{
return BigDecimal.valueOf( (Long)obj );
}
else if( obj instanceof Short )
{
return BigDecimal.valueOf( (Short)obj );
}
else if( obj instanceof Byte )
{
return BigDecimal.valueOf( (Byte)obj );
}
else if( obj instanceof Character )
{
return BigDecimal.valueOf( (Character)obj );
}
else if (obj instanceof Float)
{
// Convert a float directly to a BigDecimal via the String value; don't
// up-convert it to a double first, since converting a double can be lossy
return new BigDecimal( obj.toString());
}
else if( obj instanceof Number )
{
// Make a double from any type of number that we haven't yet dealt with
Double d = makeDoubleFrom( obj );
return new BigDecimal( d.toString() );
}
else if( obj instanceof Boolean )
{
return (Boolean) obj ? BigDecimal.ONE : BigDecimal.ZERO;
}
else if( obj instanceof Date )
{
return new BigDecimal( ((Date)obj).getTime() );
}
else if( CommonServices.getCoercionManager().canCoerce( JavaTypes.NUMBER(), TypeSystem.getFromObject( obj ) ) )
{
Number num = (Number)CommonServices.getCoercionManager().convertValue( obj, JavaTypes.NUMBER() );
return makeBigDecimalFrom( num );
}
else
{
// As a last resort, convert it to a double and then convert that to a big decimal
Double d = makeDoubleFrom( obj );
return new BigDecimal( d.toString() );
}
}
public BigInteger makeBigIntegerFrom( Object obj )
{
if( obj == null )
{
return null;
}
if( obj instanceof BigInteger )
{
return (BigInteger)obj;
}
if( obj instanceof IDimension )
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof String )
{
String strValue = (String)obj;
return makeBigIntegerFrom( parseNumber( strValue ) );
}
BigDecimal d = makeBigDecimalFrom( obj );
return d.toBigInteger();
}
public double makePrimitiveDoubleFrom( Object obj )
{
if( obj == null )
{
return Double.NaN;
}
else
{
return makeDoubleFrom( obj );
}
}
public Float makeFloatFrom( Object obj )
{
if( obj == null )
{
return Float.NaN;
}
if( obj instanceof IDimension )
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof Number )
{
return ((Number)obj).floatValue();
}
else if( obj instanceof Boolean )
{
return (Boolean) obj ? 1f : 0f;
}
else if( obj instanceof Date )
{
return (float) ((Date) obj).getTime();
}
else if( obj instanceof Character )
{
return (float) ((Character) obj).charValue();
}
else
{
try
{
return Float.parseFloat( obj.toString() );
}
catch( Throwable t )
{
// Nonparsable floating point numbers have a NaN value (a la JavaScript)
return Float.NaN;
}
}
}
public float makePrimitiveFloatFrom( Object obj )
{
if( obj == null )
{
return Float.NaN;
}
else
{
return makeFloatFrom( obj );
}
}
public String makeStringFrom( Object obj )
{
return obj == null ? null : obj.toString();
}
/**
* @return A Boolean for an arbitrary object.
*/
public boolean makePrimitiveBooleanFrom( Object obj )
{
//noinspection SimplifiableIfStatement
if( obj == null )
{
return false;
}
else
{
return Boolean.TRUE.equals( makeBooleanFrom( obj ) );
}
}
public Boolean makeBooleanFrom( Object obj )
{
if( obj == null )
{
return null;
}
if( obj instanceof IDimension )
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof Boolean )
{
return (Boolean)obj;
}
if( obj instanceof String )
{
return Boolean.valueOf( (String)obj );
}
if( obj instanceof Number )
{
return ((Number)obj).doubleValue() == 0D ? Boolean.FALSE : Boolean.TRUE;
}
return Boolean.valueOf( obj.toString() );
}
/**
* Returns a new Date instance representing the object.
*/
public Date makeDateFrom( Object obj )
{
if( obj == null )
{
return null;
}
if( obj instanceof IDimension )
{
obj = ((IDimension)obj).toNumber();
}
if( obj instanceof Date )
{
return (Date)obj;
}
if( obj instanceof Number )
{
return new Date( ((Number)obj).longValue() );
}
if( obj instanceof Calendar)
{
return ((Calendar)obj).getTime();
}
if( !(obj instanceof String) )
{
obj = obj.toString();
}
try
{
return parseDateTime( (String)obj );
}
catch( Exception e )
{
//e.printStackTrace();
}
return null;
}
@Override
public boolean isDateTime( String str ) throws java.text.ParseException
{
return parseDateTime( str ) != null;
}
/**
* Produce a date from a string using standard DateFormat parsing.
*/
public Date parseDateTime( String str ) throws java.text.ParseException
{
if( str == null )
{
return null;
}
return DateFormat.getDateInstance().parse(str);
}
/**
* Convert a string to an array of specified type.
* @param strValue the string to convert
* @param intrType the array component type
* @return the string converted to an array
*/
public static Object makeArrayFromString( String strValue, IType intrType )
{
if( JavaTypes.pCHAR() == intrType )
{
return strValue.toCharArray();
}
if( JavaTypes.CHARACTER() == intrType )
{
Character[] characters = new Character[strValue.length()];
for( int i = 0; i < characters.length; i++ )
{
characters[i] = strValue.charAt(i);
}
return characters;
}
if( JavaTypes.STRING() == intrType )
{
String[] strings = new String[strValue.length()];
for( int i = 0; i < strings.length; i++ )
{
strings[i] = String.valueOf( strValue.charAt( i ) );
}
return strings;
}
throw GosuShop.createEvaluationException( "The type, " + intrType.getName() + ", is not supported as a coercible component type to a String array." );
}
public String formatDate( Date value, String strFormat )
{
DateFormat df = new SimpleDateFormat( strFormat );
return df.format( value );
}
public String formatTime( Date value, String strFormat )
{
DateFormat df = new SimpleDateFormat( strFormat );
return df.format( value );
}
public String formatNumber( Double value, String strFormat )
{
NumberFormat nf = new DecimalFormat( strFormat );
return nf.format( value.doubleValue() );
}
public Number parseNumber( String strValue )
{
try
{
return Double.parseDouble( strValue );
}
catch( Exception e )
{
// Nonparsable floating point numbers have a NaN value (a la JavaScript)
return IGosuParser.NaN;
}
}
private static class NullSentinalCoercer extends StandardCoercer
{
private static final NullSentinalCoercer INSTANCE = new NullSentinalCoercer();
@Override
public Object coerceValue( IType typeToCoerceTo, Object value )
{
throw new IllegalStateException( "This is the null sentinal coercer, and is used only to " +
"represent a miss in the coercer cache. It should never " +
"be returned for actual use" );
}
public static NullSentinalCoercer instance()
{
return INSTANCE;
}
}
}
|
package authoring.view.graphicsview;
import java.util.Observable;
import java.util.Observer;
import java.util.ResourceBundle;
import javafx.event.EventHandler;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseDragEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import authoring.view.baseclasses.ScrollView;
/**
* View component that corresponds with the backend model component -
* GraphicsCollection. Updates if any changes occur in Graphics Collection via
* observer/observable.
*
* @author Kevin Li
*
*/
public class GraphicsView extends ScrollView implements Observer {
private static final double VIEW_HEIGHT_RATIO = .95;
private static final double VIEW_WIDTH_RATIO = 0.2;
private VBox myVbox = new VBox();
private EventHandler<MouseEvent> myOnClick;
private String myName;
public GraphicsView(ResourceBundle language, double width, double height) {
super(language, width, height);
setView(width * VIEW_WIDTH_RATIO, height * VIEW_HEIGHT_RATIO);
this.setContent(myVbox);
}
@Override
public void update(Observable o, Object arg) {
addImage((String) arg, myOnClick);
}
public void addImage(String s, EventHandler<MouseEvent> handler){
Graphic graphic = new Graphic(s, handler);
myName = s;
myVbox.getChildren().add(graphic.makeGraphic());
}
public void setAction(EventHandler<MouseEvent> action){
myOnClick = action;
}
public String getMyName(){
return myName;
}
}
|
package org.ihtsdo.buildcloud.config;
import com.amazonaws.auth.BasicAWSCredentials;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import liquibase.integration.spring.SpringLiquibase;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTextMessage;
import org.hibernate.SessionFactory;
import org.ihtsdo.otf.dao.s3.OfflineS3ClientImpl;
import org.ihtsdo.otf.dao.s3.S3Client;
import org.ihtsdo.otf.dao.s3.S3ClientFactory;
import org.ihtsdo.otf.dao.s3.S3ClientImpl;
import org.ihtsdo.otf.dao.s3.helper.S3ClientHelper;
import org.ihtsdo.otf.jms.MessagingHelper;
import org.ihtsdo.snomed.util.rf2.schema.SchemaFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.concurrent.ConcurrentMapCache;
import org.springframework.cache.support.SimpleCacheManager;
import org.springframework.cloud.aws.autoconfigure.context.ContextInstanceDataAutoConfiguration;
import org.springframework.context.annotation.*;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.jms.config.SimpleJmsListenerContainerFactory;
import org.springframework.jms.support.converter.MappingJackson2MessageConverter;
import org.springframework.jms.support.converter.MessageConverter;
import org.springframework.jms.support.converter.MessageType;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.task.DelegatingSecurityContextAsyncTaskExecutor;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Queue;
import java.io.IOException;
import java.util.Arrays;
@SpringBootApplication(exclude = {
ContextInstanceDataAutoConfiguration.class,
HibernateJpaAutoConfiguration.class}
)
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
@EnableConfigurationProperties
@ComponentScan(basePackages = {"org.ihtsdo.buildcloud"})
@EnableJpaRepositories
@EnableJms
@EnableAsync
public abstract class Config extends BaseConfiguration {
private static final String CHANGE_LOG_PATH = "classpath:org/ihtsdo/srs/db/changelog/db.changelog-master.xml";
private S3ClientFactory s3ClientFactory;
@Bean
public ObjectMapper createObjectMapper() {
return new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
@Bean
public DelegatingSecurityContextAsyncTaskExecutor securityContextAsyncTaskExecutor(
@Value("${delegate.security.context.async.task.executor.thread.pool.size:10}") final int threadPoolSize) {
return new DelegatingSecurityContextAsyncTaskExecutor(getAsyncTaskExecutor(threadPoolSize));
}
@Bean
public AsyncTaskExecutor getAsyncTaskExecutor(final int threadPoolSize) {
final ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
threadPoolTaskExecutor.setCorePoolSize(threadPoolSize);
return threadPoolTaskExecutor;
}
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean sessionFactory(@Value("${srs.jdbc.driverClassName}") final String driverClassName,
@Value("${srs.jdbc.url}") final String url,
@Value("${srs.jdbc.username}") final String username,
@Value("${srs.jdbc.password}") final String password,
@Value("${srs.hibernate.dialect}") final String dialect) {
return getSessionFactory(driverClassName, url, username, password, dialect);
}
@Bean
public HibernateTransactionManager transactionManager(@Value("${srs.jdbc.driverClassName}") final String driverClassName,
@Value("${srs.jdbc.url}") final String url,
@Value("${srs.jdbc.username}") final String username,
@Value("${srs.jdbc.password}") final String password,
@Value("${srs.hibernate.dialect}") final String dialect,
@Autowired SessionFactory sessionFactory) {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setDataSource(getBasicDataSource(driverClassName, url, username, password));
transactionManager.setSessionFactory(sessionFactory);
return transactionManager;
}
@Bean
public S3ClientFactory s3ClientFactory(@Value("${aws.key}") final String accessKey,
@Value("${aws.privateKey}") final String privateKey,
@Value("${srs.build.s3.offline.directory}") final String directory) throws IOException {
s3ClientFactory = new S3ClientFactory();
s3ClientFactory.setOnlineImplementation(new S3ClientImpl(new BasicAWSCredentials(accessKey, privateKey)));
s3ClientFactory.setOfflineImplementation(new OfflineS3ClientImpl(directory));
return s3ClientFactory;
}
@Bean
public SpringLiquibase liquibase(@Value("${srs.jdbc.driverClassName}") final String driverClassName,
@Value("${srs.jdbc.url}") final String url, @Value("${srs.jdbc.username}") final String username,
@Value("${srs.jdbc.password}") final String password,
@Value("${srs.environment.shortname}") final String shortname) {
final SpringLiquibase springLiquibase = new SpringLiquibase();
springLiquibase.setDataSource(getBasicDataSource(driverClassName, url, username, password));
springLiquibase.setChangeLog(CHANGE_LOG_PATH);
springLiquibase.setContexts(shortname);
return springLiquibase;
}
@Primary
@Bean
@DependsOn("s3ClientFactory")
public S3Client s3Client(@Value("${srs.build.offlineMode}") final boolean offlineMode) {
return s3ClientFactory.getClient(offlineMode);
}
@Bean
@DependsOn("s3ClientFactory")
public S3ClientHelper s3ClientHelper(@Value("${srs.build.offlineMode}") final boolean offlineMode) {
return new S3ClientHelper(s3Client(offlineMode));
}
@Bean
public SchemaFactory schemaFactory() {
return new SchemaFactory();
}
@Bean
public SimpleCacheManager cacheManager() {
final SimpleCacheManager cacheManager = new SimpleCacheManager();
cacheManager.setCaches(Arrays.asList(getCache("release-center-records"),
getCache("global-roles"), getCache("code-system-roles")));
return cacheManager;
}
private Cache getCache(final String name) {
return new ConcurrentMapCache(name);
}
@Bean
public StandardPasswordEncoder standardPasswordEncoder(@Value("${encryption.salt}") final String salt) {
return new StandardPasswordEncoder(salt);
}
@Bean
public Queue srsQueue(@Value("${srs.jms.queue.prefix}.build-jobs") final String queue) {
return new ActiveMQQueue(queue);
}
@Bean
public MessageConverter jacksonJmsMessageConverter() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
converter.setTargetType(MessageType.TEXT);
converter.setTypeIdPropertyName("_type");
return converter;
}
@Bean
public MessagingHelper messagingHelper() {
return new MessagingHelper();
}
@Bean
public SimpleJmsListenerContainerFactory jmsListenerContainerFactory(@Autowired ConnectionFactory connectionFactory) {
final SimpleJmsListenerContainerFactory simpleJmsListenerContainerFactory = new SimpleJmsListenerContainerFactory();
simpleJmsListenerContainerFactory.setConnectionFactory(connectionFactory);
return simpleJmsListenerContainerFactory;
}
@Bean
public ActiveMQConnectionFactoryPrefetchCustomizer queuePrefetchCustomizer(@Value("${spring.activemq.queuePrefetch:1}") int queuePrefetch) {
return new ActiveMQConnectionFactoryPrefetchCustomizer(queuePrefetch);
}
@Bean
public ActiveMQTextMessage buildStatusTextMessage(@Value("${srs.jms.queue.prefix}.build-job-status") final String queue) throws JMSException {
final ActiveMQTextMessage activeMQTextMessage = new ActiveMQTextMessage();
activeMQTextMessage.setJMSReplyTo(new ActiveMQQueue(queue));
return activeMQTextMessage;
}
}
|
package com.xpn.xwiki.plugin.watchlist;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.ecs.html.Div;
import org.apache.ecs.html.Span;
import org.suigeneris.jrcs.rcs.Version;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.AttachmentDiff;
import com.xpn.xwiki.doc.MetaDataDiff;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.ObjectDiff;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEventType;
import com.xpn.xwiki.plugin.activitystream.api.ActivityEvent;
import com.xpn.xwiki.plugin.diff.DiffPluginApi;
/**
* The class representing an event in the WatchList. The current implementation is a wrapper for one or more
* ActivityEvent.
*
* @version $Id$
*/
public class WatchListEvent implements Comparable<WatchListEvent>
{
/**
* Prefix used in inline style we put in HTML diffs.
*/
private static final String HTML_STYLE_PLACEHOLDER_PREFIX = "WATCHLIST_STYLE_DIFF_";
/**
* Suffix used to insert images later in HTML diffs.
*/
private static final String HTML_IMG_PLACEHOLDER_SUFFIX = "_WATCHLIST_IMG_PLACEHOLDER";
/**
* Prefix used to insert the metadata icon later in HTML diffs.
*/
private static final String HTML_IMG_METADATA_PREFIX = "metadata";
/**
* Prefix used to insert the attachment icon later in HTML diffs.
*/
private static final String HTML_IMG_ATTACHMENT_PREFIX = "attach";
/**
* Event hashcode.
*/
private final int hashCode;
/**
* Prefixed space in which the event happened.
*/
private final String prefixedSpace;
/**
* Prefixed document fullName in which the event happened.
*/
private final String prefixedFullName;
/**
* The XWiki context.
*/
private final XWikiContext context;
/**
* Type of the event (example: "update").
*/
private String type;
/**
* Wrapped events.
*/
private List<ActivityEvent> activityEvents = new ArrayList<ActivityEvent>();
/**
* Version of the document before the event happened.
*/
private String previousVersion;
/**
* List of versions affected by this event. It will contain only one entry if the event is not a composite event.
*/
private List<String> versions;
/**
* List of authors for this event. It will contain only one entry if the event is not a composite event.
*/
private List<String> authors;
/**
* List of dates for this event. It will contain only one entry if the event is not a composite event.
*/
private List<Date> dates;
/**
* Difference generated by update events in a document, formatted in HTML.
*/
private String htmlDiff;
/**
* Constructor.
*
* @param activityEvent activity stream event to wrap
* @param context the XWiki context
*/
public WatchListEvent(ActivityEvent activityEvent, XWikiContext context)
{
this.context = context;
this.activityEvents.add(activityEvent);
type = activityEvent.getType();
prefixedSpace = activityEvent.getWiki() + WatchListStore.WIKI_SPACE_SEP + activityEvent.getSpace();
prefixedFullName = activityEvent.getWiki() + WatchListStore.WIKI_SPACE_SEP + activityEvent.getPage();
int hash = 3;
if (ActivityEventType.UPDATE.equals(activityEvent)) {
hashCode = 42 * hash + prefixedFullName.hashCode() + activityEvent.getType().hashCode();
} else {
hashCode =
42 * hash + prefixedFullName.hashCode() + activityEvent.getType().hashCode()
+ activityEvent.getDate().hashCode();
}
}
/**
* Add another event associated to this event.
*
* @param event The event to add.
*/
public void addEvent(WatchListEvent event)
{
if (ActivityEventType.DELETE.equals(event.getType())) {
// If the document has been deleted, reset this event
activityEvents.clear();
type = event.getType();
versions.clear();
versions = null;
authors.clear();
authors = null;
previousVersion = null;
htmlDiff = null;
} else if (ActivityEventType.UPDATE.equals(event.getType()) && ActivityEventType.DELETE.equals(getType())) {
// If an update event had been fired before a delete, discard it
return;
}
activityEvents.add(event.getActivityEvent());
}
/**
* @return The wiki in which the event happened.
*/
public String getWiki()
{
return getActivityEvent().getWiki();
}
/**
* @return The space in which the event happened.
*/
public String getSpace()
{
return getActivityEvent().getSpace();
}
/**
* @return The space, prefixed with the wiki name, in which the event happened (example: "xwiki:Main").
*/
public String getPrefixedSpace()
{
return prefixedSpace;
}
/**
* @return The fullName of the document which has generated this event (example: "Main.WebHome").
*/
public String getFullName()
{
return getActivityEvent().getPage();
}
/**
* @return The fullName of the document which has generated this event, prefixed with the wiki name. Example:
* "xwiki:Main.WebHome".
*/
public String getPrefixedFullName()
{
return prefixedFullName;
}
/**
* @return The URL of the document which has fired the event
*/
public String getUrl()
{
String url = "";
try {
url = context.getWiki().getDocument(getPrefixedFullName(), context).getExternalURL("view", context);
} catch (Exception e) {
// Do nothing, we don't want to throw exceptions in notification emails.
}
return url;
}
/**
* @return The date when the event occurred.
*/
public Date getDate()
{
return getActivityEvent().getDate();
}
/**
* @return Get all the dates of a composite event, if this event is not a composite this list will contain single
* entry.
*/
public List<Date> getDates()
{
if (dates == null) {
dates = new ArrayList<Date>();
if (!isComposite()) {
dates.add(getDate());
} else {
for (ActivityEvent event : activityEvents) {
dates.add(event.getDate());
}
}
}
return dates;
}
/**
* @return The type of this event (example: "update", "delete").
*/
public String getType()
{
return type;
}
/**
* @return The underlying ActivityEvent.
*/
private ActivityEvent getActivityEvent()
{
return activityEvents.get(0);
}
/**
* @return The user who generated the event.
*/
public String getAuthor()
{
return getActivityEvent().getUser();
}
/**
* @return Get all the authors of a composite event, if this event is not a composite this list will contain single
* entry.
*/
public List<String> getAuthors()
{
if (authors == null) {
authors = new ArrayList<String>();
if (!isComposite()) {
authors.add(getAuthor());
} else {
for (ActivityEvent event : activityEvents) {
String prefixedAuthor = event.getWiki() + WatchListStore.WIKI_SPACE_SEP + event.getUser();
if (!authors.contains(prefixedAuthor)) {
authors.add(prefixedAuthor);
}
}
}
}
return authors;
}
/**
* @return The version of the document at the time it has generated the event.
*/
public String getVersion()
{
return getActivityEvent().getVersion();
}
/**
* @return All the versions from a composite event, if the event is not a composite the list will contain a single
* entry
*/
public List<String> getVersions()
{
if (versions == null) {
versions = new ArrayList<String>();
if (!isComposite()) {
if (!StringUtils.isBlank(getActivityEvent().getVersion())) {
versions.add(getActivityEvent().getVersion());
}
} else {
for (ActivityEvent event : activityEvents) {
if (!StringUtils.isBlank(event.getVersion()) && !versions.contains(event.getVersion())) {
versions.add(event.getVersion());
}
}
}
}
return versions;
}
/**
* @return The version of the document which has generated the event, before the actual event.
*/
public String getPreviousVersion()
{
if (previousVersion == null) {
String currentVersion = "";
previousVersion = "1.1";
try {
if (!isComposite()) {
currentVersion = getActivityEvent().getVersion();
} else {
List<String> allVersions = getVersions();
if (allVersions.size() > 1) {
currentVersion = allVersions.get(allVersions.size() - 1);
}
}
if (!StringUtils.isBlank(currentVersion)) {
XWikiDocument doc = context.getWiki().getDocument(prefixedFullName, context);
XWikiDocument docRev = context.getWiki().getDocument(doc, currentVersion, context);
doc.loadArchive(context);
Version version = doc.getDocumentArchive().getPrevVersion(docRev.getRCSVersion());
if (version != null) {
previousVersion = version.toString();
}
}
} catch (XWikiException e) {
// Catch the exception to be sure we won't send emails containing stacktraces to users.
e.printStackTrace();
}
}
return previousVersion;
}
/**
* @return True if the event is made of multiple events.
*/
public boolean isComposite()
{
return activityEvents.size() > 1;
}
/**
* @param classAttr The class of the div to create
* @return a HTML div element
*/
private Div createDiffDiv(String classAttr)
{
Div div = new Div();
div.setClass(classAttr);
div.setStyle(HTML_STYLE_PLACEHOLDER_PREFIX + classAttr);
return div;
}
/**
* @param classAttr The class of the span to create
* @return an opening span markup
*/
private Span createDiffSpan(String classAttr)
{
Span span = new Span();
span.setClass(classAttr);
span.setStyle(HTML_STYLE_PLACEHOLDER_PREFIX + classAttr);
return span;
}
/**
* @param objectDiffs List of object diff
* @param isXWikiClass is the diff to compute the diff for a xwiki class, the other possibility being a plain xwiki
* object
* @param documentFullName full name of the document the diff is computed for
* @param diff the diff plugin API
* @return The HTML diff
*/
private String getHTMLObjectsDiff(List<List<ObjectDiff>> objectDiffs, boolean isXWikiClass,
String documentFullName, DiffPluginApi diff)
{
StringBuffer result = new StringBuffer();
String propSeparator = ": ";
String prefix = (isXWikiClass) ? "class" : "object";
try {
for (List<ObjectDiff> oList : objectDiffs) {
if (oList.size() > 0) {
Div mainDiv = createDiffDiv(prefix + "Diff");
Span objectName = createDiffSpan(prefix + "ClassName");
if (isXWikiClass) {
objectName.addElement(getFullName());
} else {
objectName.addElement(oList.get(0).getClassName());
}
mainDiv.addElement(prefix + HTML_IMG_PLACEHOLDER_SUFFIX);
mainDiv.addElement(objectName);
for (ObjectDiff oDiff : oList) {
String propDiff =
diff.getDifferencesAsHTML(oDiff.getPrevValue().toString(), oDiff.getNewValue().toString(),
false);
if (!StringUtils.isBlank(oDiff.getPropName()) && !StringUtils.isBlank(propDiff)) {
Div propDiv = createDiffDiv("propDiffContainer");
Span propNameSpan = createDiffSpan("propName");
propNameSpan.addElement(oDiff.getPropName() + propSeparator);
String shortPropType = StringUtils.removeEnd(oDiff.getPropType(), "Class").toLowerCase();
if (StringUtils.isBlank(shortPropType)) {
// When the diff shows a property that has been deleted, its type is not available.
shortPropType = HTML_IMG_METADATA_PREFIX;
}
propDiv.addElement(shortPropType + HTML_IMG_PLACEHOLDER_SUFFIX);
propDiv.addElement(propNameSpan);
Div propDiffDiv = createDiffDiv("propDiff");
propDiffDiv.addElement(propDiff);
propDiv.addElement(propDiffDiv);
mainDiv.addElement(propDiv);
}
}
result.append(mainDiv);
}
}
} catch (XWikiException e) {
// Catch the exception to be sure we won't send emails containing stacktraces to users.
e.printStackTrace();
}
return result.toString();
}
/**
* @return The diff, formated in HTML, to display to the user when a document has been updated
*/
public String getHTMLDiff()
{
if (htmlDiff == null) {
try {
XWikiDocument d2 = context.getWiki().getDocument(getPrefixedFullName(), context);
XWikiDocument d1 = context.getWiki().getDocument(d2, getPreviousVersion(), context);
DiffPluginApi diff = (DiffPluginApi) context.getWiki().getPluginApi("diff", context);
StringBuffer result = new StringBuffer();
List<AttachmentDiff> attachDiffs = d2.getAttachmentDiff(d1, d2, context);
List<List<ObjectDiff>> objectDiffs = d2.getObjectDiff(d1, d2, context);
List<List<ObjectDiff>> classDiffs = d2.getClassDiff(d1, d2, context);
List<MetaDataDiff> metaDiffs = d2.getMetaDataDiff(d1, d2, context);
if (!d1.getContent().equals(d2.getContent())) {
Div contentDiv = createDiffDiv("contentDiff");
String contentDiff = diff.getDifferencesAsHTML(d1.getContent(), d2.getContent(), false);
contentDiv.addElement(contentDiff);
result.append(contentDiv);
}
for (AttachmentDiff aDiff : attachDiffs) {
Div attachmentDiv = createDiffDiv("attachmentDiff");
attachmentDiv.addElement(HTML_IMG_ATTACHMENT_PREFIX + HTML_IMG_PLACEHOLDER_SUFFIX);
attachmentDiv.addElement(aDiff.toString());
result.append(attachmentDiv);
}
result.append(getHTMLObjectsDiff(objectDiffs, false, getFullName(), diff));
result.append(getHTMLObjectsDiff(classDiffs, true, getFullName(), diff));
for (MetaDataDiff mDiff : metaDiffs) {
Div metaDiv = createDiffDiv("metaDiff");
metaDiv.addElement(HTML_IMG_METADATA_PREFIX + HTML_IMG_PLACEHOLDER_SUFFIX);
metaDiv.addElement(mDiff.toString());
result.append(metaDiv);
}
htmlDiff = result.toString();
} catch (XWikiException e) {
// Catch the exception to be sure we won't send emails containing stacktraces to users.
e.printStackTrace();
}
}
return htmlDiff;
}
/**
* Perform a string comparison on the prefixed fullName of the source document.
*
* @param event event to compare with
* @return the result of the string comparison
*/
public int compareTo(WatchListEvent event)
{
return getPrefixedFullName().compareTo(event.getPrefixedFullName());
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode()
{
return hashCode;
}
/**
* Overriding of the default equals method.
*
* @param obj the ActivityEvent to be compared with
* @return True if the two events have been generated by the same document and are equals or conflicting
*/
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (!(obj instanceof WatchListEvent)) {
return false;
}
// At first this method was returning true when the documents were the same and the events were the same type.
// Since we don't want to keep update events for documents that have been deleted this method has been modified
// to a point were it performs something different from a equals(), it returns true when obj is a delete event
// and 'this' is an update event. See WatchListEventManager#WatchListEventManager(Date, XWikiContext).
// TODO: refactoring.
WatchListEvent event = ((WatchListEvent) obj);
return prefixedFullName.equals(event.getPrefixedFullName()) && WatchListEventType.UPDATE.equals(getType())
&& (WatchListEventType.UPDATE.equals(event.getType()) || WatchListEventType.DELETE.equals(event.getType()));
}
}
|
package org.jcors.web;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.jcors.model.CorsHeaders;
/**
* Class that produces the correct instance for CORS requests handling
*
* @author Diego Silveira
*/
public final class RequestHandlerFactory {
private static final Logger log = Logger.getLogger(RequestHandlerFactory.class);
private static final String PREFLIGHT_REQUEST_TYPE = "preflight";
private static final String ACTUAL_REQUEST_TYPE = "actual";
private static final String NON_CORS_REQUEST_TYPE = "non-CORS";
public static RequestHandler getRequestHandler(HttpServletRequest request) {
// CORS Request
if (!isEmptyHeader(request, CorsHeaders.ORIGIN_HEADER)) {
if (!isEmptyHeader(request, CorsHeaders.ACCESS_CONTROL_REQUEST_METHOD_HEADER)) {
logRequest(PREFLIGHT_REQUEST_TYPE, request);
return new PreflightRequestHandler();
}
logRequest(ACTUAL_REQUEST_TYPE, request);
return new ActualRequestHandler();
}
logRequest(NON_CORS_REQUEST_TYPE, request);
return new SimpleRequestHandler();
}
private static boolean isEmptyHeader(HttpServletRequest request, String header) {
String headerValue = request.getHeader(header);
return headerValue == null || "".equals(headerValue.trim());
}
private static void logRequest(String requestType, HttpServletRequest request) {
String message = String.format("Handling %s request: %s (%s)", requestType, request.getRequestURI(), request.getMethod());
log.debug(message);
}
}
|
package com.bio4j.model.uniprot.nodes;
import com.bio4j.model.uniprot.UniprotGraph.ProteinType;
import com.bio4j.model.uniprot.relationships.ProteinDataset;
import com.bio4j.model.uniprot.relationships.ProteinOrganism;
import com.ohnosequences.typedGraphs.Node;
import com.ohnosequences.typedGraphs.Property;
import java.util.List;
public interface Protein<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>
>
extends Node<N, NT> {
public String name();
public String sequence();
public String fullName();
public String shortName();
public String accession();
public String modifiedDate();
public String mass();
public int length();
// properties
public static interface name<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends name<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "name";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface sequence<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends sequence<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "sequence";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface fullName<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends fullName<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "fullName";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface shortName<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends shortName<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "shortName";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface accession<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends accession<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "accession";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface modifiedDate<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends modifiedDate<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "modifiedDate";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface mass<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends mass<N, NT, P>
>
extends Property<N, NT, P, String> {
@Override
public default String name() {
return "mass";
}
@Override
public default Class<String> valueClass() {
return String.class;
}
}
public static interface length<
N extends Protein<N, NT>,
NT extends ProteinType<N, NT>,
P extends length<N, NT, P>
>
extends Property<N, NT, P, Integer> {
@Override
public default String name() {
return "length";
}
@Override
public default Class<Integer> valueClass() {
return Integer.class;
}
}
// relationships
// proteinOrganism
// outgoing
public List<? extends ProteinOrganism> proteinOrganism_out();
public List<? extends Organism> proteinOrganism_outNodes();
// proteinDataset
// outgoing
public <T extends ProteinDataset> T proteinDataset_out();
public <T extends Dataset> T proteinDataset_outNodes();
}
|
package org.jboss.as.console.client.shared.jvm;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.shared.BeanFactory;
import org.jboss.as.console.client.shared.help.FormHelpPanel;
import org.jboss.as.console.client.widgets.Feedback;
import org.jboss.as.console.client.widgets.forms.CheckBoxItem;
import org.jboss.as.console.client.widgets.forms.Form;
import org.jboss.as.console.client.widgets.forms.FormValidation;
import org.jboss.as.console.client.widgets.forms.TextBoxItem;
import org.jboss.as.console.client.widgets.tools.ToolButton;
import org.jboss.as.console.client.widgets.tools.ToolStrip;
import org.jboss.dmr.client.ModelNode;
/**
* @author Heiko Braun
* @date 4/20/11
*/
public class JvmEditor {
private JvmManagement presenter;
private Form<Jvm> form;
BeanFactory factory = GWT.create(BeanFactory.class);
private boolean hasJvm;
private ToolButton edit;
private String reference;
private Widget formWidget;
private FormHelpPanel.AddressCallback addressCallback;
public JvmEditor(JvmManagement presenter) {
this.presenter = presenter;
}
public void setAddressCallback(FormHelpPanel.AddressCallback addressCallback) {
this.addressCallback = addressCallback;
}
public Widget asWidget() {
VerticalPanel panel = new VerticalPanel();
panel.setStyleName("fill-layout-width");
ToolStrip toolStrip = new ToolStrip();
edit = new ToolButton(Console.CONSTANTS.common_label_edit());
ClickHandler editHandler = new ClickHandler(){
@Override
public void onClick(ClickEvent event) {
if(edit.getText().equals(Console.CONSTANTS.common_label_edit()))
{
onEdit();
}
else
{
onSave();
}
}
};
edit.addClickHandler(editHandler);
toolStrip.addToolButton(edit);
ToolButton delete = new ToolButton(Console.CONSTANTS.common_label_delete(), new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
if(hasJvm)
{
Feedback.confirm(Console.MESSAGES.deleteJVM(), Console.MESSAGES.deleteJVMConfirm(),
new Feedback.ConfirmationHandler() {
@Override
public void onConfirmation(boolean isConfirmed) {
if(isConfirmed)
presenter.onDeleteJvm(reference, form.getEditedEntity());
}
});
}
}
});
toolStrip.addToolButton(delete);
panel.add(toolStrip);
form = new Form<Jvm>(Jvm.class);
form.setNumColumns(2);
TextBoxItem nameItem = new TextBoxItem("name", Console.CONSTANTS.common_label_name());
TextBoxItem heapItem = new TextBoxItem("heapSize", "Heap Size");
TextBoxItem maxHeapItem = new TextBoxItem("maxHeapSize", "Max Heap Size");
//CheckBoxItem debugItem = new CheckBoxItem("debugEnabled", "Debug Enabled?");
//TextBoxItem debugOptionsItem = new TextBoxItem("debugOptions", "Debug Options");
form.setFields(nameItem, heapItem, maxHeapItem);
form.setEnabled(false);
if(addressCallback!=null)
{
final FormHelpPanel helpPanel = new FormHelpPanel(addressCallback, form);
panel.add(helpPanel.asWidget());
}
formWidget = form.asWidget();
panel.add(formWidget);
return panel;
}
private void onSave() {
FormValidation validation = form.validate();
if(!validation.hasErrors())
{
form.setEnabled(false);
edit.setText(Console.CONSTANTS.common_label_edit());
Jvm jvm = form.getUpdatedEntity();
if(hasJvm)
presenter.onUpdateJvm(reference, jvm.getName(), form.getChangedValues());
else
presenter.onCreateJvm(reference, jvm);
}
}
private void onEdit() {
edit.setText(Console.CONSTANTS.common_label_save());
form.setEnabled(true);
}
public void setSelectedRecord(String reference, Jvm jvm) {
this.reference = reference;
hasJvm = jvm!=null;
form.setEnabled(false);
edit.setText(Console.CONSTANTS.common_label_edit());
if(hasJvm)
form.edit(jvm);
else
form.edit(factory.jvm().as());
}
}
|
package org.xwiki.velocity.internal;
import org.apache.velocity.VelocityContext;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.script.service.ScriptServiceManager;
import org.xwiki.velocity.VelocityContextInitializer;
/**
* Registers the Script Service Manager in the Velocity Context so that it's available from Velocity.
*
* @version $Id$
* @since 2.3M1
* @todo in the future Velocity will be implemented using the JSR 223 API and this class won't be required anymore
*/
@Component("scriptservices")
public class ServicesVelocityContextInitializer implements VelocityContextInitializer
{
/**
* The Script Service Manager to bind in the Script Context.
*/
@Requirement
private ScriptServiceManager scriptServiceManager;
/**
* {@inheritDoc}
* @see org.xwiki.velocity.VelocityContextInitializer#initialize(org.apache.velocity.VelocityContext)
*/
public void initialize(VelocityContext context)
{
context.put("services", this.scriptServiceManager);
}
}
|
package org.kurento.modulecreator;
import static java.nio.file.FileVisitResult.CONTINUE;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystemAlreadyExistsException;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
public class PathUtils {
public static class Finder extends SimpleFileVisitor<Path> {
private final PathMatcher matcher;
private List<Path> paths = new ArrayList<>();
Finder(String pattern) {
matcher = FileSystems.getDefault()
.getPathMatcher("glob:" + pattern);
}
// Compares the glob pattern against
// the file or directory name.
void find(Path file) {
Path name = file.getFileName();
if (name != null && matcher.matches(name)) {
paths.add(file);
}
}
// Invoke the pattern matching
// method on each file.
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
find(file);
return CONTINUE;
}
// Invoke the pattern matching
// method on each directory.
@Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
find(dir);
return CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
System.err.println(exc);
return CONTINUE;
}
public List<Path> getPaths() {
return paths;
}
}
public static Path getPathInClasspath(String resourceName)
throws IOException, URISyntaxException {
return getPathInClasspath(PathUtils.class.getResource(resourceName));
}
public static Path getPathInClasspath(URL resource) throws IOException,
URISyntaxException {
Objects.requireNonNull(resource, "Resource URL cannot be null");
URI uri = resource.toURI();
String scheme = uri.getScheme();
if (scheme.equals("file")) {
return Paths.get(uri);
}
if (!scheme.equals("jar")) {
throw new IllegalArgumentException("Cannot convert to Path: " + uri);
}
String s = uri.toString();
int separator = s.indexOf("!/");
String entryName = s.substring(separator + 2);
URI fileURI = URI.create(s.substring(0, separator));
FileSystem fs = null;
try {
fs = FileSystems.newFileSystem(fileURI,
Collections.<String, Object> emptyMap());
} catch (FileSystemAlreadyExistsException e) {
fs = FileSystems.getFileSystem(fileURI);
}
return fs.getPath(entryName);
}
public static void delete(Path folder, List<String> noDeleteFiles)
throws IOException {
delete(folder, folder, noDeleteFiles);
}
public static List<Path> getPaths(String[] pathNames, String globPattern)
throws IOException {
List<Path> paths = new ArrayList<Path>();
for (String pathName : pathNames) {
Path path = Paths.get(pathName);
if (Files.exists(path)) {
paths.addAll(searchFiles(path, globPattern));
}
}
return paths;
}
public static List<Path> searchFiles(Path path, String globPattern)
throws IOException {
if (Files.isDirectory(path)) {
Finder finder = new Finder(globPattern);
Files.walkFileTree(path, finder);
return finder.getPaths();
} else {
PathMatcher matcher = FileSystems.getDefault().getPathMatcher(
"glob:" + globPattern);
if (matcher.matches(path.getFileName())) {
return Arrays.asList(path);
} else {
return Collections.emptyList();
}
}
}
public static void deleteRecursive(Path path) throws IOException {
Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
Files.delete(file);
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult postVisitDirectory(Path dir, IOException exc)
throws IOException {
if (exc == null) {
Files.delete(dir);
return FileVisitResult.CONTINUE;
} else {
throw exc;
}
}
});
}
public static void delete(Path basePath, Path path,
List<String> noDeleteFiles) throws IOException {
Path relativePath = basePath.relativize(path);
if (noDeleteFiles.contains(relativePath.toString())) {
return;
}
if (Files.isDirectory(path)) {
try (DirectoryStream<Path> directoryStream = Files
.newDirectoryStream(path)) {
for (Path c : directoryStream) {
delete(basePath, c, noDeleteFiles);
}
}
if (isEmptyDir(path)) {
Files.delete(path);
}
} else {
Files.delete(path);
}
}
public static boolean isEmptyDir(Path path) throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
Iterator<Path> files = ds.iterator();
return !files.hasNext();
}
}
}
|
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Principle extends JFrame{
private JPanel panel;
public Principle() {
panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
JButton b = new JButton("Ajouter une couleur");
b.setAlignmentX(Component.CENTER_ALIGNMENT);
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (panel.getComponentCount() < 10) {
panel.add(new Couleur());
validate();
repaint();
}
}
});
panel.add(b);
panel.add(new Couleur());
add(panel);
setSize(new Dimension(1000,500));
setTitle("Color setter");
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
setLocation((int) ((width/2 - this.getWidth()/2)), (int) (height/2 - this.getHeight()/2));
setVisible(true);
}
}
|
package com.buteam3.controller;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.buteam3.repository.MessageRepository;
import com.buteam3.entity.Message;
import com.stormpath.sdk.account.AccountList;
import com.stormpath.sdk.application.Application;
import com.stormpath.sdk.servlet.application.ApplicationResolver;
/**
* Class is controller object which handles interaction between
* front-end and database for chat tool.
*
* @author buteam3
*/
@Controller
public class ChatController {
private MessageRepository repository;
/**
* Constructor for home controller. Takes in a repository
* of messages to be loaded into chat window in UI.
*
* @param repository repository of messages
*/
@Autowired
public ChatController(MessageRepository repository) {
this.repository = repository;
}
/**
*
* @param model
* @param req
* @return
*/
public String chat(ModelMap model, HttpServletRequest req) {
Application application = ApplicationResolver.INSTANCE.getApplication(req);
AccountList accounts = application.getAccounts();
model.addAttribute("accounts", accounts);
chatmsg(model);
return "chat";
}
/**
* Loads a a list of messages from database based on channel id
*
* @param model model map linking messages to chat UI chatbox
*/
private void chatmsg(ModelMap model) {
List<Message> message = repository.findByMidGreaterThan(0);
model.addAttribute("chatbox", message);
}
/**
* Method called when a new message is entered. Saves the new message
* to the database through message repository.
*
* @param model
* @param message
* @param result
* @return
*/
@RequestMapping(value="/chat_msg/new", method = RequestMethod.POST)
public String insertData(ModelMap model,
@Valid Message message,
BindingResult result) {
if (!result.hasErrors()) {
repository.save(message);
}
model.addAttribute("messages", message);
return "fragments/chat";
}
/**
* Calls chatmsg to Load a a list of messages from database based on channel id
*
* @param model
* @param message
* @param result
* @return
*/
@RequestMapping(value="/chat_msg/read", method = RequestMethod.POST)
public String readData(ModelMap model, Long mid) {
List<Message> messages = repository.findByMidGreaterThan(mid);
model.addAttribute("messages", messages);
return "fragments/chat";
}
}
|
package com.xbox.httpclient;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.RequestBody;
public class HttpClientRequest {
private static OkHttpClient OK_CLIENT;
private Request okHttpRequest;
private Request.Builder requestBuilder;
static {
OK_CLIENT = new OkHttpClient.Builder()
.retryOnConnectionFailure(false) // Explicitly disable retries; retry logic will be managed by native code in libHttpClient
.build();
}
public HttpClientRequest() {
requestBuilder = new Request.Builder();
}
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static HttpClientRequest createClientRequest() {
return new HttpClientRequest();
}
public void setHttpUrl(String url) {
this.requestBuilder = this.requestBuilder.url(url);
}
public void setHttpMethodAndBody(String method, String contentType, byte[] body) {
if (body == null || body.length == 0) {
this.requestBuilder = this.requestBuilder.method(method, null);
} else {
this.requestBuilder = this.requestBuilder.method(method, RequestBody.create(MediaType.parse(contentType), body));
}
}
public void setHttpHeader(String name, String value) {
this.requestBuilder = requestBuilder.addHeader(name, value);
}
public void doRequestAsync(final long sourceCall) {
OK_CLIENT.newCall(this.requestBuilder.build()).enqueue(new Callback() {
@Override
public void onFailure(final Call call, IOException e) {
Log.e("HttpRequestClient", "Failed to execute async request", e);
OnRequestCompleted(sourceCall, null);
}
@Override
public void onResponse(Call call, final Response response) throws IOException {
OnRequestCompleted(sourceCall, new HttpClientResponse(response));
}
});
}
private native void OnRequestCompleted(long call, HttpClientResponse response);
}
|
package Main.Controllers;
import Main.Helpers.Medicine;
import Main.JdbcConnection.JDBC;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.function.Predicate;
public class InventoryController {
private static double drawableWidth;
public static ObservableList<Medicine> medicines;
FilteredList<Medicine> filteredData;
Boolean advancedSearchedToggle = false;
@FXML
private TextField searchField;
@FXML
private TableView<Medicine> medicineTableView;
@FXML
private TableColumn<Medicine, Integer> codeColumn;
@FXML
private TableColumn<Medicine, String> nameColumn;
@FXML
private TableColumn<Medicine, String> saltColumn;
@FXML
private TableColumn<Medicine, String> companyColumn;
@FXML
private TableColumn<Medicine, String> typeColumn;
@FXML
private TableColumn<Medicine, String> hsnColumn;
@FXML
private TableColumn<Medicine, String> batchColumn;
@FXML
private TableColumn<Medicine, String> expiryColumn;
@FXML
private TableColumn<Medicine, Integer> quantityColumn;
@FXML
private TableColumn<Medicine, Float> mrpColumn;
@FXML
private TableColumn<Medicine, Float> costColumn;
@FXML
private TableColumn<Medicine, Integer> sgstColumn;
@FXML
private TableColumn<Medicine, Integer> cgstColumn;
@FXML
private TableColumn<Medicine, Integer> igstColumn;
@FXML
private AnchorPane inventory_parent_pane;
@FXML
private Button advancedSearch;
@FXML
private RadioButton medicineButton;
@FXML
private RadioButton codeButton;
@FXML
private RadioButton saltButton;
@FXML
private RadioButton companyButton;
@FXML
private RadioButton typeButton;
@FXML
private RadioButton batchButton;
@FXML
private RadioButton hsnButton;
@FXML
private Label searchBy;
@FXML
private ToggleGroup searchGroup;
@FXML
private VBox searchVBox;
public static void setDrawableWidth(double width) {
drawableWidth = width;
}
public void initialize() {
inventory_parent_pane.setPrefWidth(drawableWidth);
initializeTable();
assignToggleValues();
onChangingSearchOption();
searchTable();
disableVisibilityAdvancedSearch();
}
public void initializeTable() {
codeColumn.setCellValueFactory(new PropertyValueFactory<Medicine, Integer>("code"));
nameColumn.setCellValueFactory(new PropertyValueFactory<Medicine, String>("name"));
saltColumn.setCellValueFactory(new PropertyValueFactory<Medicine, String>("salt"));
companyColumn.setCellValueFactory(new PropertyValueFactory<Medicine, String>("company"));
typeColumn.setCellValueFactory(new PropertyValueFactory<Medicine, String>("type"));
hsnColumn.setCellValueFactory(new PropertyValueFactory<Medicine, String>("hsn"));
batchColumn.setCellValueFactory(new PropertyValueFactory<Medicine, String>("batch"));
expiryColumn.setCellValueFactory(new PropertyValueFactory<Medicine, String>("expiry"));
quantityColumn.setCellValueFactory(new PropertyValueFactory<Medicine, Integer>("quantity"));
mrpColumn.setCellValueFactory(new PropertyValueFactory<Medicine, Float>("mrp"));
costColumn.setCellValueFactory(new PropertyValueFactory<Medicine, Float>("cost"));
sgstColumn.setCellValueFactory(new PropertyValueFactory<Medicine, Integer>("sgst"));
cgstColumn.setCellValueFactory(new PropertyValueFactory<Medicine, Integer>("cgst"));
igstColumn.setCellValueFactory(new PropertyValueFactory<Medicine, Integer>("igst"));
medicineTableView.setItems(getMedicine());
}
public void assignToggleValues() {
medicineButton.setUserData("Medicine");
codeButton.setUserData("Code");
saltButton.setUserData("Salt");
companyButton.setUserData("Company");
batchButton.setUserData("Batch Number");
typeButton.setUserData("Type");
hsnButton.setUserData("HSN Number");
}
public void onChangingSearchOption() {
searchGroup.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> ov,
Toggle old_toggle, Toggle new_toggle) {
if (searchGroup.getSelectedToggle() != null) {
searchField.setText("");
}
}
});
}
public void searchTable() {
filteredData = new FilteredList<>(medicines, e -> true);
searchField.setOnKeyReleased(e -> {
searchField.textProperty().addListener((observable, oldValue, newValue) -> {
filteredData.setPredicate((Predicate<? super Medicine>) medicine -> {
if (newValue == null || newValue.isEmpty()) {
return true;
}
String lowerCaseFilter = newValue.toLowerCase();
String codeChk = Integer.toString(medicine.getCode());
if (codeChk.contains(newValue) && searchGroup.getSelectedToggle().getUserData().toString().equals("Code")) {
return true;
} else if (medicine.getName().toLowerCase().contains(lowerCaseFilter) && searchGroup.getSelectedToggle().getUserData().toString().equals("Medicine")) {
return true;
} else if (medicine.getSalt().toLowerCase().contains(lowerCaseFilter) && searchGroup.getSelectedToggle().getUserData().toString().equals("Salt")) {
return true;
} else if (medicine.getCompany().toLowerCase().contains(lowerCaseFilter) && searchGroup.getSelectedToggle().getUserData().toString().equals("Company")) {
return true;
} else if (medicine.getBatch().toLowerCase().contains(lowerCaseFilter) && searchGroup.getSelectedToggle().getUserData().toString().equals("Batch Number")) {
return true;
} else if (medicine.getType().toLowerCase().contains(lowerCaseFilter) && searchGroup.getSelectedToggle().getUserData().toString().equals("Type")) {
return true;
} else if (medicine.getHsn().toLowerCase().contains(lowerCaseFilter) && searchGroup.getSelectedToggle().getUserData().toString().equals("HSN Number")) {
return true;
}
return false;
});
});
SortedList<Medicine> searchedData = new SortedList<Medicine>(filteredData);
searchedData.comparatorProperty().bind(medicineTableView.comparatorProperty());
medicineTableView.setItems(searchedData);
});
}
public void disableVisibilityAdvancedSearch() {
searchBy.setVisible(false);
searchVBox.setVisible(false);
}
public ObservableList<Medicine> getMedicine() {
int code = 0, quantity = 0, sgst = 0, cgst = 0, igst = 0;
String name, salt, company, type, batch, hsn, expiry;
float mrp, cost;
medicines = FXCollections.observableArrayList();
try {
Connection dbConnection = JDBC.databaseConnect();
Statement sqlStatement = dbConnection.createStatement();
ResultSet medicineResultSet = sqlStatement.executeQuery("SELECT medicine.medicine_id,medicine.name,medicine.salt,medicine.company,medicine.type,medicine.hsn_number,medicine_info.batch_number,medicine_info.expiry_date,medicine_info.mrp,medicine_info.cost_price,quantity.piece,gst.sgst,gst.cgst,gst.igst FROM medicine JOIN medicine_info ON medicine.medicine_id=medicine_info.medicine_id JOIN quantity ON medicine_info.medicine_info_id=quantity.medicine_info_id JOIN gst ON medicine.medicine_id=gst.medicine_id");
while (medicineResultSet.next()) {
code = medicineResultSet.getInt("medicine_id");
name = medicineResultSet.getString("name");
salt = medicineResultSet.getString("salt");
company = medicineResultSet.getString("company");
type = medicineResultSet.getString("type");
hsn = medicineResultSet.getString("hsn_number");
sgst = medicineResultSet.getInt("sgst");
cgst = medicineResultSet.getInt("cgst");
igst = medicineResultSet.getInt("igst");
batch = medicineResultSet.getString("batch_number");
expiry = medicineResultSet.getString("expiry_date");
mrp = medicineResultSet.getFloat("mrp");
cost = medicineResultSet.getFloat("cost_price");
quantity = medicineResultSet.getInt("piece");
medicines.add(new Medicine(code, name, salt, company, type, hsn, batch, expiry, quantity, mrp, cost, sgst, cgst, igst));
}
} catch (Exception e) {
e.printStackTrace();
}
return medicines;
}
public void advancedSearchMethod() {
if (!advancedSearchedToggle) {
advancedSearch.setText("Advanced Search v");
searchBy.setVisible(true);
searchVBox.setVisible(true);
advancedSearchedToggle = true;
} else {
advancedSearch.setText("Advanced Search >");
searchBy.setVisible(false);
searchVBox.setVisible(false);
advancedSearchedToggle = false;
}
}
}
|
package br.com.blackhubos.eventozero.party;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.entity.Player;
public final class Party {
private final List<Player> members;
private final List<Player> invited;
private final int maxPlayers;
public Party(final int maxPlayers) {
this.members = new ArrayList<>();
this.invited = new ArrayList<>();
this.maxPlayers = maxPlayers;
}
public int getMaxPlayers() {
return this.maxPlayers;
}
public Player getOwner() {
return this.members.get(0);
}
public List<Player> getMembers() {
return this.members;
}
public List<Player> getInvited() {
return this.invited;
}
public Party addMember(final Player player) {
this.members.add(player);
cancelInvite(player);
return this;
}
public Party removeMember(final Player player) {
this.members.remove(player);
return this;
}
public Party invite(final Player player) {
this.invited.add(player);
return this;
}
public Party cancelInvite(final Player player) {
this.invited.remove(player);
return this;
}
}
|
package org.lightmare.remote.rcp;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.lightmare.remote.rcp.wrappers.RcpWrapper;
import org.lightmare.remote.rpc.wrappers.RpcWrapper;
import antlr.debug.MessageEvent;
/**
* Handler @see {@link SimpleChannelHandler} for RPC response
*
* @author levan
* @since 0.0.21-SNAPSHOT
*/
public class RcpHandler extends ChannelInboundHandlerAdapter {
// Responses queue
private BlockingQueue<RcpWrapper> answer;
/**
* Implementation for {@link ChannelFutureListener} for remote procedure
* call
*
* @author levan
*
*/
private static class ResponseListener implements ChannelFutureListener {
private final BlockingQueue<RcpWrapper> answer;
private final MessageEvent ev;
public ResponseListener(final BlockingQueue<RcpWrapper> answer,
final MessageEvent ev) {
this.answer = answer;
this.ev = ev;
}
@Override
public void operationComplete(ChannelFuture future) throws Exception {
boolean offered = answer.offer((RcpWrapper) ev.getMessage());
assert offered;
}
}
public RcpHandler() {
answer = new LinkedBlockingQueue<RcpWrapper>();
}
@Override
public void messageReceived(ChannelHandlerContext ctx, final MessageEvent ev) {
ev.getFuture().getChannel().close().awaitUninterruptibly()
.addListener(new ResponseListener(answer, ev));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
/**
* Gets {@link RpcWrapper} after waiting
*
* @return {@link RpcWrapper}
*/
public RcpWrapper getWrapper() {
RcpWrapper responce;
boolean interrupted = Boolean.TRUE;
for (;;) {
try {
responce = answer.take();
if (interrupted) {
Thread.currentThread().interrupt();
}
return responce;
} catch (InterruptedException ex) {
interrupted = Boolean.FALSE;
}
}
}
}
|
package com.conveyal.taui.models;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include= JsonTypeInfo.As.PROPERTY, property="type")
@JsonSubTypes({
@JsonSubTypes.Type(name = "add-trip-pattern", value = AddTripPattern.class),
@JsonSubTypes.Type(name = "remove-trips", value = RemoveTrips.class),
@JsonSubTypes.Type(name = "remove-stops", value = RemoveStops.class),
@JsonSubTypes.Type(name = "adjust-speed", value = AdjustSpeed.class),
@JsonSubTypes.Type(name = "adjust-dwell-time", value = AdjustDwellTime.class),
@JsonSubTypes.Type(name = "convert-to-frequency", value = ConvertToFrequency.class),
@JsonSubTypes.Type(name = "reroute", value = Reroute.class)
})
public abstract class Modification extends Model implements Cloneable {
/** the type of this modification, see JsonSubTypes annotation above */
public abstract String getType ();
public Modification clone () throws CloneNotSupportedException {
return (Modification) super.clone();
}
/** What project is this modification a part of? */
public String projectId;
/** what variants is this modification a part of? */
public boolean[] variants;
/** is this modification shown on the map in the UI at the moment? */
public boolean showOnMap = true;
/** A description/comment about this modification */
public String description;
public Set<String> feedScopeIds (String feed, String[] ids) {
if (ids == null) return new HashSet<>();
return Arrays.stream(ids).map(id -> feedScopeId(feed, id)).collect(Collectors.toSet());
}
public String feedScopeId (String feed, String id) {
return String.format("%s:%s", feed, id);
}
public abstract com.conveyal.r5.analyst.scenario.Modification toR5 ();
}
|
package edu.wustl.catissuecore.testcase;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import org.junit.Test;
import edu.wustl.catissuecore.actionForm.CollectionProtocolForm;
import edu.wustl.catissuecore.actionForm.ParticipantForm;
import edu.wustl.catissuecore.bean.CollectionProtocolBean;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.Specimen;
import edu.wustl.catissuecore.domain.SpecimenCollectionGroup;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.util.MapDataParser;
/**
* Description : This class will contain following function
* 1. addCollectionProtocol()
* 2. addParticipant().
* 3. EditCollectionProtocolWithCloseActivityStatus().
* @author renuka_bajpai
*
*/
public class CollectionProtocolCloseActivityStatus extends CaTissueSuiteBaseTest
{
/**
* Test Collection Protocol Add.
* @method : testAddCollectionProtocol()
*/
@Test
public void testAddCollectionProtocol()
{
/*Collection Protocol Details*/
setRequestPathInfo("/OpenCollectionProtocol");
addRequestParameter("isParticiapantReg", "true");
addRequestParameter("principalInvestigatorId", "1");
addRequestParameter("title", "CP_11481_" + UniqueKeyGeneratorUtil.getUniqueKey());
addRequestParameter("shortTitle", "CP_11481_" + UniqueKeyGeneratorUtil.getUniqueKey());
addRequestParameter("startDate", "01-12-2009");
addRequestParameter("pageOf", "pageOfCollectionProtocol");
actionPerform();
verifyForward("success");
/*Event Details*/
setRequestPathInfo("/DefineEvents");
addRequestParameter("pageOf", "pageOfDefineEvents");
addRequestParameter("operation", "add");
addRequestParameter("invokeFunction", "null");
actionPerform();
verifyForward("pageOfDefineEvents");
setRequestPathInfo("/SaveProtocolEvents");
//addRequestParameter("pageOf", "pageOfDefineEvents");
RequestParameterUtility.setSaveProtocolEventsParams(this);
//setSaveProtocolEventsParams();
actionPerform();
verifyForwardPath("/CreateSpecimenTemplate.do?operation=add");
//1st specimen requirement.
setRequestPathInfo("/SaveSpecimenRequirements");
addRequestParameter("displayName", "spreq_1_" + UniqueKeyGeneratorUtil.getUniqueKey());
SessionDataBean bean1 = (SessionDataBean) getSession().getAttribute("sessionData");
RequestParameterUtility.setAddSpecimenRequirementParams(this, bean1);
actionPerform();
verifyForward("success");
verifyNoActionErrors();
//2nd specimen requirement.
setRequestPathInfo("/SaveSpecimenRequirements");
addRequestParameter("displayName", "spreq_2_" + UniqueKeyGeneratorUtil.getUniqueKey());
SessionDataBean bean2 = (SessionDataBean) getSession().getAttribute("sessionData");
RequestParameterUtility.setAddSpecimenRequirementParams(this, bean2);
actionPerform();
verifyForward("success");
verifyNoActionErrors();
setRequestPathInfo("/SubmitCollectionProtocol");
addRequestParameter("operation", "add");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
Map innerLoopValues = (Map) getSession().getAttribute("collectionProtocolEventMap");
Collection values = innerLoopValues.values();
CollectionProtocolBean collectionProtocolBean = (CollectionProtocolBean) getSession()
.getAttribute("collectionProtocolBean");
CollectionProtocolForm form = (CollectionProtocolForm) getActionForm();
CollectionProtocol collectionProtocol = new CollectionProtocol();
collectionProtocol.setCollectionProtocolEventCollection(values);
collectionProtocol.setId(collectionProtocolBean.getIdentifier());
collectionProtocol.setActivityStatus(form.getActivityStatus());
collectionProtocol.setTitle(form.getTitle());
collectionProtocol.setShortTitle(form.getShortTitle());
User principalInvestigator = new User();
principalInvestigator.setId(form.getPrincipalInvestigatorId());
collectionProtocol.setPrincipalInvestigator(principalInvestigator);
Date startDate = new Date();
String dd = new String();
String mm = new String();
String yyyy = new String();
dd = form.getStartDate().substring(0, 1);
mm = form.getStartDate().substring(3, 4);
yyyy = form.getStartDate().substring(6, 9);
startDate.setDate(Integer.parseInt(dd));
startDate.setMonth(Integer.parseInt(mm));
startDate.setYear(Integer.parseInt(yyyy));
collectionProtocol.setStartDate(startDate);
TestCaseUtility.setNameObjectMap("CollectionProtocolEventMapCloseActivityStatus",
innerLoopValues);
TestCaseUtility.setNameObjectMap("CollectionProtocolCloseActivityStatus",
collectionProtocol);
}
/**
* Test Participant Add.
* @method : testParticipantAdd()
*/
@Test
public void testParticipantAdd()
{
//Participant add and registration
CollectionProtocol collectionProtocol = (CollectionProtocol) TestCaseUtility
.getNameObjectMap("CollectionProtocolCloseActivityStatus");
RequestParameterUtility.setAddParticipantParams(this, collectionProtocol);
setRequestPathInfo("/ParticipantAdd");
actionPerform();
verifyForward("success");
verifyNoActionErrors();
ParticipantForm form = (ParticipantForm) getActionForm();
Participant participant = new Participant();
participant.setId(form.getId());
participant.setFirstName(form.getFirstName());
participant.setLastName(form.getLastName());
Date birthDate = new Date();
String dd = new String();
String mm = new String();
String yyyy = new String();
dd = form.getBirthDate().substring(0, 1);
mm = form.getBirthDate().substring(3, 4);
yyyy = form.getBirthDate().substring(6, 9);
birthDate.setDate(Integer.parseInt(dd));
birthDate.setMonth(Integer.parseInt(mm));
birthDate.setYear(Integer.parseInt(yyyy));
participant.setBirthDate(birthDate);
Map mapCollectionProtocolRegistrationCollection = form
.getCollectionProtocolRegistrationValues();
MapDataParser parserCollectionProtocolRegistrationCollection = new MapDataParser(
"edu.wustl.catissuecore.domain");
try
{
participant
.setCollectionProtocolRegistrationCollection(parserCollectionProtocolRegistrationCollection
.generateData(mapCollectionProtocolRegistrationCollection));
}
catch (Exception e)
{
e.printStackTrace();
}
TestCaseUtility.setNameObjectMap("ParticipantCloseActivityStatus", participant);
}
/**
*
* Test Specimen Edit.
* @method : testSpecimenEdit()
* @throws BizLogicException
*/
@Test
public void testSpecimenEdit() throws BizLogicException
{
CollectionProtocol collectionProtocol = (CollectionProtocol) TestCaseUtility
.getNameObjectMap("CollectionProtocolCloseActivityStatus");
CollectionProtocolRegistration collectionProtocolRegistration3 = null;
SpecimenCollectionGroup specimenCollectionGroup3 = null;
collectionProtocolRegistration3 = RequestParameterUtility
.getCollectionProtocolRegistration(collectionProtocol);
specimenCollectionGroup3 = RequestParameterUtility
.getSCGFromCpr(collectionProtocolRegistration3);
RequestParameterUtility.specimenEditParams(this, specimenCollectionGroup3.getId());
}
/**
* Test CollectionProtocol Edit. Collection protocol activity status is closed in this case.
* @method : testCollectionProtocolEdit()
*/
@Test
public void testCollectionProtocolEdit()
{
CollectionProtocol collectionProtocol = (CollectionProtocol) TestCaseUtility
.getNameObjectMap("CollectionProtocolCloseActivityStatus");
addRequestParameter("title", collectionProtocol.getTitle());
addRequestParameter("shortTitle", collectionProtocol.getShortTitle());
setRequestPathInfo("/CollectionProtocolEdit");
addRequestParameter("activityStatus", "Closed");
addRequestParameter("operation", "edit");
actionPerform();
verifyForward("success");
TestCaseUtility.setNameObjectMap("CollectionProtocolCloseActivityStatus_edit",
collectionProtocol);
}
/**
* Test Specimen Edit When CP is closed and parent specimen is collected.
* @method :testSpecimenEditWhenCpclosedAndParentSpecimenIsCollected()
* @throws BizLogicException
*/
@Test
public void testSpecimenEditWhenCpclosedAndParentSpecimenIsCollected() throws BizLogicException
{
CollectionProtocol collectionProtocol = (CollectionProtocol) TestCaseUtility
.getNameObjectMap("CollectionProtocolCloseActivityStatus");
CollectionProtocolRegistration collectionProtocolRegistration3 = null;
SpecimenCollectionGroup specimenCollectionGroup3 = null;
collectionProtocolRegistration3 = RequestParameterUtility
.getCollectionProtocolRegistration(collectionProtocol);
specimenCollectionGroup3 = RequestParameterUtility
.getSCGFromCpr(collectionProtocolRegistration3);
Specimen parentSpecimenCollected = (Specimen) TestCaseUtility
.getNameObjectMap("CollectedSpecimen");
RequestParameterUtility.editSpecimenFunction(this, specimenCollectionGroup3.getId());
}
/**
* Test Specimen Edit When CP is closed and parent specimen is not collected.
* @method :testSpecimenEditWhenCpclosedAndParentSpecimenIsNotCollected()
* @throws BizLogicException
*/
@Test
public void testSpecimenEditWhenCpclosedAndParentSpecimenIsNotCollected()
throws BizLogicException
{
CollectionProtocol collectionProtocol = (CollectionProtocol) TestCaseUtility
.getNameObjectMap("CollectionProtocolCloseActivityStatus");
CollectionProtocolRegistration collectionProtocolRegistration3 = null;
SpecimenCollectionGroup specimenCollectionGroup3 = null;
collectionProtocolRegistration3 = RequestParameterUtility
.getCollectionProtocolRegistration(collectionProtocol);
specimenCollectionGroup3 = RequestParameterUtility
.getSCGFromCpr(collectionProtocolRegistration3);
RequestParameterUtility.SpecimenEditCPIsClosed(this, specimenCollectionGroup3.getId());
}
}
|
// modification, are permitted provided that the following conditions are met:
// and/or other materials provided with the distribution.
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
package br.com.carlosrafaelgn.fplay;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils.TruncateAt;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import br.com.carlosrafaelgn.fplay.activity.ActivityVisualizer;
import br.com.carlosrafaelgn.fplay.list.Song;
import br.com.carlosrafaelgn.fplay.list.SongList;
import br.com.carlosrafaelgn.fplay.playback.Player;
import br.com.carlosrafaelgn.fplay.ui.BackgroundActivityMonitor;
import br.com.carlosrafaelgn.fplay.ui.BgButton;
import br.com.carlosrafaelgn.fplay.ui.BgListView;
import br.com.carlosrafaelgn.fplay.ui.BgSeekBar;
import br.com.carlosrafaelgn.fplay.ui.CustomContextMenu;
import br.com.carlosrafaelgn.fplay.ui.UI;
import br.com.carlosrafaelgn.fplay.ui.drawable.BorderDrawable;
import br.com.carlosrafaelgn.fplay.ui.drawable.ColorDrawable;
import br.com.carlosrafaelgn.fplay.ui.drawable.TextIconDrawable;
import br.com.carlosrafaelgn.fplay.util.Timer;
import br.com.carlosrafaelgn.fplay.visualizer.AlbumArtVisualizer;
import br.com.carlosrafaelgn.fplay.visualizer.OpenGLVisualizerJni;
import br.com.carlosrafaelgn.fplay.visualizer.SimpleVisualizerJni;
import br.com.carlosrafaelgn.fplay.visualizer.Visualizer;
//How to create a ListView using ArrayAdapter in Android
//Customizing Android ListView Items with Custom ArrayAdapter
//Communicating with the UI Thread
//Difference of px, dp, dip and sp in Android?
//Supporting Keyboard Navigation
//Why are nested weights bad for performance? Alternatives?
//Maintain/Save/Restore scroll position when returning to a ListView
public final class ActivityMain extends ActivityItemView implements Timer.TimerHandler, Player.PlayerObserver, View.OnClickListener, BgSeekBar.OnBgSeekBarChangeListener, BgListView.OnAttachedObserver, BgListView.OnBgListViewKeyDownObserver, ActivityFileSelection.OnFileSelectionListener, BgButton.OnPressingChangeListener {
private static final int MAX_SEEK = 10000, MNU_ADDSONGS = 100, MNU_CLEARLIST = 101, MNU_LOADLIST = 102, MNU_SAVELIST = 103, MNU_TOGGLECONTROLMODE = 104, MNU_RANDOMMODE = 105, MNU_EFFECTS = 106, MNU_VISUALIZER = 107, MNU_SETTINGS = 108, MNU_EXIT = 109, MNU_SORT_BY_TITLE = 110, MNU_SORT_BY_ARTIST = 111, MNU_SORT_BY_ALBUM = 112, MNU_VISUALIZER_SPECTRUM = 113, MNU_REPEAT = 114, MNU_REPEATONE = 115, MNU_VISUALIZER_BLUETOOTH = 116, MNU_VISUALIZER_LIQUID = 117, MNU_VISUALIZER_SPIN = 118, MNU_VISUALIZER_PARTICLE = 119, MNU_VISUALIZER_IMMERSIVE_PARTICLE = 120, MNU_VISUALIZER_ALBUMART = 121;
private View vwVolume;
private TextView lblTitle, lblArtist, lblTrack, lblAlbum, lblLength, lblMsgSelMove;
private TextIconDrawable lblTitleIcon;
private BgSeekBar barSeek, barVolume;
private ViewGroup panelControls, panelSecondary, panelSelection;
private BgButton btnAdd, btnPrev, btnPlay, btnNext, btnMenu, btnMoveSel, btnRemoveSel, btnCancelSel, btnDecreaseVolume, btnIncreaseVolume, btnVolume;
private BgListView list;
private Timer tmrSong, tmrUpdateVolumeDisplay, tmrVolume;
private int firstSel, lastSel, lastTime, volumeButtonPressed, tmrVolumeInitialDelay, vwVolumeId;
private boolean selectCurrentWhenAttached, skipToDestruction, forceFadeOut, isCreatingLayout, isBackgroundSet;//, ignoreAnnouncement;
private StringBuilder timeBuilder, volumeBuilder;
public static boolean localeHasBeenChanged;
@Override
public CharSequence getTitle() {
final Song currentSong = Player.localSong;
return "FPlay: " + ((currentSong == null) ? getText(R.string.nothing_playing) : currentSong.title);
}
private void saveListViewPosition() {
if (list != null && list.getAdapter() != null) {
final int i = list.getFirstVisiblePosition();
if (i < 0)
return;
final View v = list.getChildAt(0);
Player.listFirst = i;
Player.listTop = ((v == null) ? 0 : v.getTop());
}
}
private void restoreListViewPosition(boolean selectCurrent) {
if (list != null) {
if (Player.positionToSelect >= 0) {
list.centerItem(Player.positionToSelect);
Player.positionToSelect = -1;
return;
}
final int c = Player.songs.getCurrentPosition();
if (Player.listFirst >= 0 && (!selectCurrent || Player.songs.selecting || Player.songs.moving)) {
list.setSelectionFromTop(Player.listFirst, Player.listTop);
} else {
if (selectCurrent && Player.lastCurrent != c && c >= 0) {
if (Player.songs.getSelection() != c)
Player.songs.setSelection(c, true);
list.centerItem(c);
} else {
if (Player.listFirst >= 0)
list.setSelectionFromTop(Player.listFirst, Player.listTop);
else
list.centerItem(Player.songs.getSelection());
}
}
Player.lastCurrent = -1;
}
}
private String volumeToString(int volume) {
switch (Player.volumeControlType) {
case Player.VOLUME_CONTROL_STREAM:
//The parameter volume is only used to help properly synchronize when
//Player.volumeControlType == Player.VOLUME_CONTROL_STREAM
return Integer.toString(volume);
case Player.VOLUME_CONTROL_DB:
if (volume <= Player.VOLUME_MIN_DB)
return "-\u221E dB";
if (volume >= 0)
return "-0.00 dB";
volume = -volume;
volumeBuilder.delete(0, volumeBuilder.length());
volumeBuilder.append('-');
volumeBuilder.append(volume / 100);
volumeBuilder.append('.');
volume %= 100;
if (volume < 10)
volumeBuilder.append('0');
volumeBuilder.append(volume);
volumeBuilder.append(" dB");
return volumeBuilder.toString();
default:
volumeBuilder.delete(0, volumeBuilder.length());
volumeBuilder.append(Player.getVolumeInPercentage());
volumeBuilder.append('%');
return volumeBuilder.toString();
}
}
private void setVolumeIcon(int volume) {
if (btnVolume != null) {
final int max;
switch (Player.volumeControlType) {
case Player.VOLUME_CONTROL_STREAM:
//The parameter volume is only used to help properly synchronize when
//Player.volumeControlType == Player.VOLUME_CONTROL_STREAM
max = Player.volumeStreamMax;
break;
case Player.VOLUME_CONTROL_DB:
case Player.VOLUME_CONTROL_PERCENT:
max = -Player.VOLUME_MIN_DB;
volume += max;
break;
default:
btnVolume.setText(UI.ICON_VOLUME4);
return;
}
if (volume == max)
btnVolume.setText(UI.ICON_VOLUME4);
else if (volume == 0)
btnVolume.setText(UI.ICON_VOLUME0);
else if (volume > ((max + 1) >> 1))
btnVolume.setText(UI.ICON_VOLUME3);
else if (volume > (max >> 2))
btnVolume.setText(UI.ICON_VOLUME2);
else
btnVolume.setText(UI.ICON_VOLUME1);
}
}
private void updateVolumeDisplay(int volume) {
final int value;
if (Player.volumeControlType == Player.VOLUME_CONTROL_STREAM) {
if (volume == Integer.MIN_VALUE)
volume = Player.getSystemStreamVolume();
value = volume;
} else {
if (volume == Integer.MIN_VALUE)
volume = Player.localVolumeDB;
value = (volume - Player.VOLUME_MIN_DB) / 5;
}
if (barVolume != null) {
barVolume.setValue(value);
barVolume.setText(volumeToString(volume));
} else {
setVolumeIcon(volume);
}
}
@SuppressWarnings("deprecation")
private void startSelecting() {
if (firstSel >= 0) {
if (UI.isLargeScreen) {
final ViewGroup.LayoutParams p = lblMsgSelMove.getLayoutParams();
if (p.height != UI.defaultControlSize) {
p.height = UI.defaultControlSize;
lblMsgSelMove.setLayoutParams(p);
}
} else if (!UI.isLandscape) {
final int h = (UI.defaultControlSize << 1) + panelControls.getPaddingBottom() + panelSecondary.getPaddingBottom();
final ViewGroup.LayoutParams p = panelSelection.getLayoutParams();
if (p != null && p.height != h) {
p.height = h;
panelSelection.setLayoutParams(p);
}
if (!isBackgroundSet && UI.animationEnabled) {
isBackgroundSet = true;
((View)panelControls.getParent()).setBackgroundDrawable(new ColorDrawable(UI.color_window));
}
}
UI.animationReset();
UI.animationAddViewToShow(btnMoveSel);
UI.animationAddViewToShow(btnRemoveSel);
btnCancelSel.setText(R.string.cancel);
UI.animationAddViewToHide(panelControls);
UI.animationAddViewToHide(panelSecondary);
UI.animationAddViewToShow(panelSelection);
lblMsgSelMove.setText(R.string.msg_sel);
if (!UI.isLargeScreen)
UI.animationAddViewToHide(lblTitle);
UI.animationAddViewToShow(lblMsgSelMove);
lblMsgSelMove.setSelected(true);
if (UI.isLargeScreen) {
btnCancelSel.setNextFocusLeftId(R.id.btnRemoveSel);
UI.setNextFocusForwardId(list, R.id.btnMoveSel);
} else if (UI.isLandscape) {
btnCancelSel.setNextFocusUpId(R.id.btnRemoveSel);
UI.setNextFocusForwardId(list, R.id.btnMoveSel);
} else {
btnCancelSel.setNextFocusRightId(R.id.btnMoveSel);
UI.setNextFocusForwardId(btnCancelSel, R.id.btnMoveSel);
UI.setNextFocusForwardId(list, R.id.btnCancelSel);
}
Player.songs.selecting = true;
Player.songs.moving = false;
list.skipUpDownTranslation = true;
UI.animationCommit(isCreatingLayout, null);
}
}
private void startMovingSelection() {
if (Player.songs.getFirstSelectedPosition() >= 0) {
UI.animationReset();
UI.animationAddViewToHide(btnMoveSel);//.setVisibility(View.INVISIBLE);
UI.animationAddViewToHide(btnRemoveSel);//.setVisibility(View.INVISIBLE);
UI.animationCommit(isCreatingLayout, null);
btnCancelSel.setText(R.string.done);
lblMsgSelMove.setText(R.string.msg_move);
lblMsgSelMove.setSelected(true);
if (UI.isLargeScreen) {
btnCancelSel.setNextFocusLeftId(R.id.list);
} else if (UI.isLandscape) {
btnCancelSel.setNextFocusUpId(R.id.list);
} else {
btnCancelSel.setNextFocusRightId(R.id.list);
UI.setNextFocusForwardId(btnCancelSel, R.id.list);
}
UI.setNextFocusForwardId(list, R.id.btnCancelSel);
Player.songs.selecting = false;
Player.songs.moving = true;
list.skipUpDownTranslation = true;
}
}
private void removeSelection() {
if (Player.songs.getFirstSelectedPosition() >= 0) {
Player.songs.removeSelection();
cancelSelection(true);
} else {
list.skipUpDownTranslation = false;
}
}
private void cancelSelection(boolean removed) {
if (list.isInTouchMode()) {
final int p = Player.songs.getCurrentPosition();
if (p >= 0 && p < Player.songs.getCount())
Player.songs.setSelection(p, true);
else
Player.songs.setSelection(-1, true);
} else if (!removed && firstSel >= 0 && lastSel >= 0) {
int p = Player.songs.getSelection();
if (p < 0)
p = ((firstSel < lastSel) ? Player.songs.getFirstSelectedPosition() : Player.songs.getLastSelectedPosition());
Player.songs.setSelection(p, false);
}
Player.songs.selecting = false;
Player.songs.moving = false;
list.skipUpDownTranslation = false;
firstSel = -1;
lastSel = -1;
UI.animationReset();
UI.animationAddViewToHide(lblMsgSelMove);
if (!UI.isLargeScreen)
UI.animationAddViewToShow(lblTitle);
lblTitle.setSelected(true);
UI.animationAddViewToHide(panelSelection);
UI.setNextFocusForwardId(list, UI.isLargeScreen ? vwVolumeId : R.id.btnPrev);
UI.animationAddViewToShow(panelControls);
UI.animationAddViewToShow(panelSecondary);
UI.animationCommit(isCreatingLayout, null);
}
private void bringCurrentIntoView() {
if (!Player.songs.moving && !Player.songs.selecting) {
final int p = Player.songs.getCurrentPosition();
if (p <= list.getFirstVisiblePosition() || p >= list.getLastVisiblePosition())
list.centerItemSmoothly(p);
}
}
private void addSongs(View sourceView) {
if (Player.state == Player.STATE_ALIVE) {
Player.alreadySelected = false;
startActivity(new ActivityBrowser2(), 0, sourceView, sourceView != null);
}
}
private boolean decreaseVolume() {
final int volume = Player.decreaseVolume();
if (volume != Integer.MIN_VALUE) {
setVolumeIcon(volume);
return true;
}
return false;
}
private boolean increaseVolume() {
final int volume = Player.increaseVolume();
if (volume != Integer.MIN_VALUE) {
setVolumeIcon(volume);
return true;
}
return false;
}
@Override
public void onPlayerChanged(Song currentSong, boolean songHasChanged, boolean preparingHasChanged, Throwable ex) {
final String icon = (Player.localPlaying ? UI.ICON_PAUSE : UI.ICON_PLAY);
if (btnPlay != null) {
btnPlay.setText(icon);
btnPlay.setContentDescription(getText(Player.localPlaying ? R.string.pause : R.string.play));
}
if (lblTitleIcon != null)
lblTitleIcon.setIcon(icon);
if (songHasChanged) {
if (lblTitle != null) {
lblTitle.setText((currentSong == null) ? getText(R.string.nothing_playing) : ((barSeek == null && Player.isPreparing()) ? (getText(R.string.loading) + " " + currentSong.title) : currentSong.title));
lblTitle.setSelected(true);
//if (ignoreAnnouncement)
// ignoreAnnouncement = false;
//else if (UI.accessibilityManager != null && UI.accessibilityManager.isEnabled())
// UI.announceAccessibilityText(title);
}
if (lblArtist != null)
lblArtist.setText((currentSong == null) ? "-" : currentSong.artist);
if (lblTrack != null)
lblTrack.setText((currentSong == null || currentSong.track <= 0) ? "-" : Integer.toString(currentSong.track));
if (lblAlbum != null)
lblAlbum.setText((currentSong == null) ? "-" : currentSong.album);
if (lblLength != null)
lblLength.setText((currentSong == null) ? "-" : currentSong.length);
} else if (preparingHasChanged) {
if (barSeek != null) {
if (Player.isPreparing() && !barSeek.isTracking()) {
barSeek.setText(R.string.loading);
barSeek.setValue(0);
}
} else if (lblTitle != null) {
lblTitle.setText((currentSong == null) ? getText(R.string.nothing_playing) : (Player.isPreparing() ? (getText(R.string.loading) + " " + currentSong.title) : currentSong.title));
lblTitle.setSelected(true);
}
}
if (Player.localPlaying && !Player.controlMode) {
if (!tmrSong.isAlive())
tmrSong.start(250);
} else {
tmrSong.stop();
}
lastTime = -2;
handleTimer(tmrSong, null);
}
@Override
public void onPlayerControlModeChanged(boolean controlMode) {
if (Player.songs.selecting || Player.songs.moving)
cancelSelection(false);
if (controlMode)
Player.lastCurrent = Player.songs.getCurrentPosition();
onCleanupLayout();
forceFadeOut = !controlMode;
onCreateLayout(false);
forceFadeOut = false;
resume(true);
System.gc();
}
@Override
public void onPlayerGlobalVolumeChanged(int volume) {
updateVolumeDisplay(volume);
}
@Override
public void onPlayerAudioSinkChanged(int audioSink) {
//when changing the output, the global volume usually changes
if (Player.volumeControlType == Player.VOLUME_CONTROL_STREAM) {
updateVolumeDisplay(Integer.MIN_VALUE);
if (barVolume != null)
barVolume.setMax(Player.volumeStreamMax);
tmrUpdateVolumeDisplay.start(750);
}
}
@Override
public void onPlayerMediaButtonPrevious() {
if (!Player.controlMode)
bringCurrentIntoView();
}
@Override
public void onPlayerMediaButtonNext() {
if (!Player.controlMode)
bringCurrentIntoView();
}
@Override
public View getNullContextMenuView() {
return ((!Player.songs.selecting && !Player.songs.moving && Player.state == Player.STATE_ALIVE) ? btnMenu : null);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
if (UI.forcedLocale != UI.LOCALE_NONE && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN && !localeHasBeenChanged) {
localeHasBeenChanged = true;
UI.reapplyForcedLocale(getApplication(), getHostActivity());
}
UI.prepare(menu);
menu.add(0, MNU_ADDSONGS, 0, R.string.add_songs)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_FPLAY));
UI.separator(menu, 0, 1);
Menu s2, s = menu.addSubMenu(1, 0, 0, R.string.list)
.setIcon(new TextIconDrawable(UI.ICON_LIST));
UI.prepare(s);
s.add(0, MNU_CLEARLIST, 0, R.string.clear_list)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_REMOVE));
s.add(0, MNU_LOADLIST, 1, R.string.load_list)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_LOAD));
s.add(0, MNU_SAVELIST, 2, R.string.save_list)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_SAVE));
UI.separator(s, 0, 3);
s.add(0, MNU_SORT_BY_TITLE, 4, R.string.sort_by_title)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_MOVE));
s.add(0, MNU_SORT_BY_ARTIST, 5, R.string.sort_by_artist)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_MOVE));
s.add(0, MNU_SORT_BY_ALBUM, 6, R.string.sort_by_album)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_MOVE));
UI.separator(menu, 1, 1);
menu.add(2, MNU_TOGGLECONTROLMODE, 0, R.string.control_mode)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(Player.controlMode ? UI.ICON_OPTCHK : UI.ICON_OPTUNCHK));
if (UI.isLandscape && !UI.isLargeScreen) {
s = menu.addSubMenu(2, 0, 1, R.string.more)
.setIcon(new TextIconDrawable(UI.ICON_MENU));
UI.prepare(s);
} else {
s = menu;
}
if (Player.songs.isRepeatingOne()) {
s2 = s.addSubMenu(2, 0, 0, getText(R.string.repeat_one) + "\u2026")
.setIcon(new TextIconDrawable(UI.ICON_REPEATONE));
} else if (Player.songs.isInRandomMode()) {
s2 = s.addSubMenu(2, 0, 0, getText(R.string.random_mode) + "\u2026")
.setIcon(new TextIconDrawable(UI.ICON_SHUFFLE));
} else {
s2 = s.addSubMenu(2, 0, 0, getText(R.string.repeat_all) + "\u2026")
.setIcon(new TextIconDrawable(UI.ICON_REPEAT));
}
UI.prepare(s2);
s2.add(2, MNU_REPEAT, 0, getText(R.string.repeat_all))
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable((Player.songs.isRepeatingOne() || Player.songs.isInRandomMode()) ? UI.ICON_RADIOUNCHK : UI.ICON_RADIOCHK));
s2.add(2, MNU_REPEATONE, 0, getText(R.string.repeat_one))
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(Player.songs.isRepeatingOne() ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK));
s2.add(2, MNU_RANDOMMODE, 0, getText(R.string.random_mode))
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(Player.songs.isInRandomMode() ? UI.ICON_RADIOCHK : UI.ICON_RADIOUNCHK));
UI.separator(s, 2, 1);
s.add(2, MNU_EFFECTS, 2, R.string.audio_effects)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_EQUALIZER));
s2 = s.addSubMenu(2, 0, 3, getText(R.string.visualizer) + "\u2026")
.setIcon(new TextIconDrawable(UI.ICON_VISUALIZER));
UI.prepare(s2);
s2.add(2, MNU_VISUALIZER_SPECTRUM, 0, "Spectrum")
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_VISUALIZER));
s2.add(2, MNU_VISUALIZER_SPIN, 1, "Spinning Rainbow")
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_VISUALIZER));
s2.add(2, MNU_VISUALIZER_PARTICLE, 2, "Sound Particles")
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_VISUALIZER));
s2.add(2, MNU_VISUALIZER_IMMERSIVE_PARTICLE, 3, "Into the Particles")
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_3DPAN));
UI.separator(s2, 2, 4);
s2.add(2, MNU_VISUALIZER_ALBUMART, 5, R.string.album_art)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_ALBUMART));
s2.add(2, MNU_VISUALIZER_BLUETOOTH, 6, "Bluetooth + Arduino")
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_BLUETOOTH));
UI.separator(s2, 2, 7);
s2.add(2, MNU_VISUALIZER_LIQUID, 8, "Liquid Spectrum")
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_VISUALIZER));
s2.add(2, MNU_VISUALIZER, 9, "Classic")
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_VISUALIZER));
s.add(2, MNU_SETTINGS, 4, R.string.settings)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_SETTINGS));
UI.separator(menu, 2, 5);
menu.add(3, MNU_EXIT, 0, R.string.exit)
.setOnMenuItemClickListener(this)
.setIcon(new TextIconDrawable(UI.ICON_EXIT));
}
@Override
public boolean onMenuItemClick(MenuItem item) {
final int id = item.getItemId();
if (id == MNU_EXIT) {
getHostActivity().setExitOnDestroy(true);
Player.pause();
finish(0, null, false);
return true;
}
if (Player.state != Player.STATE_ALIVE)
return true;
switch (item.getItemId()) {
case MNU_ADDSONGS:
addSongs(null);
break;
case MNU_CLEARLIST:
Player.songs.clear();
break;
case MNU_LOADLIST:
Player.alreadySelected = false;
startActivity(new ActivityFileSelection(getText(R.string.load_list), MNU_LOADLIST, false, true, getText(R.string.item_list).toString(), "#lst", this), 0, null, false);
break;
case MNU_SAVELIST:
startActivity(new ActivityFileSelection(getText(R.string.save_list), MNU_SAVELIST, true, false, getText(R.string.item_list).toString(), "#lst", this), 0, null, false);
break;
case MNU_SORT_BY_TITLE:
Player.songs.sort(SongList.SORT_BY_TITLE);
break;
case MNU_SORT_BY_ARTIST:
Player.songs.sort(SongList.SORT_BY_ARTIST);
break;
case MNU_SORT_BY_ALBUM:
Player.songs.sort(SongList.SORT_BY_ALBUM);
break;
case MNU_TOGGLECONTROLMODE:
Player.setControlMode(!Player.controlMode);
break;
case MNU_REPEAT:
Player.songs.setRepeatingOne(false);
Player.songs.setRandomMode(false);
break;
case MNU_REPEATONE:
Player.songs.setRepeatingOne(true);
break;
case MNU_RANDOMMODE:
Player.songs.setRandomMode(!Player.songs.isInRandomMode());
break;
case MNU_EFFECTS:
startActivity(new ActivityEffects(), 0, null, false);
break;
case MNU_VISUALIZER:
getHostActivity().startActivity((new Intent(getApplication(), ActivityVisualizer.class)).putExtra(Visualizer.EXTRA_VISUALIZER_CLASS_NAME, SimpleVisualizerJni.class.getName()));
break;
case MNU_VISUALIZER_SPECTRUM:
getHostActivity().startActivity((new Intent(getApplication(), ActivityVisualizer.class)).putExtra(Visualizer.EXTRA_VISUALIZER_CLASS_NAME, OpenGLVisualizerJni.class.getName()));
break;
case MNU_VISUALIZER_LIQUID:
getHostActivity().startActivity((new Intent(getApplication(), ActivityVisualizer.class)).putExtra(Visualizer.EXTRA_VISUALIZER_CLASS_NAME, OpenGLVisualizerJni.class.getName()).putExtra(OpenGLVisualizerJni.EXTRA_VISUALIZER_TYPE, OpenGLVisualizerJni.TYPE_LIQUID));
break;
case MNU_VISUALIZER_SPIN:
getHostActivity().startActivity((new Intent(getApplication(), ActivityVisualizer.class)).putExtra(Visualizer.EXTRA_VISUALIZER_CLASS_NAME, OpenGLVisualizerJni.class.getName()).putExtra(OpenGLVisualizerJni.EXTRA_VISUALIZER_TYPE, OpenGLVisualizerJni.TYPE_SPIN));
break;
case MNU_VISUALIZER_PARTICLE:
getHostActivity().startActivity((new Intent(getApplication(), ActivityVisualizer.class)).putExtra(Visualizer.EXTRA_VISUALIZER_CLASS_NAME, OpenGLVisualizerJni.class.getName()).putExtra(OpenGLVisualizerJni.EXTRA_VISUALIZER_TYPE, OpenGLVisualizerJni.TYPE_PARTICLE));
break;
case MNU_VISUALIZER_IMMERSIVE_PARTICLE:
getHostActivity().startActivity((new Intent(getApplication(), ActivityVisualizer.class)).putExtra(Visualizer.EXTRA_VISUALIZER_CLASS_NAME, OpenGLVisualizerJni.class.getName()).putExtra(OpenGLVisualizerJni.EXTRA_VISUALIZER_TYPE, OpenGLVisualizerJni.TYPE_IMMERSIVE_PARTICLE));
break;
case MNU_VISUALIZER_BLUETOOTH:
startActivity(new ActivitySettings(false, true), 0, null, false);
break;
case MNU_VISUALIZER_ALBUMART:
getHostActivity().startActivity((new Intent(getApplication(), ActivityVisualizer.class)).putExtra(Visualizer.EXTRA_VISUALIZER_CLASS_NAME, AlbumArtVisualizer.class.getName()));
break;
case MNU_SETTINGS:
startActivity(new ActivitySettings(false, false), 0, null, false);
break;
}
return true;
}
@Override
public void onClick(View view) {
if (view == btnAdd) {
addSongs(view);
} else if (view == btnPrev) {
Player.previous();
if (!Player.controlMode)
bringCurrentIntoView();
} else if (view == btnPlay) {
Player.playPause();
} else if (view == btnNext) {
Player.next();
if (!Player.controlMode)
bringCurrentIntoView();
} else if (view == btnMenu) {
CustomContextMenu.openContextMenu(btnMenu, this);
} else if (view == btnMoveSel) {
startMovingSelection();
} else if (view == btnRemoveSel) {
removeSelection();
} else if (view == btnCancelSel) {
cancelSelection(false);
} else if (view == btnDecreaseVolume) {
//this click will only actually perform an action when triggered by keys
if (volumeButtonPressed == 0)
decreaseVolume();
} else if (view == btnIncreaseVolume) {
//this click will only actually perform an action when triggered by keys
if (volumeButtonPressed == 0)
increaseVolume();
} else if (view == btnVolume) {
Player.showStreamVolumeUI();
} else if (view == lblTitle) {
if (Player.controlMode)
Player.playPause();
} else if (view == list) {
if (Player.songs.getCount() == 0)
addSongs(view);
}
}
@Override
public void processItemClick(int position) {
if (Player.songs.selecting) {
lastSel = position;
Player.songs.setSelection(firstSel, position, position, true, true);
} else if (Player.songs.moving) {
Player.songs.moveSelection(position);
} else {
if (UI.doubleClickMode) {
if (Player.songs.getFirstSelectedPosition() == position) {
if (Player.songs.getItemT(position) == Player.localSong && !Player.localPlaying)
Player.playPause();
else
Player.play(position);
} else {
Player.songs.setSelection(position, position, true, true);
}
} else {
Player.songs.setSelection(position, position, true, true);
if (Player.songs.getItemT(position) == Player.localSong && !Player.localPlaying)
Player.playPause();
else
Player.play(position);
}
}
}
@Override
public void processItemLongClick(int position) {
if (!Player.songs.selecting && !Player.songs.moving) {
//select the clicked item before opening the menu
if (!Player.songs.isSelected(position))
Player.songs.setSelection(position, position, position, true, true);
firstSel = Player.songs.getFirstSelectedPosition();
lastSel = firstSel;
startSelecting();
}
}
@Override
public boolean onBackPressed() {
/*if (Player.controlMode) {
Player.setControlMode(false);
return true;
} else*/ if (Player.songs.selecting || Player.songs.moving) {
cancelSelection(false);
return true;
}
return UI.blockBackKey;
}
@Override
protected void onCreate() {
if (Player.state >= Player.STATE_TERMINATING) {
skipToDestruction = true;
return;
} else {
skipToDestruction = false;
}
localeHasBeenChanged = false;
addWindowFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
if (UI.keepScreenOn)
addWindowFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
else
clearWindowFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (UI.notFullscreen)
clearWindowFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
getHostActivity().setRequestedOrientation((UI.forcedOrientation == 0) ? ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED : ((UI.forcedOrientation < 0) ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT));
//whenever the activity is being displayed, the volume keys must control
//the music volume and nothing else!
getHostActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC);
Player.songs.selecting = false;
Player.songs.moving = false;
firstSel = -1;
lastSel = -1;
lastTime = -2;
timeBuilder = new StringBuilder(16);
volumeBuilder = new StringBuilder(16);
tmrSong = new Timer(this, "Song Timer", false, true, true);
tmrUpdateVolumeDisplay = new Timer(this, "Update Volume Display Timer", true, true, false);
tmrVolume = new Timer(this, "Volume Timer", false, true, true);
}
@SuppressWarnings("deprecation")
@Override
protected void onCreateLayout(boolean firstCreation) {
if (Player.state >= Player.STATE_TERMINATING || skipToDestruction) {
skipToDestruction = true;
finish(0, null, false);
return;
}
setContentView(Player.controlMode ? (UI.isLandscape ? R.layout.activity_main_control_l : R.layout.activity_main_control) : (UI.isLandscape ? ((UI.isLargeScreen && UI.controlsToTheLeft) ? R.layout.activity_main_l_left : R.layout.activity_main_l) : R.layout.activity_main), true, forceFadeOut);
lblTitle = (TextView)findViewById(R.id.lblTitle);
btnPrev = (BgButton)findViewById(R.id.btnPrev);
btnPrev.setOnClickListener(this);
btnNext = (BgButton)findViewById(R.id.btnNext);
btnNext.setOnClickListener(this);
btnMenu = (BgButton)findViewById(R.id.btnMenu);
btnMenu.setOnClickListener(this);
if (Player.controlMode) {
findViewById(R.id.panelControls).setBackgroundDrawable(new ColorDrawable(UI.color_control_mode));
UI.largeText(lblTitle);
btnPrev.setIconNoChanges(UI.ICON_PREV);
btnNext.setIconNoChanges(UI.ICON_NEXT);
btnMenu.setIconNoChanges(UI.ICON_MENU);
btnPrev.setIconStretchable(true);
btnNext.setIconStretchable(true);
btnMenu.setIconStretchable(true);
volumeButtonPressed = 0;
btnDecreaseVolume = (BgButton)findViewById(R.id.btnDecreaseVolume);
btnDecreaseVolume.setOnClickListener(this);
btnDecreaseVolume.setOnPressingChangeListener(this);
btnDecreaseVolume.setIconNoChanges(UI.ICON_DECREASE_VOLUME);
btnDecreaseVolume.setIconStretchable(true);
btnIncreaseVolume = (BgButton)findViewById(R.id.btnIncreaseVolume);
btnIncreaseVolume.setOnClickListener(this);
btnIncreaseVolume.setOnPressingChangeListener(this);
btnIncreaseVolume.setIconNoChanges(UI.ICON_INCREASE_VOLUME);
btnIncreaseVolume.setIconStretchable(true);
btnVolume = (BgButton)findViewById(R.id.btnVolume);
btnVolume.setIconNoChanges(UI.ICON_VOLUME0);
btnVolume.setIconStretchable(true);
btnVolume.setEnabled(false);
Player.songs.selecting = false;
Player.songs.moving = false;
lblTitle.setOnClickListener(this);
final int w = getDecorViewWidth(), h = getDecorViewHeight();
final int min, max;
if (w < h) {
min = w;
max = h;
} else {
min = h;
max = w;
}
int panelH = (UI.isLandscape ? ((min * 25) / 100) : ((max * 14) / 100));
if (!UI.isLandscape && panelH > (min >> 2))
panelH = (min >> 2);
findViewById(R.id.panelTop).setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, panelH));
RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(panelH, panelH);
rp.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
btnDecreaseVolume.setLayoutParams(rp);
rp = new RelativeLayout.LayoutParams(panelH, panelH);
rp.addRule(RelativeLayout.RIGHT_OF, R.id.btnDecreaseVolume);
btnVolume.setLayoutParams(rp);
rp = new RelativeLayout.LayoutParams(panelH, panelH);
rp.addRule(RelativeLayout.RIGHT_OF, R.id.btnVolume);
btnIncreaseVolume.setLayoutParams(rp);
rp = new RelativeLayout.LayoutParams(panelH, panelH);
rp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
btnMenu.setLayoutParams(rp);
lblTitleIcon = new TextIconDrawable(UI.ICON_PLAY, UI.colorState_text_control_mode_reactive.getDefaultColor(), panelH >> 1);
lblTitle.setCompoundDrawables(null, null, lblTitleIcon, null);
final int lds = ((UI.isLowDpiScreen && !UI.isLargeScreen) ? (UI.isLandscape ? ((UI.controlMargin * 3) >> 1) : UI.controlMargin) : UI.controlLargeMargin);
btnDecreaseVolume.setPadding(lds, lds, lds, lds);
btnIncreaseVolume.setPadding(lds, lds, lds, lds);
btnVolume.setPadding(lds, lds, lds, lds);
btnMenu.setPadding(lds, lds, lds, lds);
if (UI.isLandscape) {
lblTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, (min * 9) / 100);
final int pa = (min * 7) / 100;
btnPrev.setPadding(pa, pa, pa, pa);
btnNext.setPadding(pa, pa, pa, pa);
} else {
LinearLayout.LayoutParams p2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, (max * 40) / 100);
p2.topMargin = UI.controlLargeMargin;
p2.bottomMargin = UI.controlLargeMargin;
lblTitle.setLayoutParams(p2);
lblTitle.setTextSize(TypedValue.COMPLEX_UNIT_PX, (max * 5) / 100);
final int ph = (min * 12) / 100, pv = (max * 12) / 100;
btnPrev.setPadding(ph, pv, ph, pv);
btnNext.setPadding(ph, pv, ph, pv);
}
btnDecreaseVolume.setTextColor(UI.colorState_text_control_mode_reactive);
btnVolume.setTextColor(UI.colorState_text_control_mode_reactive);
btnIncreaseVolume.setTextColor(UI.colorState_text_control_mode_reactive);
btnMenu.setTextColor(UI.colorState_text_control_mode_reactive);
lblTitle.setTextColor(UI.colorState_text_control_mode_reactive);
btnPrev.setTextColor(UI.colorState_text_control_mode_reactive);
btnNext.setTextColor(UI.colorState_text_control_mode_reactive);
} else {
UI.largeText(lblTitle);
btnPrev.setIcon(UI.ICON_PREV);
btnNext.setIcon(UI.ICON_NEXT);
btnMenu.setIcon(UI.ICON_MENU);
btnAdd = (BgButton)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnAdd.setIcon(UI.ICON_FPLAY);
if (!UI.marqueeTitle) {
lblTitle.setEllipsize(TruncateAt.END);
lblTitle.setHorizontallyScrolling(false);
} else {
lblTitle.setHorizontalFadingEdgeEnabled(false);
lblTitle.setVerticalFadingEdgeEnabled(false);
lblTitle.setFadingEdgeLength(0);
}
lblTitle.setTextColor(UI.colorState_text_title_static);
lblArtist = (TextView)findViewById(R.id.lblArtist);
if (UI.isLargeScreen != (lblArtist != null))
UI.isLargeScreen = (lblArtist != null);
lblMsgSelMove = (TextView)findViewById(R.id.lblMsgSelMove);
UI.largeText(lblMsgSelMove);
lblMsgSelMove.setTextColor(UI.colorState_text_title_static);
lblMsgSelMove.setHorizontalFadingEdgeEnabled(false);
lblMsgSelMove.setVerticalFadingEdgeEnabled(false);
lblMsgSelMove.setFadingEdgeLength(0);
barSeek = (BgSeekBar)findViewById(R.id.barSeek);
barSeek.setAdditionalContentDescription(getText(R.string.go_to).toString());
barSeek.setOnBgSeekBarChangeListener(this);
barSeek.setMax(MAX_SEEK);
barSeek.setVertical(UI.isLandscape && !UI.isLargeScreen);
barSeek.setFocusable(false);
btnPlay = (BgButton)findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(this);
btnPlay.setIcon(UI.ICON_PLAY);
list = (BgListView)findViewById(R.id.list);
list.setScrollBarType(UI.songListScrollBarType);
list.setOnKeyDownObserver(this);
list.setEmptyListOnClickListener(this);
//Apparently, not all devices can properly draw the character ♫ :(
final String originalText = getText(R.string.touch_to_add_songs).toString();
final int iconIdx = originalText.indexOf('\u266B');
if (iconIdx > 0) {
final SpannableStringBuilder txt = new SpannableStringBuilder(originalText);
txt.setSpan(new ImageSpan(new TextIconDrawable(UI.ICON_FPLAY, UI.color_text_disabled, UI._22sp, 0), DynamicDrawableSpan.ALIGN_BASELINE), iconIdx, iconIdx + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
list.setCustomEmptyText(txt);
} else {
list.setCustomEmptyText(originalText);
}
panelControls = (ViewGroup)findViewById(R.id.panelControls);
panelSecondary = (ViewGroup)findViewById(R.id.panelSecondary);
panelSelection = (ViewGroup)findViewById(R.id.panelSelection);
btnMoveSel = (BgButton)findViewById(R.id.btnMoveSel);
btnMoveSel.setOnClickListener(this);
btnMoveSel.setIcon(UI.ICON_MOVE, UI.isLargeScreen || !UI.isLandscape, true);
btnRemoveSel = (BgButton)findViewById(R.id.btnRemoveSel);
btnRemoveSel.setOnClickListener(this);
btnRemoveSel.setIcon(UI.ICON_DELETE, UI.isLargeScreen || !UI.isLandscape, true);
btnCancelSel = (BgButton)findViewById(R.id.btnCancelSel);
btnCancelSel.setOnClickListener(this);
barVolume = (BgSeekBar)findViewById(R.id.barVolume);
btnVolume = (BgButton)findViewById(R.id.btnVolume);
if (UI.isLargeScreen) {
UI.mediumTextAndColor((TextView)findViewById(R.id.lblTitleStatic));
UI.mediumTextAndColor((TextView)findViewById(R.id.lblArtistStatic));
UI.mediumTextAndColor((TextView)findViewById(R.id.lblTrackStatic));
UI.mediumTextAndColor((TextView)findViewById(R.id.lblAlbumStatic));
UI.mediumTextAndColor((TextView)findViewById(R.id.lblLengthStatic));
lblArtist.setTextColor(UI.colorState_text_title_static);
UI.largeText(lblArtist);
lblTrack = (TextView)findViewById(R.id.lblTrack);
lblTrack.setTextColor(UI.colorState_text_title_static);
UI.largeText(lblTrack);
lblAlbum = (TextView)findViewById(R.id.lblAlbum);
lblAlbum.setTextColor(UI.colorState_text_title_static);
UI.largeText(lblAlbum);
lblLength = (TextView)findViewById(R.id.lblLength);
lblLength.setTextColor(UI.colorState_text_title_static);
UI.largeText(lblLength);
} else {
lblTrack = null;
lblAlbum = null;
lblLength = null;
}
if (Player.volumeControlType == Player.VOLUME_CONTROL_NONE) {
panelSecondary.removeView(barVolume);
barVolume = null;
btnVolume.setVisibility(View.VISIBLE);
btnVolume.setOnClickListener(this);
btnVolume.setIcon(UI.ICON_VOLUME4);
vwVolume = btnVolume;
vwVolumeId = R.id.btnVolume;
if (UI.isLargeScreen) {
UI.setNextFocusForwardId(list, R.id.btnVolume);
UI.setNextFocusForwardId(barSeek, R.id.btnVolume);
barSeek.setNextFocusRightId(R.id.btnVolume);
if (!UI.isLandscape)
btnAdd.setNextFocusLeftId(R.id.btnVolume);
btnAdd.setNextFocusUpId(R.id.btnVolume);
btnPrev.setNextFocusUpId(R.id.btnVolume);
btnPlay.setNextFocusUpId(R.id.btnVolume);
btnNext.setNextFocusUpId(R.id.btnVolume);
btnMenu.setNextFocusUpId(R.id.btnVolume);
} else {
if (UI.isLandscape) {
btnPrev.setNextFocusRightId(R.id.btnVolume);
btnPlay.setNextFocusRightId(R.id.btnVolume);
btnNext.setNextFocusRightId(R.id.btnVolume);
btnAdd.setNextFocusRightId(R.id.btnVolume);
} else {
btnPrev.setNextFocusDownId(R.id.btnVolume);
btnPlay.setNextFocusDownId(R.id.btnVolume);
btnNext.setNextFocusDownId(R.id.btnVolume);
btnAdd.setNextFocusDownId(R.id.btnVolume);
}
UI.setNextFocusForwardId(btnMenu, R.id.btnVolume);
btnMenu.setNextFocusRightId(R.id.btnVolume);
btnMenu.setNextFocusDownId(R.id.btnVolume);
}
} else {
panelSecondary.removeView(btnVolume);
btnVolume = null;
barVolume.setAdditionalContentDescription(getText(R.string.volume).toString());
barVolume.setOnBgSeekBarChangeListener(this);
barVolume.setMax((Player.volumeControlType == Player.VOLUME_CONTROL_STREAM) ? Player.volumeStreamMax : (-Player.VOLUME_MIN_DB / 5));
barVolume.setVertical(UI.isLandscape && !UI.isLargeScreen);
barVolume.setKeyIncrement((Player.volumeControlType == Player.VOLUME_CONTROL_STREAM) ? 1 : 20);
vwVolume = barVolume;
vwVolumeId = R.id.barVolume;
}
if (UI.isLargeScreen) {
findViewById(R.id.panelInfo).setBackgroundDrawable(new BorderDrawable(UI.color_highlight, UI.color_window, ((UI.isLandscape && !UI.controlsToTheLeft) ? UI.thickDividerSize : 0), (!UI.isLandscape ? UI.thickDividerSize : 0), ((UI.isLandscape && UI.controlsToTheLeft) ? UI.thickDividerSize : 0), 0, true));
} else {
if (UI.isLandscape && UI.extraSpacing) {
findViewById(R.id.panelInfo).setBackgroundDrawable(new ColorDrawable(UI.color_window));
} else {
lblTitle.setBackgroundDrawable(new ColorDrawable(UI.color_window));
lblMsgSelMove.setBackgroundDrawable(new ColorDrawable(UI.color_window));
panelControls.setBackgroundDrawable(new ColorDrawable(UI.color_window));
}
if (UI.isLandscape) {
list.setTopLeftBorders();
if (!UI.extraSpacing) {
panelSecondary.setBackgroundDrawable(new ColorDrawable(UI.color_window));
panelSelection.setBackgroundDrawable(new ColorDrawable(UI.color_window));
}
} else {
panelSecondary.setBackgroundDrawable(new BorderDrawable(UI.color_highlight, UI.color_window, 0, 0, 0, UI.thickDividerSize, true));
panelSelection.setBackgroundDrawable(new BorderDrawable(UI.color_highlight, UI.color_window, 0, 0, 0, UI.thickDividerSize, true));
panelSecondary.setPadding(0, 0, 0, UI.controlMargin + UI.thickDividerSize);
}
if (UI.extraSpacing) {
if (UI.isLandscape) {
panelControls.setPadding(UI.controlMargin, 0, UI.controlMargin, 0);
final ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams)panelControls.getLayoutParams();
p.bottomMargin = UI.controlMargin;
panelControls.setLayoutParams(p);
} else {
panelControls.setPadding(UI.controlMargin, 0, UI.controlMargin, UI.controlMargin);
}
panelSelection.setPadding(UI.controlMargin, 0, UI.controlMargin, UI.controlMargin + (UI.isLandscape ? 0 : UI.thickDividerSize));
} else {
if (!UI.isLandscape)
panelControls.setPadding(0, 0, 0, UI.isLowDpiScreen ? 0 : UI.controlMargin);
if (btnVolume != null) {
final ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams)btnVolume.getLayoutParams();
p.rightMargin = 0;
btnVolume.setLayoutParams(p);
}
}
}
btnCancelSel.setDefaultHeight();
UI.prepareEdgeEffectColor(getApplication());
final boolean m = Player.songs.moving;
isBackgroundSet = false;
isCreatingLayout = true;
if (m || Player.songs.selecting)
startSelecting();
if (m)
startMovingSelection();
isCreatingLayout = false;
}
}
@Override
public void onBgListViewAttached(BgListView list) {
restoreListViewPosition(selectCurrentWhenAttached);
selectCurrentWhenAttached = false;
}
@Override
public boolean onBgListViewKeyDown(BgListView list, int keyCode) {
switch (keyCode) {
case UI.KEY_LEFT:
if (btnCancelSel != null && btnMoveSel != null && btnRemoveSel != null && btnMenu != null && vwVolume != null) {
if (Player.songs.selecting)
(UI.isLargeScreen ? btnCancelSel : (UI.isLandscape ? btnMoveSel : btnRemoveSel)).requestFocus();
else if (Player.songs.moving)
btnCancelSel.requestFocus();
else if (UI.isLargeScreen)
btnMenu.requestFocus();
else
vwVolume.requestFocus();
}
return true;
case UI.KEY_RIGHT:
if (btnCancelSel != null && btnMoveSel != null && btnAdd != null && btnPrev != null && vwVolume != null) {
if (Player.songs.selecting)
((UI.isLargeScreen || UI.isLandscape) ? btnMoveSel : btnCancelSel).requestFocus();
else if (Player.songs.moving)
btnCancelSel.requestFocus();
else if (UI.isLargeScreen)
(UI.isLandscape ? btnAdd : vwVolume).requestFocus();
else if (UI.isLandscape)
btnPrev.requestFocus();
else
btnAdd.requestFocus();
}
return true;
}
final int s = Player.songs.getSelection();
if (Player.songs.moving || Player.songs.selecting) {
switch (keyCode) {
case UI.KEY_DEL:
if (s >= 0)
removeSelection();
return true;
case UI.KEY_EXTRA:
case UI.KEY_ENTER:
if (Player.songs.selecting)
startMovingSelection();
else
cancelSelection(false);
return true;
case UI.KEY_UP:
case UI.KEY_DOWN:
case UI.KEY_PAGE_UP:
case UI.KEY_PAGE_DOWN:
case UI.KEY_HOME:
case UI.KEY_END:
int n = list.getNewPosition(s, keyCode, false);
if (n < 0)
return true;
final boolean center = (n <= (list.getFirstVisiblePosition() + 1) || n >= (list.getLastVisiblePosition() - 1));
if (Player.songs.moving) {
Player.songs.moveSelection(n);
} else {
lastSel = n;
Player.songs.setSelection(firstSel, n, n, true, true);
}
if (center)
list.centerItem(n);
return true;
}
} else {
switch (keyCode) {
case UI.KEY_DEL:
if (s >= 0)
Player.songs.removeSelection();
return true;
case UI.KEY_EXTRA:
if (s >= 0)
processItemLongClick(s);
return true;
case UI.KEY_ENTER:
if (s >= 0) {
if (Player.songs.getItemT(s) == Player.localSong && !Player.localPlaying)
Player.playPause();
else
Player.play(s);
}
return true;
}
}
return false;
}
private void resume(boolean selectCurrent) {
UI.songActivity = this;
Player.songs.setObserver(list);
updateVolumeDisplay(Integer.MIN_VALUE);
if (list != null) {
selectCurrentWhenAttached = selectCurrent;
list.notifyMeWhenFirstAttached(this);
}
//ignoreAnnouncement = true;
onPlayerChanged(Player.localSong, true, true, null);
}
@Override
protected void onResume() {
Player.isMainActiveOnTop = true;
Player.observer = this;
Player.registerMediaButtonEventReceiver();
resume(true);
UI.showNextStartupMsg(getHostActivity());
}
@Override
protected void onOrientationChanged() {
onCleanupLayout();
onCreateLayout(false);
resume(false);
}
@Override
protected void onPause() {
if (skipToDestruction)
return;
Player.isMainActiveOnTop = false;
saveListViewPosition();
if (tmrSong != null)
tmrSong.stop();
if (tmrUpdateVolumeDisplay != null)
tmrUpdateVolumeDisplay.stop();
if (tmrVolume != null)
tmrVolume.stop();
volumeButtonPressed = 0;
if (Player.songs.selecting || Player.songs.moving)
cancelSelection(false);
UI.songActivity = null;
Player.songs.setObserver(null);
Player.observer = null;
lastTime = -2;
if (!Player.controlMode)
Player.lastCurrent = Player.songs.getCurrentPosition();
if (UI.forcedLocale != UI.LOCALE_NONE && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN && !localeHasBeenChanged) {
localeHasBeenChanged = true;
UI.reapplyForcedLocale(getApplication(), getHostActivity());
}
}
@Override
protected void onCleanupLayout() {
UI.animationReset();
saveListViewPosition();
lblTitle = null;
lblArtist = null;
lblTrack = null;
lblAlbum = null;
lblLength = null;
lblTitleIcon = null;
lblMsgSelMove = null;
barSeek = null;
barVolume = null;
vwVolume = null;
btnAdd = null;
btnPrev = null;
btnPlay = null;
btnNext = null;
btnMenu = null;
panelControls = null;
panelSecondary = null;
panelSelection = null;
btnMoveSel = null;
btnRemoveSel = null;
btnCancelSel = null;
btnDecreaseVolume = null;
btnIncreaseVolume = null;
btnVolume = null;
list = null;
if (tmrSong != null)
tmrSong.stop();
if (tmrUpdateVolumeDisplay != null)
tmrUpdateVolumeDisplay.stop();
if (tmrVolume != null)
tmrVolume.stop();
}
@Override
protected void onDestroy() {
skipToDestruction = false;
if (tmrSong != null) {
tmrSong.release();
tmrSong = null;
}
if (tmrUpdateVolumeDisplay != null) {
tmrUpdateVolumeDisplay.release();
tmrUpdateVolumeDisplay = null;
}
if (tmrVolume != null) {
tmrVolume.release();
tmrVolume = null;
}
timeBuilder = null;
volumeBuilder = null;
}
@Override
public void handleTimer(Timer timer, Object param) {
if (timer == tmrVolume) {
if (tmrVolumeInitialDelay > 0) {
tmrVolumeInitialDelay
} else {
switch (volumeButtonPressed) {
case 1:
if (!decreaseVolume())
tmrVolume.stop();
break;
case 2:
if (!increaseVolume())
tmrVolume.stop();
break;
default:
tmrVolume.stop();
break;
}
}
return;
} else if (timer == tmrUpdateVolumeDisplay) {
updateVolumeDisplay(Integer.MIN_VALUE);
return;
}
if (Player.isPreparing()) {
if (barSeek != null && !barSeek.isTracking()) {
barSeek.setText(R.string.loading);
barSeek.setValue(0);
}
return;
}
final int m = Player.getPosition(),
t = ((m < 0) ? -1 : (m / 1000));
if (t == lastTime) return;
lastTime = t;
if (t < 0) {
if (barSeek != null && !barSeek.isTracking()) {
barSeek.setText(R.string.no_info);
barSeek.setValue(0);
}
} else {
Song.formatTimeSec(t, timeBuilder);
if (barSeek != null && !barSeek.isTracking()) {
final Song s = Player.localSong;
int v = 0;
if (s != null && s.lengthMS > 0) {
if (m >= 214740) //avoid overflow! ;)
v = (int)(((long)m * (long)MAX_SEEK) / (long)s.lengthMS);
else
v = (m * MAX_SEEK) / s.lengthMS;
}
barSeek.setText(timeBuilder.toString());
barSeek.setValue(v);
}
}
}
private int getMSFromBarValue(int value) {
final Song s = Player.localSong;
if (s == null || s.lengthMS <= 0 || value < 0)
return -1;
return (int)(((long)value * (long)s.lengthMS) / (long)MAX_SEEK);
}
@Override
public void onValueChanged(BgSeekBar seekBar, int value, boolean fromUser, boolean usingKeys) {
if (fromUser) {
if (seekBar == barVolume) {
seekBar.setText(volumeToString(Player.setVolume((Player.volumeControlType == Player.VOLUME_CONTROL_STREAM) ? value : ((value * 5) + Player.VOLUME_MIN_DB))));
} else if (seekBar == barSeek) {
value = getMSFromBarValue(value);
if (value < 0) {
seekBar.setText(R.string.no_info);
seekBar.setValue(0);
} else {
Song.formatTime(value, timeBuilder);
seekBar.setText(timeBuilder.toString());
}
}
}
}
@Override
public boolean onStartTrackingTouch(BgSeekBar seekBar) {
if (seekBar == barSeek) {
if (Player.localSong != null && Player.localSong.lengthMS > 0) {
if (UI.expandSeekBar && !UI.isLargeScreen) {
UI.animationReset();
UI.animationAddViewToHide(vwVolume);
UI.animationCommit(isCreatingLayout, null);
}
return true;
}
return false;
}
return true;
}
@Override
public void onStopTrackingTouch(BgSeekBar seekBar, boolean cancelled) {
if (seekBar == barSeek) {
if (Player.localSong != null) {
final int ms = getMSFromBarValue(seekBar.getValue());
if (cancelled || ms < 0)
handleTimer(tmrSong, null);
else
Player.seekTo(ms);
}
if (UI.expandSeekBar && !UI.isLargeScreen) {
UI.animationReset();
UI.animationAddViewToShow(vwVolume);
UI.animationCommit(isCreatingLayout, null);
}
}
}
@Override
public void onFileSelected(int id, String path, String name) {
if (id == MNU_LOADLIST) {
Player.songs.clear();
Player.songs.startDeserializing(getApplication(), path, true, false, false);
BackgroundActivityMonitor.start(getHostActivity());
} else {
Player.songs.serialize(getApplication(), path);
}
}
@Override
public void onAddClicked(int id, String path, String name) {
if (id == MNU_LOADLIST) {
Player.songs.startDeserializing(getApplication(), path, false, true, false);
BackgroundActivityMonitor.start(getHostActivity());
}
}
@Override
public void onPlayClicked(int id, String path, String name) {
if (id == MNU_LOADLIST) {
Player.songs.startDeserializing(getApplication(), path, false, !Player.clearListWhenPlayingFolders, true);
BackgroundActivityMonitor.start(getHostActivity());
}
}
@Override
public void onPressingChanged(BgButton button, boolean pressed) {
if (button == btnDecreaseVolume) {
if (pressed) {
if (Player.volumeControlType == Player.VOLUME_CONTROL_NONE) {
Player.showStreamVolumeUI();
tmrVolume.stop();
} else {
volumeButtonPressed = 1;
tmrVolumeInitialDelay = 3;
if (decreaseVolume())
tmrVolume.start(175);
else
tmrVolume.stop();
}
} else if (volumeButtonPressed == 1) {
volumeButtonPressed = 0;
tmrVolume.stop();
}
} else if (button == btnIncreaseVolume) {
if (pressed) {
if (Player.volumeControlType == Player.VOLUME_CONTROL_NONE) {
Player.showStreamVolumeUI();
tmrVolume.stop();
} else {
volumeButtonPressed = 2;
tmrVolumeInitialDelay = 3;
if (increaseVolume())
tmrVolume.start(175);
else
tmrVolume.stop();
}
} else if (volumeButtonPressed == 2) {
volumeButtonPressed = 0;
tmrVolume.stop();
}
}
}
}
|
package jp.classmethod.android.componentlibrary.widget;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.widget.TimePicker;
public class GBNumberPickerController extends UITimePickerController {
@Override
public void overrideTimePicker(UITimePicker picker) {
try {
Field f = TimePicker.class.getDeclaredField("mMinutePicker");
f.setAccessible(true);
Object numberPicker = f.get(picker);
Class<?>[] args = {
int.class,
int.class,
String[].class
};
Class<?> clazz = Class.forName("android.widget.NumberPicker");
Method m = clazz.getDeclaredMethod("setRange", args);
String[] items = createMinItems(unit);
maxIdx = items.length - 1;
Object[] params = {
0,
maxIdx,
items
};
m.invoke(numberPicker, params);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
}
|
package br.com.tupinikimtecnologia.view;
import br.com.tupinikimtecnologia.constants.GeralConstants;
import br.com.tupinikimtecnologia.db.Db;
import br.com.tupinikimtecnologia.db.TPostData;
import br.com.tupinikimtecnologia.db.TTarget;
import br.com.tupinikimtecnologia.http.Flooder;
import br.com.tupinikimtecnologia.objects.Target;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.util.List;
import java.util.ArrayList;
public class MainForm {
private JPanel panel1;
private JComboBox urlComboBox;
private JRadioButton getRadioButton;
private JRadioButton postRadioButton;
private JCheckBox randAgentCheckBox;
private JComboBox postDataComboBox;
private JCheckBox randomDataCheckBox;
private JButton randomDataHelpButton;
private JSpinner delaySpinner;
private JButton startButton;
private JProgressBar progressBar1;
private JLabel textField;
private JLabel responseCodeText;
private JComboBox userAgentComboBox;
private boolean respCodeThRunning;
private Flooder flooder;
private Thread flooderThread;
private Thread responseCodeThread;
private Db db;
private Connection conn;
private TTarget tTarget;
private TPostData tPostData;
private List<Target> targetList;
public MainForm() {
db = new Db();
conn = db.conectDb();
tTarget = new TTarget(conn);
tPostData = new TPostData(conn);
//tPostData.insertTableTarget("postdataaaaaa", 1);
delaySpinner.setModel(new SpinnerNumberModel(0,0,10000,1));
targetList = tTarget.selectTargetAll();
setUrlComboBoxAll();
userAgentComboBox.setModel(new DefaultComboBoxModel(GeralConstants.USER_ANGET));
userAgentComboBox.setPrototypeDisplayValue("XXXXXXXXXXXXXXXXXX");
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startFlooder();
}
});
postRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
postDataComboBox.setEnabled(true);
}
});
getRadioButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
postDataComboBox.setEnabled(false);
}
});
randAgentCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(randAgentCheckBox.isSelected()){
userAgentComboBox.setEnabled(false);
}else{
userAgentComboBox.setEnabled(true);
}
}
});
}
private void setUrlComboBoxAll(){
for(Target t : targetList){
urlComboBox.addItem(t.getUrl());
}
}
private String insertUrlOnDb(){
String url = urlComboBox.getSelectedItem().toString().trim();
if(!tTarget.checkIfUrlExists(url)){
Target target = new Target();
target.setUrl(url);
tTarget.insertTarget(url);
target.setId(tTarget.selectIdByUrl(url));
targetList.add(target);
urlComboBox.addItem(url);
}
return url;
}
private void startFlooder(){
if(startButton.getText().equals("START!")){
if(validateForm()) {
startButton.setText("STOP!");
startButton.setForeground(Color.RED);
if (getRadioButton.isSelected()) {
flooder = new Flooder(insertUrlOnDb());
} else if (postRadioButton.isSelected()) {
String postData = postDataComboBox.getSelectedItem().toString().trim();
String url = insertUrlOnDb();
int targetId = tTarget.selectIdByUrl(url);
if(!tPostData.checkIfPostDataExists(postData, targetId)){
if(targetId!=-1){
tPostData.insertPostData(postData, targetId);
}
}
flooder = new Flooder(url, postData);
}
if (!randAgentCheckBox.isSelected()) {
flooder.setUserAgent(userAgentComboBox.getSelectedItem().toString());
flooder.setRandomAgent(false);
} else {
flooder.setRandomAgent(true);
}
flooder.setDelay((int) delaySpinner.getValue());
flooderThread = new Thread(flooder);
flooderThread.start();
startRespCodeThread();
progressBar1.setIndeterminate(true);
}
}else{
respCodeThRunning = false;
flooder.stop();
flooderThread.interrupt();
responseCodeThread.interrupt();
startButton.setText("START!");
startButton.setForeground(Color.BLUE);
progressBar1.setIndeterminate(false);
}
}
private void startRespCodeThread(){
respCodeThRunning = true;
responseCodeThread = new Thread(new Runnable() {
@Override
public void run() {
while(respCodeThRunning){
int respCode = flooder.getLastResponseCode();
responseCodeText.setText(""+respCode);
responseCodeText.setForeground(setRespCodeColor(respCode));
}
}
});
responseCodeThread.start();
}
private Color setRespCodeColor(int respCode){
if(respCode>=200 && respCode<=226){
return Color.GREEN;
}
if(respCode>=300 && respCode<=308){
return Color.yellow;
}
if(respCode>=400 && respCode<=499){
return Color.red;
}
if(respCode>=500 && respCode<=599){
return new Color(117,8,8);
}
return Color.black;
}
private boolean validateForm(){
if(urlComboBox.getSelectedItem() == null || urlComboBox.getSelectedItem().toString().isEmpty()){
JOptionPane.showMessageDialog(null, "Enter the Target URL field", "Target URL Empty", JOptionPane.ERROR_MESSAGE);
return false;
}else{
if(postDataComboBox.isEnabled()) {
if (postDataComboBox.getSelectedItem() != null) {
if (postDataComboBox.getSelectedItem().toString().isEmpty()) {
JOptionPane.showMessageDialog(null, "Enter the Post Data field", "Post Data Empty", JOptionPane.ERROR_MESSAGE);
return false;
}
} else {
JOptionPane.showMessageDialog(null, "Enter the Post Data field", "Post Data Empty", JOptionPane.ERROR_MESSAGE);
return false;
}
}
}
return true;
}
public static void setMainMenu(JFrame frame){
JMenuBar menuBar;
JMenu menu;
JMenuItem menuItem;
//target menu
menuBar = new JMenuBar();
menu = new JMenu("Target");
menu.setMnemonic(KeyEvent.VK_A);
menuBar.add(menu);
menuItem = new JMenuItem("Target History",
new ImageIcon("img/target_icon.png"));
menuItem.setMnemonic(KeyEvent.VK_T);
menu.add(menuItem);
//help menu
menu = new JMenu("Help");
menu.setMnemonic(KeyEvent.VK_E);
menuBar.add(menu);
menuItem = new JMenuItem("How it works?",
new ImageIcon("img/help_icon.png"));
menuItem.setMnemonic(KeyEvent.VK_H);
menu.add(menuItem);
menuItem = new JMenuItem("About",
new ImageIcon("img/about_icon.png"));
menuItem.setMnemonic(KeyEvent.VK_B);
menu.add(menuItem);
frame.setJMenuBar(menuBar);
}
public static void main(String[] args) {
JFrame frame = new JFrame("HttpFlooder");
frame.setContentPane(new MainForm().panel1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
setMainMenu(frame);
}
}
|
package com.easternedgerobotics.rov;
import com.easternedgerobotics.rov.event.BroadcastEventPublisher;
import com.easternedgerobotics.rov.event.EventPublisher;
import com.easternedgerobotics.rov.measure.Depth;
import com.easternedgerobotics.rov.value.ExternalPressureValueA;
import com.easternedgerobotics.rov.value.ExternalPressureValueB;
import com.easternedgerobotics.rov.value.VideoFlipValueA;
import com.easternedgerobotics.rov.value.VideoValueA;
import com.easternedgerobotics.rov.video.PicameraVideo;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.pmw.tinylog.Logger;
import rx.broadcast.BasicOrder;
import rx.broadcast.UdpBroadcast;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeUnit;
final class PicameraA {
private final EventPublisher eventPublisher;
private final CompositeSubscription subscriptions;
private final CompositeSubscription flips;
private PicameraA(final EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
this.subscriptions = new CompositeSubscription();
this.flips = new CompositeSubscription();
}
private void initCameraA() {
subscriptions.add(
eventPublisher.valuesOfType(VideoValueA.class)
.map(value -> new PicameraVideo(value.getHost(), value.getPort()))
.scan((old, event) -> {
flips.clear();
old.stop();
return event;
})
.delay(1, TimeUnit.SECONDS)
.subscribe(video -> {
video.start();
flips.add(eventPublisher.valuesOfType(VideoFlipValueA.class).subscribe(f -> video.flip()));
}));
}
public static void main(final String[] args) throws InterruptedException, SocketException, UnknownHostException {
final String app = "picamera-a";
final HelpFormatter formatter = new HelpFormatter();
final Option broadcast = Option.builder("b")
.longOpt("broadcast")
.hasArg()
.argName("ADDRESS")
.desc("use ADDRESS to broadcast messages")
.required()
.build();
final Options options = new Options();
options.addOption(broadcast);
try {
final CommandLineParser parser = new DefaultParser();
final CommandLine arguments = parser.parse(options, args);
final InetAddress broadcastAddress = InetAddress.getByName(arguments.getOptionValue("b"));
final int broadcastPort = BroadcastEventPublisher.DEFAULT_BROADCAST_PORT;
final DatagramSocket socket = new DatagramSocket(broadcastPort);
final EventPublisher eventPublisher = new BroadcastEventPublisher(new UdpBroadcast<>(
socket, broadcastAddress, broadcastPort, new BasicOrder<>()));
final PicameraA picamera = new PicameraA(eventPublisher);
eventPublisher.valuesOfType(ExternalPressureValueA.class)
.observeOn(Schedulers.computation())
.map(Depth::fromPressure)
.observeOn(Schedulers.io())
.subscribe(eventPublisher::emit);
eventPublisher.valuesOfType(ExternalPressureValueB.class)
.observeOn(Schedulers.computation())
.map(Depth::fromPressure)
.observeOn(Schedulers.io())
.subscribe(eventPublisher::emit);
picamera.initCameraA();
Logger.info("Started");
eventPublisher.await();
} catch (final ParseException e) {
formatter.printHelp(app, options, true);
System.exit(1);
}
}
}
|
package org.diorite.impl.connection.packets.play.in;
import java.io.IOException;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.diorite.impl.connection.EnumProtocol;
import org.diorite.impl.connection.EnumProtocolDirection;
import org.diorite.impl.connection.packets.PacketClass;
import org.diorite.impl.connection.packets.PacketDataSerializer;
import org.diorite.impl.connection.packets.play.PacketPlayInListener;
import org.diorite.impl.inventory.item.ItemStackImpl;
import org.diorite.BlockFace;
import org.diorite.BlockLocation;
@PacketClass(id = 0x08, protocol = EnumProtocol.PLAY, direction = EnumProtocolDirection.SERVERBOUND)
public class PacketPlayInBlockPlace implements PacketPlayIn
{
private BlockLocation location;
private BlockFace blockFace;
private ItemStackImpl itemStack; // ignored by server, always read as null to prevent memory leaks and client ability to crash server.
private float cursorX;
private float cursorY;
private float cursorZ;
public PacketPlayInBlockPlace()
{
}
public PacketPlayInBlockPlace(final ItemStackImpl itemStack)
{
this.itemStack = itemStack;
}
public PacketPlayInBlockPlace(final BlockLocation location, final BlockFace blockFace, final ItemStackImpl itemStack, final float cursorX, final float cursorY, final float cursorZ)
{
this.location = location;
this.blockFace = blockFace;
this.itemStack = itemStack;
this.cursorX = cursorX;
this.cursorY = cursorY;
this.cursorZ = cursorZ;
}
@SuppressWarnings("MagicNumber")
@Override
public void readPacket(final PacketDataSerializer data) throws IOException
{
this.location = data.readBlockLocation();
this.blockFace = data.readBlockFace();
// this.itemStack = data.readItemStack(); // don't read item stack, skip all bytes instead
data.skipBytes(data.readableBytes() - 3); // skip rest of bytes, except last 3 (cursor pos)
this.cursorX = ((float) data.readUnsignedByte()) / 16.0f;
this.cursorY = ((float) data.readUnsignedByte()) / 16.0f;
this.cursorZ = ((float) data.readUnsignedByte()) / 16.0f;
}
@SuppressWarnings("MagicNumber")
@Override
public void writePacket(final PacketDataSerializer data) throws IOException
{
data.writeBlockLocation(this.location);
data.writeBlockFace(this.blockFace);
data.writeItemStack(this.itemStack);
data.writeByte((int) (this.cursorX * 16));
data.writeByte((int) (this.cursorY * 16));
data.writeByte((int) (this.cursorZ * 16));
}
public BlockLocation getLocation()
{
return this.location;
}
public void setLocation(final BlockLocation location)
{
this.location = location;
}
public BlockFace getBlockFace()
{
return this.blockFace;
}
public void setBlockFace(final BlockFace blockFace)
{
this.blockFace = blockFace;
}
public ItemStackImpl getItemStack()
{
return this.itemStack;
}
public void setItemStack(final ItemStackImpl itemStack)
{
this.itemStack = itemStack;
}
public float getCursorX()
{
return this.cursorX;
}
public void setCursorX(final float cursorX)
{
this.cursorX = cursorX;
}
public float getCursorY()
{
return this.cursorY;
}
public void setCursorY(final float cursorY)
{
this.cursorY = cursorY;
}
public float getCursorZ()
{
return this.cursorZ;
}
public void setCursorZ(final float cursorZ)
{
this.cursorZ = cursorZ;
}
@Override
public void handle(final PacketPlayInListener listener)
{
listener.handle(this);
}
@Override
public String toString()
{
return new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE).appendSuper(super.toString()).append("location", this.location).append("blockFace", this.blockFace).append("itemStack", this.itemStack).append("cursorX", this.cursorX).append("cursorY", this.cursorY).append("cursorZ", this.cursorZ).toString();
}
}
|
package io.github.ihongs.serv.auth;
import io.github.ihongs.Cnst;
import io.github.ihongs.Core;
import io.github.ihongs.CoreSerial;
import io.github.ihongs.HongsException;
import io.github.ihongs.action.ActionHelper;
import io.github.ihongs.db.DB;
import io.github.ihongs.db.util.FetchCase;
import io.github.ihongs.db.Table;
import io.github.ihongs.util.Syno;
import io.github.ihongs.util.Synt;
import java.io.File;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
*
* @author Hongs
*/
public class RoleSet extends CoreSerial implements CoreSerial.LastModified, Set<String> {
public String userId;
public Set<String> roles;
public long rtime;
private RoleSet(String userId) throws HongsException {
this.userId = userId;
init("master/role/" + Syno.splitPath(userId));
}
@Override
protected void imports() throws HongsException {
roles = new HashSet();
DB db;
Table tb;
Table td;
Table tt;
FetchCase fc;
List<Map> rz;
db = DB.getInstance("master");
/
tb = db.getTable("user_role");
fc = new FetchCase( FetchCase.STRICT )
.from (tb.tableName, tb.name)
.select(tb.name+".role")
.filter(tb.name+".user_id = ?", userId);
rz = db.fetchMore(fc);
for (Map rm : rz) {
roles.add((String) rm.get("role"));
}
/
tb = db.getTable("dept_role");
td = db.getTable("dept_user");
tt = db.getTable("dept");
fc = new FetchCase( FetchCase.STRICT )
.from (tb.tableName, tb.name)
.join (td.tableName, td.name , tb.name+".dept_id = "+td.name+".dept_id")
.join (tt.tableName, tt.name , td.name+".dept_id = "+tt.name+".id" )
.select(tb.name+".role")
.filter(td.name+".user_id = ?", userId)
.filter(tt.name+".state > 0" );
rz = db.fetchMore(fc);
for (Map rm : rz) {
roles.add((String) rm.get("role"));
}
/
rtime = System.currentTimeMillis() / 1000L;
}
@Override
protected byte read(File f) throws HongsException {
DB db;
Table tb;
Table td;
FetchCase fc;
Map rs;
int st;
long rt;
long ot;
db = DB.getInstance("master");
tb = db.getTable("user");
fc = new FetchCase( FetchCase.STRICT )
.from (tb.tableName, tb.name)
.select(tb.name+".state, "+tb.name+".rtime")
.filter(tb.name+".id = ?", userId);
rs = db.fetchLess(fc);
st = Synt.declare(rs.get("state"), 0 );
rt = Synt.declare(rs.get("rtime"), 0L);
if (st <= 0) {
return -1;
}
tb = db.getTable("dept");
td = db.getTable("dept_user");
fc = new FetchCase( FetchCase.STRICT )
.from (tb.tableName, tb.name)
.join (td.tableName, td.name , td.name+".dept_id = "+tb.name+".id" )
.select("MAX("+tb.name+".state) AS state, MAX("+tb.name+".rtime) AS rtime")
.filter(td.name+".user_id = ?", userId )
.gather(td.name+".user_id");
rs = db.fetchLess(fc);
st = Synt.declare(rs.get("state"), 1 );
ot = Synt.declare(rs.get("rtime"), 0L);
if (st <= 0) {
return -1;
}
if (rt < ot) {
rt = ot;
}
if (!f.exists()) {
return 0;
}
load(f);
if (rt > rtime ) {
return 0;
} else {
return 1;
}
}
@Override
public long lastModified() {
return rtime * 1000L;
}
/
public static RoleSet getInstance(String userId)
throws HongsException {
String k = RoleSet.class.getName() +":"+ userId ;
Core c = Core.getInstance( );
if (c.containsKey(k)) {
return (RoleSet) c.get( k );
}
RoleSet s = new RoleSet(userId);
if (s . rtime == 0L ) {
s = null;
}
c.put(k , s);
return s;
}
public static RoleSet getInstance()
throws HongsException {
Object id = Core.getInstance (ActionHelper.class)
.getSessibute( Cnst.UID_SES );
if (id == null) {
return null;
}
return getInstance((String) id);
}
//** Set **/
@Override
public int size() {
return roles.size();
}
@Override
public boolean isEmpty() {
return roles.isEmpty();
}
@Override
public boolean contains(Object o) {
return roles.contains(o);
}
@Override
public boolean containsAll(Collection c) {
return roles.containsAll(c);
}
@Override
public boolean add(String e) {
return roles.add(e);
}
@Override
public boolean addAll(Collection c) {
return roles.addAll(c);
}
@Override
public boolean remove(Object o) {
return roles.remove(o);
}
@Override
public boolean removeAll(Collection c) {
return roles.removeAll(c);
}
@Override
public boolean retainAll(Collection c) {
return roles.retainAll(c);
}
@Override
public void clear() {
roles.clear();
}
@Override
public Iterator iterator() {
return roles.iterator();
}
@Override
public Object[] toArray( ) {
return roles.toArray( );
}
@Override
public Object[] toArray(Object[] a) {
return roles.toArray(a);
}
}
|
package ca.cumulonimbus.pressurenetsdk;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabaseLockedException;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.net.ConnectivityManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.PowerManager;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
/**
* Represent developer-facing pressureNET API Background task; manage and run
* everything Handle Intents
*
* @author jacob
*
*/
public class CbService extends Service {
private CbDataCollector dataCollector;
private CbLocationManager locationManager;
private CbSettingsHandler settingsHandler;
private CbDb db;
public CbService service = this;
private String mAppDir;
IBinder mBinder;
ReadingSender sender;
Message recentMsg;
String serverURL = CbConfiguration.SERVER_URL;
public static String ACTION_SEND_MEASUREMENT = "ca.cumulonimbus.pressurenetsdk.ACTION_SEND_MEASUREMENT";
public static String ACTION_REGISTER = "ca.cumulonimbus.pressurenetsdk.ACTION_REGISTER";
// Service Interaction API Messages
public static final int MSG_OKAY = 0;
public static final int MSG_STOP = 1;
public static final int MSG_GET_BEST_LOCATION = 2;
public static final int MSG_BEST_LOCATION = 3;
public static final int MSG_GET_BEST_PRESSURE = 4;
public static final int MSG_BEST_PRESSURE = 5;
public static final int MSG_START_AUTOSUBMIT = 6;
public static final int MSG_STOP_AUTOSUBMIT = 7;
public static final int MSG_SET_SETTINGS = 8;
public static final int MSG_GET_SETTINGS = 9;
public static final int MSG_SETTINGS = 10;
// Live sensor streaming
public static final int MSG_START_STREAM = 11;
public static final int MSG_DATA_STREAM = 12;
public static final int MSG_STOP_STREAM = 13;
// PressureNet Live API
public static final int MSG_GET_LOCAL_RECENTS = 14;
public static final int MSG_LOCAL_RECENTS = 15;
public static final int MSG_GET_API_RECENTS = 16;
public static final int MSG_API_RECENTS = 17;
public static final int MSG_MAKE_API_CALL = 18;
public static final int MSG_API_RESULT_COUNT = 19;
// PressureNet API Cache
public static final int MSG_CLEAR_LOCAL_CACHE = 20;
public static final int MSG_REMOVE_FROM_PRESSURENET = 21;
public static final int MSG_CLEAR_API_CACHE = 22;
// Current Conditions
public static final int MSG_ADD_CURRENT_CONDITION = 23;
public static final int MSG_GET_CURRENT_CONDITIONS = 24;
public static final int MSG_CURRENT_CONDITIONS = 25;
// Sending Data
public static final int MSG_SEND_OBSERVATION = 26;
public static final int MSG_SEND_CURRENT_CONDITION = 27;
// Current Conditions API
public static final int MSG_MAKE_CURRENT_CONDITIONS_API_CALL = 28;
// Notifications
public static final int MSG_CHANGE_NOTIFICATION = 31;
// Data management
public static final int MSG_COUNT_LOCAL_OBS = 32;
public static final int MSG_COUNT_API_CACHE = 33;
public static final int MSG_COUNT_LOCAL_OBS_TOTALS = 34;
public static final int MSG_COUNT_API_CACHE_TOTALS = 35;
// Graphing
public static final int MSG_GET_API_RECENTS_FOR_GRAPH = 36;
public static final int MSG_API_RECENTS_FOR_GRAPH = 37;
// Success / Failure notification for data submission
public static final int MSG_DATA_RESULT = 38;
// Statistics
public static final int MSG_MAKE_STATS_CALL = 39;
public static final int MSG_STATS = 40;
// External Weather Services
public static final int MSG_GET_EXTERNAL_LOCAL_EXPANDED = 41;
public static final int MSG_EXTERNAL_LOCAL_EXPANDED = 42;
// User contributions summary
public static final int MSG_GET_CONTRIBUTIONS = 43;
public static final int MSG_CONTRIBUTIONS = 44;
// Database info, test suites/debugging
public static final int MSG_GET_DATABASE_INFO = 45;
// Multitenancy Support
public static final int MSG_GET_PRIMARY_APP = 46;
public static final int MSG_IS_PRIMARY = 47;
// Intents
public static final String PRESSURE_CHANGE_ALERT = "ca.cumulonimbus.pressurenetsdk.PRESSURE_CHANGE_ALERT";
public static final String LOCAL_CONDITIONS_ALERT = "ca.cumulonimbus.pressurenetsdk.LOCAL_CONDITIONS_ALERT";
public static final String PRESSURE_SENT_TOAST = "ca.cumulonimbus.pressurenetsdk.PRESSURE_SENT_TOAST";
public static final String CONDITION_SENT_TOAST = "ca.cumulonimbus.pressurenetsdk.CONDITION_SENT_TOAST";
// Support for new sensor type constants
private final int TYPE_AMBIENT_TEMPERATURE = 13;
private final int TYPE_RELATIVE_HUMIDITY = 12;
long lastAPICall = System.currentTimeMillis();
long lastConditionNotification = System.currentTimeMillis() - (1000 * 60 * 60 * 6);
private CbObservation collectedObservation;
private final Handler mHandler = new Handler();
Messenger mMessenger = new Messenger(new IncomingHandler());
ArrayList<CbObservation> offlineBuffer = new ArrayList<CbObservation>();
private long lastPressureChangeAlert = 0;
private Messenger lastMessenger;
private boolean fromUser = false;
CbAlarm alarm = new CbAlarm();
double recentPressureReading = 0.0;
int recentPressureAccuracy = 0;
int batchReadingCount = 0;
private long lastSubmit = 0;
private PowerManager.WakeLock wl;
private boolean hasBarometer = true;
ArrayList<CbSensorStreamer> activeStreams = new ArrayList<CbSensorStreamer>();
/**
* Collect data from onboard sensors and store locally
*
* @author jacob
*
*/
public class CbDataCollector implements SensorEventListener {
private SensorManager sm;
Sensor pressureSensor;
private final int TYPE_AMBIENT_TEMPERATURE = 13;
private final int TYPE_RELATIVE_HUMIDITY = 12;
private ArrayList<CbObservation> recentObservations = new ArrayList<CbObservation>();
int stopSoonCalls = 0;
public ArrayList<CbObservation> getRecentObservations() {
return recentObservations;
}
/**
* Access the database to fetch recent, locally-recorded observations
*
* @return
*/
public ArrayList<CbObservation> getRecentDatabaseObservations() {
ArrayList<CbObservation> recentDbList = new ArrayList<CbObservation>();
CbDb db = new CbDb(getApplicationContext());
db.open();
Cursor c = db.fetchAllObservations();
while (c.moveToNext()) {
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(c.getDouble(1));
location.setLongitude(c.getDouble(2));
location.setAltitude(c.getDouble(3));
location.setAccuracy(c.getInt(4));
location.setProvider(c.getString(5));
obs.setLocation(location);
obs.setObservationType(c.getString(6));
obs.setObservationUnit(c.getString(7));
obs.setObservationValue(c.getDouble(8));
obs.setSharing(c.getString(9));
obs.setTime(c.getInt(10));
obs.setTimeZoneOffset(c.getInt(11));
obs.setUser_id(c.getString(12));
recentDbList.add(obs);
}
db.close();
return recentDbList;
}
public void setRecentObservations(
ArrayList<CbObservation> recentObservations) {
this.recentObservations = recentObservations;
}
/**
* Start collecting sensor data.
*
* @param m
* @return
*/
public boolean startCollectingData() {
batchReadingCount = 0;
stopSoonCalls = 0;
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
pressureSensor = sm.getDefaultSensor(Sensor.TYPE_PRESSURE);
if(wl!=null) {
log("cbservice startcollectingdata wakelock " + wl.isHeld());
if(!wl.isHeld()) {
log("cbservice startcollectingdata no wakelock, bailing");
return false;
}
}
boolean collecting = false;
try {
if(sm != null) {
if (pressureSensor != null) {
log("cbservice sensor SDK " + android.os.Build.VERSION.SDK_INT + "");
if(android.os.Build.VERSION.SDK_INT == 19) {
collecting = sm.registerListener(this, pressureSensor,SensorManager.SENSOR_DELAY_UI); // , 100000);
} else {
collecting = sm.registerListener(this, pressureSensor,SensorManager.SENSOR_DELAY_UI);
}
} else {
log("cbservice pressure sensor is null");
}
} else {
log("cbservice sm is null");
}
return collecting;
} catch (Exception e) {
log("cbservice sensor error " + e.getMessage());
e.printStackTrace();
return collecting;
}
}
/**
* Stop collecting sensor data
*/
public void stopCollectingData() {
log("cbservice stop collecting data");
// sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if(sm!=null) {
log("cbservice sensormanager not null, unregistering");
sm.unregisterListener(this);
sm = null;
} else {
log("cbservice sensormanager null, walk away");
/*
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.unregisterListener(this);
sm = null;
*/
}
}
public CbDataCollector() {
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
if (sensor.getType() == Sensor.TYPE_PRESSURE) {
recentPressureAccuracy = accuracy;
log("cbservice accuracy changed, new barometer accuracy " + recentPressureAccuracy);
}
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_PRESSURE) {
if(event.values.length > 0) {
if(event.values[0] >= 0) {
log("cbservice sensor; new pressure reading " + event.values[0]);
recentPressureReading = event.values[0];
} else {
log("cbservice sensor; pressure reading is 0 or negative" + event.values[0]);
}
} else {
log("cbservice sensor; no event values");
}
}
if(stopSoonCalls<=1) {
stopSoon();
}
/*
batchReadingCount++;
if(batchReadingCount>2) {
log("batch readings " + batchReadingCount + ", stopping");
stopCollectingData();
} else {
log("batch readings " + batchReadingCount + ", not stopping");
}
*/
}
private class SensorStopper implements Runnable {
@Override
public void run() {
stopCollectingData();
}
}
private void stopSoon() {
stopSoonCalls++;
SensorStopper stop = new SensorStopper();
mHandler.postDelayed(stop, 100);
}
}
/**
* Collect data from onboard sensors and store locally
*
* @author jacob
*
*/
public class CbSensorStreamer implements SensorEventListener {
public int sensorId;
private Messenger replyTo;
private SensorManager sm;
Sensor sensor;
/**
* Start collecting sensor data.
*
* @param m
* @return
*/
public void startSendingData() {
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sm.getDefaultSensor(sensorId);
try {
if(sm != null) {
if (sensor != null) {
log("CbService streamer registering sensorID " + sensorId);
sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI);
} else {
log("cbservice streaming sensor is null");
}
} else {
log("cbservice sm is null");
}
} catch (Exception e) {
log("cbservice sensor error " + e.getMessage());
}
}
/**
* Stop collecting sensor data
*/
public void stopSendingData() {
log("cbservice streaming stop collecting data");
if(sm!=null) {
log("cbservice streaming sensormanager not null, unregistering");
sm.unregisterListener(this);
sm = null;
} else {
log("cbservice streaming sensormanager null, walk away");
}
}
public CbSensorStreamer(int id, Messenger reply) {
this.sensorId = id;
this.replyTo = reply;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
if (sensor.getType() == sensorId) {
}
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == sensorId) {
// new sensor reading
CbObservation obs = new CbObservation();
obs.setObservationValue(event.values[0]);
try {
replyTo.send(Message.obtain(null,
MSG_DATA_STREAM, obs));
} catch (RemoteException re) {
re.printStackTrace();
}
}
}
}
/**
* Check if a sensor is already being used in an active stream
* to avoid multiple listeners on the same sensor.
* @param sensorId
* @return
*/
private boolean isSensorStreaming(int sensorId) {
for(CbSensorStreamer s : activeStreams) {
if (s.sensorId == sensorId) {
return true;
}
}
return false;
}
/**
* Start live sensor streaming from the service
* to the app. MSG_START_STREAM
*/
public void startSensorStream(int sensorId, Messenger reply) {
if(!isSensorStreaming(sensorId)) {
log("CbService starting live sensor streaming " + sensorId);
CbSensorStreamer streamer = new CbSensorStreamer(sensorId, reply);
activeStreams.add(streamer);
streamer.startSendingData();
} else {
log("CbService not starting live sensor streaming " + sensorId + ", already streaming");
}
}
/**
* Stop live sensor streaming. MSG_STOP_STREAM
*/
public void stopSensorStream(int sensorId) {
if(isSensorStreaming(sensorId)) {
log("CbService stopping live sensor streaming " + sensorId);
for(CbSensorStreamer s : activeStreams) {
if (s.sensorId == sensorId) {
s.stopSendingData();
activeStreams.remove(s);
break;
}
}
} else {
log("CbService not stopping live sensor streaming " + sensorId + " sensor not running");
}
}
/**
* Find all the data for an observation.
*
* Location, Measurement values, etc.
*
* @return
*/
public CbObservation collectNewObservation() {
try {
CbObservation pressureObservation = new CbObservation();
log("cb collecting new observation");
// Location values
locationManager = new CbLocationManager(getApplicationContext());
locationManager.startGettingLocations();
// Measurement values
pressureObservation = buildPressureObservation();
pressureObservation.setLocation(locationManager
.getCurrentBestLocation());
log("returning pressure obs: "
+ pressureObservation.getObservationValue());
return pressureObservation;
} catch (Exception e) {
//e.printStackTrace();
return null;
}
}
private class LocationStopper implements Runnable {
@Override
public void run() {
try {
//System.out.println("locationmanager stop getting locations");
locationManager.stopGettingLocations();
} catch (Exception e) {
//e.printStackTrace();
}
}
}
/**
* Send a single reading. TODO: Combine with ReadingSender for less code duplication.
* ReadingSender. Fix that.
*/
public class SingleReadingSender implements Runnable {
@Override
public void run() {
checkForLocalConditionReports();
if(settingsHandler == null) {
log("single reading sender, loading settings from prefs");
loadSetttingsFromPreferences();
}
log("collecting and submitting single "
+ settingsHandler.getServerURL());
CbObservation singleObservation = new CbObservation();
if (hasBarometer && settingsHandler.isCollectingData()) {
// Collect
dataCollector = new CbDataCollector();
dataCollector.startCollectingData();
singleObservation = collectNewObservation();
if (singleObservation.getObservationValue() != 0.0) {
// Store in database
db.open();
long count = db.addObservation(singleObservation);
db.close();
try {
if (settingsHandler.isSharingData()) {
// Send if we're online
if (isNetworkAvailable()) {
log("online and sending single");
singleObservation
.setClientKey(CbConfiguration.API_KEY);
fromUser = true;
sendCbObservation(singleObservation);
fromUser = false;
// also check and send the offline buffer
if (offlineBuffer.size() > 0) {
log("sending " + offlineBuffer.size()
+ " offline buffered obs");
for (CbObservation singleOffline : offlineBuffer) {
sendCbObservation(singleObservation);
}
offlineBuffer.clear();
}
} else {
log("didn't send, not sharing data; i.e., offline");
// / offline buffer variable
// TODO: put this in the DB to survive longer
offlineBuffer.add(singleObservation);
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
}
}
}
/**
* Check if we have a barometer. Use info to disable menu items, choose to
* run the service or not, etc.
*/
private boolean checkBarometer() {
PackageManager packageManager = this.getPackageManager();
hasBarometer = packageManager
.hasSystemFeature(PackageManager.FEATURE_SENSOR_BAROMETER);
return hasBarometer;
}
/**
* Collect and send data in a different thread. This runs itself every
* "settingsHandler.getDataCollectionFrequency()" milliseconds
*/
private class ReadingSender implements Runnable {
public void run() {
checkForLocalConditionReports();
long now = System.currentTimeMillis();
if(now - lastSubmit < 2000) {
log("cbservice readingsender too soon, bailing");
return;
}
// retrieve updated settings
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler = settingsHandler.getSettings();
log("collecting and submitting " + settingsHandler.getServerURL());
boolean okayToGo = true;
// Check if we're supposed to be charging and if we are.
// Bail if appropriate
if (settingsHandler.isOnlyWhenCharging()) {
if (!isCharging()) {
okayToGo = false;
}
}
if(!hasBarometer) {
okayToGo = false;
}
if (okayToGo && settingsHandler.isCollectingData()) {
// Collect
// start collecting data
dataCollector = new CbDataCollector();
dataCollector.startCollectingData();
CbObservation singleObservation = new CbObservation();
singleObservation = collectNewObservation();
if (singleObservation != null) {
if (singleObservation.getObservationValue() != 0.0) {
// Store in database
db.open();
long count = db.addObservation(singleObservation);
db.close();
try {
if (settingsHandler.isSharingData()) {
// Send if we're online
if (isNetworkAvailable()) {
lastSubmit = System.currentTimeMillis();
log("online and sending");
singleObservation
.setClientKey(CbConfiguration.API_KEY);
sendCbObservation(singleObservation);
// also check and send the offline buffer
if (offlineBuffer.size() > 0) {
log("sending " + offlineBuffer.size()
+ " offline buffered obs");
for (CbObservation singleOffline : offlineBuffer) {
sendCbObservation(singleObservation);
}
offlineBuffer.clear();
}
} else {
log("didn't send");
// / offline buffer variable
// TODO: put this in the DB to survive
// longer
offlineBuffer.add(singleObservation);
}
} else {
log("cbservice not sharing data, didn't send");
}
// If notifications are enabled,
log("is send notif "
+ settingsHandler.isSendNotifications());
if (settingsHandler.isSendNotifications()) {
// check for pressure local trend changes and
// notify
// the client
// ensure this only happens every once in a
// while
long rightNow = System.currentTimeMillis();
long sixHours = 1000 * 60 * 60 * 6;
if (rightNow - lastPressureChangeAlert > (sixHours)) {
long timeLength = 1000 * 60 * 60 * 3;
db.open();
Cursor localCursor = db.runLocalAPICall(
-90, 90, -180, 180,
System.currentTimeMillis()
- (timeLength),
System.currentTimeMillis(), 1000);
ArrayList<CbObservation> recents = new ArrayList<CbObservation>();
while (localCursor.moveToNext()) {
// just need observation value, time,
// and
// location
CbObservation obs = new CbObservation();
obs.setObservationValue(localCursor
.getDouble(8));
obs.setTime(localCursor.getLong(10));
Location location = new Location(
"network");
location.setLatitude(localCursor
.getDouble(1));
location.setLongitude(localCursor
.getDouble(2));
obs.setLocation(location);
recents.add(obs);
}
String tendencyChange = CbScience
.changeInTrend(recents);
db.close();
log("cbservice tendency changes: "
+ tendencyChange);
if (tendencyChange.contains(",")
&& (!tendencyChange.toLowerCase()
.contains("unknown"))) {
String[] tendencies = tendencyChange
.split(",");
if (!tendencies[0]
.equals(tendencies[1])) {
log("Trend change! "
+ tendencyChange);
Intent intent = new Intent();
intent.setAction(PRESSURE_CHANGE_ALERT);
intent.putExtra("ca.cumulonimbus.pressurenetsdk.tendencyChange", tendencyChange);
sendBroadcast(intent);
try {
if (lastMessenger != null) {
lastMessenger
.send(Message
.obtain(null,
MSG_CHANGE_NOTIFICATION,
tendencyChange));
} else {
log("readingsender didn't send notif, no lastMessenger");
}
} catch (Exception e) {
//e.printStackTrace();
}
lastPressureChangeAlert = rightNow;
// TODO: saveinprefs;
} else {
log("tendency equal");
}
}
} else {
// wait
log("tendency; hasn't been 6h, min wait time yet");
}
}
} catch (Exception e) {
//e.printStackTrace();
}
}
} else {
log("singleobservation is null, not sending");
}
} else {
log("cbservice is not collecting data.");
}
}
}
/**
* Put together all the information that defines
* an observation and store it in a single object.
* @return
*/
public CbObservation buildPressureObservation() {
CbObservation pressureObservation = new CbObservation();
pressureObservation.setTime(System.currentTimeMillis());
pressureObservation.setTimeZoneOffset(Calendar.getInstance()
.getTimeZone().getRawOffset());
pressureObservation.setUser_id(getID());
pressureObservation.setObservationType("pressure");
pressureObservation.setObservationValue(recentPressureReading);
pressureObservation.setObservationUnit("mbar");
// pressureObservation.setSensor(sm.getSensorList(Sensor.TYPE_PRESSURE).get(0));
pressureObservation.setSharing(settingsHandler.getShareLevel());
pressureObservation.setVersionNumber(getSDKVersion());
log("cbservice buildobs, share level "
+ settingsHandler.getShareLevel() + " " + getID());
return pressureObservation;
}
/**
* Return the version number of the SDK sending this reading
* @return
*/
public String getSDKVersion() {
String version = "-1.0";
try {
version = getPackageManager()
.getPackageInfo("ca.cumulonimbus.pressurenetsdk", 0).versionName;
} catch (NameNotFoundException nnfe) {
// TODO: this is not an okay return value
// (Don't send error messages as version numbers)
version = nnfe.getMessage();
}
return version;
}
/**
* Periodically check to see if someone has
* reported a current condition nearby. If it's
* appropriate, send a notification
*/
private void checkForLocalConditionReports() {
long now = System.currentTimeMillis();
long minWaitTime = 1000 * 60 * 60;
if(now - minWaitTime > lastConditionNotification) {
if(locationManager == null) {
locationManager = new CbLocationManager(getApplicationContext());
}
log("cbservice checking for local conditions reports");
// it has been long enough; make a conditions API call
// for the local area
CbApi conditionApi = new CbApi(getApplicationContext());
CbApiCall conditionApiCall = buildLocalConditionsApiCall();
if(conditionApiCall!=null) {
log("cbservice making conditions api call for local reports");
conditionApi.makeAPICall(conditionApiCall, service,
mMessenger, "Conditions");
// TODO: store this more permanently
lastConditionNotification = now;
}
} else {
log("cbservice not checking for local conditions, too recent");
}
}
/**
* Make a CbApiCall object for local conditions
* @return
*/
public CbApiCall buildLocalConditionsApiCall() {
CbApiCall conditionApiCall = new CbApiCall();
conditionApiCall.setCallType("Conditions");
Location location = new Location("network");
location.setLatitude(0);
location.setLongitude(0);
if(locationManager != null) {
location = locationManager.getCurrentBestLocation();
if(location != null) {
conditionApiCall.setMinLat(location.getLatitude() - .1);
conditionApiCall.setMaxLat(location.getLatitude() + .1);
conditionApiCall.setMinLon(location.getLongitude() - .1);
conditionApiCall.setMaxLon(location.getLongitude() + .1);
conditionApiCall.setStartTime(System.currentTimeMillis() - (1000 * 60 * 60));
conditionApiCall.setEndTime(System.currentTimeMillis());
return conditionApiCall;
} else {
return null;
}
} else {
log("cbservice not checking location condition reports, no locationmanager");
return null;
}
}
/**
* Check for network connection, return true
* if we're online.
*
* @return
*/
public boolean isNetworkAvailable() {
log("is net available?");
ConnectivityManager cm = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
log("yes");
return true;
} else {
log("no");
return false;
}
}
/**
* Stop all listeners, active sensors, etc, and shut down.
*
*/
public void stopAutoSubmit() {
if (locationManager != null) {
locationManager.stopGettingLocations();
}
if (dataCollector != null) {
dataCollector.stopCollectingData();
}
log("cbservice stop autosubmit");
// alarm.cancelAlarm(getApplicationContext());
}
/**
* Send the observation to the server
*
* @param observation
* @return
*/
public boolean sendCbObservation(CbObservation observation) {
try {
CbDataSender sender = new CbDataSender(getApplicationContext());
settingsHandler = settingsHandler.getSettings();
if(settingsHandler.getServerURL().equals("")) {
log("cbservice settings are empty; defaults");
//loadSetttingsFromPreferences();
// settingsHandler = settingsHandler.getSettings();
}
log("sendCbObservation with wakelock " + wl.isHeld() + " and settings " + settingsHandler);
sender.setSettings(settingsHandler, locationManager,
lastMessenger, fromUser);
sender.execute(observation.getObservationAsParams());
return true;
} catch (Exception e) {
return false;
}
}
/**
* Send a new account to the server
*
* @param account
* @return
*/
public boolean sendCbAccount(CbAccount account) {
try {
CbDataSender sender = new CbDataSender(getApplicationContext());
sender.setSettings(settingsHandler, locationManager,
null, true);
sender.execute(account.getAccountAsParams());
fromUser = false;
return true;
} catch (Exception e) {
return false;
}
}
/**
* Send the current condition to the server
*
* @param observation
* @return
*/
public boolean sendCbCurrentCondition(CbCurrentCondition condition) {
log("sending cbcurrent condition");
try {
CbDataSender sender = new CbDataSender(getApplicationContext());
fromUser = true;
sender.setSettings(settingsHandler, locationManager,
lastMessenger, fromUser);
sender.execute(condition.getCurrentConditionAsParams());
fromUser = false;
return true;
} catch (Exception e) {
return false;
}
}
/**
* Start the periodic data collection.
*/
public void startSubmit() {
log("CbService: Starting to auto-collect and submit data.");
fromUser = false;
if (!alarm.isRepeating()) {
settingsHandler = settingsHandler.getSettings();
log("cbservice alarm not repeating, starting alarm at " + settingsHandler.getDataCollectionFrequency());
alarm.setAlarm(getApplicationContext(),
settingsHandler.getDataCollectionFrequency());
} else {
log("cbservice startsubmit, alarm is already repeating. restarting at " + settingsHandler.getDataCollectionFrequency());
alarm.restartAlarm(getApplicationContext(),
settingsHandler.getDataCollectionFrequency());
}
}
@Override
public void onDestroy() {
log("cbservice on destroy");
stopAutoSubmit();
unregisterReceiver(receiver);
super.onDestroy();
}
@Override
public void onCreate() {
setUpFiles();
log("cb on create");
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler.getSettings();
db = new CbDb(getApplicationContext());
fromUser = false;
prepForRegistration();
super.onCreate();
}
/**
* SDK registration
*/
private void prepForRegistration() {
IntentFilter filter = new IntentFilter();
filter.addAction(CbService.ACTION_REGISTER);
registerReceiver(receiver, filter);
}
/**
* Check charge state for preferences.
*
*/
public boolean isCharging() {
// Check battery and charging status
IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = getApplicationContext().registerReceiver(null,
ifilter);
// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
|| status == BatteryManager.BATTERY_STATUS_FULL;
return isCharging;
}
/**
* Each app registers with the SDK. Send the package name
* to
*/
private void sendRegistrationInfo() {
log("SDKTESTS: sending registration info");
Intent intent = new Intent(ACTION_REGISTER);
intent.putExtra("packagename", getApplicationContext().getPackageName());
intent.putExtra("time", System.currentTimeMillis());
sendBroadcast(intent);
}
private final BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ACTION_REGISTER)) {
String registeredName = intent.getStringExtra("packagename");
Long registeredTime = intent.getLongExtra("time", 0);
log("SDKTESTS: registering " + registeredName + " registered at " + registeredTime);
// addRegistration
db.open();
db.addRegistration(registeredName, registeredTime);
// check status
if(db.isPrimaryApp()) {
log("SDKTESTS: " + getApplicationContext().getPackageName() + " is primary");
} else {
log("SDKTESTS: " + getApplicationContext().getPackageName() + " is not primary");
}
db.close();
}
}
};
/**
* Start running background data collection methods.
*
*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
log("cbservice onstartcommand");
checkBarometer();
// wakelock management
if(wl!=null) {
log("cbservice wakelock not null:");
if(wl.isHeld()) {
log("cbservice existing wakelock; releasing");
wl.release();
} else {
log("cbservice wakelock not null but no existing lock");
}
}
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP , "CbService"); // PARTIAL_WAKE_LOCK
wl.acquire(1000);
log("cbservice acquiring wakelock " + wl.isHeld());
dataCollector = new CbDataCollector();
try {
if (intent != null) {
if (intent.getAction() != null) {
if (intent.getAction().equals(ACTION_SEND_MEASUREMENT)) {
// send just a single measurement
fromUser = false;
log("sending single observation, request from intent");
sendSingleObs();
return START_NOT_STICKY;
}
} else if (intent.getBooleanExtra("alarm", false)) {
// This runs when the service is started from the alarm.
// Submit a data point
log("cbservice alarm firing, sending data");
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler = settingsHandler.getSettings();
removeOldSDKApps();
sendRegistrationInfo();
if(settingsHandler.isSharingData()) {
//dataCollector.startCollectingData();
startWithIntent(intent, true);
} else {
log("cbservice not sharing data");
}
LocationStopper stop = new LocationStopper();
mHandler.postDelayed(stop, 1000 * 3);
return START_NOT_STICKY;
} else {
// Check the database
log("starting service with db");
startWithDatabase();
return START_NOT_STICKY;
}
}
} catch (Exception e) {
log("cbservice onstartcommand exception " + e.getMessage());
}
super.onStartCommand(intent, flags, startId);
return START_NOT_STICKY;
}
public void removeAllUninstalledApps() {
db.open();
db.close();
}
private void removeOldSDKApps() {
db.open();
db.removeOldSDKApps(1);
db.close();
}
/**
* Convert time ago text to ms. TODO: not this. values in xml.
*
* @param timeAgo
* @return
*/
public static long stringTimeToLongHack(String timeAgo) {
if (timeAgo.equals("1 minute")) {
return 1000 * 60;
} else if (timeAgo.equals("5 minutes")) {
return 1000 * 60 * 5;
} else if (timeAgo.equals("10 minutes")) {
return 1000 * 60 * 10;
} else if (timeAgo.equals("30 minutes")) {
return 1000 * 60 * 30;
} else if (timeAgo.equals("1 hour")) {
return 1000 * 60 * 60;
} else if (timeAgo.equals("3 hours")) {
return 1000 * 60 * 60 * 3;
} else if(timeAgo.equals("6 hours")) {
return 1000 * 60 * 60 * 6;
} else if(timeAgo.equals("12 hours")) {
return 1000 * 60 * 60 * 12;
}
return 1000 * 60 * 10;
}
public void loadSetttingsFromPreferences() {
log("cbservice loading settings from prefs");
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler.setServerURL(serverURL);
settingsHandler.setAppID(getApplication().getPackageName());
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
String preferenceCollectionFrequency = sharedPreferences.getString(
"autofrequency", "10 minutes");
boolean preferenceShareData = sharedPreferences.getBoolean(
"autoupdate", true);
String preferenceShareLevel = sharedPreferences.getString(
"sharing_preference", "Us, Researchers and Forecasters");
boolean preferenceSendNotifications = sharedPreferences.getBoolean(
"send_notifications", false);
settingsHandler
.setDataCollectionFrequency(stringTimeToLongHack(preferenceCollectionFrequency));
settingsHandler.setSendNotifications(preferenceSendNotifications);
boolean useGPS = sharedPreferences.getBoolean("use_gps", true);
boolean onlyWhenCharging = sharedPreferences.getBoolean(
"only_when_charging", false);
settingsHandler.setUseGPS(useGPS);
settingsHandler.setOnlyWhenCharging(onlyWhenCharging);
settingsHandler.setSharingData(preferenceShareData);
settingsHandler.setShareLevel(preferenceShareLevel);
// Seems like new settings. Try adding to the db.
settingsHandler.saveSettings();
}
public void startWithIntent(Intent intent, boolean fromAlarm) {
try {
if (!fromAlarm) {
// We arrived here from the user (i.e., not the alarm)
// start/(update?) the alarm
startSubmit();
} else {
// alarm. Go!
ReadingSender reading = new ReadingSender();
mHandler.post(reading);
}
} catch (Exception e) {
for (StackTraceElement ste : e.getStackTrace()) {
log(ste.getMethodName() + ste.getLineNumber());
}
}
}
public void startWithDatabase() {
try {
db.open();
// Check the database for Settings initialization
settingsHandler = new CbSettingsHandler(getApplicationContext());
Cursor allSettings = db.fetchSettingByApp(getPackageName());
log("cb intent null; checking db, size " + allSettings.getCount());
if (allSettings.moveToFirst()) {
settingsHandler.setAppID(allSettings.getString(1));
settingsHandler.setDataCollectionFrequency(allSettings
.getLong(2));
settingsHandler.setServerURL(serverURL);
int sendNotifications = allSettings.getInt(4);
int useGPS = allSettings.getInt(5);
int onlyWhenCharging = allSettings.getInt(6);
int sharingData = allSettings.getInt(7);
settingsHandler.setShareLevel(allSettings.getString(9));
boolean boolCharging = (onlyWhenCharging > 0);
boolean boolGPS = (useGPS > 0);
boolean boolSendNotifications = (sendNotifications > 0);
boolean boolSharingData = (sharingData > 0);
log("only when charging processed " + boolCharging + " gps "
+ boolGPS);
settingsHandler.setSendNotifications(boolSendNotifications);
settingsHandler.setOnlyWhenCharging(boolCharging);
settingsHandler.setUseGPS(boolGPS);
settingsHandler.setSharingData(boolSharingData);
settingsHandler.saveSettings();
}
log("cbservice startwithdb, " + settingsHandler);
ReadingSender reading = new ReadingSender();
mHandler.post(reading);
startSubmit();
db.close();
} catch (Exception e) {
for (StackTraceElement ste : e.getStackTrace()) {
log(ste.getMethodName() + ste.getLineNumber());
}
}
}
/**
* Handler of incoming messages from clients.
*/
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_STOP:
log("message. bound service says stop");
try {
alarm.cancelAlarm(getApplicationContext());
} catch(Exception e) {
}
break;
case MSG_GET_BEST_LOCATION:
log("cbservice message. bound service requesting location");
if (locationManager != null) {
Location best = locationManager.getCurrentBestLocation();
try {
log("service sending best location");
msg.replyTo.send(Message.obtain(null,
MSG_BEST_LOCATION, best));
} catch (RemoteException re) {
re.printStackTrace();
}
} else {
log("error: location null, not returning");
}
break;
case MSG_GET_BEST_PRESSURE:
log("message. bound service requesting pressure. not responding");
break;
case MSG_START_AUTOSUBMIT:
// log("start autosubmit");
// startWithDatabase();
break;
case MSG_STOP_AUTOSUBMIT:
log("cbservice stop autosubmit");
stopAutoSubmit();
break;
case MSG_GET_SETTINGS:
log("get settings");
if(settingsHandler != null) {
settingsHandler.getSettings();
} else {
settingsHandler = new CbSettingsHandler(getApplicationContext());
settingsHandler.getSettings();
}
try {
msg.replyTo.send(Message.obtain(null, MSG_SETTINGS,
settingsHandler));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_START_STREAM:
int sensorToStream = msg.arg1;
startSensorStream(sensorToStream, msg.replyTo);
break;
case MSG_STOP_STREAM:
int sensorToStop = msg.arg1;
stopSensorStream(sensorToStop);
break;
case MSG_SET_SETTINGS:
settingsHandler = (CbSettingsHandler) msg.obj;
log("cbservice set settings " + settingsHandler);
settingsHandler.saveSettings();
startSubmit();
break;
case MSG_GET_LOCAL_RECENTS:
log("get local recents");
recentMsg = msg;
CbApiCall apiCall = (CbApiCall) msg.obj;
if (apiCall == null) {
// log("apicall null, bailing");
break;
}
// run API call
db.open();
Cursor cursor = db.runLocalAPICall(apiCall.getMinLat(),
apiCall.getMaxLat(), apiCall.getMinLon(),
apiCall.getMaxLon(), apiCall.getStartTime(),
apiCall.getEndTime(), 2000);
ArrayList<CbObservation> results = new ArrayList<CbObservation>();
while (cursor.moveToNext()) {
// TODO: This is duplicated in CbDataCollector. Fix that
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(cursor.getDouble(1));
location.setLongitude(cursor.getDouble(2));
location.setAltitude(cursor.getDouble(3));
location.setAccuracy(cursor.getInt(4));
location.setProvider(cursor.getString(5));
obs.setLocation(location);
obs.setObservationType(cursor.getString(6));
obs.setObservationUnit(cursor.getString(7));
obs.setObservationValue(cursor.getDouble(8));
obs.setSharing(cursor.getString(9));
obs.setTime(cursor.getLong(10));
obs.setTimeZoneOffset(cursor.getInt(11));
obs.setUser_id(cursor.getString(12));
obs.setTrend(cursor.getString(18));
results.add(obs);
}
db.close();
log("cbservice: " + results.size() + " local api results");
try {
msg.replyTo.send(Message.obtain(null, MSG_LOCAL_RECENTS,
results));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_GET_API_RECENTS:
CbApiCall apiCacheCall = (CbApiCall) msg.obj;
log("get api recents " + apiCacheCall.toString());
// run API call
try {
db.open();
Cursor cacheCursor = db.runAPICacheCall(
apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(),
apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(),
apiCacheCall.getStartTime(),
apiCacheCall.getEndTime(), apiCacheCall.getLimit());
ArrayList<CbObservation> cacheResults = new ArrayList<CbObservation>();
while (cacheCursor.moveToNext()) {
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(cacheCursor.getDouble(1));
location.setLongitude(cacheCursor.getDouble(2));
location.setAltitude(cacheCursor.getDouble(3));
obs.setLocation(location);
obs.setObservationValue(cacheCursor.getDouble(4));
obs.setTime(cacheCursor.getLong(5));
cacheResults.add(obs);
}
// and get a few recent local results
Cursor localCursor = db.runLocalAPICall(
apiCacheCall.getMinLat(), apiCacheCall.getMaxLat(),
apiCacheCall.getMinLon(), apiCacheCall.getMaxLon(),
apiCacheCall.getStartTime(),
apiCacheCall.getEndTime(), 5);
ArrayList<CbObservation> localResults = new ArrayList<CbObservation>();
while (localCursor.moveToNext()) {
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(localCursor.getDouble(1));
location.setLongitude(localCursor.getDouble(2));
obs.setLocation(location);
obs.setObservationValue(localCursor.getDouble(8));
obs.setTime(localCursor.getLong(10));
localResults.add(obs);
}
db.close();
cacheResults.addAll(localResults);
try {
msg.replyTo.send(Message.obtain(null, MSG_API_RECENTS,
cacheResults));
} catch (RemoteException re) {
// re.printStackTrace();
}
} catch (Exception e) {
}
break;
case MSG_GET_API_RECENTS_FOR_GRAPH:
// TODO: Put this in a method. It's a copy+paste from
// GET_API_RECENTS
CbApiCall apiCacheCallGraph = (CbApiCall) msg.obj;
log("get api recents " + apiCacheCallGraph.toString());
// run API call
db.open();
Cursor cacheCursorGraph = db.runAPICacheCall(
apiCacheCallGraph.getMinLat(),
apiCacheCallGraph.getMaxLat(),
apiCacheCallGraph.getMinLon(),
apiCacheCallGraph.getMaxLon(),
apiCacheCallGraph.getStartTime(),
apiCacheCallGraph.getEndTime(),
apiCacheCallGraph.getLimit());
ArrayList<CbObservation> cacheResultsGraph = new ArrayList<CbObservation>();
while (cacheCursorGraph.moveToNext()) {
CbObservation obs = new CbObservation();
Location location = new Location("network");
location.setLatitude(cacheCursorGraph.getDouble(1));
location.setLongitude(cacheCursorGraph.getDouble(2));
obs.setLocation(location);
obs.setObservationValue(cacheCursorGraph.getDouble(3));
obs.setTime(cacheCursorGraph.getLong(4));
cacheResultsGraph.add(obs);
}
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_API_RECENTS_FOR_GRAPH, cacheResultsGraph));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_MAKE_API_CALL:
CbApi api = new CbApi(getApplicationContext());
CbApiCall liveApiCall = (CbApiCall) msg.obj;
liveApiCall.setCallType("Readings");
long timeDiff = System.currentTimeMillis() - lastAPICall;
deleteOldData();
lastAPICall = api.makeAPICall(liveApiCall, service,
msg.replyTo, "Readings");
break;
case MSG_MAKE_CURRENT_CONDITIONS_API_CALL:
CbApi conditionApi = new CbApi(getApplicationContext());
CbApiCall conditionApiCall = (CbApiCall) msg.obj;
conditionApiCall.setCallType("Conditions");
conditionApi.makeAPICall(conditionApiCall, service,
msg.replyTo, "Conditions");
break;
case MSG_CLEAR_LOCAL_CACHE:
db.open();
db.clearLocalCache();
long count = db.getUserDataCount();
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_COUNT_LOCAL_OBS_TOTALS, (int) count, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_REMOVE_FROM_PRESSURENET:
// TODO: Implement a secure system to remove user data
break;
case MSG_CLEAR_API_CACHE:
db.open();
db.clearAPICache();
long countCache = db.getDataCacheCount();
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_COUNT_API_CACHE_TOTALS, (int) countCache, 0));
} catch (RemoteException re) {
//re.printStackTrace();
}
break;
case MSG_ADD_CURRENT_CONDITION:
CbCurrentCondition cc = (CbCurrentCondition) msg.obj;
try {
db.open();
db.addCondition(cc);
db.close();
} catch(SQLiteDatabaseLockedException dble) {
}
break;
case MSG_GET_CURRENT_CONDITIONS:
recentMsg = msg;
CbApiCall currentConditionAPI = (CbApiCall) msg.obj;
ArrayList<CbCurrentCondition> conditions = getCurrentConditionsFromLocalAPI(currentConditionAPI);
try {
msg.replyTo.send(Message.obtain(null,
MSG_CURRENT_CONDITIONS, conditions));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_SEND_CURRENT_CONDITION:
CbCurrentCondition condition = (CbCurrentCondition) msg.obj;
if (settingsHandler == null) {
settingsHandler = new CbSettingsHandler(
getApplicationContext());
settingsHandler.setServerURL(serverURL);
settingsHandler
.setAppID(getApplication().getPackageName());
}
try {
condition
.setSharing_policy(settingsHandler.getShareLevel());
sendCbCurrentCondition(condition);
} catch (Exception e) {
//e.printStackTrace();
}
break;
case MSG_SEND_OBSERVATION:
log("sending single observation, request from app");
sendSingleObs();
break;
case MSG_COUNT_LOCAL_OBS:
db.open();
long countLocalObsOnly = db.getUserDataCount();
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_COUNT_LOCAL_OBS_TOTALS,
(int) countLocalObsOnly, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_COUNT_API_CACHE:
db.open();
long countCacheOnly = db.getDataCacheCount();
db.close();
try {
msg.replyTo.send(Message
.obtain(null, MSG_COUNT_API_CACHE_TOTALS,
(int) countCacheOnly, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
case MSG_CHANGE_NOTIFICATION:
log("cbservice dead code, change notification");
break;
case MSG_API_RESULT_COUNT:
log("cbservice msg_api_result_count");
// Current conditions API call for (made for local conditions alerts)
// returns here.
// potentially notify about nearby conditions
CbApiCall localConditions = buildLocalCurrentConditionsCall(1);
ArrayList<CbCurrentCondition> localRecentConditions = getCurrentConditionsFromLocalAPI(localConditions);
Intent intent = new Intent();
intent.setAction(CbService.LOCAL_CONDITIONS_ALERT);
if(localRecentConditions!=null) {
if(localRecentConditions.size()> 0) {
intent.putExtra("ca.cumulonimbus.pressurenetsdk.conditionNotification", localRecentConditions.get(0));
sendBroadcast(intent);
}
}
break;
case MSG_MAKE_STATS_CALL:
log("CbService received message to make stats API call");
CbStatsAPICall statsCall = (CbStatsAPICall) msg.obj;
CbApi statsApi = new CbApi(getApplicationContext());
statsApi.makeStatsAPICall(statsCall, service, msg.replyTo);
break;
case MSG_GET_CONTRIBUTIONS:
CbContributions contrib = new CbContributions();
db.open();
contrib.setPressureAllTime(db.getAllTimePressureCount());
contrib.setPressureLast24h(db.getLast24hPressureCount());
contrib.setPressureLast7d(db.getLast7dPressureCount());
contrib.setConditionsAllTime(db.getAllTimeConditionCount(getID()));
contrib.setConditionsLastWeek(db.getLast7dConditionCount(getID()));
contrib.setConditionsLastDay(db.getLastDayConditionCount(getID()));
db.close();
try {
msg.replyTo.send(Message
.obtain(null, MSG_CONTRIBUTIONS, contrib));
} catch (RemoteException re) {
// re.printStackTrace();
}
break;
case MSG_GET_DATABASE_INFO:
db.open();
long localObsCount = db.getUserDataCount();
db.close();
log("SDKTESTS: CbService says localObsCount is " + localObsCount);
/*
try {
msg.replyTo.send(Message.obtain(null,
MSG_COUNT_LOCAL_OBS_TOTALS,
(int) countLocalObsOnly2, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
*/
break;
case MSG_GET_PRIMARY_APP:
db.open();
boolean primary = db.isPrimaryApp();
int p = (primary==true) ? 1 : 0;
db.close();
try {
msg.replyTo.send(Message.obtain(null,
MSG_IS_PRIMARY, p, 0));
} catch (RemoteException re) {
re.printStackTrace();
}
break;
default:
super.handleMessage(msg);
}
}
}
private ArrayList<CbCurrentCondition> getCurrentConditionsFromLocalAPI(CbApiCall currentConditionAPI) {
ArrayList<CbCurrentCondition> conditions = new ArrayList<CbCurrentCondition>();
try {
db.open();
Cursor ccCursor = db.getCurrentConditions(
currentConditionAPI.getMinLat(),
currentConditionAPI.getMaxLat(),
currentConditionAPI.getMinLon(),
currentConditionAPI.getMaxLon(),
currentConditionAPI.getStartTime(),
currentConditionAPI.getEndTime(), 1000);
while (ccCursor.moveToNext()) {
CbCurrentCondition cur = new CbCurrentCondition();
Location location = new Location("network");
double latitude = ccCursor.getDouble(1);
double longitude = ccCursor.getDouble(2);
location.setLatitude(latitude);
location.setLongitude(longitude);
cur.setLat(latitude);
cur.setLon(longitude);
location.setAltitude(ccCursor.getDouble(3));
location.setAccuracy(ccCursor.getInt(4));
location.setProvider(ccCursor.getString(5));
cur.setLocation(location);
cur.setSharing_policy(ccCursor.getString(6));
cur.setTime(ccCursor.getLong(7));
cur.setTzoffset(ccCursor.getInt(8));
cur.setUser_id(ccCursor.getString(9));
cur.setGeneral_condition(ccCursor.getString(10));
cur.setWindy(ccCursor.getString(11));
cur.setFog_thickness(ccCursor.getString(12));
cur.setCloud_type(ccCursor.getString(13));
cur.setPrecipitation_type(ccCursor.getString(14));
cur.setPrecipitation_amount(ccCursor.getDouble(15));
cur.setPrecipitation_unit(ccCursor.getString(16));
cur.setThunderstorm_intensity(ccCursor.getString(17));
cur.setUser_comment(ccCursor.getString(18));
conditions.add(cur);
}
} catch (Exception e) {
log("cbservice get_current_conditions failed " + e.getMessage());
} finally {
db.close();
}
return conditions;
}
private CbApiCall buildLocalCurrentConditionsCall(double hoursAgo) {
log("building map conditions call for hours: "
+ hoursAgo);
long startTime = System.currentTimeMillis()
- (int) ((hoursAgo * 60 * 60 * 1000));
long endTime = System.currentTimeMillis();
CbApiCall api = new CbApiCall();
double minLat = 0;
double maxLat = 0;
double minLon = 0;
double maxLon = 0;
try {
Location lastKnown = locationManager.getCurrentBestLocation();
if(lastKnown.getLatitude() != 0) {
minLat = lastKnown.getLatitude() - .1;
maxLat = lastKnown.getLatitude() + .1;
minLon = lastKnown.getLongitude() - .1;
maxLon = lastKnown.getLongitude() + .1;
} else {
log("no location, bailing on csll");
return null;
}
api.setMinLat(minLat);
api.setMaxLat(maxLat);
api.setMinLon(minLon);
api.setMaxLon(maxLon);
api.setStartTime(startTime);
api.setEndTime(endTime);
api.setLimit(500);
api.setCallType("Conditions");
} catch(NullPointerException npe) {
}
return api;
}
public void sendSingleObs() {
if (settingsHandler != null) {
if (settingsHandler.getServerURL() == null) {
settingsHandler.getSettings();
}
}
SingleReadingSender singleSender = new SingleReadingSender();
mHandler.post(singleSender);
}
/**
* Remove older data from cache to keep the size reasonable
*
* @return
*/
public void deleteOldData() {
log("deleting old data");
db.open();
db.deleteOldCacheData();
db.close();
}
public boolean notifyAPIResult(Messenger reply, int count) {
try {
if (reply == null) {
log("cannot notify, reply is null");
} else {
reply.send(Message.obtain(null, MSG_API_RESULT_COUNT, count, 0));
}
} catch (RemoteException re) {
re.printStackTrace();
} catch (NullPointerException npe) {
//npe.printStackTrace();
}
return false;
}
public boolean notifyAPIStats(Messenger reply, ArrayList<CbStats> statsResult) {
try {
if (reply == null) {
log("cannot notify, reply is null");
} else {
log("cbservice notifying, " + statsResult.size());
reply.send(Message.obtain(null, MSG_STATS, statsResult));
}
} catch (RemoteException re) {
re.printStackTrace();
} catch (NullPointerException npe) {
npe.printStackTrace();
}
return false;
}
public CbObservation recentPressureFromDatabase() {
CbObservation obs = new CbObservation();
double pressure = 0.0;
try {
long rowId = db.fetchObservationMaxID();
Cursor c = db.fetchObservation(rowId);
while (c.moveToNext()) {
pressure = c.getDouble(8);
}
log(pressure + " pressure from db");
if (pressure == 0.0) {
log("returning null");
return null;
}
obs.setObservationValue(pressure);
return obs;
} catch (Exception e) {
obs.setObservationValue(pressure);
return obs;
}
}
/**
* Get a hash'd device ID
*
* @return
*/
public String getID() {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
String actual_id = Secure.getString(getApplicationContext()
.getContentResolver(), Secure.ANDROID_ID);
byte[] bytes = actual_id.getBytes();
byte[] digest = md.digest(bytes);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < digest.length; i++) {
hexString.append(Integer.toHexString(0xFF & digest[i]));
}
return hexString.toString();
} catch (Exception e) {
return "
}
}
// Used to write a log to SD card. Not used unless logging enabled.
public void setUpFiles() {
try {
File homeDirectory = getExternalFilesDir(null);
if (homeDirectory != null) {
mAppDir = homeDirectory.getAbsolutePath();
}
} catch (Exception e) {
//e.printStackTrace();
}
}
// Log data to SD card for debug purposes.
// To enable logging, ensure the Manifest allows writing to SD card.
public void logToFile(String text) {
try {
OutputStream output = new FileOutputStream(mAppDir + "/log.txt",
true);
String logString = (new Date()).toString() + ": " + text + "\n";
output.write(logString.getBytes());
output.close();
} catch (FileNotFoundException e) {
//e.printStackTrace();
} catch (IOException ioe) {
//ioe.printStackTrace();
}
}
@Override
public IBinder onBind(Intent intent) {
log("on bind");
return mMessenger.getBinder();
}
@Override
public void onRebind(Intent intent) {
log("on rebind");
super.onRebind(intent);
}
public void log(String message) {
if(CbConfiguration.DEBUG_MODE) {
logToFile(message);
System.out.println(message);
}
}
public CbDataCollector getDataCollector() {
return dataCollector;
}
public void setDataCollector(CbDataCollector dataCollector) {
this.dataCollector = dataCollector;
}
public CbLocationManager getLocationManager() {
return locationManager;
}
public void setLocationManager(CbLocationManager locationManager) {
this.locationManager = locationManager;
}
}
|
package com.experimentmob.core;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.logging.Logger;
import redis.clients.jedis.Jedis;
public class DatabaseHelper {
private static String PROPERTIES_HOSTNAME = "redis-hostname";
private static String PROPERTIES_PORT = "redis-port";
private static String FILES_PATH = "filespath";
private static DatabaseHelper dbHelper;
private static Logger logger = Logger.getLogger(DatabaseHelper.class.getCanonicalName());
private Jedis jedis;
private String filespath;
private Properties prop;
private DatabaseHelper() throws IOException {
prop = new Properties();
FileInputStream inputFileInputStream = new FileInputStream("config.properties");
prop.load(inputFileInputStream);
if (Util.isNullOrEmpty(prop.getProperty(PROPERTIES_HOSTNAME), prop.getProperty(PROPERTIES_PORT), prop.getProperty(FILES_PATH))) {
throw new IOException("Please set the properties of hostname, port and filespath in config.properties");
}
filespath = prop.getProperty(FILES_PATH);
File filePath = new File(filespath);
if(!filePath.canWrite()) {
throw new IOException("Can't write into filepath. Please ensure that the path given in the config.properties file is writable");
}
logger.info("Connecting to jedis");
jedis = new Jedis(prop.getProperty(PROPERTIES_HOSTNAME, "localhost"), Integer.parseInt(prop.getProperty(PROPERTIES_PORT, "6379")));
jedis.connect();
logger.info(("Server is running: " + jedis.ping()));
setShutdownHook();
}
private static void setShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
logger.info("Service has shut down");
dbHelper.jedis.disconnect();
}
}));
}
public Jedis getJedis() {
return jedis;
}
public String getFilespath() {
return filespath;
}
public void reInitJedis() {
jedis = new Jedis(prop.getProperty(PROPERTIES_HOSTNAME, "localhost"), Integer.parseInt(prop.getProperty(PROPERTIES_PORT, "6379")));
logger.info(("Server is running: " + jedis.ping()));
}
public static DatabaseHelper getInstance() throws IOException {
if (dbHelper == null) {
dbHelper = new DatabaseHelper();
}
return dbHelper;
}
}
|
package org.mockenize.service;
import java.io.IOException;
import java.util.Collection;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import org.mockenize.exception.ScriptNotFoundException;
import org.mockenize.model.ScriptBean;
import org.mockenize.repository.ScriptRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class ScriptService {
private static final String ENGINE_NAME = "JavaScript";
private static final String DEFAUL_FUNCTION_NAME = "_func";
private static final String PARSE_FUNCTION = ""
+ "function _func(url, body) {"
+ "try{obj=JSON.parse(body)}catch(ex){};"
+ "ret = func(url, body, obj);"
+ "try{return (typeof ret === 'string') ? ret : JSON.stringify(ret)}catch(ex){};"
+ "return ret};";
private static final String EMPTY = "";
@Autowired
private ObjectMapper objectMapper;
@Autowired
private ScriptRespository scriptRespository;
public ScriptBean getByKey(String jsName) {
ScriptBean scriptBean = scriptRespository.findByKey(jsName);
if (scriptBean == null) {
throw new ScriptNotFoundException();
}
return scriptBean;
}
public ScriptBean delete(ScriptBean scriptBean) {
return scriptRespository.delete(scriptBean.getName());
}
public Collection<ScriptBean> deleteAll() {
return scriptRespository.deleteAll();
}
public void save(ScriptBean scriptBean) {
scriptRespository.save(scriptBean);
}
public Collection<ScriptBean> getAll() {
return scriptRespository.findAll();
}
public JsonNode execute(ScriptBean scriptBean, String uri, JsonNode body)
throws ScriptException, NoSuchMethodException, IOException {
ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(ENGINE_NAME);
scriptEngine.eval(PARSE_FUNCTION + scriptBean.getValue());
Invocable invocable = (Invocable) scriptEngine;
String stringBody = body != null ? body.toString() : EMPTY;
String ret = String.valueOf(invocable.invokeFunction(DEFAUL_FUNCTION_NAME, uri, stringBody));
try {
return objectMapper.readTree(ret);
} catch(JsonParseException parseException) {
return objectMapper.createObjectNode().textNode(ret);
}
}
public Collection<String> getAllKeys() {
return scriptRespository.findAllKeys();
}
}
|
package org.motechproject.nms.imi.service.impl;
import org.joda.time.DateTime;
import org.motechproject.nms.imi.domain.CallDetailRecord;
import org.motechproject.nms.kilkari.dto.CallDetailRecordDto;
import org.motechproject.nms.props.domain.CallDisconnectReason;
import org.motechproject.nms.props.domain.RequestId;
import org.motechproject.nms.props.domain.StatusCode;
/**
* Helper class to parse a CSV line to a CallSummaryRecord (and vice versa, for use in ITs)
*/
public final class CsvHelper {
public static final String CDR_HEADER = "RequestId,Msisdn,CallId,AttemptNo,CallStartTime,CallAnswerTime," +
"CallEndTime,CallDurationInPulse,CallStatus,LanguageLocationId,ContentFile,MsgPlayStartTime," +
"MsgPlayEndTime,CircleId,OperatorId,Priority,CallDisconnectReason,WeekId";
private static final long MIN_MSISDN = 1000000000L;
private static final long MAX_MSISDN = 9999999999L;
private enum FieldName {
REQUEST_ID,
MSISDN,
CALL_ID,
ATTEMPT_NO,
CALL_START_TIME,
CALL_ANSWER_TIME,
CALL_END_TIME,
CALL_DURATION_IN_PULSE,
CALL_STATUS,
LANGUAGE_LOCATION_ID,
CONTENT_FILE,
MSG_PLAY_START_TIME,
MSG_PLAY_END_TIME,
CIRCLE_ID,
OPERATOR_ID,
PRIORITY,
CALL_DISCONNECT_REASON,
WEEK_ID,
FIELD_COUNT;
}
private CsvHelper() { }
private static long msisdnFromString(String msisdn) {
try {
Long l = Long.parseLong(msisdn);
if (l < MIN_MSISDN || l > MAX_MSISDN) {
throw new IllegalArgumentException("MSISDN must be >= 1000000000 and <= 9999999999");
}
return l;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("MSISDN must be an integer", e);
}
}
private static Long longOrNullFromString(String which, String s) {
if (s == null || s.isEmpty()) { return null; }
return longFromString(which, s);
}
private static long longFromString(String which, String s) {
try {
return Long.parseLong(s);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format("%s must be an integer", which), e);
}
}
private static int integerFromString(String which, String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
throw new IllegalArgumentException(String.format("%s must be an integer", which), e);
}
}
private static Integer calculateMsgPlayDuration(String msgPlayStartTime, String msgPlayEndTime) {
Long start;
Long end;
try {
start = longFromString("MsgPlayStartTime", msgPlayStartTime);
end = longFromString("MsgPlayEndTime", msgPlayEndTime);
} catch (IllegalArgumentException e) {
// MsgPlayStart is optional, so if either is missing return the play time as 0
return 0;
}
if (end < start) {
throw new IllegalArgumentException("MsgPlayEndTime cannot be before MsgPlayStartTime");
}
if ((end - start) > Integer.MAX_VALUE) {
throw new IllegalArgumentException(
"The difference between MsgPlayEndTime and MsgPlayStartTime is too large");
}
return ((int) (end - start));
}
public static CallDetailRecordDto csvLineToCdrDto(String line) {
CallDetailRecordDto cdr = new CallDetailRecordDto();
String[] fields = line.split(",");
if (fields.length != FieldName.FIELD_COUNT.ordinal()) {
throw new IllegalArgumentException(String.format(
"Invalid field count, expecting %d but received %d", FieldName.FIELD_COUNT.ordinal(),
fields.length));
}
/*
* See API 4.4.3 - CDR Detail File Format
*/
cdr.setRequestId(RequestId.fromString(fields[FieldName.REQUEST_ID.ordinal()]));
cdr.setMsisdn(msisdnFromString(fields[FieldName.MSISDN.ordinal()]));
Long callAnswerTime = longOrNullFromString("CallAnswerTime",
fields[FieldName.CALL_ANSWER_TIME.ordinal()]);
if (callAnswerTime != null) {
cdr.setCallAnswerTime(new DateTime(callAnswerTime));
} else {
cdr.setCallAnswerTime(null);
}
cdr.setMsgPlayDuration(calculateMsgPlayDuration(fields[FieldName.MSG_PLAY_START_TIME.ordinal()],
fields[FieldName.MSG_PLAY_END_TIME.ordinal()]));
cdr.setStatusCode(StatusCode.fromInt(integerFromString("CallStatus",
fields[FieldName.CALL_STATUS.ordinal()])));
cdr.setLanguageLocationId(fields[FieldName.LANGUAGE_LOCATION_ID.ordinal()]);
cdr.setContentFile(fields[FieldName.CONTENT_FILE.ordinal()]);
cdr.setCircleId(fields[FieldName.CIRCLE_ID.ordinal()]);
cdr.setOperatorId(fields[FieldName.OPERATOR_ID.ordinal()]);
cdr.setCallDisconnectReason(CallDisconnectReason.fromInt(integerFromString("CallDisconnectReason",
fields[FieldName.CALL_DISCONNECT_REASON.ordinal()])));
cdr.setWeekId(fields[FieldName.WEEK_ID.ordinal()]);
return cdr;
}
public static CallDetailRecord csvLineToCdr(String line) {
CallDetailRecord cdr = new CallDetailRecord();
String[] fields = line.split(",");
if (fields.length != FieldName.FIELD_COUNT.ordinal()) {
throw new IllegalArgumentException(String.format(
"Invalid field count, expecting %d but received %d", FieldName.FIELD_COUNT.ordinal(),
fields.length));
}
/*
* See API 4.4.3 - CDR Detail File Format
*/
cdr.setRequestId(fields[FieldName.REQUEST_ID.ordinal()]);
cdr.setMsisdn(fields[FieldName.MSISDN.ordinal()]);
cdr.setCallId(fields[FieldName.CALL_ID.ordinal()]);
cdr.setAttemptNo(fields[FieldName.ATTEMPT_NO.ordinal()]);
cdr.setCallStartTime(fields[FieldName.CALL_START_TIME.ordinal()]);
cdr.setCallAnswerTime(fields[FieldName.CALL_ANSWER_TIME.ordinal()]);
cdr.setCallEndTime(fields[FieldName.CALL_END_TIME.ordinal()]);
cdr.setCallDurationInPulse(fields[FieldName.CALL_DURATION_IN_PULSE.ordinal()]);
cdr.setCallStatus(fields[FieldName.CALL_STATUS.ordinal()]);
cdr.setLanguageLocationId(fields[FieldName.LANGUAGE_LOCATION_ID.ordinal()]);
cdr.setContentFile(fields[FieldName.CONTENT_FILE.ordinal()]);
cdr.setMsgPlayStartTime(fields[FieldName.MSG_PLAY_START_TIME.ordinal()]);
cdr.setMsgPlayEndTime(fields[FieldName.MSG_PLAY_END_TIME.ordinal()]);
cdr.setCircleId(fields[FieldName.CIRCLE_ID.ordinal()]);
cdr.setOperatorId(fields[FieldName.OPERATOR_ID.ordinal()]);
cdr.setPriority(fields[FieldName.PRIORITY.ordinal()]);
cdr.setCallDisconnectReason(fields[FieldName.CALL_DISCONNECT_REASON.ordinal()]);
cdr.setWeekId(fields[FieldName.WEEK_ID.ordinal()]);
return cdr;
}
/**
* Validate Header coming in CDR file from IMI
*
* @param line a CSV line from a CDR Detail File from IMI
*
*/
public static void validateCdrHeader(String line) {
if (!(CDR_HEADER.equalsIgnoreCase(line))) {
throw new IllegalArgumentException("Invalid CDR header");
}
}
}
|
package com.flicklib.module;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
/**
* Demo implementation of netflix auth
*
* @author francisdb
*/
public class NetFlixAuthModule extends AbstractModule {
private String apikey;
private String sharedsecret;
public NetFlixAuthModule(final String apikey, final String sharedsecret) {
this.apikey = apikey;
this.sharedsecret = sharedsecret;
}
/* (non-Javadoc)
* @see com.google.inject.AbstractModule#configure()
*/
@Override
protected void configure() {
bindConstant().annotatedWith(Names.named("netflix.key")).to(apikey);
bindConstant().annotatedWith(Names.named("netflix.secret")).to(sharedsecret);
}
}
|
package org.myrobotlab.service;
import java.io.File;
import java.io.IOException;
import java.util.Locale;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.io.FileIO;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.service.interfaces.PortConnector;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.slf4j.Logger;
/**
* InMoovTorso - The inmoov torso. This will allow control of the topStom,
* midStom, and lowStom servos.
*
*/
public class InMoov2Torso extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(InMoov2Torso.class);
transient public ServoControl topStom;
transient public ServoControl midStom;
transient public ServoControl lowStom;
public InMoov2Torso(String n, String id) {
super(n, id);
// TODO: just call startPeers here.
// // createReserves(n); // Ok this might work but IT CANNOT BE IN SERVICE
// // FRAMEWORK !!!!!
// topStom = (ServoControl) createPeer("topStom");
// midStom = (ServoControl) createPeer("midStom");
// lowStom = (ServoControl) createPeer("lowStom");
// // controller = (ServoController) createPeer("arduino");
// FIXME - createPeers ?
}
public void startService() {
super.startService();
startPeers();
topStom.setPin(27);
midStom.setPin(28);
lowStom.setPin(29);
topStom.map(60.0, 120.0, 60.0, 120.0);
midStom.map(0.0, 180.0, 0.0, 180.0);
lowStom.map(0.0, 180.0, 0.0, 180.0);
topStom.setRest(90.0);
topStom.setPosition(90.0);
midStom.setRest(90.0);
midStom.setPosition(90.0);
lowStom.setRest(90.0);
lowStom.setPosition(90.0);
setVelocity(5.0, 5.0, 5.0);
}
public void releaseService() {
try {
disable();
releasePeers();
super.releaseService();
} catch (Exception e) {
error(e);
}
}
public void enable() {
topStom.enable();
midStom.enable();
lowStom.enable();
}
public void setAutoDisable(Boolean param) {
topStom.setAutoDisable(param);
midStom.setAutoDisable(param);
lowStom.setAutoDisable(param);
}
@Override
public void broadcastState() {
if (topStom != null)topStom.broadcastState();
if (midStom != null)midStom.broadcastState();
if (lowStom != null)lowStom.broadcastState();
}
public void disable() {
topStom.disable();
midStom.disable();
lowStom.disable();
}
public long getLastActivityTime() {
long minLastActivity = Math.max(topStom.getLastActivityTime(), midStom.getLastActivityTime());
minLastActivity = Math.max(minLastActivity, lowStom.getLastActivityTime());
return minLastActivity;
}
@Deprecated /* use LangUtils */
public String getScript(String inMoovServiceName) {
return String.format(Locale.ENGLISH, "%s.moveTorso(%.2f,%.2f,%.2f)\n", inMoovServiceName, topStom.getCurrentInputPos(), midStom.getCurrentInputPos(), lowStom.getCurrentInputPos());
}
public void moveTo(double topStom, double midStom, double lowStom) {
if (log.isDebugEnabled()) {
log.debug("{} moveTo {} {} {}", getName(), topStom, midStom, lowStom);
}
this.topStom.moveTo(topStom);
this.midStom.moveTo(midStom);
this.lowStom.moveTo(lowStom);
}
public void moveToBlocking(Double topStom, Double midStom, Double lowStom) {
log.info("init {} moveToBlocking ", getName());
moveTo(topStom, midStom, lowStom);
waitTargetPos();
log.info("end {} moveToBlocking", getName());
}
public void waitTargetPos() {
topStom.waitTargetPos();
midStom.waitTargetPos();
lowStom.waitTargetPos();
}
public void rest() {
topStom.rest();
midStom.rest();
lowStom.rest();
}
@Override
public boolean save() {
super.save();
topStom.save();
midStom.save();
lowStom.save();
return true;
}
@Deprecated
public boolean loadFile(String file) {
File f = new File(file);
Python p = (Python) Runtime.getService("python");
log.info("Loading Python file {}", f.getAbsolutePath());
if (p == null) {
log.error("Python instance not found");
return false;
}
String script = null;
try {
script = FileIO.toString(f.getAbsolutePath());
} catch (IOException e) {
log.error("IO Error loading file : ", e);
return false;
}
// evaluate the scripts in a blocking way.
boolean result = p.exec(script, true);
if (!result) {
log.error("Error while loading file {}", f.getAbsolutePath());
return false;
} else {
log.debug("Successfully loaded {}", f.getAbsolutePath());
}
return true;
}
/**
* Sets the output min/max values for all servos in the torso. input limits on servos
* are not modified in this method.
*
* @param topStomMin
* @param topStomMax
* @param midStomMin
* @param midStomMax
* @param lowStomMin
* @param lowStomMax
*/
public void setLimits(double topStomMin, double topStomMax, double midStomMin, double midStomMax, double lowStomMin, double lowStomMax) {
topStom.setMinMaxOutput(topStomMin, topStomMax);
midStom.setMinMaxOutput(midStomMin, midStomMax);
lowStom.setMinMaxOutput(lowStomMin, lowStomMax);
}
public void setpins(Integer topStomPin, Integer midStomPin, Integer lowStomPin) {
// createPeers();
/*
* this.topStom.setPin(topStom); this.midStom.setPin(midStom);
* this.lowStom.setPin(lowStom);
*/
/**
* FIXME - has to be done outside of
*
* arduino.servoAttachPin(topStom, topStomPin);
* arduino.servoAttachPin(topStom, midStomPin);
* arduino.servoAttachPin(topStom, lowStomPin);
*/
}
public void setSpeed(Double topStom, Double midStom, Double lowStom) {
log.warn("setspeed deprecated please use setvelocity");
this.topStom.setSpeed(topStom);
this.midStom.setSpeed(midStom);
this.lowStom.setSpeed(lowStom);
}
public void test() {
topStom.moveTo(topStom.getCurrentInputPos() + 2);
midStom.moveTo(midStom.getCurrentInputPos() + 2);
lowStom.moveTo(lowStom.getCurrentInputPos() + 2);
moveTo(35.0, 45.0, 55.0);
}
@Deprecated /* use setSpeed */
public void setVelocity(Double topStom, Double midStom, Double lowStom) {
this.topStom.setSpeed(topStom);
this.midStom.setSpeed(midStom);
this.lowStom.setSpeed(lowStom);
}
static public void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
VirtualArduino v = (VirtualArduino) Runtime.start("virtual", "VirtualArduino");
v.connect("COM4");
InMoov2Torso torso = (InMoov2Torso) Runtime.start("i01.torso", "InMoovTorso");
Runtime.start("webgui", "WebGui");
torso.test();
} catch (Exception e) {
log.error("main threw", e);
}
}
public void fullSpeed() {
topStom.fullSpeed();
midStom.fullSpeed();
lowStom.fullSpeed();
}
public void stop() {
topStom.stop();
midStom.stop();
lowStom.stop();
}
}
|
package gluewine.hibernate;
import java.util.ArrayList;
import java.util.List;
import org.gluewine.console.CLICommand;
import org.gluewine.console.CommandContext;
import org.gluewine.core.Glue;
import org.gluewine.persistence.TransactionCallback;
import org.gluewine.persistence.Transactional;
import org.gluewine.persistence_jpa.Filter;
import org.gluewine.persistence_jpa.FilterLine;
import org.gluewine.persistence_jpa.FilterOperator;
import org.gluewine.persistence_jpa_hibernate.HibernateSessionProvider;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import gluewine.entities.User;
public class UserService {
@Glue
private HibernateSessionProvider provider;
/*
*The method user_list.
* With this method we can print a list of all the users in the database
*/
@Transactional
public void _user_list(CommandContext cc)
{
//We need to get all the users that are in the database
List<User> users = provider.getSession().getAll(User.class);
cc.tableHeader("Id", "Username", "Is admin");
for (User user : users) {
cc.tableRow(Long.toString(user.getId()), user.getUsername(), Boolean.toString(user.getRole()));
}
cc.printTable();
}
/*
* The metohd user_search.
* With this method we can search for a user on criteria 'username'.
*/
@Transactional
public void _user_search(CommandContext cc)
{
String text = cc.getOption("-text");
Filter filter = new Filter();
FilterLine filterline = new FilterLine();
filterline.setFieldName("username");
filterline.setOperator(FilterOperator.ICONTAINS);
filterline.setValue(text);
filter.setLimit(10);
filter.addFilterLine(filterline);
List <User> l = provider.getSession().getFiltered(User.class, filter);
cc.tableHeader("Id", "Username", "Is admin");
for (User user : l) {
cc.tableRow(Long.toString(user.getId()), user.getUsername(), Boolean.toString(user.getRole()));
}
cc.printTable();
}
@Transactional
public void _testing(CommandContext cc) {
cc.tableHeader("testing");
}
/*
* (non-Javadoc)
* @see org.gluewine.console.CommandProvider#getCommands()
*/
public List<CLICommand> getCommands()
{
List<CLICommand> l = new ArrayList<>();
//list all the users in the db
CLICommand cmd_user_list = new CLICommand("user_list", "Lists the users");
l.add(cmd_user_list);
//search a car
CLICommand cmd_user_search = new CLICommand("user_search", "Searches a user on criteria 'username'");
cmd_user_search.addOption("-text", "%criteria%", true, true);
l.add(cmd_user_search);
CLICommand cmd_testing = new CLICommand("testing","testing description");
l.add(cmd_testing);
return l;
}
}
|
package alma.acs.tmcdb.translator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.cfg.reveng.AssociationInfo;
import org.hibernate.cfg.reveng.DefaulAssociationInfo;
import org.hibernate.cfg.reveng.DelegatingReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.ReverseEngineeringStrategy;
import org.hibernate.cfg.reveng.TableIdentifier;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.ForeignKey;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.tool.hbm2x.MetaAttributeConstants;
import alma.acs.tmcdb.translator.AbstractTableInheritance.CascadeType;
public abstract class AbstractReverseEngineeringStrategy extends DelegatingReverseEngineeringStrategy {
private static final String ORACLE_SEQUENCE = "oracle-sequence";
private static final String IS_XML_CLOB_TYPE = "isXmlClobType";
private static final String HAS_XML_CLOB_TYPE = "hasXmlClobType";
private static final String HAS_ENUM_TYPES = "has-enum-types";
private static final String ENUM_TYPES = "enum-types";
private static final String IS_SUPER_CLASS = "isSuperClass";
private static final String IS_ENUM_TYPE = "is-enum-type";
private static final String ENUM_TYPE_NAME = "enum-type-name";
protected AbstractColumn2Attribute []columnTranslators;
protected AbstractTable2Class []tableTranslators;
protected AbstractTableInheritance []inheritanceTranslators;
/**
* Default constructor, that shouldn't be ever used
*/
public AbstractReverseEngineeringStrategy() { super(null); };
public AbstractReverseEngineeringStrategy(ReverseEngineeringStrategy delegate) { super(delegate); };
@Override
public String tableToClassName(TableIdentifier table) {
String className = null;
for(int i=0; i!=tableTranslators.length; i++) {
AbstractTable2Class trans = tableTranslators[i];
className = trans.getMap().get(table.getName().toLowerCase());
if( className != null )
break;
}
return className;
}
@Override
public String columnToPropertyName(TableIdentifier table, String column) {
String propertyName = null;
for (int i = 0; i != columnTranslators.length; i++) {
AbstractColumn2Attribute trans = columnTranslators[i];
Map<String, String> tableMap = trans.getMap().get(
table.getName().toLowerCase());
if (tableMap != null) {
propertyName = tableMap.get(column.toLowerCase());
if (propertyName != null)
break;
}
}
return propertyName;
}
// Used to provide only Object types (e.g., Integer instead of int)
@Override
public String columnToHibernateTypeName(TableIdentifier table,
String columnName, int sqlType, int length, int precision,
int scale, boolean nullable, boolean generatedIdentifier) {
String tableName = table.getName().toLowerCase();
for (int i = 0; i < inheritanceTranslators.length; i++) {
if( inheritanceTranslators[i].getEnumTypeForColumn(tableName, columnName.toLowerCase()) != null ) {
return inheritanceTranslators[i].getEnumTypeForColumn(tableName, columnName.toLowerCase());
}
}
return super.columnToHibernateTypeName(table, columnName, sqlType, length,
precision, scale, true, generatedIdentifier);
}
@SuppressWarnings("unchecked")
@Override
public Map tableToMetaAttributes(TableIdentifier tableIdentifier) {
Map map = super.tableToMetaAttributes(tableIdentifier);
if( map == null )
map = new HashMap<String, MetaAttribute>();
// Check if table contains a XMLCLOB column
for (int i = 0; i < inheritanceTranslators.length; i++) {
String tableName = tableIdentifier.getName();
if( inheritanceTranslators[i].hasXmlClobType(tableName) ) {
MetaAttribute mattr = new MetaAttribute(HAS_XML_CLOB_TYPE);
mattr.addValue("true");
map.put(HAS_XML_CLOB_TYPE,mattr);
break;
}
}
// Check if table has a generated ID, necessary to generate the GenericGenerator custom annotation
for (int i = 0; i < inheritanceTranslators.length; i++) {
String tableName = tableIdentifier.getName();
String sequence = inheritanceTranslators[i].getSequenceForTable(tableName);
if( sequence != null ) {
MetaAttribute mattr = new MetaAttribute(ORACLE_SEQUENCE);
mattr.addValue(sequence);
map.put(ORACLE_SEQUENCE,mattr);
break;
}
}
// Check all CHECK constraints for this table
for (int i = 0; i < inheritanceTranslators.length; i++) {
String tableName = tableIdentifier.getName().toLowerCase();
Map<String, String> typesForTable = inheritanceTranslators[i].getEnumTypesForTable(tableName);
if( typesForTable == null || typesForTable.size() == 0) {
continue;
} else {
MetaAttribute mattr2 = new MetaAttribute(HAS_ENUM_TYPES);
mattr2.addValue("true");
map.put(HAS_ENUM_TYPES, mattr2);
mattr2 = new MetaAttribute(ENUM_TYPES);
Iterator<Map.Entry<String, String>> it = typesForTable.entrySet().iterator();
StringBuilder sb = new StringBuilder();
while(it.hasNext()) {
Map.Entry<String, String> entry = it.next();
sb.append(entry.getKey());
sb.append("|");
sb.append(entry.getValue());
if(it.hasNext())
sb.append(",");
}
mattr2.addValue(sb.toString());
map.put(ENUM_TYPES, mattr2);
}
}
// Check if table is superclass or child class
for (int i = 0; i < inheritanceTranslators.length; i++) {
String tableName = tableIdentifier.getName().toLowerCase();
String superClass = inheritanceTranslators[i].getSuperTable(tableName);
if( superClass != null ) {
MetaAttribute mattr = new MetaAttribute(MetaAttributeConstants.EXTENDS);
mattr.addValue(superClass);
map.put("extends",mattr);
return map;
}
else {
MetaAttribute mattr = new MetaAttribute(MetaAttributeConstants.EXTENDS);
mattr.addValue("alma.acs.tmcdb.translator.TmcdbObject");
map.put("extends",mattr);
for(int j=0; j!= inheritanceTranslators.length; j++) {
if( inheritanceTranslators[j].isSuperClass(tableName) ) {
mattr = new MetaAttribute(IS_SUPER_CLASS);
mattr.addValue("true");
map.put(IS_SUPER_CLASS,mattr);
return map;
}
}
}
}
return map;
}
@SuppressWarnings("unchecked")
@Override
public Map columnToMetaAttributes(TableIdentifier identifier, String column) {
Map map = super.columnToMetaAttributes(identifier, column);
if( map == null )
map = new HashMap<String, MetaAttribute>();
String tableName = identifier.getName().toLowerCase();
// Don't generate getter/setters for inheritance-related fields
MetaAttribute mattr = new MetaAttribute(MetaAttributeConstants.GEN_PROPERTY);
for (int i = 0; i < inheritanceTranslators.length; i++) {
List<String> columns = inheritanceTranslators[i].getPkFkCombinationColumns(tableName);
if( columns != null && columns.contains(column.toLowerCase()) ) {
mattr.addValue("false");
map.put("gen-property", mattr);
return map;
}
}
// Make everything protected
mattr.addValue("protected");
map.put("scope-field",mattr);
// Check for special XMLCLOB types, they get a specific annotation generated
for (int i = 0; i < inheritanceTranslators.length; i++) {
if( inheritanceTranslators[i].hasXmlClobType(tableName) ) {
if( inheritanceTranslators[i].isXmlClobType(tableName, column) ) {
MetaAttribute mattr2 = new MetaAttribute(IS_XML_CLOB_TYPE);
mattr2.addValue("true");
map.put(IS_XML_CLOB_TYPE, mattr2);
break;
}
}
}
for (int i = 0; i < inheritanceTranslators.length; i++) {
if( inheritanceTranslators[i].isKeyPiece(tableName, column) ) {
MetaAttribute mattr2 = new MetaAttribute("use-in-equals");
mattr2.addValue("true");
map.put("use-in-equals", mattr2);
break;
}
}
return map;
}
@SuppressWarnings("unchecked")
@Override
public boolean excludeForeignKeyAsCollection(String keyname,
TableIdentifier fromTable, List fromColumns,
TableIdentifier referencedTable, List referencedColumns) {
if( excludeForeignKey(keyname, fromTable, fromColumns, referencedTable, referencedColumns, true) )
return true;
return super.excludeForeignKeyAsCollection(keyname, fromTable, fromColumns,
referencedTable, referencedColumns);
}
@SuppressWarnings("unchecked")
private boolean excludeForeignKey(String keyname,
TableIdentifier fromTable, List fromColumns,
TableIdentifier referencedTable, List referencedColumns,
boolean checkDuplicatedFK) {
for (int i = 0; i < inheritanceTranslators.length; i++) {
String tName = fromTable.getName().toLowerCase();
String superTable = inheritanceTranslators[i].getSuperTable(tName);
String keyName = inheritanceTranslators[i].getKeynameLowercase(tName);
if( superTable != null &&
superTable.toLowerCase().equals(referencedTable.getName().toLowerCase()) &&
keyname.toLowerCase().equals(keyName) ) {
return true;
}
if( checkDuplicatedFK && !inheritanceTranslators[i].generateInverseCollection(tName, ((Column)fromColumns.get(0)).getName() ) )
return true;
}
return false;
}
@SuppressWarnings("unchecked")
@Override
public boolean excludeForeignKeyAsManytoOne(String keyname,
TableIdentifier fromTable, List fromColumns,
TableIdentifier referencedTable, List referencedColumns) {
return excludeForeignKey(keyname, fromTable, fromColumns, referencedTable, referencedColumns, false);
}
@Override
public AssociationInfo foreignKeyToAssociationInfo(
ForeignKey foreignKey) {
DefaulAssociationInfo info = new DefaulAssociationInfo();
String name = foreignKey.getName();
for (int i = 0; i < inheritanceTranslators.length; i++) {
CascadeType cType = inheritanceTranslators[i].getCascadeTypeForForeigKey(name);
if( cType != null ) {
if( cType == CascadeType.NONE) {
info.setCascade("none"); // if not set, it produces an EJB3 "all" cascading
break;
}
else if( cType == CascadeType.AGGREGATION ) {
info.setCascade("save-update, persist, lock");
break;
}
else if( cType == CascadeType.COMPOSITION ) {
info.setCascade("all-delete-orphan");
break;
}
else {
info.setCascade("none"); // fallback
break;
}
}
}
return info;
}
@Override
public AssociationInfo foreignKeyToInverseAssociationInfo(
ForeignKey foreignKey) {
DefaulAssociationInfo info = new DefaulAssociationInfo();
String name = foreignKey.getName();
for (int i = 0; i < inheritanceTranslators.length; i++) {
CascadeType cType = inheritanceTranslators[i].getCascadeTypeForForeigKey(name);
if( cType != null ) {
if( cType == CascadeType.AGGREGATION_INVERSE ) {
info.setCascade("save-update, persist, lock");
break;
}
else if( cType == CascadeType.COMPOSITION_INVERSE ) {
info.setCascade("all-delete-orphan");
break;
}
else {
info.setCascade("none"); // fallback
break;
}
}
}
return info;
}
// @Override
// public boolean excludeColumn(TableIdentifier identifier, String columnName) {
// String tableName = identifier.getName().toLowerCase();
// for (int i = 0; i < inheritanceTranslators.length; i++) {
// List<String> columns = inheritanceTranslators[i].getPkFkCombinationColumns(tableName);
// if( columns != null && columns.contains(columnName.toLowerCase()) ) {
// System.out.println("KeyColumns!!!!!!! " + tableName + ":" + columnName);
// return true;
// return super.excludeColumn(identifier, columnName);
}
|
package com.github.aesteve.vertx.nubes;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.github.aesteve.vertx.nubes.auth.AuthMethod;
import com.github.aesteve.vertx.nubes.context.RateLimit;
import com.github.aesteve.vertx.nubes.handlers.AnnotationProcessorRegistry;
import com.github.aesteve.vertx.nubes.handlers.Processor;
import com.github.aesteve.vertx.nubes.marshallers.PayloadMarshaller;
import com.github.aesteve.vertx.nubes.reflections.RouteRegistry;
import com.github.aesteve.vertx.nubes.reflections.injectors.annot.AnnotatedParamInjectorRegistry;
import com.github.aesteve.vertx.nubes.reflections.injectors.typed.TypedParamInjectorRegistry;
import com.github.aesteve.vertx.nubes.services.ServiceRegistry;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.AuthProvider;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.sockjs.SockJSHandlerOptions;
import io.vertx.ext.web.templ.HandlebarsTemplateEngine;
import io.vertx.ext.web.templ.JadeTemplateEngine;
import io.vertx.ext.web.templ.MVELTemplateEngine;
import io.vertx.ext.web.templ.TemplateEngine;
import io.vertx.ext.web.templ.ThymeleafTemplateEngine;
public class Config {
private Config() {
bundlesByLocale = new HashMap<>();
globalHandlers = new ArrayList<>();
templateEngines = new HashMap<>();
sockJSOptions = new SockJSHandlerOptions();
marshallers = new HashMap<>();
}
public JsonObject json;
public String srcPackage;
public List<String> controllerPackages;
public List<String> fixturePackages;
public String verticlePackage;
public String domainPackage;
public RateLimit rateLimit;
public String webroot;
public String assetsPath;
public String tplDir;
public boolean displayErrors;
public Vertx vertx;
public AuthProvider authProvider;
public AuthMethod authMethod;
public String i18nDir;
public AnnotationProcessorRegistry apRegistry;
public Map<Class<? extends Annotation>, Set<Handler<RoutingContext>>> annotationHandlers;
public Map<Class<?>, Processor> typeProcessors;
public TypedParamInjectorRegistry typeInjectors;
public AnnotatedParamInjectorRegistry annotInjectors;
public ServiceRegistry serviceRegistry;
public RouteRegistry routeRegistry;
public Map<Class<?>, Handler<RoutingContext>> paramHandlers;
public Map<String, Handler<RoutingContext>> aopHandlerRegistry;
public Map<Locale, ResourceBundle> bundlesByLocale;
public List<Handler<RoutingContext>> globalHandlers;
public Map<String, TemplateEngine> templateEngines;
public SockJSHandlerOptions sockJSOptions;
public Map<String, PayloadMarshaller> marshallers;
/**
* TODO : check config instead of throwing exceptions
*
* @param json
* @return config
*/
@SuppressWarnings("unchecked")
public static Config fromJsonObject(JsonObject json, Vertx vertx) {
Config instance = new Config();
JsonObject services;
JsonArray templates;
instance.json = json;
instance.vertx = vertx;
instance.srcPackage = json.getString("src-package");
instance.i18nDir = json.getString("i18nDir", "web/i18n/");
if (!instance.i18nDir.endsWith("/")) {
instance.i18nDir = instance.i18nDir + "/";
}
JsonArray controllers = json.getJsonArray("controller-packages", new JsonArray().add(instance.srcPackage + ".controllers"));
instance.controllerPackages = controllers.getList();
instance.verticlePackage = json.getString("verticle-package", instance.srcPackage + ".verticles");
instance.domainPackage = json.getString("domain-package", instance.srcPackage + ".domains");
JsonArray fixtures = json.getJsonArray("fixture-packages",new JsonArray().add(instance.srcPackage + ".fixtures"));
instance.fixturePackages = fixtures.getList();
//register services included in config
services = json.getJsonObject("services", new JsonObject());
instance.serviceRegistry = new ServiceRegistry(vertx);
for (Map.Entry<String, Object> service : services) {
String name = service.getKey();
String className = (String)service.getValue();
try {
Class<?> clazz = Class.forName(className);
instance.serviceRegistry.registerService(name, clazz.newInstance());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
templates = json.getJsonArray("templates", new JsonArray());
//Register templateEngines for extensions added in config
if(templates.contains("hbs")) {
instance.templateEngines.put("hbs", HandlebarsTemplateEngine.create());
}
if(templates.contains("jade")) {
instance.templateEngines.put("jade", JadeTemplateEngine.create());
}
if(templates.contains("templ")){
instance.templateEngines.put("templ", MVELTemplateEngine.create());
}
if(templates.contains("thymeleaf")){
instance.templateEngines.put("html", ThymeleafTemplateEngine.create());
}
JsonObject rateLimitJson = json.getJsonObject("throttling");
if (rateLimitJson != null) {
int count = rateLimitJson.getInteger("count");
int value = rateLimitJson.getInteger("time-frame");
TimeUnit timeUnit = TimeUnit.valueOf(rateLimitJson.getString("time-unit"));
instance.rateLimit = new RateLimit(count, value, timeUnit);
}
instance.webroot = json.getString("webroot", "web/assets");
instance.assetsPath = json.getString("static-path", "/assets");
instance.tplDir = json.getString("views-dir", "web/views");
instance.displayErrors = json.getBoolean("display-errors", Boolean.FALSE);
// TODO : read sockJSOptions from config
return instance;
}
public ResourceBundle getResourceBundle(Locale loc) {
return bundlesByLocale.get(loc);
}
}
|
package org.railwaystations.api.model;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
public class Photo {
public static final String FLAG_DEFAULT = "0";
private static final BiMap<String, String> FLAGS = HashBiMap.create();
static {
FLAGS.put("1", "@RecumbentTravel");
}
private final Station.Key stationKey;
private final String url;
private final String photographer;
private final String photographerUrl;
private final Long createdAt;
private final String license;
private final String statUser;
private final String flag;
public Photo(final Station.Key stationKey, final String url, final String photographer, final String photographerUrl, final Long createdAt, final String license) {
this(stationKey, url, photographer, photographerUrl, createdAt, license, FLAG_DEFAULT);
}
public Photo(final Station.Key stationKey, final String url, final String photographer, final String photographerUrl, final Long createdAt, final String license, final String flag) {
this.stationKey = stationKey;
this.url = url;
this.photographer = photographer;
this.photographerUrl = photographerUrl;
this.createdAt = createdAt;
this.license = license;
this.flag = flag;
this.statUser = getStatUser(flag, photographer);
}
/**
* Gets the user for the statistic, deanonymizes if mapping exists
*/
public static String getStatUser(final String flag, final String photographer) {
return FLAGS.getOrDefault(flag, photographer);
}
public static String getFlag(final String photographerName) {
return FLAGS.inverse().getOrDefault(photographerName, FLAG_DEFAULT);
}
public String getUrl() {
return url;
}
public String getPhotographer() {
return photographer;
}
public Station.Key getStationKey() {
return stationKey;
}
public String getLicense() {
return license;
}
public String getPhotographerUrl() {
return photographerUrl;
}
public String getStatUser() {
return statUser;
}
public Long getCreatedAt() {
return createdAt;
}
public String getFlag() {
return flag;
}
}
|
package com.hubspot.singularity.data.zkmigrations;
import javax.inject.Singleton;
import javax.ws.rs.WebApplicationException;
import org.apache.curator.framework.CuratorFramework;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.mesos.JavaUtils;
import com.hubspot.singularity.ScheduleType;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityRequestWithState;
import com.hubspot.singularity.data.RequestManager;
import com.hubspot.singularity.data.SingularityValidator;
import com.hubspot.singularity.data.transcoders.Transcoder;
@Singleton
public class ScheduleMigration extends ZkDataMigration {
private static final Logger LOG = LoggerFactory.getLogger(ScheduleMigration.class);
private final RequestManager requestManager;
private final SingularityValidator validator;
private final CuratorFramework curator;
private final Transcoder<SingularityRequestWithState> requestTranscoder;
@Inject
public ScheduleMigration(CuratorFramework curator, RequestManager requestManager, SingularityValidator validator, Transcoder<SingularityRequestWithState> requestTranscoder) {
super(7);
this.curator = curator;
this.requestManager = requestManager;
this.validator = validator;
this.requestTranscoder = requestTranscoder;
}
@Override
public void applyMigration() {
LOG.info("Starting migration to fix certain CRON schedules");
final long start = System.currentTimeMillis();
int num = 0;
for (SingularityRequestWithState requestWithState : requestManager.getRequests()) {
if (requestWithState.getRequest().isScheduled()) {
Optional<String> schedule = requestWithState.getRequest().getSchedule();
Optional<String> quartzSchedule = requestWithState.getRequest().getQuartzSchedule();
Optional<ScheduleType> scheduleType = requestWithState.getRequest().getScheduleType();
if (scheduleType.isPresent() && scheduleType.get() != ScheduleType.CRON) {
LOG.info("Skipping {}, it had schedule type: {}", requestWithState.getRequest().getId(), scheduleType.get());
continue;
}
if (quartzSchedule.isPresent() && schedule.isPresent() && quartzSchedule.get().equals(schedule.get())) {
LOG.info("Skipping {}, assuming it was quartz - it had quartz schedule == schedule {}", requestWithState.getRequest().getId(), schedule.get());
continue;
}
if (!schedule.isPresent()) {
LOG.info("Skipping {}, it had no schedule", requestWithState.getRequest().getId());
continue;
}
String actualSchedule = schedule.get();
String newQuartzSchedule = null;
try {
newQuartzSchedule = validator.getQuartzScheduleFromCronSchedule(actualSchedule);
} catch (WebApplicationException e) {
LOG.error("Failed to convert {} due to {}", actualSchedule, e.getResponse().getEntity());
throw e;
}
if (quartzSchedule.isPresent() && quartzSchedule.get().equals(newQuartzSchedule)) {
LOG.info("Skipping {}, migration had no effect {}", requestWithState.getRequest().getId(), newQuartzSchedule);
continue;
}
SingularityRequest newRequest = requestWithState.getRequest().toBuilder().setQuartzSchedule(Optional.of(newQuartzSchedule)).build();
try {
curator.setData().forPath("/requests/all/" + newRequest.getId(),
requestTranscoder.toBytes(new SingularityRequestWithState(newRequest, requestWithState.getState(), requestWithState.getTimestamp())));
num++;
} catch (Throwable t) {
LOG.error("Failed to write {}", newRequest.getId(), t);
}
}
}
LOG.info("Applied {} in {}", num, JavaUtils.duration(start));
}
}
|
package com.github.davidcarboni.restolino;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.reflections.Reflections;
import org.reflections.util.ClasspathHelper;
import com.github.davidcarboni.restolino.helpers.Path;
import com.github.davidcarboni.restolino.interfaces.Boom;
import com.github.davidcarboni.restolino.interfaces.Endpoint;
import com.github.davidcarboni.restolino.interfaces.Home;
import com.github.davidcarboni.restolino.interfaces.NotFound;
import com.github.davidcarboni.restolino.json.Serialiser;
import com.github.davidcarboni.restolino.reload.classes.ClassMonitor;
/**
* This is the framework controller.
*
* @author David Carboni
*
*/
public class Api {
static final String KEY_CLASSES = "restolino.classes";
static RequestHandler defaultRequestHandler;
static Map<String, RequestHandler> get = new HashMap<>();
static Map<String, RequestHandler> put = new HashMap<>();
static Map<String, RequestHandler> post = new HashMap<>();
static Map<String, RequestHandler> delete = new HashMap<>();
static Map<String, RequestHandler> getMap(Class<? extends Annotation> type) {
if (GET.class.isAssignableFrom(type))
return get;
else if (PUT.class.isAssignableFrom(type))
return put;
else if (POST.class.isAssignableFrom(type))
return post;
else if (DELETE.class.isAssignableFrom(type))
return delete;
return null;
}
static Home home;
static Boom boom;
static NotFound notFound;
static ClassLoader classLoader;
public static void init() {
// Start with the standard webapp classloader:
ClassLoader classLoader = Api.class.getClassLoader();
setup(classLoader);
// If we're reloading classes, start the monitoring process:
String path = System.getProperty(KEY_CLASSES);
if (StringUtils.isNotBlank(path)) {
try {
ClassMonitor.start(path, classLoader);
} catch (IOException e) {
throw new RuntimeException("Error starting class reloader", e);
}
}
}
static void setup(ClassLoader classLoader) {
// Set up reflections:
Reflections reflections = new Reflections(
ClasspathHelper.forClassLoader(classLoader));
// Get the default handler:
defaultRequestHandler = new RequestHandler();
defaultRequestHandler.endpointClass = DefaultRequestHandler.class;
try {
defaultRequestHandler.method = DefaultRequestHandler.class
.getMethod("notImplemented", HttpServletRequest.class,
HttpServletResponse.class);
} catch (NoSuchMethodException | SecurityException e) {
throw new RuntimeException(
"Code issue - default request handler not found", e);
}
configureEndpoints(reflections);
configureHome(reflections);
configureNotFound(reflections);
configureBoom(reflections);
}
/**
* Searches for and configures all your lovely endpoints.
*
* @param reflections
* The instance to use to find classes.
*/
static void configureEndpoints(Reflections reflections) {
System.out.println("Scanning for endpoints..");
Set<Class<?>> endpoints = reflections
.getTypesAnnotatedWith(Endpoint.class);
System.out.println("Found " + endpoints.size() + " endpoints.");
System.out.println("Examining endpoint methods..");
// Configure the classes:
for (Class<?> endpointClass : endpoints) {
System.out.println(" - " + endpointClass.getSimpleName());
String endpointName = StringUtils.lowerCase(endpointClass
.getSimpleName());
for (Method method : endpointClass.getMethods()) {
// Skip Object methods
if (method.getDeclaringClass() == Object.class)
continue;
// We're looking for public methods that take reqest, responso
// and optionally a message type:
Class<?>[] parameterTypes = method.getParameterTypes();
// System.out.println("Examining method " + method.getName());
// if (Modifier.isPublic(method.getModifiers()))
// System.out.println(".public");
// System.out.println("." + parameterTypes.length +
// " parameters");
// if (parameterTypes.length == 2 || parameterTypes.length == 3)
// if (HttpServletRequest.class
// .isAssignableFrom(parameterTypes[0]))
// System.out.println(".request OK");
// if (HttpServletResponse.class
// .isAssignableFrom(parameterTypes[1]))
// System.out.println(".response OK");
if (Modifier.isPublic(method.getModifiers())
&& parameterTypes.length >= 2
&& HttpServletRequest.class
.isAssignableFrom(parameterTypes[0])
&& HttpServletResponse.class
.isAssignableFrom(parameterTypes[1])) {
// Which HTTP method(s) will this method respond to?
List<Annotation> annotations = Arrays.asList(method
.getAnnotations());
// System.out.println(" > processing " +
// method.getName());
// for (Annotation annotation : annotations)
// System.out.println(" > annotation " +
// annotation.getClass().getName());
for (Annotation annotation : annotations) {
Map<String, RequestHandler> map = getMap(annotation
.getClass());
if (map != null) {
clashCheck(endpointName, annotation.getClass(),
endpointClass, method);
System.out.print(" - "
+ annotation.getClass().getInterfaces()[0]
.getSimpleName());
RequestHandler requestHandler = new RequestHandler();
requestHandler.endpointClass = endpointClass;
requestHandler.method = method;
System.out.print(" " + method.getName());
if (parameterTypes.length > 2) {
requestHandler.requestMessageType = parameterTypes[2];
System.out.print(" request:"
+ requestHandler.requestMessageType
.getSimpleName());
}
if (method.getReturnType() != void.class) {
requestHandler.responseMessageType = method
.getReturnType();
System.out.print(" response:"
+ requestHandler.responseMessageType
.getSimpleName());
}
map.put(endpointName, requestHandler);
System.out.println();
}
}
}
}
// Set default handlers where needed:
if (!get.containsKey(endpointName))
get.put(endpointName, defaultRequestHandler);
if (!put.containsKey(endpointName))
put.put(endpointName, defaultRequestHandler);
if (!post.containsKey(endpointName))
post.put(endpointName, defaultRequestHandler);
if (!delete.containsKey(endpointName))
delete.put(endpointName, defaultRequestHandler);
}
}
private static void clashCheck(String name,
Class<? extends Annotation> annotation, Class<?> endpointClass,
Method method) {
Map<String, RequestHandler> map = getMap(annotation);
if (map != null) {
if (map.containsKey(name))
System.out.println(" ! method " + method.getName() + " in "
+ endpointClass.getName() + " overwrites "
+ map.get(name).method.getName() + " in "
+ map.get(name).endpointClass.getName() + " for "
+ annotation.getSimpleName());
} else {
System.out.println("WAT. Expected GET/PUT/POST/DELETE but got "
+ annotation.getName());
}
}
/**
* Searches for and configures the / endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
static void configureHome(Reflections reflections) {
System.out.println("Checking for a / endpoint..");
home = getEndpoint(Home.class, "/", reflections);
if (home != null)
System.out.println("Class " + home.getClass().getSimpleName()
+ " configured as / endpoint");
}
/**
* Searches for and configures the not found endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
static void configureNotFound(Reflections reflections) {
System.out.println("Checking for a not-found endpoint..");
notFound = getEndpoint(NotFound.class, "not-found", reflections);
if (notFound != null)
System.out.println("Class " + notFound.getClass().getSimpleName()
+ " configured as not-found endpoint");
}
/**
* Searches for and configures the not found endpoint.
*
* @param reflections
* The instance to use to find classes.
*/
static void configureBoom(Reflections reflections) {
System.out.println("Checking for an error endpoint..");
boom = getEndpoint(Boom.class, "error", reflections);
if (boom != null)
System.out.println("Class " + boom.getClass().getSimpleName()
+ " configured as error endpoint");
}
/**
* Locates a single endpoint class.
*
* @param type
* @param name
* @param reflections
* @return
*/
private static <E> E getEndpoint(Class<E> type, String name,
Reflections reflections) {
E result = null;
// Get annotated classes:
System.out.println("Looking for a " + name + " endpoint..");
Set<Class<? extends E>> endpointClasses = reflections
.getSubTypesOf(type);
if (endpointClasses.size() == 0)
// No endpoint found:
System.out.println("No " + name
+ " endpoint configured. Just letting you know.");
else {
// Dump multiple endpoints:
if (endpointClasses.size() > 1) {
System.out.println("Warning: found multiple candidates for "
+ name + " endpoint: " + endpointClasses);
}
// Instantiate the endpoint:
try {
result = endpointClasses.iterator().next().newInstance();
} catch (Exception e) {
System.out.println("Error: cannot instantiate " + name
+ " endpoint class "
+ endpointClasses.iterator().next());
e.printStackTrace();
}
}
return result;
}
public static void doGet(HttpServletRequest request,
HttpServletResponse response) {
if (home != null && isRootRequest(request)) {
// Handle a / request:
Object responseMessage = home.get(request, response);
if (responseMessage != null)
writeMessage(response, responseMessage.getClass(),
responseMessage);
} else {
doMethod(request, response, get);
}
}
public static void doPut(HttpServletRequest request,
HttpServletResponse response) {
doMethod(request, response, put);
}
public static void doPost(HttpServletRequest request,
HttpServletResponse response) {
doMethod(request, response, post);
}
public static void doDelete(HttpServletRequest request,
HttpServletResponse response) {
doMethod(request, response, delete);
}
public static void doOptions(HttpServletRequest request,
HttpServletResponse response) {
List<String> result = new ArrayList<>();
if (home != null && isRootRequest(request)) {
// We only allow GET to the root resource:
result.add("GET");
} else {
// Determine which methods are configured:
if (mapRequestPath(get, request) != null)
result.add("GET");
if (mapRequestPath(put, request) != null)
result.add("PUT");
if (mapRequestPath(post, request) != null)
result.add("POST");
if (mapRequestPath(delete, request) != null)
result.add("DELETE");
}
response.setHeader("Allow", StringUtils.join(result, ','));
// writeMessage(response, List.class, result);
}
/**
* Determines if the given request is for the root resource (ie /).
*
* @param request
* The {@link HttpServletRequest}
* @return If {@link HttpServletRequest#getPathInfo()} is null, empty string
* or "/" ten true.
*/
private static boolean isRootRequest(HttpServletRequest request) {
String path = request.getPathInfo();
if (StringUtils.isBlank(path))
return true;
if (StringUtils.equals("/", path))
return true;
return false;
}
/**
* GO!
*
* @param request
* The request.
* @param response
* The response.
* @param requestHandlers
* One of the handler maps.
*/
static void doMethod(HttpServletRequest request,
HttpServletResponse response,
Map<String, RequestHandler> requestHandlers) {
// Locate a request handler:
RequestHandler requestHandler = mapRequestPath(requestHandlers, request);
try {
if (requestHandler != null) {
Object handler = instantiate(requestHandler.endpointClass);
Object responseMessage = invoke(request, response, handler,
requestHandler.method,
requestHandler.requestMessageType);
if (requestHandler.responseMessageType != null) {
writeMessage(response, requestHandler.responseMessageType,
responseMessage);
}
} else {
// Not found
response.setStatus(HttpStatus.SC_NOT_FOUND);
if (notFound != null)
notFound.handle(request, response);
}
} catch (Throwable t) {
// Set a default response code:
response.setStatus(HttpStatus.SC_INTERNAL_SERVER_ERROR);
if (boom != null) {
try {
// Attempt to handle the error gracefully:
boom.handle(request, response, requestHandler, t);
} catch (Throwable t2) {
t2.printStackTrace();
}
} else {
t.printStackTrace();
}
}
}
private static Object invoke(HttpServletRequest request,
HttpServletResponse response, Object handler, Method method,
Class<?> requestMessage) {
Object result = null;
System.out.println("Invoking method " + method.getName() + " on "
+ handler.getClass().getSimpleName() + " for request message "
+ requestMessage);
try {
if (requestMessage != null) {
Object message = readMessage(request, requestMessage);
result = method.invoke(handler, request, response, message);
} else {
result = method.invoke(handler, request, response);
}
} catch (Exception e) {
System.out.println("Error");
throw new RuntimeException("Error invoking method "
+ method.getName() + " on "
+ handler.getClass().getSimpleName());
}
System.out.println("Result is " + result);
return result;
}
private static Object readMessage(HttpServletRequest request,
Class<?> requestMessageType) {
try (InputStreamReader streamReader = new InputStreamReader(
request.getInputStream(), "UTF8")) {
return Serialiser.getBuilder().create()
.fromJson(streamReader, requestMessageType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding", e);
} catch (IOException e) {
throw new RuntimeException("Error reading message", e);
}
}
private static void writeMessage(HttpServletResponse response,
Class<?> responseMessageType, Object responseMessage) {
if (responseMessage != null) {
response.setContentType("application/json");
response.setCharacterEncoding("UTF8");
try (OutputStreamWriter writer = new OutputStreamWriter(
response.getOutputStream(), "UTF8")) {
Serialiser.getBuilder().create()
.toJson(responseMessage, responseMessageType, writer);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unsupported encoding", e);
} catch (IOException e) {
throw new RuntimeException("Error reading message", e);
}
}
}
/**
* Locates a {@link RequestHandler} for the path of the given request.
*
* @param requestHandlers
* One of the handler maps.
* @param request
* The request.
* @return A matching handler, if one exists.
*/
private static RequestHandler mapRequestPath(
Map<String, RequestHandler> requestHandlers,
HttpServletRequest request) {
String endpointName = Path.newInstance(request).firstSegment();
endpointName = StringUtils.lowerCase(endpointName);
// System.out.println("Mapping endpoint " + endpointName);
return requestHandlers.get(endpointName);
}
private static Object instantiate(Class<?> endpointClass) {
// Instantiate:
Object result = null;
try {
result = endpointClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Unable to instantiate "
+ endpointClass.getSimpleName(), e);
} catch (IllegalAccessException e) {
throw new RuntimeException("Unable to access "
+ endpointClass.getSimpleName(), e);
} catch (NullPointerException e) {
throw new RuntimeException("No class to instantiate", e);
}
return result;
}
}
|
package org.sipfoundry.sipxbridge;
import java.util.Map;
public interface Symmitron {
/*
* The following reserved keywords are used to refer to values that are
* returned in the Map structures that the Symmitron returns. The following
* are returned with every return map.
*/
/**
* The status code OK or ERROR.
*/
public static final String STATUS_CODE = "status-code";
/**
* A standard error code -- see definitions below.
*/
public static final String ERROR_CODE = "faultCode";
/**
* Detailed error information.
*/
public static final String ERROR_INFO = "faultString";
/**
* Instance handle of Symmitron
*/
public static final String INSTANCE_HANDLE = "instance-handle";
/*
* The following are specific to individual method calls.
*/
/**
* Id of sym bridge.
*/
public static final String BRIDGE_ID = "bridge-id";
/**
* references a map that defines an sym
*/
public static final String SYM_SESSION = "sym";
/**
* references collection or sym Session statistics
*/
public static final String SYM_SESSION_STATS = "sym-stats";
/**
* The current time of day
*/
public static final String CURRENT_TIME_OF_DAY = "current-time-of-day";
/**
* The sym Bridge State.
*/
public static final String BRIDGE_STATE = "bridge-state";
/**
* The time the bridge was created.
*/
public static final String CREATION_TIME = "creation-time";
/**
* Time the last packet was received.
*/
public static String LAST_PACKET_RECEIVED = "last-packet-received";
/**
* The sym Session State.
*/
public static final String SESSION_STATE = "sym-state";
/**
* The number of packets received.
*/
public static final String PACKETS_RECEIVED = "packets-received";
/**
* The number of packets sent.
*/
public static final String PACKETS_SENT = "packets-sent";
/**
* The number of packets processed.
*/
public static final String PACKETS_PROCESSED = "packets-processed";
/**
* Successful return.
*/
public static final String OK = "ok";
/**
* Error return.
*/
public static final String ERROR = "error";
/*
* Error Codes
*/
public static final int HANDLE_NOT_FOUND = 1;
public static final int PROCESSING_ERROR = 2;
public static final int SESSION_NOT_FOUND = 3;
public static final int ILLEGAL_ARGUMENT = 0; // Consistent with
// framework.
public static final int ILLEGAL_STATE = 5;
public static final int PORTS_NOT_AVAILABLE = 6;
/**
* Starting port for Sym allocation.
*
*/
public static final int EVEN = 1;
public static final int ODD = 2;
/**
* Sign in to symmmitron. This allows remote hosts to sign into symmitron.
* Returns a controllerHandle that is used in subsequent interactions with
* the symmitron. The controllerHandle is used as a generation Identifier.
*
*
*
* @param controllerHandle -
* instance handle of the controller.
*
*
* @return -- a standard map. Note that the standard map contains the
* instance handle of the Symmitron that is used by the client to
* detect Symmitron reboots.
*
*/
public Map<String, Object> signIn(String controllerHandle);
/**
* Sign out of the symmitron. This allows remote hosts to delete all
* resources.
*
* @param controllerHandle --
* instance handle of the controller.
*
* @return -- a standard map
*/
public Map<String, Object> signOut(String controllerHandle);
/**
* Allocate a set of syms. This returns with the receivers end running. This
* method does not specify an Id.
*
* @param controllerHandle -
* the controller handle that is making this call.
*
* @param count -
* number of syms to be allocated.
*
* @param parity -
* 1 Even or 2 Odd the allocated set is a contiguous set of
* ports.
*
*
*
* @return a map containing a key that references a map containing the
* allocated sym if any in addition to the standard entries.
*
*/
public Map<String, Object> createSyms(String controllerHandle, int count,
int parity);
/**
* Destroy a sym. This deallocates any resources ( sockets, ports ) that
* have been reserved for that Sym
*
* @param controllerHandle --
* the controller handle.
*
* @param symId -
* the id of the sym to be destroyed.
*/
public Map<String, Object> destroySym(String controllerHandle, String symId);
/**
* Get an sym Session given its ID if it exists.
*
* @param controllerHandle -
* the controller handle that is making this call.
*
* @param symId -
* the symId that we want to get
*
* @return a map containing a key "sym" that references a map containing the
* Sym. If such a session cannot be found, then the entry is not
* present in the returned map.
*
*/
public Map<String, Object> getSym(String controllerHandle, String symId);
/**
* Hold a sym. When a sym is in the paused state, it does not send any data
* to the remote endpoint.
*
* @param controllerHandle -
* the controller handle making this call.
* @param symId --
* the session Id for the sym.
*
*
* @return a standard map.
*/
public Map<String, Object> pauseSym(String controllerHandle, String symId);
/**
* Resume an sym Session.
*
* @param controllerHandle --
* the controller handle.
* @param symId --
* the session ID for the sym.
*
* @return a standard map
*/
public Map<String, Object> resumeSym(String controllerHandle, String symId);
/**
*
* Set the remote session endpoint.
*
* @param controllerHandle -
* the controller handle that is making this call.
*
* @param symId --
* the Sym Identifier for the sym Session for which we need to
* add a remote endpoint.
*
*
* @param destinationIpAddress --
* the destinationIpAddress
*
* @param destinationPort --
* the destination port.
*
* @param keepAliveTime --
* the keep alive time (0 means no keep alive packets).
*
* @param keepAliveMethod --
* can be one of the following "NONE",
* "USE-LAST-SENT","USE-EMPTY-PACKET" "USE-SPECIFIED-PAYLOAD"
*
* @param keepAlivePacketData --
* the keep alive packet data. This parameter is relevant if
* USE-SPECIFIED-PAYLOAD is specified. This is a uuencoded
* string. It is uudecoded to extract the keepalive data.
*
* @param autoLearnDestination --
* true implies auto discover remote port - send port is based on
* remote port of last seen packet ( useful for dealing with NAT
* reboots ).
*
*
* @return - a standard map
*
*/
public Map<String, Object> setDestination(String controllerHandle,
String symId, String destinationIpAddress, int destinationPort,
int keepAliveTime, String keepaliveMethod,
String keepAlivePacketData, boolean autoLearnDestination);
/**
* Remove a sym from a bridge.
*
* @param controllerHandle --
* the controller handle.
*
* @param bridgeId --
* the sym bridge id.
* @param symId --
* the session Id of the sym to remove.
*
* @return a standard map.
*/
public Map<String, Object> removeSym(String cotrollerHandle,
String bridgeId, String symId);
/**
* Add an sym to a bridge.
*
* @param controllerHandle --
* the controller handle.
* @param bridgeId --
* the sym Bridge ID.
* @param symId --
* the sym id.
*
* @return a standard map
*/
public Map<String, Object> addSym(String controllerHandle, String bridgeId,
String symId);
/**
* Create an empty sym bridge.
*
* @param controllerHandle --
* the controller handle.
*
* @return a map containing the allocated bridge ID.
*/
public Map<String, Object> createBridge(String controllerHandle);
/**
* Destroy a bridge. This method destroys all the syms associated with the
* bridge. Once the bridge is destroyed all references to its handle are
* removed from memory.
*
* @param controllerHandle --
* the controller handle.
*
* @return a standard map
*/
public Map<String, Object> destroyBridge(String controllerHandle,
String bridgeId);
/**
* Start shuffling data on the specified bridge.
*
* @param controllerHandle -
* the controller handle that is making this call.
*
* @param bridgeId --
* the bridge Id.
*
* @return A standard map.
*
*/
public Map<String, Object> startBridge(String controllerHandle,
String bridgeId);
/**
* Pause the bridge. When you pause the bridge, all data shuffling will
* stop.
*
* @param bridgeId --
* the bridge Id.
* @param controllerHandle --
* the controller handle.
*
* @return A standard map.
*/
public Map<String, Object> pauseBridge(String controllerHandle,
String bridgeId);
/**
* Resume bridge operation. When you resume the bridge, data shuffling will
* resume.
*
* @param bridgeId --
* the bridge Id.
* @param controllerHandle --
* the controller Handle.
*
* @return A standard map.
*/
public Map<String, Object> resumeBridge(String controllerHandle,
String bridgeId);
/**
* Set the timeout for a sym.
*
* @param controllerHandle --
* the controller handle.
* @param symId --
* the sym id.
* @param timeout (
* milliseconds ) after which inactivity is recorded.
*/
public Map<String, Object> setTimeout(String controllerHandle,
String symId, int timeout);
/**
* Ping and test for liveness of monitored Syms.
*
* @param controllerHandle --
* the controller handle making the call.
*
* @param symId --
* the sym Id.
*
* @return an array containing the syms that have not seen inbound for a
* time t > the threshold timer value. Note that this is an
* instantaneous measure. The inactivity flag is a boolean that
* indicates if a timeout has occurred on the LAST received packet
* at the time the reading is made.
*
*
*/
public Map<String, Object> ping(String controllerHandle);
/**
* Get Sym statistics.
*
* @param controllerHandle --
* the controller handle making this call.
*
* @param symId --
* the sym id.
*
* @return A map containing statistics for the sym . On successful lookup, a
* map containing the following keys will be returned.
* <ul>
* <li><it>current-time-of-day</it> - the current time of day (
* according to symitrons clock )
* <li><it>sym</it> - pointer to a hash map containing the sym (
* note that this contains the current receiver port.
* <li><it>creation-time</it> - time this session was created.
* <li><it>idle-timer-starts</it> - number of times ( from start
* of session ) that the idle timer kicked in.
* <li><it>packets-sent</it> - number of packets sent.
* <li><it>packets-received</it> - number of packets received.
* </ul>
*/
public Map<String, Object> getSymStatistics(String controllerHandle,
String symId);
/**
* Get the bridge statistics.
*
* @param controllerHandle --
* the controller handle making this call.
*
* @param bridgeId --
* the bridge id.
*
*
* @return A map containing the statistics for the bridge. A map containing
* the following statistics is returned.
* <ul>
* <li><it>current-time-of-day</it> -- current time of day.
* <li><it>creation-time</it> -- time this bridge was created.
* <li><it>bridge-state</it> -- the bridge state.
* <li><it>packets-processed</it> -- the number of packets
* processed.
* <li><it>sym-stats</it> -- a collection of statistics for the
* individual sym Sessions that are part of this Bridge.
* </ul>
*/
public Map<String, Object> getBridgeStatistics(String controllerHandle,
String bridgeId);
}
|
package eu.modelwriter.configuration.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Path;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ResourceSet;
import edu.mit.csail.sdg.alloy4viz.AlloyInstance;
import edu.mit.csail.sdg.alloy4viz.AlloyRelation;
import edu.mit.csail.sdg.alloy4viz.AlloyTuple;
import eu.modelwriter.marker.internal.MarkUtilities;
import eu.modelwriter.traceability.core.persistence.AlloyType;
import eu.modelwriter.traceability.core.persistence.AtomType;
import eu.modelwriter.traceability.core.persistence.DocumentRoot;
import eu.modelwriter.traceability.core.persistence.EntryType;
import eu.modelwriter.traceability.core.persistence.FieldType;
import eu.modelwriter.traceability.core.persistence.ItemType;
import eu.modelwriter.traceability.core.persistence.RelationType;
import eu.modelwriter.traceability.core.persistence.SigType;
import eu.modelwriter.traceability.core.persistence.TupleType;
import eu.modelwriter.traceability.core.persistence.TypeType;
import eu.modelwriter.traceability.core.persistence.TypesType;
import eu.modelwriter.traceability.core.persistence.persistenceFactory;
import eu.modelwriter.traceability.core.persistence.internal.ModelIO;
public class AlloyUtilities {
final public static String GROUP_ID = "groupId";
final public static String LEADER_ID = "leaderId";
final public static String MARKER_URI = "uri";
final public static String OFFSET = "offset";
final public static String RESOURCE = "resource";
public static ResourceSet resourceSet;
final public static String TEXT = "text";
public static Map<String, Integer> typeHashMap = new HashMap<String, Integer>();
public static String xmlFileLocation = ".modelwriter\\persistence.xml";
public static void addMapping2RelationType(IMarker fromMarker, IMarker toMarker) {
fromMarker = MarkUtilities.getLeaderOfMarker(fromMarker);
toMarker = MarkUtilities.getLeaderOfMarker(toMarker);
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final RelationType relationType = documentRoot.getAlloy().getRelation();
final TupleType tupleType = persistenceFactory.eINSTANCE.createTupleType();
relationType.getTuple().add(tupleType);
final AtomType fromAtom = persistenceFactory.eINSTANCE.createAtomType();
tupleType.getAtom().add(fromAtom);
fromAtom.setLabel(MarkUtilities.getSourceId(fromMarker));
final AtomType toAtom = persistenceFactory.eINSTANCE.createAtomType();
tupleType.getAtom().add(toAtom);
toAtom.setLabel(MarkUtilities.getSourceId(toMarker));
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static void addMarkerToRepository(final IMarker marker) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
if (AlloyUtilities.findItemTypeInRepository(marker) == -1) {
final ItemType itemType = persistenceFactory.eINSTANCE.createItemType();
documentRoot.getAlloy().getRepository().getItem().add(itemType);
itemType.setId(MarkUtilities.getSourceId(marker));
AlloyUtilities.setEntries(itemType, marker);
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static void addRelation2Markers(IMarker fromMarker, IMarker toMarker,
final String relation) {
fromMarker = MarkUtilities.getLeaderOfMarker(fromMarker);
toMarker = MarkUtilities.getLeaderOfMarker(toMarker);
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final AtomType fromAtom = persistenceFactory.eINSTANCE.createAtomType();
fromAtom.setLabel(MarkUtilities.getSourceId(fromMarker));
final AtomType toAtom = persistenceFactory.eINSTANCE.createAtomType();
toAtom.setLabel(MarkUtilities.getSourceId(toMarker));
final TupleType tuple = persistenceFactory.eINSTANCE.createTupleType();
tuple.getAtom().add(fromAtom);
tuple.getAtom().add(toAtom);
final EList<FieldType> fields = documentRoot.getAlloy().getInstance().getField();
for (final FieldType fieldType : fields) {
if (relation.equals(fieldType.getLabel())) {
if (!AlloyUtilities.isContainTuple(fieldType, tuple)) {
fieldType.getTuple().add(tuple);
}
break;
}
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static void addRelation2Markers(IMarker selectedMarker, final Object[] checkedMarkers,
final Map<IMarker, String> relationMap) {
selectedMarker = MarkUtilities.getLeaderOfMarker(selectedMarker);
for (final Object object : checkedMarkers) {
if (object instanceof IMarker) {
IMarker marker = (IMarker) object;
marker = MarkUtilities.getLeaderOfMarker(marker);
final String relationName = relationMap.get(marker);
AlloyUtilities.addRelation2Markers(selectedMarker, marker, relationName);
}
}
}
public static void addTypeToMarker(final IMarker marker) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final AtomType atom = persistenceFactory.eINSTANCE.createAtomType();
atom.setLabel(MarkUtilities.getSourceId(marker));
final String type = MarkUtilities.getType(marker);
final EList<SigType> sigs = documentRoot.getAlloy().getInstance().getSig();
final int idOfTypeSigInSigType = AlloyUtilities.isTypeInSig(type);
for (final SigType sigType : sigs) {
if (type.equals(sigType.getLabel().substring(sigType.getLabel().indexOf("/") + 1))) {
sigType.getAtom().add(atom);
} else if (idOfTypeSigInSigType != -1 && sigType.getID() == idOfTypeSigInSigType) {
final AtomType typeAtom = persistenceFactory.eINSTANCE.createAtomType();
typeAtom.setLabel(MarkUtilities.getSourceId(marker));
sigType.getAtom().add(typeAtom);
}
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static int findItemTypeInRepository(final IMarker marker) {
final String markerId = MarkUtilities.getSourceId(marker);
final EList<ItemType> itemTypes = AlloyUtilities.getItemtypes();
int itemTypeIndex = 0;
for (final ItemType itemType : itemTypes) {
if (markerId.equals(itemType.getId())) {
return itemTypeIndex;
}
itemTypeIndex++;
}
return -1;
}
public static IMarker findMarker(final String sigTypeName, final int index) {
final SigType sigType =
AlloyUtilities.getSigTypeById(AlloyUtilities.getSigTypeIdByName(sigTypeName));
final EList<AtomType> atoms = sigType.getAtom();
final String markerId = atoms.get(index).getLabel();
final ItemType itemType = AlloyUtilities.getItemById(markerId);
final String path = AlloyUtilities.getValueOfEntry(itemType, AlloyUtilities.RESOURCE);
final IMarker marker = MarkUtilities.getiMarker(markerId, path);
return marker;
}
public static ArrayList<Integer> getAllChildIds(final int id) {
final ArrayList<Integer> ids = new ArrayList<Integer>();
final ArrayList<SigType> sigTypes = AlloyUtilities.getSigTypeListByParentId(id);
for (final SigType sigType : sigTypes) {
ids.addAll(AlloyUtilities.getAllChildIds(sigType.getID()));
}
ids.add(id);
return ids;
}
public static ArrayList<Integer> getAllParentIds(int id) {
final ArrayList<Integer> ids = new ArrayList<Integer>();
do {
ids.add(id);
final SigType sigType = AlloyUtilities.getSigTypeById(id);
if (sigType.getType().size() == 0) {
id = sigType.getParentID();
} else {
id = sigType.getType().get(0).getID();
}
} while (id != 0);
return ids;
}
public static String getAtomNameById(final String id) {
final EList<SigType> sigList = AlloyUtilities.getSigTypes(AlloyUtilities.getDocumentRoot());
for (final SigType sigType : sigList) {
final EList<AtomType> atoms = sigType.getAtom();
int index = 0;
final String sigLabel = sigType.getLabel().substring(sigType.getLabel().indexOf("/") + 1);
for (final AtomType atomType : atoms) {
if (atomType.getLabel().equals(id)) {
return sigLabel + "$" + index;
}
index++;
}
}
return null;
}
public static AtomType getAtomTypeBySourceIdFromSig(final DocumentRoot documentRoot,
final String sourceId) {
final AlloyType alloyType = documentRoot.getAlloy();
final EList<SigType> listOfSigs = alloyType.getInstance().getSig();
for (final SigType sigType : listOfSigs) {
final EList<AtomType> atoms = sigType.getAtom();
for (final AtomType atomType : atoms) {
if (atomType.getLabel().equals(sourceId)) {
return atomType;
}
}
}
return null;
}
public static ArrayList<String> getChangedAtoms() {
final EList<SigType> sigList = AlloyUtilities.getSigTypes(AlloyUtilities.getDocumentRoot());
final ArrayList<String> changedAtoms = new ArrayList<>();
for (final SigType sigType : sigList) {
final EList<AtomType> atoms = sigType.getAtom();
int index = 0;
final String sigLabel = sigType.getLabel().substring(sigType.getLabel().indexOf("/") + 1);
for (final AtomType atomType : atoms) {
if (atomType.getChanged() != null && atomType.getChanged()) {
changedAtoms.add(sigLabel + "$" + index);
}
index++;
}
}
return changedAtoms;
}
public static DocumentRoot getDocumentRoot() {
@SuppressWarnings("rawtypes")
final ModelIO modelIO = new ModelIO<>();
@SuppressWarnings("rawtypes")
final List list = modelIO.read(AlloyUtilities.getUri());
if (list.isEmpty()) {
return null;
}
final DocumentRoot documentRoot = (DocumentRoot) list.get(0);
return documentRoot;
}
public static DocumentRoot getDocumentRootForMetaModel(final String filename) {
@SuppressWarnings("rawtypes")
final ModelIO modelIO = new ModelIO<>();
@SuppressWarnings("rawtypes")
final List list =
modelIO.read(URI.createFileURI(AlloyUtilities.getLocationForMetamodel(filename)));
if (list.isEmpty()) {
return null;
}
final DocumentRoot documentRoot = (DocumentRoot) list.get(0);
return documentRoot;
}
public static List<String> getFieldNames() {
final List<String> fieldNames = new ArrayList<>();
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final EList<FieldType> fields = documentRoot.getAlloy().getInstance().getField();
for (final FieldType fieldType : fields) {
fieldNames.add(fieldType.getLabel());
}
return fieldNames;
}
public static EList<FieldType> getFieldTypes() {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
return documentRoot.getAlloy().getInstance().getField();
}
/**
* @param typeName
* @param side if true, return FieldType List according left side type
* @return
*/
public static ArrayList<FieldType> getFieldTypesList(final String typeName, final boolean side) {
final EList<FieldType> fields = AlloyUtilities.getFieldTypes();
final ArrayList<FieldType> foundFieldTypes = new ArrayList<FieldType>();
final int id = AlloyUtilities.getSigTypeIdByName(typeName);
final ArrayList<Integer> idList = AlloyUtilities.getAllParentIds(id);
for (final Integer typeId : idList) {
for (final FieldType fieldType : fields) {
final EList<TypesType> typesTypes = fieldType.getTypes();
for (final TypesType typesType : typesTypes) {
final EList<TypeType> typeTypes = typesType.getType();
if (side && typeTypes.get(0).getID() == typeId) {
foundFieldTypes.add(fieldType);
break;
} else if (!side && typeTypes.get(1).getID() == typeId) {
foundFieldTypes.add(fieldType);
break;
}
}
}
}
return foundFieldTypes;
}
public static ArrayList<ArrayList<String>> getImpactedAtoms() {
final EList<FieldType> fieldList = AlloyUtilities.getFieldTypes();
final ArrayList<ArrayList<String>> impactedAtoms = new ArrayList<>();
for (final FieldType fieldType : fieldList) {
final EList<TupleType> tupleList = fieldType.getTuple();
for (final TupleType tupleType : tupleList) {
if (tupleType.getAtom().get(1).getImpact() != null
&& tupleType.getAtom().get(1).getImpact()) {
final AtomType atom = AlloyUtilities.getAtomTypeBySourceIdFromSig(
AlloyUtilities.getDocumentRoot(), tupleType.getAtom().get(1).getLabel());
final AtomType changedAtom = AlloyUtilities.getAtomTypeBySourceIdFromSig(
AlloyUtilities.getDocumentRoot(), tupleType.getAtom().get(0).getLabel());
final ArrayList<String> impactedRelations = new ArrayList<>();
impactedRelations.add(AlloyUtilities.getAtomNameById(atom.getLabel()));
impactedRelations.add(AlloyUtilities.getAtomNameById(changedAtom.getLabel()));
impactedAtoms.add(impactedRelations);
}
}
}
return impactedAtoms;
}
public static ItemType getItemById(final String id) {
final EList<ItemType> itemTypes = AlloyUtilities.getItemtypes();
for (final ItemType itemType : itemTypes) {
if (id.equals(itemType.getId())) {
return itemType;
}
}
return null;
}
public static EList<ItemType> getItemtypes() {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
return documentRoot.getAlloy().getRepository().getItem();
}
public static String getLocation() {
return ResourcesPlugin.getWorkspace().getRoot().getLocation() + "/"
+ AlloyUtilities.xmlFileLocation;
}
public static String getLocationForMetamodel(final String filename) {
return ResourcesPlugin.getWorkspace().getRoot().getLocation() + "/" + ".modelwriter\\"
+ filename + ".xml";
}
public static Map<IMarker, String> getRelationsOfFirstSideMarker(IMarker selectedMarker) {
selectedMarker = MarkUtilities.getLeaderOfMarker(selectedMarker);
final Map<IMarker, String> relationsOfMarker = new HashMap<IMarker, String>();
if (MarkUtilities.getType(selectedMarker) == null) {
return relationsOfMarker;
}
final ArrayList<FieldType> fieldTypesOfSelectedMarkerType =
AlloyUtilities.getFieldTypesList(MarkUtilities.getType(selectedMarker), true);
final String selectedMarkerId = MarkUtilities.getSourceId(selectedMarker);
for (final FieldType fieldType : fieldTypesOfSelectedMarkerType) {
final EList<TupleType> tupleTypes = fieldType.getTuple();
for (final TupleType tupleType : tupleTypes) {
final EList<AtomType> atoms = tupleType.getAtom();
final AtomType firstAtomType = atoms.get(0);
if (firstAtomType.getLabel().equals(selectedMarkerId)) {
final AtomType secondAtomType = atoms.get(1);
final ItemType itemTypeOfAtom = AlloyUtilities.getItemById(secondAtomType.getLabel());
final IMarker toMarker = MarkUtilities.getiMarker(secondAtomType.getLabel(),
AlloyUtilities.getValueOfEntry(itemTypeOfAtom, AlloyUtilities.RESOURCE));
relationsOfMarker.put(toMarker, fieldType.getLabel());
}
}
}
return relationsOfMarker;
}
public static Map<IMarker, String> getRelationsOfSecondSideMarker(IMarker selectedMarker) {
selectedMarker = MarkUtilities.getLeaderOfMarker(selectedMarker);
final Map<IMarker, String> relationsOfMarker = new HashMap<IMarker, String>();
if (MarkUtilities.getType(selectedMarker) == null) {
return relationsOfMarker;
}
final ArrayList<FieldType> fieldTypesOfSelectedMarkerType =
AlloyUtilities.getFieldTypesList(MarkUtilities.getType(selectedMarker), false);
final String selectedMarkerId = MarkUtilities.getSourceId(selectedMarker);
for (final FieldType fieldType : fieldTypesOfSelectedMarkerType) {
final EList<TupleType> tupleTypes = fieldType.getTuple();
for (final TupleType tupleType : tupleTypes) {
final EList<AtomType> atoms = tupleType.getAtom();
final AtomType firstAtomType = atoms.get(1);
if (firstAtomType.getLabel().equals(selectedMarkerId)) {
final AtomType secondAtomType = atoms.get(0);
final ItemType itemTypeOfAtom = AlloyUtilities.getItemById(secondAtomType.getLabel());
final IMarker toMarker = MarkUtilities.getiMarker(secondAtomType.getLabel(),
AlloyUtilities.getValueOfEntry(itemTypeOfAtom, AlloyUtilities.RESOURCE));
relationsOfMarker.put(toMarker, fieldType.getLabel());
}
}
}
return relationsOfMarker;
}
/**
* This method is used to get Relations
*
* @return
*/
public static RelationType getRelationType(final DocumentRoot documentRoot) {
return documentRoot.getAlloy().getRelation();
}
public static ArrayList<String> getRelationTypesForFirstSide(final String typeName) {
final ArrayList<String> relationTypeNames = new ArrayList<String>();
final int TypeId = AlloyUtilities.getSigTypeIdByName(typeName);
final ArrayList<Integer> parentIds = AlloyUtilities.getAllParentIds(TypeId);
final EList<FieldType> fieldTypes = AlloyUtilities.getFieldTypes();
for (final FieldType fieldType : fieldTypes) {
for (final Integer parentId : parentIds) {
if (fieldType.getParentID() == parentId) {
relationTypeNames.add(fieldType.getLabel());
break;
}
}
}
return relationTypeNames;
}
public static ArrayList<AtomType> getSecondSideAtomsBySourceIdOfFirstSide(
final DocumentRoot documentRoot, final String sourceId) {
final AlloyType alloyType = documentRoot.getAlloy();
final ArrayList<AtomType> atoms = new ArrayList<AtomType>();
final EList<FieldType> listOfField = alloyType.getInstance().getField();
for (final FieldType fieldType : listOfField) {
final EList<TupleType> tuples = fieldType.getTuple();
for (final TupleType tupleType : tuples) {
if (tupleType.getAtom().get(0).getLabel().equals(sourceId)) {
atoms.add(tupleType.getAtom().get(1));
}
}
}
return atoms;
}
public static ArrayList<IMarker> getSecondSideMarkerIdsByMarkerAndRelation(IMarker marker,
final String relation) {
marker = MarkUtilities.getLeaderOfMarker(marker);
final EList<FieldType> fieldTypes = AlloyUtilities.getFieldTypes();
final String markerId = MarkUtilities.getSourceId(marker);
final ArrayList<IMarker> suitableMarkers = new ArrayList<IMarker>();
for (final FieldType fieldType : fieldTypes) {
if (fieldType.getLabel().equals(relation)) {
final EList<TupleType> tuples = fieldType.getTuple();
for (final TupleType tupleType : tuples) {
final EList<AtomType> atoms = tupleType.getAtom();
if (atoms.get(0).getLabel().equals(markerId)) {
final ItemType itemType = AlloyUtilities.getItemById(atoms.get(1).getLabel());
final IMarker suitableMarker = MarkUtilities.getiMarker(itemType.getId(),
AlloyUtilities.getValueOfEntry(itemType, AlloyUtilities.RESOURCE));
suitableMarkers.add(suitableMarker);
}
}
break;
}
}
return suitableMarkers;
}
/**
* This method is used to get Target List of iMarker. Also iMarker doesn't contain any marker
* type.
*
* @param iMarker
* @return
*/
public static ArrayList<IMarker> getSecondSideMarkerIdsByMarkerAndRelationV2(IMarker iMarker) {
iMarker = MarkUtilities.getLeaderOfMarker(iMarker);
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final RelationType relationType = AlloyUtilities.getRelationType(documentRoot);
final EList<TupleType> tupleTypes = relationType.getTuple();
final String markerId = MarkUtilities.getSourceId(iMarker);
final ArrayList<IMarker> suitableMarkers = new ArrayList<IMarker>();
for (final TupleType tupleType : tupleTypes) {
final EList<AtomType> atoms = tupleType.getAtom();
if (atoms.get(0).getLabel().equals(markerId)) {
final ItemType itemType = AlloyUtilities.getItemById(atoms.get(1).getLabel());
final IMarker suitableMarker = MarkUtilities.getiMarker(itemType.getId(),
AlloyUtilities.getValueOfEntry(itemType, AlloyUtilities.RESOURCE));
suitableMarkers.add(suitableMarker);
}
}
return suitableMarkers;
}
public static SigType getSigTypeById(final int id) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final EList<SigType> sigTypes = AlloyUtilities.getSigTypes(documentRoot);
for (final SigType sigType : sigTypes) {
if (id == sigType.getID()) {
return sigType;
}
}
return null;
}
public static int getSigTypeIdByName(final String typeName) {
int id = -1;
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
if (AlloyUtilities.typeHashMap.get(typeName) == null) {
final EList<SigType> sigTypes = AlloyUtilities.getSigTypes(documentRoot);
for (final SigType sigType : sigTypes) {
if (typeName.equals(sigType.getLabel().substring(sigType.getLabel().indexOf("/") + 1))) {
id = sigType.getID();
AlloyUtilities.typeHashMap.put(typeName, id);
break;
}
}
} else {
id = AlloyUtilities.typeHashMap.get(typeName);
}
return id;
}
public static ArrayList<SigType> getSigTypeListByParentId(final int id) {
final ArrayList<SigType> suitableSigTypes = new ArrayList<>();
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final EList<SigType> sigTypes = AlloyUtilities.getSigTypes(documentRoot);
for (final SigType sigType : sigTypes) {
if (sigType.getParentID() == id) {
suitableSigTypes.add(sigType);
}
}
return suitableSigTypes;
}
public static EList<SigType> getSigTypes(final DocumentRoot documentRoot) {
return documentRoot.getAlloy().getInstance().getSig();
}
/**
* This method is used to get source marker list of iMarker. Also iMarker doesn't contain any
* marker type.
*
* @param iMarker
* @return
*/
public static ArrayList<IMarker> getSourcesOfMarkerAtRelations(IMarker iMarker) {
iMarker = MarkUtilities.getLeaderOfMarker(iMarker);
final ArrayList<IMarker> sources = new ArrayList<IMarker>();
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final RelationType relationType = AlloyUtilities.getRelationType(documentRoot);
final String selectedMarkerId = MarkUtilities.getSourceId(iMarker);
final EList<TupleType> tupleTypes = relationType.getTuple();
for (final TupleType tupleType : tupleTypes) {
final EList<AtomType> atoms = tupleType.getAtom();
final AtomType firstAtomType = atoms.get(0);
final AtomType secondAtomType = atoms.get(1);
if (secondAtomType.getLabel().equals(selectedMarkerId)) {
final ItemType itemTypeOfAtom = AlloyUtilities.getItemById(firstAtomType.getLabel());
final IMarker toMarker = MarkUtilities.getiMarker(firstAtomType.getLabel(),
AlloyUtilities.getValueOfEntry(itemTypeOfAtom, AlloyUtilities.RESOURCE));
sources.add(toMarker);
}
}
return sources;
}
public static ArrayList<String> getSuitableSecondSideTypesOfRelation(final String relationName,
final String firstSideType) {
final EList<FieldType> fields = AlloyUtilities.getFieldTypes();
final ArrayList<String> suitableRelationNames = new ArrayList<String>();
final int firstSideTypeId = AlloyUtilities.getSigTypeIdByName(firstSideType);
int id = -1;
for (final FieldType fieldType : fields) {
if (fieldType.getLabel().equals(relationName)
&& fieldType.getTypes().get(0).getType().get(0).getID() == firstSideTypeId) {
id = fieldType.getTypes().get(0).getType().get(1).getID();
}
}
final ArrayList<Integer> suitableIds = AlloyUtilities.getAllChildIds(id);
for (final Integer suitableId : suitableIds) {
suitableRelationNames.add(AlloyUtilities.getSigTypeById(suitableId).getLabel());
}
return suitableRelationNames;
}
/**
* This method is used to when iMarker has marker type and we want to find it's sources both have
* marker type or not.
*
* @param iMarker
* @return
*/
public static ArrayList<IMarker> getSumSources(IMarker iMarker) {
iMarker = MarkUtilities.getLeaderOfMarker(iMarker);
final Map<IMarker, String> sourcesMap = AlloyUtilities.getRelationsOfSecondSideMarker(iMarker);
final ArrayList<IMarker> sourcesList = AlloyUtilities.getSourcesOfMarkerAtRelations(iMarker);
final ArrayList<IMarker> resultList = new ArrayList<IMarker>(sourcesList);
final Set<IMarker> sourceMarkers = sourcesMap.keySet();
final Iterator<IMarker> iter = sourceMarkers.iterator();
while (iter.hasNext()) {
final IMarker iMarkerSet = iter.next();
if (!sourcesList.contains(iMarkerSet)) {
resultList.add(iMarkerSet);
}
}
return resultList;
}
/**
* This method is used to get target marker list of iMarker. Also iMarker doesn't contain any
* marker type.
*
* @param iMarker
* @return
*/
public static ArrayList<IMarker> getTargetsOfMarkerAtRelations(IMarker iMarker) {
iMarker = MarkUtilities.getLeaderOfMarker(iMarker);
final ArrayList<IMarker> targets = new ArrayList<IMarker>();
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final RelationType relationType = AlloyUtilities.getRelationType(documentRoot);
final String selectedMarkerId = MarkUtilities.getSourceId(iMarker);
final EList<TupleType> tupleTypes = relationType.getTuple();
for (final TupleType tupleType : tupleTypes) {
final EList<AtomType> atoms = tupleType.getAtom();
final AtomType firstAtomType = atoms.get(0);
if (firstAtomType.getLabel().equals(selectedMarkerId)) {
final AtomType secondAtomType = atoms.get(1);
final ItemType itemTypeOfAtom = AlloyUtilities.getItemById(secondAtomType.getLabel());
final IMarker toMarker = MarkUtilities.getiMarker(secondAtomType.getLabel(),
AlloyUtilities.getValueOfEntry(itemTypeOfAtom, AlloyUtilities.RESOURCE));
targets.add(toMarker);
}
}
return targets;
}
public static URI getUri() {
return URI.createFileURI(AlloyUtilities.getLocation());
}
public static String getValueOfEntry(final ItemType itemType, final String key) {
String value = null;
final EList<EntryType> entries = itemType.getEntry();
for (final EntryType entryType : entries) {
if (key.equals(entryType.getKey())) {
value = entryType.getValue();
}
}
return value;
}
public static boolean isContainTuple(final FieldType fieldType,
final TupleType searchedTupleType) {
final EList<TupleType> tuples = fieldType.getTuple();
final EList<AtomType> searchedAtoms = searchedTupleType.getAtom();
for (final TupleType tupleType : tuples) {
final EList<AtomType> atoms = tupleType.getAtom();
if (atoms.get(0).getLabel().equals(searchedAtoms.get(0).getLabel())
&& atoms.get(1).getLabel().equals(searchedAtoms.get(1).getLabel())) {
return true;
}
}
return false;
}
/**
* @return true if Alloy file parsed and XML file is constructed , false if doesn't.
*/
public static boolean isExists() {
final Path path = new Path(AlloyUtilities.getLocation());
return path.toFile().exists() ? true : false;
}
public static int isTypeInSig(final String sigTypeName) {
final SigType sigType =
AlloyUtilities.getSigTypeById(AlloyUtilities.getSigTypeIdByName(sigTypeName));
return sigType.getType().isEmpty() ? -1 : sigType.getType().get(0).getID();
}
public static void removeAllRelationsOfMarker(IMarker marker) {
marker = MarkUtilities.getLeaderOfMarker(marker);
if (marker != null) {
Iterator<Entry<IMarker, String>> iter;
final Map<IMarker, String> relationsOfFirstSide =
AlloyUtilities.getRelationsOfFirstSideMarker(marker);
iter = relationsOfFirstSide.entrySet().iterator();
while (iter.hasNext()) {
@SuppressWarnings("rawtypes")
final Map.Entry pair = iter.next();
AlloyUtilities.removeFieldOfMarkers(marker, (IMarker) pair.getKey(),
(String) pair.getValue());
}
final Map<IMarker, String> relationsOfSecondSide =
AlloyUtilities.getRelationsOfSecondSideMarker(marker);
iter = relationsOfSecondSide.entrySet().iterator();
while (iter.hasNext()) {
@SuppressWarnings("rawtypes")
final Map.Entry pair = iter.next();
AlloyUtilities.removeFieldOfMarkers((IMarker) pair.getKey(), marker,
(String) pair.getValue());
}
}
}
public static void removeFieldOfMarkers(IMarker fromMarker, IMarker toMarker,
final String relationName) {
fromMarker = MarkUtilities.getLeaderOfMarker(fromMarker);
toMarker = MarkUtilities.getLeaderOfMarker(toMarker);
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final EList<FieldType> fieldTypes = documentRoot.getAlloy().getInstance().getField();
final String fromMarkerId = MarkUtilities.getSourceId(fromMarker);
final String toMarkerId = MarkUtilities.getSourceId(toMarker);
for (final FieldType fieldType : fieldTypes) {
if (fieldType.getLabel().equals(relationName)) {
final Iterator<TupleType> tupleTypesIter = fieldType.getTuple().iterator();
while (tupleTypesIter.hasNext()) {
final EList<AtomType> atoms = tupleTypesIter.next().getAtom();
if (atoms.get(0).getLabel().equals(fromMarkerId)
&& atoms.get(1).getLabel().equals(toMarkerId)) {
tupleTypesIter.remove();
AlloyUtilities.writeDocumentRoot(documentRoot);
return;
}
}
}
}
}
/**
* This method is used to when fromMarker doesn't map toMarker any more.
*
* @param fromMarker
* @param toMarker
*/
public static void removeMappingFromRelationType(IMarker fromMarker, IMarker toMarker) {
fromMarker = MarkUtilities.getLeaderOfMarker(fromMarker);
toMarker = MarkUtilities.getLeaderOfMarker(toMarker);
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final RelationType relationType = AlloyUtilities.getRelationType(documentRoot);
final String fromMarkerId = MarkUtilities.getSourceId(fromMarker);
final String toMarkerId = MarkUtilities.getSourceId(toMarker);
final Iterator<TupleType> iter = relationType.getTuple().iterator();
while (iter.hasNext()) {
final EList<AtomType> atoms = iter.next().getAtom();
if (atoms.get(0).getLabel().equals(fromMarkerId)
&& atoms.get(1).getLabel().equals(toMarkerId)) {
iter.remove();
AlloyUtilities.writeDocumentRoot(documentRoot);
return;
}
}
}
public static void removeMarkerFromRepository(final IMarker marker) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final int itemTypeIndex = AlloyUtilities.findItemTypeInRepository(marker);
if (itemTypeIndex == -1) {
return;
}
documentRoot.getAlloy().getRepository().getItem().remove(itemTypeIndex);
AlloyUtilities.writeDocumentRoot(documentRoot);
}
/**
* Removes relation of given marker
*
* @param marker which will be deleted relation of
*/
public static void removeRelationOfMarker(IMarker marker) {
marker = MarkUtilities.getLeaderOfMarker(marker);
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final String id = MarkUtilities.getSourceId(marker);
final EList<TupleType> tupleTypes = AlloyUtilities.getRelationType(documentRoot).getTuple();
final Iterator<TupleType> iter = tupleTypes.iterator();
while (iter.hasNext()) {
final TupleType tupleType = iter.next();
final AtomType firstSideAtom = tupleType.getAtom().get(0);
final AtomType secondSideAtom = tupleType.getAtom().get(1);
if (firstSideAtom.getLabel().equals(id) || secondSideAtom.getLabel().equals(id)) {
iter.remove();
}
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static void removeTypeFromMarker(final IMarker marker) {
if (MarkUtilities.compare(marker, MarkUtilities.getLeaderOfMarker(marker))) {
AlloyUtilities.removeAllRelationsOfMarker(marker);
}
if (MarkUtilities.getType(marker) == null || MarkUtilities.getType(marker).isEmpty()) {
return;
}
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final String type = MarkUtilities.getType(marker);
final String markerId = MarkUtilities.getSourceId(marker);
final int idOfTypeSigInSigType = AlloyUtilities.isTypeInSig(type);
final EList<SigType> sigs = documentRoot.getAlloy().getInstance().getSig();
for (final SigType sigType : sigs) {
if (type.equals(sigType.getLabel().substring(sigType.getLabel().indexOf("/") + 1))
|| idOfTypeSigInSigType != -1 && sigType.getID() == idOfTypeSigInSigType) {
final Iterator<AtomType> atomsIter = sigType.getAtom().iterator();
while (atomsIter.hasNext()) {
final AtomType atomType = atomsIter.next();
if (atomType.getLabel().equals(markerId)) {
atomsIter.remove();
break;
}
}
}
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
private static void setEntries(final ItemType itemType, final IMarker marker) {
if (MarkUtilities.getPath(marker) != null) {
final EntryType resourceEntry = persistenceFactory.eINSTANCE.createEntryType();
resourceEntry.setKey(AlloyUtilities.RESOURCE);
resourceEntry.setValue(MarkUtilities.getPath(marker));
itemType.getEntry().add(resourceEntry);
}
if (MarkUtilities.getStart(marker) != -1) {
final EntryType offsetEntry = persistenceFactory.eINSTANCE.createEntryType();
offsetEntry.setKey(AlloyUtilities.OFFSET);
offsetEntry.setValue(Integer.toString(MarkUtilities.getStart(marker)));
itemType.getEntry().add(offsetEntry);
}
if (MarkUtilities.getText(marker) != null) {
final EntryType textEntry = persistenceFactory.eINSTANCE.createEntryType();
textEntry.setKey(AlloyUtilities.TEXT);
textEntry.setValue(MarkUtilities.getText(marker));
itemType.getEntry().add(textEntry);
}
if (MarkUtilities.getUri(marker) != null) {
final EntryType uriEntry = persistenceFactory.eINSTANCE.createEntryType();
uriEntry.setKey(AlloyUtilities.MARKER_URI);
uriEntry.setValue(MarkUtilities.getUri(marker));
itemType.getEntry().add(uriEntry);
}
if (MarkUtilities.getLeaderId(marker) != null) {
final EntryType leaderIdEntry = persistenceFactory.eINSTANCE.createEntryType();
leaderIdEntry.setKey(AlloyUtilities.LEADER_ID);
leaderIdEntry.setValue(MarkUtilities.getLeaderId(marker));
itemType.getEntry().add(leaderIdEntry);
}
if (MarkUtilities.getGroupId(marker) != null) {
final EntryType groupIdEntry = persistenceFactory.eINSTANCE.createEntryType();
groupIdEntry.setKey(AlloyUtilities.GROUP_ID);
groupIdEntry.setValue(MarkUtilities.getGroupId(marker));
itemType.getEntry().add(groupIdEntry);
}
}
// public static void showViz() {
// final String xmlFileName = Util.canon(AlloyUtilities.getLocation());
// File f = new File(xmlFileName);
// AlloyInstance myInstance = null;
// try {
// if (!f.exists()) {
// throw new IOException("File " + xmlFileName + " does not exist.");
// myInstance = StaticInstanceReader.parseInstance(f);
// } catch (Err e1) {
// e1.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// VizState myState = null;
// myState = new VizState(myInstance);
// // VizCustomizationPanel customizationPanel = new VizCustomizationPanel(null, myState);
// // myState.loadPaletteXML("C:\\Users\\3\\Desktop\\theme.thm");
// // myState.useOriginalName(true);
// VizGraphPanel graph = new VizGraphPanel(myState, false);
// JFrame frame = new JFrame("Traceability Virtualization");
// frame.add(graph);
// frame.setVisible(true);
// frame.pack();
// Dimension dim = new Dimension(500, 500);
// frame.setMinimumSize(dim);
// JMenu modelWriterMenu = new JMenu("ModelWriter");
// JMenuItem deleteMarkerMenuItem = new JMenuItem("Delete Marker");
// JMenuItem removeTypeMenuItem = new JMenuItem("Remove Type");
// JMenuItem removeRelationMenuItem = new JMenuItem("Remove Relation");
// JMenuItem mapMarkerMenuItem = new JMenuItem("Map Marker");
// ActionListener acl = new ActionListener() {
// @Override
// public void actionPerformed(ActionEvent e) {
// if (e.getSource() == mapMarkerMenuItem) {
// if (AlloyUtilities.isExists()) {
// System.out.println("markers are successfully mapped.");
// } else {
// System.out.println("alloy file has not been parsed.");
// } else if (e.getSource() == deleteMarkerMenuItem) {
// System.out.println("marker is deleted.");
// } else if (e.getSource() == removeTypeMenuItem) {
// System.out.println("type is removed.");
// modelWriterMenu.add(deleteMarkerMenuItem, 0);
// modelWriterMenu.add(removeTypeMenuItem, 1);
// modelWriterMenu.add(removeRelationMenuItem, 2);
// modelWriterMenu.add(mapMarkerMenuItem, 3);
// deleteMarkerMenuItem.addActionListener(acl);
// removeTypeMenuItem.addActionListener(acl);
// removeRelationMenuItem.addActionListener(acl);
// mapMarkerMenuItem.addActionListener(acl);
// graph.alloyGetViewer().pop.add(modelWriterMenu, 0);
// graph.alloyGetViewer().addMouseMotionListener(new MouseMotionAdapter() {
// @Override
// public void mouseMoved(MouseEvent e) {
// Object annotation = graph.alloyGetViewer().alloyGetAnnotationAtXY(e.getX(), e.getY());
// JComponent cmpnt = (JComponent) e.getComponent();
// String tooltip = null;
// if (annotation instanceof AlloyAtom) {
// AlloyAtom highLightedAtom =
// (AlloyAtom) graph.alloyGetViewer().alloyGetAnnotationAtXY(e.getX(), e.getY());
// String atomType = highLightedAtom.getType().getName();
// String stringIndex = highLightedAtom.toString().substring(atomType.length());
// int index = 0;
// if (!stringIndex.isEmpty()) {
// index = Integer.parseInt(stringIndex);
// IMarker marker = AlloyUtilities.findMarker(atomType, index);
// if (marker == null) {
// return;
// tooltip = MarkUtilities.getText(marker);
// } else if (annotation instanceof AlloyTuple) {
// AlloyTuple tuple =
// (AlloyTuple) graph.alloyGetViewer().alloyGetAnnotationAtXY(e.getX(), e.getY());
// AlloyAtom highLightedAtomStart = tuple.getStart();
// AlloyAtom highLightedAtomEnd = tuple.getEnd();
// String atomTypeStart = highLightedAtomStart.getType().getName();
// String atomTypeEnd = highLightedAtomEnd.getType().getName();
// String stringIndexStart =
// highLightedAtomStart.toString().substring(atomTypeStart.length());
// String stringIndexEnd = highLightedAtomEnd.toString().substring(atomTypeEnd.length());
// int indexStart = 0;
// int indexEnd = 0;
// if (!stringIndexStart.isEmpty() && !stringIndexEnd.isEmpty()) {
// indexStart = Integer.parseInt(stringIndexStart);
// indexEnd = Integer.parseInt(stringIndexEnd);
// IMarker markerStart = AlloyUtilities.findMarker(atomTypeStart, indexStart);
// IMarker markerEnd = AlloyUtilities.findMarker(atomTypeEnd, indexEnd);
// if (markerStart == null || markerEnd == null) {
// return;
// tooltip = MarkUtilities.getText(markerStart) + " --> " + MarkUtilities.getText(markerEnd);
// cmpnt.setToolTipText(tooltip);
// graph.alloyGetViewer().addMouseListener(new MouseAdapter() {
// @Override
// public void mouseClicked(MouseEvent e) {
// // TODO Auto-generated method stub
// super.mouseClicked(e);
// System.out.println("Clicked");
// System.out.println(e.getComponent());
// GraphViewer viewer = (GraphViewer) e.getSource();
// if (viewer.alloyGetHighlightedAnnotation() == null
// || !(viewer.alloyGetHighlightedAnnotation() instanceof AlloyAtom)) {
// return;
// AlloyAtom highLightedAtom = (AlloyAtom) viewer.alloyGetHighlightedAnnotation();
// String atomType = highLightedAtom.getType().getName();
// String stringIndex = highLightedAtom.toString().substring(atomType.length());
// int index = 0;
// if (!stringIndex.isEmpty()) {
// index = Integer.parseInt(stringIndex);
// IMarker marker = AlloyUtilities.findMarker(atomType, index);
// if (marker == null) {
// return;
// if (e.getClickCount() > 1) {
// MarkUtilities.focusMarker(marker);
// } else {
// System.out.println(MarkUtilities.getText(marker));
// @Override
// public void mousePressed(MouseEvent e) {
// switch (e.getButton()) {
// case MouseEvent.BUTTON3: // right click
// Object annotation = graph.alloyGetViewer().alloyGetAnnotationAtXY(e.getX(), e.getY());
// JMenu menu = (JMenu) graph.alloyGetViewer().pop.getComponent(0);
// if (annotation == null) {
// menu.setVisible(false);
// } else {
// if (annotation instanceof AlloyAtom) {
// menu.getItem(0).setVisible(true);
// menu.getItem(1).setVisible(true);
// menu.getItem(2).setVisible(false);
// menu.getItem(3).setVisible(true);
// } else if (annotation instanceof AlloyTuple) {
// menu.getItem(0).setVisible(false);
// menu.getItem(1).setVisible(false);
// menu.getItem(2).setVisible(true);
// menu.getItem(3).setVisible(false);
// menu.setVisible(true);
// default:
// break;
// // JDialog dialog = new JDialog();
// // dialog.add(graph);
// // dialog.setVisible(true);
// // dialog.pack();
public static void setImpactAndChanged(final IMarker marker) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final AlloyType alloyType = documentRoot.getAlloy();
if (MarkUtilities.getType(marker) != null) {
final EList<SigType> listOfSigs = alloyType.getInstance().getSig();
for (final SigType sigType : listOfSigs) {
final EList<AtomType> atoms = sigType.getAtom();
for (final AtomType atomType : atoms) {
if (atomType.getLabel().equals(MarkUtilities.getSourceId(marker))) {
atomType.setChanged(true);
}
}
}
final EList<FieldType> listOfField = alloyType.getInstance().getField();
for (final FieldType fieldType : listOfField) {
final EList<TupleType> tuples = fieldType.getTuple();
for (final TupleType tupleType : tuples) {
if (tupleType.getAtom().get(0).getLabel().equals(MarkUtilities.getSourceId(marker))) {
tupleType.getAtom().get(1).setImpact(true);
}
}
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
}
public static void setMetamodel(final String filename, final boolean state) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRootForMetaModel(filename);
if (state == true) {
documentRoot.getAlloy().getInstance().setMetamodel("yes");
} else {
documentRoot.getAlloy().getInstance().setMetamodel(null);
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static void unsetChanged(final IMarker fromMarker) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final String sourceIdOfFromMarker = MarkUtilities.getSourceId(fromMarker);
final AtomType atom =
AlloyUtilities.getAtomTypeBySourceIdFromSig(documentRoot, sourceIdOfFromMarker);
atom.setChanged(null);
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static void unsetChangedAndAllImpacted(final IMarker changedMarker) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final String sourceIdOfChangedMarker = MarkUtilities.getSourceId(changedMarker);
final AtomType atom =
AlloyUtilities.getAtomTypeBySourceIdFromSig(documentRoot, sourceIdOfChangedMarker);
final ArrayList<AtomType> secondSideAtoms = AlloyUtilities
.getSecondSideAtomsBySourceIdOfFirstSide(documentRoot, sourceIdOfChangedMarker);
for (final AtomType atomType : secondSideAtoms) {
if (atomType.getImpact() != null && atomType.getImpact()) {
atomType.setImpact(null);
}
}
atom.setChanged(null);
AlloyUtilities.writeDocumentRoot(documentRoot);
}
public static void unsetImpactAndChanged(final IMarker fromMarker, final IMarker toMarker) {
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final String sourceIdOfFromMarker = MarkUtilities.getSourceId(fromMarker);
final String sourceIdOfToMarker = MarkUtilities.getSourceId(toMarker);
final AtomType atom =
AlloyUtilities.getAtomTypeBySourceIdFromSig(documentRoot, sourceIdOfFromMarker);
final ArrayList<AtomType> secondSideAtoms =
AlloyUtilities.getSecondSideAtomsBySourceIdOfFirstSide(documentRoot, sourceIdOfFromMarker);
int impactCount = 0;
for (final AtomType atomType : secondSideAtoms) {
if (atomType.getImpact() != null) {
impactCount++;
if (atomType.getLabel().equals(sourceIdOfToMarker)) {
atomType.setImpact(null);
}
}
}
if (impactCount == 1) {
atom.setChanged(null);
}
AlloyUtilities.writeDocumentRoot(documentRoot);
}
@SuppressWarnings("unchecked")
public static void writeDocumentRoot(final DocumentRoot documentRoot) {
@SuppressWarnings("rawtypes")
final ModelIO modelIO = new ModelIO<>();
modelIO.write(AlloyUtilities.getUri(), documentRoot);
}
@SuppressWarnings("unchecked")
public static void writeDocumentRootForMetamodel(final DocumentRoot documentRoot,
final String filename) {
@SuppressWarnings("rawtypes")
final ModelIO modelIO = new ModelIO<>();
modelIO.write(
URI.createFileURI(AlloyUtilities
.getLocationForMetamodel(filename.substring(filename.lastIndexOf("/") + 1))),
documentRoot);
}
public static void setReasonedTuples(AlloyInstance instance) {
final EList<FieldType> fieldList = AlloyUtilities.getFieldTypes();
Map<TupleType, FieldType> reasonedTuplesInFields = new HashMap<>();
for (final FieldType fieldType : fieldList) {
final EList<TupleType> tuples = fieldType.getTuple();
for (TupleType tupleType : tuples) {
if (tupleType.isReasoned()) {
reasonedTuplesInFields.put(tupleType, fieldType);
}
}
}
for (Entry<TupleType, FieldType> reasonedEntry : reasonedTuplesInFields.entrySet()) {
TupleType tupleType = reasonedEntry.getKey();
FieldType fieldType = reasonedEntry.getValue();
for (Entry<AlloyRelation, Set<AlloyTuple>> entry : instance.rel2tuples.entrySet()) {
if (entry.getKey().getName().equals(fieldType.getLabel())) {
Iterator<AlloyTuple> tupleSetIter = entry.getValue().iterator();
while (tupleSetIter.hasNext()) {
AlloyTuple alloyTuple = (AlloyTuple) tupleSetIter.next();
boolean tuplesREqual = true;
for (int i = 0; i < tupleType.getAtom().size(); i++) {
if (!getAtomNameById(tupleType.getAtom().get(i).getLabel())
.equals(alloyTuple.getAtoms().get(i).getOriginalName())) {
tuplesREqual = false;
break;
}
}
if (tuplesREqual) {
alloyTuple.isDashed = true;
}
}
}
}
}
}
public static void resetReasoned(IMarker fromMarker, IMarker toMarker,
final String relationName) {
fromMarker = MarkUtilities.getLeaderOfMarker(fromMarker);
toMarker = MarkUtilities.getLeaderOfMarker(toMarker);
final DocumentRoot documentRoot = AlloyUtilities.getDocumentRoot();
final EList<FieldType> fieldTypes = documentRoot.getAlloy().getInstance().getField();
final String fromMarkerId = MarkUtilities.getSourceId(fromMarker);
final String toMarkerId = MarkUtilities.getSourceId(toMarker);
for (final FieldType fieldType : fieldTypes) {
if (fieldType.getLabel().equals(relationName)) {
final Iterator<TupleType> tupleTypesIter = fieldType.getTuple().iterator();
while (tupleTypesIter.hasNext()) {
TupleType tupleType = tupleTypesIter.next();
final EList<AtomType> atoms = tupleType.getAtom();
if (atoms.get(0).getLabel().equals(fromMarkerId)
&& atoms.get(1).getLabel().equals(toMarkerId)) {
tupleType.setReasoned(false);
AlloyUtilities.writeDocumentRoot(documentRoot);
return;
}
}
}
}
}
}
|
package com.github.ferstl.jarscan;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.adoptopenjdk.jitwatch.jarscan.JarScan;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.filter.AndArtifactFilter;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.plugins.annotations.ResolutionScope;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.artifact.filter.ScopeArtifactFilter;
import org.apache.maven.shared.artifact.filter.StrictPatternExcludesArtifactFilter;
import org.apache.maven.shared.artifact.filter.StrictPatternIncludesArtifactFilter;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
@Mojo(
name = "scan",
aggregator = false,
defaultPhase = LifecyclePhase.NONE,
inheritByDefault = false,
requiresDependencyCollection = ResolutionScope.TEST,
requiresDependencyResolution = ResolutionScope.TEST,
requiresDirectInvocation = false,
threadSafe = true)
public class JarScanMojo extends AbstractMojo {
@Component
private MavenProject project;
/**
* The value of {@code XX:FreqInlineSize} option. The default is 325.
*
* @since 1.0.0
*/
@Parameter(property = "freqInlineSize", defaultValue = "325")
private int freqInlineSize;
/**
* The path of the report file. If not set the report is written to the console.
*
* @since 1.0.0
*/
@Parameter(property = "reportFile")
private File reportFile;
/**
* Analyze dependency of the project.
*
* @since 1.0.0
*/
@Parameter(property = "analyzeDependencies", defaultValue = "false")
private boolean analyzeDependencies;
/**
* The scope of the artifacts that should be included. Only relevant when {@code analyzeDependencies=true}.
*
* @since 1.0.0
*/
@Parameter(property = "scope")
private String scope;
/**
* Comma-separated list of artifacts to be included in the form of {@code groupId:artifactId:type:classifier}.
* Only relevant when {@code analyzeDependencies=true}.
*
* @since 1.0.0
*/
@Parameter(property = "includes", defaultValue = "")
private List<String> includes;
/**
* Comma-separated list of artifacts to be excluded in the form of {@code groupId:artifactId:type:classifier}.
* Only relevant when {@code analyzeDependencies=true}.
*
* @since 1.0.0
*/
@Parameter(property = "excludes", defaultValue = "")
private List<String> excludes;
@Override
public void execute() throws MojoExecutionException {
analyzeOwnArtifact();
if (this.analyzeDependencies) {
analyzeDependencies();
}
}
private void analyzeOwnArtifact() throws MojoExecutionException {
String buildDirectory = this.project.getBuild().getDirectory();
String finalName = this.project.getBuild().getFinalName();
Path jarFile = Paths.get(buildDirectory, finalName + ".jar");
if (Files.exists(jarFile)) {
printReport(this.project.getArtifact().toString(), jarFile.toFile());
}
}
private void analyzeDependencies() throws MojoExecutionException {
@SuppressWarnings("unchecked")
Set<Artifact> dependencies = this.project.getDependencyArtifacts();
ArtifactFilter filter = createArtifactFilter();
for (Artifact dependency : dependencies) {
if (filter.include(dependency)) {
printReport(dependency.toString(), dependency.getFile());
}
}
}
private void printReport(String name, File file) throws MojoExecutionException {
try (PrintWriter writer = createReportWriter()){
System.out.println("Artifact: " + name);
JarScan.iterateJar(file, this.freqInlineSize, writer);
System.out.println();
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage());
}
}
private ArtifactFilter createArtifactFilter() {
List<ArtifactFilter> filters = new ArrayList<>(3);
if (this.scope != null) {
filters.add(new ScopeArtifactFilter(this.scope));
}
if (!this.includes.isEmpty()) {
filters.add(new StrictPatternIncludesArtifactFilter(this.includes));
}
if (!this.excludes.isEmpty()) {
filters.add(new StrictPatternExcludesArtifactFilter(this.excludes));
}
return new AndArtifactFilter(filters);
}
private PrintWriter createReportWriter() throws IOException{
if (this.reportFile != null) {
BufferedWriter bw = Files.newBufferedWriter(this.reportFile.toPath(), StandardCharsets.UTF_8, CREATE, TRUNCATE_EXISTING);
return new PrintWriter(bw);
}
return new PrintWriter(new OutputStreamWriter(System.out)) {
@Override
public void close() { /* NOP */ }
};
}
}
|
package org.snomed.otf.scheduler.domain;
import java.util.*;
import javax.persistence.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
@Entity
public class Job {
enum ProductionStatus {TESTING, PROD_READY, HIDEME}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@JsonIgnore
private long id;
String name;
String description;
ProductionStatus productionStatus;
@ManyToOne
@JsonIgnore //Will be evident in JSON from structure, causes infinite recursion if included explicitly.
JobCategory category;
@ElementCollection
@CollectionTable(name="ParameterNames", joinColumns=@JoinColumn(name="job_id"))
@Column(name="parameterName")
List<String> parameterNames;
@OneToMany
List<JobSchedule> schedules;
public Job() {};
public Job(JobCategory category, String name, String description, String[] params, ProductionStatus prodStatus) {
this.category = category;
this.name = name;
this.description = description;
parameterNames = Arrays.asList(params);
this.productionStatus = prodStatus;
}
public Job(JobCategory category, String name, String description, String[] params) {
this(category, name, description, params, ProductionStatus.PROD_READY);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public JobCategory getCategory() {
return category;
}
public void setCategory(JobCategory category) {
this.category = category;
}
public List<String> getParameterNames() {
return parameterNames;
}
public void setParameterNames(List<String> parameterNames) {
this.parameterNames = parameterNames;
}
public List<JobSchedule> getSchedules() {
return schedules;
}
public void setSchedules(List<JobSchedule> schedules) {
this.schedules = schedules;
}
@Override
public boolean equals (Object other) {
if (other instanceof Job) {
Job otherJob = (Job)other;
if (category.equals(otherJob.getCategory())) {
return name.equals(otherJob.getName());
}
}
return false;
}
@Override
public String toString() {
return getCategory() + "/" + getName();
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public ProductionStatus getProductionStatus() {
return productionStatus;
}
public void setProductionStatus(ProductionStatus productionStatus) {
this.productionStatus = productionStatus;
}
}
|
package com.strengthcoach.strengthcoach.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.SaveCallback;
import com.roomorama.caldroid.CaldroidFragment;
import com.roomorama.caldroid.CaldroidListener;
import com.strengthcoach.strengthcoach.R;
import com.strengthcoach.strengthcoach.helpers.Constants;
import com.strengthcoach.strengthcoach.models.BlockedSlots;
import com.strengthcoach.strengthcoach.models.SimpleUser;
import com.strengthcoach.strengthcoach.models.Trainer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
public class BlockSlotActivity extends ActionBarActivity{
CaldroidFragment caldroidFragment;
Date currentDate, dateAfterMonth;
Button bProceedToPayment, bAddToCart;
Date previousDate = null;
String userSelectedDate;
Spinner spSelectSlot;
String dayOfTheWeek, selectedDate;
SimpleDateFormat simpleDayFormat = new SimpleDateFormat(Constants.DAY_OF_WEEK_FORMAT);
SimpleDateFormat simpleDateStrFormat = new SimpleDateFormat(Constants.DATE_FORMAT);
Date date = new Date();
ArrayList<String> listOfSlots = new ArrayList<String>();
ArrayList<Integer> arBookedSlots = new ArrayList<Integer>();
ArrayList<Integer> arraySlots = new ArrayList<Integer>();
ArrayList<String> listOfAvailableDays = new ArrayList<String>();
String name, phoneno;
BlockedSlots bSlots ;
boolean flag;
Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block_slot);
// setup Toolbar
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_back_arrow);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
spSelectSlot = (Spinner) findViewById(R.id.spSelectSlot);
bAddToCart = (Button) findViewById(R.id.bAddToCart);
bProceedToPayment = (Button)findViewById(R.id.bProceedToPayment);
name = getIntent().getStringExtra("etName");
phoneno = getIntent().getStringExtra("etPhoneNumber");
flag=false;
if (savedInstanceState == null) {
caldroidFragment = new CaldroidFragment();
Bundle args = new Bundle();
Calendar cal = Calendar.getInstance();
args.putInt(CaldroidFragment.MONTH, cal.get(Calendar.MONTH) + 1);
args.putInt(CaldroidFragment.YEAR, cal.get(Calendar.YEAR));
args.putBoolean(CaldroidFragment.SQUARE_TEXT_VIEW_CELL, false);
caldroidFragment.setArguments(args);
currentDate = Calendar.getInstance().getTime();// get current date
// adding one month to current date
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 1);
dateAfterMonth = calendar.getTime();
caldroidFragment.setMinDate(currentDate); // disable dates prior to current date
caldroidFragment.setMaxDate(dateAfterMonth);// disable dates after a month from current date
getDaysBetweenDates(currentDate, dateAfterMonth, Trainer.currentTrainerObjectId);
setupCaldroidListener();
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.flCalendar, caldroidFragment);
t.commit();
}
dayOfTheWeek = simpleDayFormat.format(date);
selectedDate = simpleDateStrFormat.format(date);
userSelectedDate = selectedDate;
alreadyBookedSlots(Trainer.currentTrainerObjectId, dayOfTheWeek, selectedDate);
setupListener();
if (getLoggedInUserId().equals("")) {
// Start login activity
Intent intent = new Intent(this, LoginActivity.class);
startActivityForResult(intent, 20);
}
}
public void getDaysBetweenDates(final Date startdate, final Date enddate, String trainerId) {
ParseObject trainer = ParseObject.createWithoutData("Trainer", trainerId);
ParseQuery<ParseObject> query = ParseQuery.getQuery("TrainerSlots");
query.selectKeys(Arrays.asList("day"));
query.include("trainer_id");
query.whereEqualTo("trainer_id", trainer);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> trainerSlots, com.parse.ParseException e) {
if (e == null) {
listOfAvailableDays.clear();
for (ParseObject slots : trainerSlots) {
String availableDay = slots.getString("day");
listOfAvailableDays.add(availableDay);
}
ArrayList<Date> unAvailableDates = new ArrayList<Date>();
Calendar calendar = new GregorianCalendar();
calendar.setTime(startdate);
while (calendar.getTime().before(enddate)) {
Date result = calendar.getTime();
for (int i = 0; i < listOfAvailableDays.size(); i++) {
if (listOfAvailableDays.contains(simpleDayFormat.format(result))) {
caldroidFragment.setBackgroundResourceForDate(R.color.colorPrimary, result);
caldroidFragment.setTextColorForDate(R.color.white, result);
} else {
unAvailableDates.add(result);
}
}
calendar.add(Calendar.DATE, 1);
}
caldroidFragment.setDisableDates(unAvailableDates);
caldroidFragment.refreshView();
} else {
Log.d("DEBUG", "Error: " + e.getMessage());
}
}
});
}
public void setupListener(){
// spSelectSlot.setOnItemSelectedListener(this);
bProceedToPayment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
callCartActivity();
}
});
bAddToCart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bSlots = new BlockedSlots();
// need to save data to user model;
String currentUser;
if (SimpleUser.currentUserObjectId == null) {
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
currentUser = pref.getString("userId", "");
} else {
currentUser = SimpleUser.currentUserObjectId;
}
if (!spSelectSlot.getSelectedItem().toString().equals("Select a slot") && spSelectSlot.getSelectedItem().toString() != null) {
ParseObject trainer = ParseObject.createWithoutData("Trainer", Trainer.currentTrainerObjectId);
ParseObject user = ParseObject.createWithoutData("SimpleUser", currentUser);
bSlots.setTrainerId(trainer);
bSlots.setBookedByUserId(user);
bSlots.setSlotDate(userSelectedDate);
String[] selectedSlot = spSelectSlot.getSelectedItem().toString().split(" ");
String slotTime = selectedSlot[0];
String finalSelectedSlot = "";
if (selectedSlot[1].equals(Constants.AM)) {
finalSelectedSlot = slotTime;
} else if (selectedSlot[1].equals(Constants.PM)) {
if (slotTime.equals("12")) {
finalSelectedSlot = slotTime;
} else {
int intSlot = 12 + Integer.valueOf(slotTime);
finalSelectedSlot = Integer.toString(intSlot);
}
}
bSlots.setSlotTime(finalSelectedSlot);
bSlots.setStatus(Constants.ADD_TO_CART);
bSlots.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
Log.d("DEBUG!!!", "Slot Saved Successfully ");
} else {
Log.d("DEBUG!!!", "Slot Not Saved");
}
}
});
bProceedToPayment.setVisibility(View.VISIBLE);
spSelectSlot.setSelection(0);
} else {
Toast.makeText(BlockSlotActivity.this, "Select a slot", Toast.LENGTH_SHORT).show();
}
}
});
}
public void setupCaldroidListener(){
// Setup listener
final CaldroidListener listener = new CaldroidListener() {
@Override
public void onSelectDate(Date date, View view) {
// changing the background color of earlier selected date to blue
if (previousDate != null ){
caldroidFragment.setBackgroundResourceForDate(R.color.colorPrimary, previousDate);
caldroidFragment.refreshView();
}
flag=false;
// changing the background color of selected date to pink
caldroidFragment.setBackgroundResourceForDate(R.color.pink, date);
previousDate = date;
caldroidFragment.refreshView();
userSelectedDate = simpleDateStrFormat.format(date);
alreadyBookedSlots(Trainer.currentTrainerObjectId,simpleDayFormat.format(date),simpleDateStrFormat.format(date));
}
@Override
public void onChangeMonth(int month, int year) {
}
@Override
public void onLongClickDate(Date date, View view) {
}
@Override
public void onCaldroidViewCreated() {
if (caldroidFragment.getLeftArrowButton() != null) {
/*Toast.makeText(getApplicationContext(),
"Caldroid view is created", Toast.LENGTH_SHORT)
.show();*/
}
}
};
caldroidFragment.setCaldroidListener(listener);
}
public void alreadyBookedSlots(final String trainerId, final String sDay, final String sDate) {
arBookedSlots.clear();
ParseObject trainer = ParseObject.createWithoutData("Trainer", trainerId);
ParseQuery<ParseObject> query = ParseQuery.getQuery("BlockedSlots");
query.selectKeys(Arrays.asList("slot_time"));
query.include("trainer_id");
query.whereEqualTo("trainer_id", trainer);
query.whereEqualTo("slot_date", sDate);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> bookedSlots, com.parse.ParseException e) {
if (e == null) {
for (ParseObject slots : bookedSlots) {
int slotTime = Integer.valueOf(slots.getString("slot_time"));
arBookedSlots.add(slotTime);
}
} else {
Log.d("DEBUG", "Error: " + e.getMessage());
}
populateAvailableSlots(trainerId, sDay, sDate);
}
});
}
public void populateAvailableSlots(final String trainerId, final String day, final String sDate) {
final ParseObject trainer = ParseObject.createWithoutData("Trainer",trainerId);
ParseQuery<ParseObject> query = ParseQuery.getQuery("TrainerSlots");
query.selectKeys(Arrays.asList("start_time", "end_time"));
query.include("trainer_id");
query.whereEqualTo("trainer_id", trainer);
query.whereEqualTo("day", day);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> trainerSlots, com.parse.ParseException e) {
if (e == null) {
listOfSlots.clear();
listOfSlots.add(Constants.SELECT_SLOT);
for (ParseObject slots : trainerSlots) {
int startTimeInt = Integer.valueOf(slots.getString("start_time"));
int endTimeInt = Integer.valueOf(slots.getString("end_time"));
arraySlots.clear();
for (int i = startTimeInt; startTimeInt < endTimeInt; startTimeInt++) {
arraySlots.add(startTimeInt);
}
// find out time slots not in arBookedSlots
List<Integer> noBookedSlots = new ArrayList<Integer>(arraySlots);
noBookedSlots.removeAll(arBookedSlots);
for (int k = 0; k < noBookedSlots.size(); k++) {
int intSlotsWithoutBookedSlots = noBookedSlots.get(k);
String slotsWithoutBookedSlots;
if (intSlotsWithoutBookedSlots <= 11) {
slotsWithoutBookedSlots = intSlotsWithoutBookedSlots + " " + Constants.AM;
} else if (intSlotsWithoutBookedSlots == 12) {
slotsWithoutBookedSlots = intSlotsWithoutBookedSlots + " " + Constants.PM;
} else {
slotsWithoutBookedSlots = (intSlotsWithoutBookedSlots - 12) + " " + Constants.PM;
}
listOfSlots.add(slotsWithoutBookedSlots);
}
try {
Date d = simpleDateStrFormat.parse(sDate);
caldroidFragment.setBackgroundResourceForDate(R.color.pink, d);
previousDate = d;
caldroidFragment.refreshView();
} catch (java.text.ParseException e1) {
e1.printStackTrace();
}
spSelectSlot.setAdapter(new ArrayAdapter<String>(BlockSlotActivity.this,
android.R.layout.simple_spinner_item, listOfSlots));
}
} else {
Log.d("DEBUG", "Error: " + e.getMessage());
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_block_slot, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 20) {
if(resultCode != RESULT_OK){
// User didn't login cancel book slot
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
}
}
}
public void onCartClick(MenuItem item){
callCartActivity();
}
public void callCartActivity() {
Intent intent = new Intent(BlockSlotActivity.this, CartActivity.class);
startActivity(intent);
}
private String getLoggedInUserId() {
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String userId = pref.getString("userId", "");
return userId;
}
@Override
public void onBackPressed() {
Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);
finish();
overridePendingTransition(R.anim.stay_in_place, R.anim.exit_to_bottom);
}
}
|
package com.github.jonathanxd.codeapi;
import com.github.jonathanxd.codeapi.builder.AnnotationBuilder;
import com.github.jonathanxd.codeapi.builder.ClassBuilder;
import com.github.jonathanxd.codeapi.builder.ConcatHelper;
import com.github.jonathanxd.codeapi.builder.ConstructorBuilder;
import com.github.jonathanxd.codeapi.builder.EnumBuilder;
import com.github.jonathanxd.codeapi.builder.InterfaceBuilder;
import com.github.jonathanxd.codeapi.builder.MethodBuilder;
import com.github.jonathanxd.codeapi.builder.OperateHelper;
import com.github.jonathanxd.codeapi.common.CodeArgument;
import com.github.jonathanxd.codeapi.common.CodeModifier;
import com.github.jonathanxd.codeapi.common.CodeParameter;
import com.github.jonathanxd.codeapi.common.FullInvokeSpec;
import com.github.jonathanxd.codeapi.common.FullMethodSpec;
import com.github.jonathanxd.codeapi.common.InvokeDynamic;
import com.github.jonathanxd.codeapi.common.InvokeType;
import com.github.jonathanxd.codeapi.common.IterationType;
import com.github.jonathanxd.codeapi.common.IterationTypes;
import com.github.jonathanxd.codeapi.common.MethodType;
import com.github.jonathanxd.codeapi.common.Scope;
import com.github.jonathanxd.codeapi.common.SwitchType;
import com.github.jonathanxd.codeapi.common.SwitchTypes;
import com.github.jonathanxd.codeapi.common.TypeSpec;
import com.github.jonathanxd.codeapi.gen.value.source.PlainSourceGenerator;
import com.github.jonathanxd.codeapi.generic.GenericSignature;
import com.github.jonathanxd.codeapi.helper.Helper;
import com.github.jonathanxd.codeapi.helper.PredefinedTypes;
import com.github.jonathanxd.codeapi.impl.AnnotationImpl;
import com.github.jonathanxd.codeapi.impl.AnnotationPropertyImpl;
import com.github.jonathanxd.codeapi.impl.ArrayConstructorImpl;
import com.github.jonathanxd.codeapi.impl.ArrayLengthImpl;
import com.github.jonathanxd.codeapi.impl.ArrayLoadImpl;
import com.github.jonathanxd.codeapi.impl.ArrayStoreImpl;
import com.github.jonathanxd.codeapi.impl.BreakImpl;
import com.github.jonathanxd.codeapi.impl.CodeClass;
import com.github.jonathanxd.codeapi.impl.CodeConstructor;
import com.github.jonathanxd.codeapi.impl.CodeField;
import com.github.jonathanxd.codeapi.impl.CodeInterface;
import com.github.jonathanxd.codeapi.impl.CodeMethod;
import com.github.jonathanxd.codeapi.impl.ContinueImpl;
import com.github.jonathanxd.codeapi.impl.EnumEntryImpl;
import com.github.jonathanxd.codeapi.impl.EnumValueImpl;
import com.github.jonathanxd.codeapi.impl.MethodSpecImpl;
import com.github.jonathanxd.codeapi.impl.OperateImpl;
import com.github.jonathanxd.codeapi.interfaces.AccessOuter;
import com.github.jonathanxd.codeapi.interfaces.AccessSuper;
import com.github.jonathanxd.codeapi.interfaces.AccessThis;
import com.github.jonathanxd.codeapi.interfaces.Annotation;
import com.github.jonathanxd.codeapi.interfaces.AnnotationProperty;
import com.github.jonathanxd.codeapi.interfaces.ArrayConstructor;
import com.github.jonathanxd.codeapi.interfaces.ArrayLength;
import com.github.jonathanxd.codeapi.interfaces.ArrayLoad;
import com.github.jonathanxd.codeapi.interfaces.ArrayStore;
import com.github.jonathanxd.codeapi.interfaces.Break;
import com.github.jonathanxd.codeapi.interfaces.Case;
import com.github.jonathanxd.codeapi.interfaces.Casted;
import com.github.jonathanxd.codeapi.interfaces.CatchBlock;
import com.github.jonathanxd.codeapi.interfaces.Continue;
import com.github.jonathanxd.codeapi.interfaces.DoWhileBlock;
import com.github.jonathanxd.codeapi.interfaces.ElseBlock;
import com.github.jonathanxd.codeapi.interfaces.EnumEntry;
import com.github.jonathanxd.codeapi.interfaces.EnumValue;
import com.github.jonathanxd.codeapi.interfaces.FieldDeclaration;
import com.github.jonathanxd.codeapi.interfaces.ForBlock;
import com.github.jonathanxd.codeapi.interfaces.ForEachBlock;
import com.github.jonathanxd.codeapi.interfaces.IfBlock;
import com.github.jonathanxd.codeapi.interfaces.IfExpr;
import com.github.jonathanxd.codeapi.interfaces.InstanceOf;
import com.github.jonathanxd.codeapi.interfaces.MethodFragment;
import com.github.jonathanxd.codeapi.interfaces.MethodInvocation;
import com.github.jonathanxd.codeapi.interfaces.Operate;
import com.github.jonathanxd.codeapi.interfaces.Return;
import com.github.jonathanxd.codeapi.interfaces.Switch;
import com.github.jonathanxd.codeapi.interfaces.ThrowException;
import com.github.jonathanxd.codeapi.interfaces.TryBlock;
import com.github.jonathanxd.codeapi.interfaces.TryWithResources;
import com.github.jonathanxd.codeapi.interfaces.Typed;
import com.github.jonathanxd.codeapi.interfaces.VariableAccess;
import com.github.jonathanxd.codeapi.interfaces.VariableDeclaration;
import com.github.jonathanxd.codeapi.interfaces.VariableOperate;
import com.github.jonathanxd.codeapi.interfaces.WhileBlock;
import com.github.jonathanxd.codeapi.literals.Literals;
import com.github.jonathanxd.codeapi.operators.Operator;
import com.github.jonathanxd.codeapi.operators.Operators;
import com.github.jonathanxd.codeapi.types.CodeType;
import com.github.jonathanxd.codeapi.types.GenericType;
import com.github.jonathanxd.codeapi.types.PlainCodeType;
import com.github.jonathanxd.codeapi.util.ArrayToList;
import com.github.jonathanxd.codeapi.util.BiMultiVal;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* Factory class.
*
* Is highly recommended to use Builders instead of factory methods, because the documentation of
* this class isn't complete.
*/
public final class CodeAPI {
private static final Annotation[] EMPTY_ANNOTATIONS = {};
// Annotations
public static AnnotationBuilder annotationBuilder() {
return AnnotationBuilder.builder();
}
/**
* Create an annotation property of type {@code type} and name {@code name}.
*
* @param type Property type.
* @param name Property name.
* @return Property.
*/
public static AnnotationProperty property(CodeType type, String name) {
return factory__property(null, type, name, null);
}
/**
* Create an annotation property of type {@code type} and name {@code name}.
*
* @param type Property type.
* @param name Property name.
* @return Property.
*/
public static AnnotationProperty property(Class<?> type, String name) {
return factory__property(null, CodeAPI.toCodeType(type), name, null);
}
/**
* Create an annotation property of type {@code type} and name {@code name} with default value
* {@code value}.
*
* @param type Property type.
* @param name Property name.
* @param value Default annotation value. The value must be: {@link Byte}, {@link Boolean},
* {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Float},
* {@link Double}, {@link String}, {@link CodeType}, OBJECT, ARRAY, {@link
* EnumValue} or other {@link Annotation}.
* @return Property.
*/
public static AnnotationProperty property(CodeType type, String name, Object value) {
return factory__property(null, type, name, value);
}
/**
* Create an annotation property of type {@code type} and name {@code name} with default value
* {@code value}.
*
* @param type Property type.
* @param name Property name.
* @param value Default annotation value. The value must be: {@link Byte}, {@link Boolean},
* {@link Character}, {@link Short}, {@link Integer}, {@link Long}, {@link Float},
* {@link Double}, {@link String}, {@link CodeType}, OBJECT, ARRAY, {@link
* EnumValue} or other {@link Annotation}.
* @return Property.
*/
public static AnnotationProperty property(Class<?> type, String name, Object value) {
return factory__property(null, CodeAPI.toCodeType(type), name, value);
}
/**
* Create an annotation property of type {@code type} and name {@code name} with default value
* {@code value} and annotated with {@code annotations}.
*
* @param annotations Annotations.
* @param type Property type.
* @param name Property name.
* @param value Default annotation value. The value must be: {@link Byte}, {@link
* Boolean}, {@link Character}, {@link Short}, {@link Integer}, {@link Long},
* {@link Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return Property.
*/
public static AnnotationProperty property(List<Annotation> annotations, CodeType type, String name, Object value) {
return factory__property(annotations, type, name, value);
}
/**
* Create an annotation property of type {@code type} and name {@code name} with default value
* {@code value} and annotated with {@code annotations}.
*
* @param annotations Annotations.
* @param type Property type.
* @param name Property name.
* @param value Default annotation value. The value must be: {@link Byte}, {@link
* Boolean}, {@link Character}, {@link Short}, {@link Integer}, {@link Long},
* {@link Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return Property.
*/
public static AnnotationProperty property(List<Annotation> annotations, Class<?> type, String name, Object value) {
return factory__property(annotations, CodeAPI.toCodeType(type), name, value);
}
/**
* Create an annotation property of type {@code type} and name {@code name} and annotated with
* {@code annotations}.
*
* @param annotations Annotations.
* @param type Property type.
* @param name Property name.
* @return Property.
*/
public static AnnotationProperty property(List<Annotation> annotations, CodeType type, String name) {
return factory__property(annotations, type, name, null);
}
/**
* Create an annotation property of type {@code type} and name {@code name} and annotated with
* {@code annotations}.
*
* @param annotations Annotations.
* @param type Property type.
* @param name Property name.
* @return Property.
*/
public static AnnotationProperty property(List<Annotation> annotations, Class<?> type, String name) {
return factory__property(annotations, CodeAPI.toCodeType(type), name, null);
}
private static AnnotationProperty factory__property(List<Annotation> annotationList,
CodeType type,
String name,
Object value) {
return new AnnotationPropertyImpl(annotationList, type, name, value);
}
// Interfaces
/**
* Create a {@link InterfaceBuilder}.
*
* @return New {@link InterfaceBuilder}.
*/
public static InterfaceBuilder anInterfaceBuilder() {
return InterfaceBuilder.builder();
}
/**
* Create an interface.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @return {@link CodeInterface} instance.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName) {
return anInterface__factory(modifiers, qualifiedName, null, null);
}
/**
* Create an interface with generic signature.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature
* @return {@link CodeInterface} instance.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, GenericSignature<GenericType> signature) {
return anInterface__factory(modifiers, qualifiedName, signature, null);
}
/**
* Create an interface that extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param extensions Interfaces to extend.
* @return {@link CodeInterface} instance.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, CodeType... extensions) {
return anInterface__factory(modifiers, qualifiedName, null, null, extensions);
}
/**
* Create an interface with generic signature and extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature
* @param extensions Interfaces to extend.
* @return {@link CodeInterface} instance.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, CodeType... extensions) {
return anInterface__factory(modifiers, qualifiedName, signature, null, extensions);
}
// Class
/**
* Create an interface that extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param extensions Interfaces to extend.
* @return {@link CodeInterface} instance.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, Class<?>... extensions) {
return anInterface__factory(modifiers, qualifiedName, null, null, toCodeType(extensions));
}
/**
* Create an interface with generic signature and extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature
* @param extensions Interfaces to extend.
* @return {@link CodeInterface} instance.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Class<?>... extensions) {
return anInterface__factory(modifiers, qualifiedName, signature, null, toCodeType(extensions));
}
// ** Source **
/**
* Create an interface.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param source Function that receives the {@link CodeInterface} instance and returns
* the body to define.
* @return {@link CodeInterface} instance with provided body.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, Function<CodeInterface, CodeSource> source) {
return anInterface__factory(modifiers, qualifiedName, null, source);
}
/**
* Create an interface with generic signature.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature
* @param source Function that receives the {@link CodeInterface} instance and returns
* the body to define.
* @return {@link CodeInterface} instance with provided body.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Function<CodeInterface, CodeSource> source) {
return anInterface__factory(modifiers, qualifiedName, signature, source);
}
/**
* Create an interface that extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param extensions Interfaces to extend.
* @param source Function that receives the {@link CodeInterface} instance and returns
* the body to define.
* @return {@link CodeInterface} instance with provided body.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, CodeType[] extensions, Function<CodeInterface, CodeSource> source) {
return anInterface__factory(modifiers, qualifiedName, null, source, extensions);
}
/**
* Create an interface with generic signature and extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature
* @param extensions Interfaces to extend.
* @param source Function that receives the {@link CodeInterface} instance and returns
* the body to define.
* @return {@link CodeInterface} instance with provided body.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, CodeType[] extensions, Function<CodeInterface, CodeSource> source) {
return anInterface__factory(modifiers, qualifiedName, signature, source, extensions);
}
/**
* Create an interface that extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param extensions Interfaces to extend.
* @param source Function that receives the {@link CodeInterface} instance and returns
* the body to define.
* @return {@link CodeInterface} instance with provided body.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, Class<?>[] extensions, Function<CodeInterface, CodeSource> source) {
return anInterface__factory(modifiers, qualifiedName, null, source, toCodeType(extensions));
}
/**
* Create an interface with generic signature and extends another interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature
* @param extensions Interfaces to extend.
* @param source Function that receives the {@link CodeInterface} instance and returns
* the body to define.
* @return {@link CodeInterface} instance with provided body.
*/
public static CodeInterface anInterface(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Class<?>[] extensions, Function<CodeInterface, CodeSource> source) {
return anInterface__factory(modifiers, qualifiedName, signature, source, toCodeType(extensions));
}
// Factory
private static CodeInterface anInterface__factory(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Function<CodeInterface, CodeSource> source, CodeType... extensions) {
CodeInterface codeInterface = new CodeInterface(null, CodeModifier.extractModifiers(modifiers), ArrayToList.toList(extensions), signature, new CodeSource(), qualifiedName);
if (source != null)
return codeInterface.setBody(source.apply(codeInterface));
return codeInterface;
}
// Classes
/**
* Create a {@link ClassBuilder}.
*
* @return New {@link ClassBuilder}.
*/
public static ClassBuilder aClassBuilder() {
return ClassBuilder.builder();
}
/**
* Create a class.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, String qualifiedName) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, null, null);
}
/**
* Create an annotated class.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param annotations Annotations
* @param qualifiedName Qualified name of interface.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName) {
return aClass__factory(modifiers, annotations, qualifiedName, null, null, null);
}
/**
* Create a class with generic signature.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, signature, null);
}
/**
* Create an annotated class with generic signature.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param annotations Annotations
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature) {
return aClass__factory(modifiers, annotations, qualifiedName, null, signature, null);
}
/**
* Create a class that implements a set of interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param implementations Implementations.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, String qualifiedName, CodeType... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, null, null, implementations);
}
/**
* Create an annotated class that implements a set of interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param annotations Annotations
* @param qualifiedName Qualified name of interface.
* @param implementations Implementations.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, CodeType... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, null, null, null, implementations);
}
/**
* Create a class with generic signature and implements a set of interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature.
* @param implementations Implementations.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, CodeType... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, signature, null, implementations);
}
/**
* Create an annotated class with generic signature and implements a set of interfaces.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param annotations Annotations
* @param qualifiedName Qualified name of interface.
* @param signature Generic signature.
* @param implementations Implementations.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, CodeType... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, null, signature, null, implementations);
}
// Class
/**
* Create a class.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param qualifiedName Qualified name of interface.
* @param implementations Implementations.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, String qualifiedName, Class<?>... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, null, null, toCodeType(implementations));
}
/**
* Create an annotated class.
*
* @param modifiers Java Modifiers flag: {@link java.lang.reflect.Modifier} ({@link
* java.lang.reflect.Modifier#PUBLIC}, {@link java.lang.reflect.Modifier#PRIVATE},
* {@link java.lang.reflect.Modifier#PROTECTED}, or 0 to package-private
* visibility).
* @param annotations Annotations
* @param qualifiedName Qualified name of interface.
* @param implementations Implementations.
* @return {@link CodeClass} instance.
*/
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, Class<?>... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, null, null, null, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Class<?>... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, signature, null, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, Class<?>... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, null, signature, null, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, String qualifiedName, CodeType superType, CodeType... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, superType, null, null, implementations);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, CodeType superType, CodeType... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, superType, null, null, implementations);
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, CodeType superType, CodeType... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, superType, signature, null, implementations);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, CodeType superType, CodeType... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, superType, signature, null, implementations);
}
public static CodeClass aClass(int modifiers, String qualifiedName, Class<?> superType, Class<?>... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, Helper.getJavaType(superType), null, null, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, Class<?> superType, Class<?>... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, Helper.getJavaType(superType), null, null, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Class<?> superType, Class<?>... implementations) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, Helper.getJavaType(superType), signature, null, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, Class<?> superType, Class<?>... implementations) {
return aClass__factory(modifiers, annotations, qualifiedName, Helper.getJavaType(superType), signature, null, toCodeType(implementations));
}
// ** Source **
public static CodeClass aClass(int modifiers, String qualifiedName, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, null, source);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, null, null, source);
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, signature, source);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, null, signature, source);
}
public static CodeClass aClass(int modifiers, String qualifiedName, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, null, source, implementations);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, null, null, source, implementations);
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, signature, source, implementations);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, null, signature, source, implementations);
}
public static CodeClass aClass(int modifiers, String qualifiedName, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, null, source, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, null, null, source, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, null, signature, source, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, null, signature, source, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, String qualifiedName, CodeType superType, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, superType, null, source, implementations);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, CodeType superType, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, superType, null, source, implementations);
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, CodeType superType, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, superType, signature, source, implementations);
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, CodeType superType, CodeType[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, superType, signature, source, implementations);
}
public static CodeClass aClass(int modifiers, String qualifiedName, Class<?> superType, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, Helper.getJavaType(superType), null, source, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, Class<?> superType, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, Helper.getJavaType(superType), null, source, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, String qualifiedName, GenericSignature<GenericType> signature, Class<?> superType, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, EMPTY_ANNOTATIONS, qualifiedName, Helper.getJavaType(superType), signature, source, toCodeType(implementations));
}
public static CodeClass aClass(int modifiers, Annotation[] annotations, String qualifiedName, GenericSignature<GenericType> signature, Class<?> superType, Class<?>[] implementations, Function<CodeClass, CodeSource> source) {
return aClass__factory(modifiers, annotations, qualifiedName, Helper.getJavaType(superType), signature, source, toCodeType(implementations));
}
// Factory
private static CodeClass aClass__factory(int modifiers, Annotation[] annotations, String qualifiedName, CodeType superType, GenericSignature<GenericType> signature, Function<CodeClass, CodeSource> source, CodeType... implementations) {
CodeClass codeClass = new CodeClass(null, qualifiedName, CodeModifier.extractModifiers(modifiers), superType, ArrayToList.toList(implementations), signature, Arrays.asList(annotations), new CodeSource());
if (source != null)
return codeClass.setBody(source.apply(codeClass));
return codeClass;
}
// Enums
/**
* Creates a new enum builder.
*
* @return New enum builder
*/
public static EnumBuilder enumBuilder() {
return EnumBuilder.builder();
}
/**
* Create an named enum entry.
*
* @param name name of enum entry.
* @return New enum entry.
*/
public static EnumEntry enumEntry(String name) {
return enumEntry__factory(name, null, null, null);
}
/**
* Create an named enum entry with a body.
*
* @param name Name of enum entry.
* @param body Body of enum entry.
* @return New enum entry.
*/
public static EnumEntry enumEntry(String name, CodeSource body) {
return enumEntry__factory(name, body, null, null);
}
/**
* Create a new enum entry that calls the Enum constructor.
*
* @param name Name of entry.
* @param constructorSpec Constructor specification.
* @param constructorArguments Constructor arguments.
* @return new enum entry.
*/
public static EnumEntry enumEntry(String name, TypeSpec constructorSpec, List<CodeArgument> constructorArguments) {
return enumEntry__factory(name, null, constructorSpec, constructorArguments);
}
/**
* Create a new enum entry that have a body and calls the Enum constructor.
*
* @param name Name of entry.
* @param constructorSpec Constructor specification.
* @param constructorArguments Constructor arguments.
* @param body Enum entry body.
* @return new enum entry.
*/
public static EnumEntry enumEntry(String name, TypeSpec constructorSpec, List<CodeArgument> constructorArguments, CodeSource body) {
if (body.isEmpty())
body = null;
return enumEntry__factory(name, body, constructorSpec, constructorArguments);
}
// Factory
private static EnumEntry enumEntry__factory(String name, CodeSource body, TypeSpec spec, List<CodeArgument> arguments) {
return new EnumEntryImpl(name, body, spec, arguments);
}
// Methods
/**
* Create a {@link MethodBuilder}.
*
* @return New {@link MethodBuilder}.
*/
public static MethodBuilder methodBuilder() {
return MethodBuilder.builder();
}
public static CodeMethod method(int modifiers, String name, CodeType returnType, CodeParameter... parameters) {
return method__factory(modifiers, null, name, returnType, null, parameters);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, CodeType returnType, CodeParameter... parameters) {
return method__factory(modifiers, signature, name, returnType, null, parameters);
}
public static CodeMethod method(int modifiers, String name, CodeType returnType) {
return method__factory(modifiers, null, name, returnType, null);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, CodeType returnType) {
return method__factory(modifiers, signature, name, returnType, null);
}
public static CodeMethod method(String name, CodeType returnType, CodeParameter... parameters) {
return method__factory(0, null, name, returnType, null, parameters);
}
public static CodeMethod method(GenericSignature<GenericType> signature, String name, CodeType returnType, CodeParameter... parameters) {
return method__factory(0, signature, name, returnType, null, parameters);
}
public static CodeMethod method(String name, CodeType returnType) {
return method__factory(0, null, name, returnType, null);
}
public static CodeMethod method(GenericSignature<GenericType> signature, String name, CodeType returnType) {
return method__factory(0, signature, name, returnType, null);
}
/// Class
public static CodeMethod method(int modifiers, String name, Class<?> returnType, CodeParameter... parameters) {
return method__factory(modifiers, null, name, Helper.getJavaType(returnType), null, parameters);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, Class<?> returnType, CodeParameter... parameters) {
return method__factory(modifiers, signature, name, Helper.getJavaType(returnType), null, parameters);
}
public static CodeMethod method(int modifiers, String name, Class<?> returnType) {
return method__factory(modifiers, null, name, Helper.getJavaType(returnType), null);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, Class<?> returnType) {
return method__factory(modifiers, signature, name, Helper.getJavaType(returnType), null);
}
public static CodeMethod method(String name, Class<?> returnType, CodeParameter... parameters) {
return method__factory(0, null, name, Helper.getJavaType(returnType), null, parameters);
}
public static CodeMethod method(GenericSignature<GenericType> signature, String name, Class<?> returnType, CodeParameter... parameters) {
return method__factory(0, signature, name, Helper.getJavaType(returnType), null, parameters);
}
public static CodeMethod method(String name, Class<?> returnType) {
return method__factory(0, null, name, Helper.getJavaType(returnType), null);
}
public static CodeMethod method(GenericSignature<GenericType> signature, String name, Class<?> returnType) {
return method__factory(0, signature, name, Helper.getJavaType(returnType), null);
}
// ** Source **
public static CodeMethod method(int modifiers, String name, CodeType returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, null, name, returnType, source, parameters);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, CodeType returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, signature, name, returnType, source, parameters);
}
public static CodeMethod method(int modifiers, String name, CodeType returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, null, name, returnType, source);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, CodeType returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, signature, name, returnType, source);
}
public static CodeMethod method(String name, CodeType returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(0, null, name, returnType, source, parameters);
}
public static CodeMethod method(GenericSignature<GenericType> signature, String name, CodeType returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(0, signature, name, returnType, source, parameters);
}
public static CodeMethod method(String name, CodeType returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(0, null, name, returnType, source);
}
public static CodeMethod method(GenericSignature<GenericType> signature, String name, CodeType returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(0, signature, name, returnType, source);
}
/// Class
public static CodeMethod method(int modifiers, String name, Class<?> returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, null, name, Helper.getJavaType(returnType), source, parameters);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, Class<?> returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, signature, name, Helper.getJavaType(returnType), source, parameters);
}
public static CodeMethod method(int modifiers, String name, Class<?> returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, null, name, Helper.getJavaType(returnType), source);
}
public static CodeMethod method(int modifiers, GenericSignature<GenericType> signature, String name, Class<?> returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(modifiers, signature, name, Helper.getJavaType(returnType), source);
}
public static CodeMethod method(String name, Class<?> returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(0, null, name, Helper.getJavaType(returnType), source, parameters);
}
public static CodeMethod method(String name, GenericSignature<GenericType> signature, Class<?> returnType, CodeParameter[] parameters, Function<CodeMethod, CodeSource> source) {
return method__factory(0, signature, name, Helper.getJavaType(returnType), source, parameters);
}
public static CodeMethod method(String name, Class<?> returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(0, null, name, Helper.getJavaType(returnType), source);
}
public static CodeMethod method(String name, GenericSignature<GenericType> signature, Class<?> returnType, Function<CodeMethod, CodeSource> source) {
return method__factory(0, signature, name, Helper.getJavaType(returnType), source);
}
// Factory
private static CodeMethod method__factory(int modifiers, GenericSignature<GenericType> signature, String name, CodeType returnType, Function<CodeMethod, CodeSource> source, CodeParameter... parameters) {
CodeMethod method = new CodeMethod(name, CodeModifier.extractModifiers(modifiers), ArrayToList.toList(parameters), returnType, signature, new CodeSource());
if (source != null)
return method.setBody(source.apply(method));
return method;
}
// Constructors
/**
* Create a {@link ConstructorBuilder}.
*
* @return New {@link ConstructorBuilder}.
*/
public static ConstructorBuilder constructorBuilder() {
return ConstructorBuilder.builder();
}
public static CodeConstructor constructor(int modifiers, CodeParameter... parameters) {
return constructor__factory(modifiers, null, parameters);
}
public static CodeConstructor constructor(int modifiers) {
return constructor__factory(modifiers, null);
}
// ** Source **
public static CodeConstructor constructor(int modifiers, CodeParameter[] parameters, Function<CodeConstructor, CodeSource> source) {
return constructor__factory(modifiers, source, parameters);
}
public static CodeConstructor constructor(int modifiers, Function<CodeConstructor, CodeSource> source) {
return constructor__factory(modifiers, source);
}
// Factory
private static CodeConstructor constructor__factory(int modifiers, Function<CodeConstructor, CodeSource> source, CodeParameter... parameters) {
CodeConstructor codeConstructor = new CodeConstructor(CodeModifier.extractModifiers(modifiers), ArrayToList.toList(parameters), new CodeSource());
if (source != null)
return codeConstructor.setBody(source.apply(codeConstructor));
return codeConstructor;
}
// Fields
// ** Source **
public static CodeField field(int modifiers, CodeType type, String name, CodePart value) {
return field__factory(modifiers, type, name, value);
}
public static CodeField field(int modifiers, CodeType type, String name) {
return field__factory(modifiers, type, name, null);
}
public static CodeField field(CodeType type, String name, CodePart value) {
return field__factory(0, type, name, value);
}
public static CodeField field(CodeType type, String name) {
return field__factory(0, type, name, null);
}
/// Class
public static CodeField field(int modifiers, Class<?> type, String name, CodePart value) {
return field__factory(modifiers, Helper.getJavaType(type), name, value);
}
public static CodeField field(int modifiers, Class<?> type, String name) {
return field__factory(modifiers, Helper.getJavaType(type), name, null);
}
public static CodeField field(Class<?> type, String name, CodePart value) {
return field__factory(0, Helper.getJavaType(type), name, value);
}
public static CodeField field(Class<?> type, String name) {
return field__factory(0, Helper.getJavaType(type), name, null);
}
// Factory
private static CodeField field__factory(int modifiers, CodeType type, String name, CodePart value) {
return new CodeField(name, type, value, CodeModifier.extractModifiers(modifiers));
}
// Array Constructors
public static ArrayConstructor arrayConstruct(CodeType arrayType, CodePart[] dimensions, CodeArgument... arguments) {
return arrayConstruct__factory(arrayType, dimensions, arguments);
}
public static ArrayConstructor arrayConstruct(CodeType arrayType, CodePart[] dimensions) {
return arrayConstruct__factory(arrayType, dimensions);
}
// Class
public static ArrayConstructor arrayConstruct(Class<?> arrayType, CodePart[] dimensions) {
return arrayConstruct__factory(Helper.getJavaType(arrayType), dimensions);
}
public static ArrayConstructor arrayConstruct(Class<?> arrayType, CodePart[] dimensions, CodeArgument... arguments) {
return arrayConstruct__factory(Helper.getJavaType(arrayType), dimensions, arguments);
}
// Factory
private static ArrayConstructor arrayConstruct__factory(CodeType arrayType, CodePart[] dimensions, CodeArgument... arguments) {
return new ArrayConstructorImpl(arrayType, dimensions, ArrayToList.toList(arguments));
}
// Array Manipulate
public static ArrayLength getArrayLength(VariableAccess access) {
return getArrayLength__factory(access);
}
public static ArrayLoad getArrayValue(CodeType arrayType, VariableAccess access, CodePart index) {
return getArrayValue__factory(index, access, arrayType);
}
public static ArrayStore setArrayValue(CodeType arrayType, VariableAccess access, CodePart index, CodePart value) {
return setArrayValue__factory(index, access, arrayType, value);
}
// Class
public static ArrayLoad getArrayValue(Class<?> arrayType, VariableAccess access, CodePart index) {
return getArrayValue__factory(index, access, Helper.getJavaType(arrayType));
}
public static ArrayStore setArrayValue(Class<?> arrayType, VariableAccess access, CodePart index, CodePart value) {
return setArrayValue__factory(index, access, Helper.getJavaType(arrayType), value);
}
// Factory
private static ArrayLength getArrayLength__factory(VariableAccess access) {
return new ArrayLengthImpl(access);
}
private static ArrayLoad getArrayValue__factory(CodePart index, VariableAccess access, CodeType arrayType) {
return new ArrayLoadImpl(index, access, arrayType);
}
private static ArrayStore setArrayValue__factory(CodePart index, VariableAccess access, CodeType arrayType, CodePart value) {
return new ArrayStoreImpl(index, access, arrayType, value);
}
// Source
public static CodeSource emptySource() {
return new CodeSource();
}
public static MutableCodeSource emptyMutableSource() {
return new MutableCodeSource();
}
public static CodeSource sourceOfParts(CodePart... codeParts) {
return new CodeSource(codeParts);
}
public static <T> Function<T, CodeSource> source(CodePart... codeParts) {
return (t) -> new CodeSource(codeParts);
}
public static <T> Function<T, CodeSource> source(Function<T, CodeSource> sourceFunction) {
return sourceFunction;
}
// Return
public static Return returnValue(CodeType valueType, CodePart value) {
return Helper.returnValue(valueType, value);
}
public static Return returnValue(Class<?> valueType, CodePart value) {
return Helper.returnValue(Helper.getJavaType(valueType), value);
}
public static Return returnLocalVariable(CodeType fieldType, String fieldName) {
return Helper.returnValue(fieldType, Helper.accessLocalVariable(fieldName, fieldType));
}
public static Return returnLocalVariable(Class<?> fieldType, String fieldName) {
return Helper.returnValue(Helper.getJavaType(fieldType), Helper.accessLocalVariable(fieldName, Helper.getJavaType(fieldType)));
}
public static Return returnThisField(CodeType fieldType, String fieldName) {
return Helper.returnValue(fieldType, Helper.accessVariable(null, Helper.accessThis(), fieldName, fieldType));
}
public static Return returnThisField(Class<?> fieldType, String fieldName) {
return Helper.returnValue(Helper.getJavaType(fieldType), Helper.accessVariable(null, Helper.accessThis(), fieldName, Helper.getJavaType(fieldType)));
}
public static Return returnField(CodeType localization, Class<?> fieldType, String fieldName) {
return Helper.returnValue(Helper.getJavaType(fieldType), Helper.accessVariable(localization, fieldName, Helper.getJavaType(fieldType)));
}
public static Return returnField(Class<?> localization, Class<?> fieldType, String fieldName) {
return Helper.returnValue(Helper.getJavaType(fieldType), Helper.accessVariable(Helper.getJavaType(localization), fieldName, Helper.getJavaType(fieldType)));
}
// Parameters
/**
* Create a {@link CodeParameter parameter}.
*
* @param type Parameter value type.
* @param name Name of the parameter.
* @return {@link CodeParameter} instance.
*/
public static CodeParameter parameter(CodeType type, String name) {
return new CodeParameter(name, type);
}
/**
* Create a {@link CodeParameter parameter}.
*
* @param type Parameter value type.
* @param name Name of the parameter.
* @return {@link CodeParameter} instance.
*/
public static CodeParameter parameter(Class<?> type, String name) {
return new CodeParameter(name, Helper.getJavaType(type));
}
// Arguments
/**
* Create an {@link CodeArgument argument}.
*
* @param value Value of argument.
* @return {@link CodeArgument} instance.
*/
public static CodeArgument argument(CodePart value) {
return new CodeArgument(value);
}
/**
* Create an {@link CodeArgument argument}.
*
* @param value Value of argument.
* @param type Type of argument value.
* @return {@link CodeArgument} instance.
*/
public static CodeArgument argument(CodePart value, CodeType type) {
return new CodeArgument(value, type);
}
/**
* Create an {@link CodeArgument argument}.
*
* @param value Value of argument.
* @param type Type of argument value.
* @return {@link CodeArgument} instance.
*/
public static CodeArgument argument(CodePart value, Class<?> type) {
return new CodeArgument(value, Helper.getJavaType(type));
}
// Invoke
/**
* Invoke this constructor.
*
* @param constructorSpec Type specification of constructor.
* @param arguments Constructor Arguments.
* @return Invocation of super constructor of current class.
*/
public static MethodInvocation invokeThisConstructor(TypeSpec constructorSpec, CodeArgument... arguments) {
return invokeThisConstructor__factory(constructorSpec, arguments);
}
/**
* Invoke super constructor of current type declaration.
*
* @param constructorSpec Type specification of constructor.
* @param arguments Constructor Arguments.
* @return Invocation of super constructor of current class.
*/
public static MethodInvocation invokeSuperConstructor(TypeSpec constructorSpec, CodeArgument... arguments) {
return invokeSuperConstructor__factory(null, constructorSpec, arguments);
}
/**
* Invoke super constructor of current type declaration.
*
* @param superClass Super class of current type declaration (if null, CodeAPI will
* determine it automatically).
* @param constructorSpec Type specification of constructor.
* @param arguments Constructor Arguments.
* @return Invocation of super constructor of current type declaration.
*/
public static MethodInvocation invokeSuperConstructor(CodeType superClass, TypeSpec constructorSpec, CodeArgument... arguments) {
return invokeSuperConstructor__factory(superClass, constructorSpec, arguments);
}
/**
* Invoke super constructor of current type declaration.
*
* @param superClass Super class of current type declaration (if null, CodeAPI will
* determine it automatically).
* @param constructorSpec Type specification of constructor.
* @param arguments Constructor Arguments.
* @return Invocation of super constructor of current type declaration.
*/
public static MethodInvocation invokeSuperConstructor(Class<?> superClass, TypeSpec constructorSpec, CodeArgument... arguments) {
return invokeSuperConstructor__factory(Helper.getJavaType(superClass), constructorSpec, arguments);
}
/**
* Invoke constructor of a {@link CodeType}.
*
* @param type Type to invoke constructor.
* @return Invocation of constructor of {@code type}.
*/
public static MethodInvocation invokeConstructor(CodeType type) {
return invokeConstructor__factory(type);
}
/**
* Invoke constructor of a {@link CodeType}.
*
* @param type Type to invoke constructor.
* @param arguments Arguments to pass to constructor.
* @return Invocation of constructor of {@code type} with provided arguments.
*/
public static MethodInvocation invokeConstructor(CodeType type, CodeArgument... arguments) {
return invokeConstructor__factory(type, arguments);
}
/**
* Invoke constructor of a {@link CodeType}.
*
* @param type Type to invoke constructor.
* @param spec Method specification.
* @param arguments Arguments to pass to constructor.
* @return Invocation of constructor of {@code type} with provided arguments.
*/
public static MethodInvocation invokeConstructor(CodeType type, TypeSpec spec, CodeArgument... arguments) {
return invokeConstructor__factory(type, spec, Arrays.asList(arguments));
}
/**
* Invoke constructor of a {@link CodeType}.
*
* @param type Type to invoke constructor.
* @param spec Method specification.
* @param arguments Arguments to pass to constructor.
* @return Invocation of constructor of {@code type} with provided arguments.
*/
public static MethodInvocation invokeConstructor(CodeType type, TypeSpec spec, List<CodeArgument> arguments) {
return invokeConstructor__factory(type, spec, arguments);
}
/**
* Invoke a static method.
*
* @param localization Localization of the method.
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of static method.
*/
public static MethodInvocation invokeStatic(CodeType localization, String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_STATIC, localization, localization,
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a static method in current TypeDeclaration.
*
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of static method.
*/
public static MethodInvocation invokeStatic(String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_STATIC, null, null,
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a instance method.
*
* @param localization Localization of the method.
* @param target Instance.
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of instance method.
*/
public static MethodInvocation invokeVirtual(CodeType localization, CodePart target, String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_VIRTUAL, localization, target,
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a instance method of current type declaration.
*
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of instance method.
*/
public static MethodInvocation invokeVirtual(String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_VIRTUAL, null, CodeAPI.accessThis(),
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a interface method of current type declaration.
*
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of interface method.
*/
public static MethodInvocation invokeInterface(String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_INTERFACE, null, CodeAPI.accessThis(),
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a interface method.
*
* @param localization Localization of the method.
* @param target Instance.
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of interface method.
*/
public static MethodInvocation invokeInterface(CodeType localization, CodePart target, String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_INTERFACE, localization, target,
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a method dynamically.
*
* @param invokeDynamic Invoke dynamic instance.
* @param methodInvocation Method to invoke dynamically.
* @return Dynamic invocation.
*/
public static MethodInvocation invokeDynamic(InvokeDynamic invokeDynamic, MethodInvocation methodInvocation) {
return invokeDynamic__factory(invokeDynamic, methodInvocation);
}
/**
* Invoke a lambda method dynamically.
*
* @param fragment Method to invoke.
* @return Dynamic invocation.
* @see MethodFragment
*/
public static MethodInvocation invokeDynamicFragment(InvokeDynamic.LambdaFragment fragment) {
return invokeDynamic__factory(fragment);
}
// Class
/**
* Invoke constructor of a {@link Class}.
*
* @param type Type to invoke constructor.
* @return Invocation of constructor of {@code type}.
*/
public static MethodInvocation invokeConstructor(Class<?> type) {
return invokeConstructor__factory(Helper.getJavaType(type));
}
/**
* Invoke constructor of a {@link Class}.
*
* @param type Type to invoke constructor.
* @param arguments Arguments to pass to constructor.
* @return Invocation of constructor of {@code type} with provided arguments.
*/
public static MethodInvocation invokeConstructor(Class<?> type, CodeArgument... arguments) {
return invokeConstructor__factory(Helper.getJavaType(type), arguments);
}
/**
* Invoke a static method.
*
* @param localization Localization of the method.
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of static method.
*/
public static MethodInvocation invokeStatic(Class<?> localization, String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_STATIC, Helper.getJavaType(localization), Helper.getJavaType(localization),
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a instance method.
*
* @param localization Localization of the method.
* @param target Instance.
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of instance method.
*/
public static MethodInvocation invokeVirtual(Class<?> localization, CodePart target, String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_VIRTUAL, Helper.getJavaType(localization), target,
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
/**
* Invoke a interface method.
*
* @param localization Localization of the method.
* @param target Instance.
* @param methodName Name of the method.
* @param methodDescription Method type description.
* @param arguments Method arguments.
* @return Invocation of interface method.
*/
public static MethodInvocation invokeInterface(Class<?> localization, CodePart target, String methodName, TypeSpec methodDescription, CodeArgument... arguments) {
return invoke__factory(InvokeType.INVOKE_INTERFACE, Helper.getJavaType(localization), target,
spec__factory(methodName, methodDescription, MethodType.METHOD, arguments));
}
// Factory
private static MethodSpecImpl spec__factory(String methodName, TypeSpec methodDescription, MethodType methodType, CodeArgument... arguments) {
return new MethodSpecImpl(methodName, methodDescription, ArrayToList.toList(arguments), methodType);
}
private static MethodInvocation invoke__factory(InvokeType invokeType, CodeType localization, CodePart target, MethodSpecImpl methodSpecImpl) {
return Helper.invoke(invokeType, localization, target, methodSpecImpl);
}
private static MethodInvocation invokeDynamic__factory(InvokeDynamic invokeDynamic, MethodInvocation methodInvocation) {
return Helper.invokeDynamic(invokeDynamic, methodInvocation);
}
private static MethodInvocation invokeDynamic__factory(InvokeDynamic.LambdaFragment fragment) {
return Helper.invokeDynamicFragment(fragment);
}
private static MethodInvocation invokeConstructor__factory(CodeType type, CodeArgument... arguments) {
return Helper.invokeConstructor(type, arguments);
}
private static MethodInvocation invokeConstructor__factory(CodeType type, TypeSpec spec, List<CodeArgument> arguments) {
return Helper.invokeConstructor(type, spec, arguments);
}
private static MethodInvocation invokeSuperConstructor__factory(CodeType type, TypeSpec constructorSpec, CodeArgument... arguments) {
return Helper.invokeSuperInit(type, constructorSpec, arguments);
}
private static MethodInvocation invokeThisConstructor__factory(TypeSpec constructorSpec, CodeArgument... arguments) {
return Helper.invoke(InvokeType.INVOKE_SPECIAL, (CodeType) null, CodeAPI.accessThis(),
new MethodSpecImpl("<init>", constructorSpec, Arrays.asList(arguments), MethodType.SUPER_CONSTRUCTOR));
}
// Access Variables & Fields
/**
* Access a variable declaration.
*
* @param declaration Declaration.
* @return Access to {@code declaration}.
*/
public static VariableAccess accessDeclaration(VariableDeclaration declaration) {
return accessField__Factory(declaration.getLocalization().orElse(null), declaration.getTarget().orElse(null), declaration.getVariableType(), declaration.getName());
}
/**
* Access a static field of current class.
*
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a static field.
*/
public static VariableAccess accessStaticField(CodeType fieldType, String name) {
return accessField__Factory(null, null, fieldType, name);
}
/**
* Access a static field of {@link CodeType type} {@code localization}.
*
* @param localization Localization of the field.
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a static field.
*/
public static VariableAccess accessStaticField(CodeType localization, CodeType fieldType, String name) {
return accessField__Factory(localization, null, fieldType, name);
}
/**
* Access a field or variable.
*
* @param localization Localization of the field.
* @param at Scope localization or instance of localization.
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a field or variable.
*/
public static VariableAccess accessField(CodeType localization, CodePart at, CodeType fieldType, String name) {
return accessField__Factory(localization, at, fieldType, name);
}
/**
* Access a static field of current class.
*
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a static field of current class.
*/
public static VariableAccess accessThisField(CodeType fieldType, String name) {
return accessField__Factory(null, Helper.accessThis(), fieldType, name);
}
/**
* Access a local variable.
*
* @param variableType Type of the variable value.
* @param name Name of the variable.
* @return Access to variable.
*/
public static VariableAccess accessLocalVariable(CodeType variableType, String name) {
return accessField__Factory(null, Helper.accessLocal(), variableType, name);
}
// Class
/**
* Access a static field of current class.
*
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a static field.
*/
public static VariableAccess accessStaticField(Class<?> fieldType, String name) {
return accessField__Factory(null, null, Helper.getJavaType(fieldType), name);
}
/**
* Access a static field of {@link CodeType type} {@code localization}.
*
* @param localization Localization of the field.
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a static field.
*/
public static VariableAccess accessStaticField(Class<?> localization, Class<?> fieldType, String name) {
return accessField__Factory(Helper.getJavaType(localization), null, Helper.getJavaType(fieldType), name);
}
/**
* Access a field or variable.
*
* @param localization Localization of the field.
* @param at Scope localization or instance of localization.
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a field or variable.
*/
public static VariableAccess accessField(Class<?> localization, CodePart at, Class<?> fieldType, String name) {
return accessField__Factory(Helper.getJavaType(localization), at, Helper.getJavaType(fieldType), name);
}
/**
* Access a static field of current class.
*
* @param fieldType Type of the field.
* @param name Name of the field.
* @return Access to a static field of current class.
*/
public static VariableAccess accessThisField(Class<?> fieldType, String name) {
return accessField__Factory(null, Helper.accessThis(), Helper.getJavaType(fieldType), name);
}
/**
* Access a local variable.
*
* @param variableType Type of the variable value.
* @param name Name of the variable.
* @return Access to variable.
*/
public static VariableAccess accessLocalVariable(Class<?> variableType, String name) {
return accessField__Factory(null, Helper.accessLocal(), Helper.getJavaType(variableType), name);
}
// Factory
private static VariableAccess accessField__Factory(CodeType localization, CodePart at, CodeType type, String name) {
return Helper.accessVariable(localization, at, name, type);
}
// Set Variables & Fields
public static VariableDeclaration setDeclarationValue(VariableDeclaration declaration, CodePart value) {
return setField__Factory(declaration.getLocalization().orElse(null), declaration.getTarget().orElse(null), declaration.getVariableType(), declaration.getName(), value);
}
public static VariableDeclaration setStaticThisField(CodeType fieldType, String name, CodePart value) {
return setField__Factory(null, Helper.accessThis(), fieldType, name, value);
}
public static VariableDeclaration setStaticField(CodeType localization, CodeType fieldType, String name, CodePart value) {
return setField__Factory(localization, null, fieldType, name, value);
}
public static VariableDeclaration setField(CodeType localization, CodePart at, CodeType fieldType, String name, CodePart value) {
return setField__Factory(localization, at, fieldType, name, value);
}
public static VariableDeclaration setThisField(CodeType fieldType, String name, CodePart value) {
return setField__Factory(null, Helper.accessThis(), fieldType, name, value);
}
public static VariableDeclaration setLocalVariable(CodeType variableType, String name, CodePart value) {
return setField__Factory(null, Helper.accessLocal(), variableType, name, value);
}
// Class
public static VariableDeclaration setStaticThisField(Class<?> fieldType, String name, CodePart value) {
return setField__Factory(null, Helper.accessThis(), Helper.getJavaType(fieldType), name, value);
}
public static VariableDeclaration setStaticField(Class<?> localization, Class<?> fieldType, String name, CodePart value) {
return setField__Factory(Helper.getJavaType(localization), null, Helper.getJavaType(fieldType), name, value);
}
public static VariableDeclaration setField(Class<?> localization, CodePart at, Class<?> fieldType, String name, CodePart value) {
return setField__Factory(Helper.getJavaType(localization), at, Helper.getJavaType(fieldType), name, value);
}
public static VariableDeclaration setThisField(Class<?> fieldType, String name, CodePart value) {
return setField__Factory(null, Helper.accessThis(), Helper.getJavaType(fieldType), name, value);
}
public static VariableDeclaration setLocalVariable(Class<?> variableType, String name, CodePart value) {
return setField__Factory(null, Helper.accessLocal(), Helper.getJavaType(variableType), name, value);
}
// Factory
private static VariableDeclaration setField__Factory(CodeType localization, CodePart at, CodeType type, String name, CodePart value) {
return Helper.setVariable(localization, at, name, type, value);
}
// Operate Variables & Fields & Values
public static Operate operate(CodePart part, Operator operation, CodePart value) {
return factory__operate(part, operation, value);
}
public static VariableOperate operateDeclarationValue(VariableDeclaration declaration, Operator operation, CodePart value) {
return operateField__Factory(declaration.getLocalization().orElse(null), declaration.getTarget().orElse(null), declaration.getVariableType(), declaration.getName(), operation, value);
}
public static VariableOperate operateDeclarationValue(VariableDeclaration declaration, Operator operation) {
return operateField__Factory(declaration.getLocalization().orElse(null), declaration.getTarget().orElse(null), declaration.getVariableType(), declaration.getName(), operation, null);
}
public static VariableOperate operateStaticThisField(CodeType fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(null, Helper.accessThis(), fieldType, name, operation, value);
}
public static VariableOperate operateStaticThisField(CodeType fieldType, String name, Operator operation) {
return operateField__Factory(null, Helper.accessThis(), fieldType, name, operation, null);
}
public static VariableOperate operateStaticField(CodeType localization, CodeType fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(localization, null, fieldType, name, operation, value);
}
public static VariableOperate operateStaticField(CodeType localization, CodeType fieldType, String name, Operator operation) {
return operateField__Factory(localization, null, fieldType, name, operation, null);
}
public static VariableOperate operateField(CodeType localization, CodePart at, CodeType fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(localization, at, fieldType, name, operation, value);
}
public static VariableOperate operateField(CodeType localization, CodePart at, CodeType fieldType, String name, Operator operation) {
return operateField__Factory(localization, at, fieldType, name, operation, null);
}
public static VariableOperate operateThisField(CodeType fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(null, Helper.accessThis(), fieldType, name, operation, value);
}
public static VariableOperate operateThisField(CodeType fieldType, String name, Operator operation) {
return operateField__Factory(null, Helper.accessThis(), fieldType, name, operation, null);
}
public static VariableOperate operateLocalVariable(CodeType variableType, String name, Operator operation, CodePart value) {
return operateField__Factory(null, Helper.accessLocal(), variableType, name, operation, value);
}
public static VariableOperate operateLocalVariable(CodeType variableType, String name, Operator operation) {
return operateField__Factory(null, Helper.accessLocal(), variableType, name, operation, null);
}
// Class
public static VariableOperate operateStaticThisField(Class<?> fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(null, Helper.accessThis(), Helper.getJavaType(fieldType), name, operation, value);
}
public static VariableOperate operateStaticThisField(Class<?> fieldType, String name, Operator operation) {
return operateField__Factory(null, Helper.accessThis(), Helper.getJavaType(fieldType), name, operation, null);
}
public static VariableOperate operateStaticField(Class<?> localization, Class<?> fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(Helper.getJavaType(localization), null, Helper.getJavaType(fieldType), name, operation, value);
}
public static VariableOperate operateStaticField(Class<?> localization, Class<?> fieldType, String name, Operator operation) {
return operateField__Factory(Helper.getJavaType(localization), null, Helper.getJavaType(fieldType), name, operation, null);
}
public static VariableOperate operateField(Class<?> localization, CodePart at, Class<?> fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(Helper.getJavaType(localization), at, Helper.getJavaType(fieldType), name, operation, value);
}
public static VariableOperate operateField(Class<?> localization, CodePart at, Class<?> fieldType, String name, Operator operation) {
return operateField__Factory(Helper.getJavaType(localization), at, Helper.getJavaType(fieldType), name, operation, null);
}
public static VariableOperate operateThisField(Class<?> fieldType, String name, Operator operation, CodePart value) {
return operateField__Factory(null, Helper.accessThis(), Helper.getJavaType(fieldType), name, operation, value);
}
public static VariableOperate operateThisField(Class<?> fieldType, String name, Operator operation) {
return operateField__Factory(null, Helper.accessThis(), Helper.getJavaType(fieldType), name, operation, null);
}
public static VariableOperate operateLocalVariable(Class<?> variableType, String name, Operator operation, CodePart value) {
return operateField__Factory(null, Helper.accessLocal(), Helper.getJavaType(variableType), name, operation, value);
}
public static VariableOperate operateLocalVariable(Class<?> variableType, String name, Operator operation) {
return operateField__Factory(null, Helper.accessLocal(), Helper.getJavaType(variableType), name, operation, null);
}
// Factory
private static VariableOperate operateField__Factory(CodeType localization, CodePart at, CodeType type, String name, Operator operation, CodePart value) {
return Helper.operateVariable(localization, at, name, type, operation, value);
}
private static Operate factory__operate(CodePart part, Operator operation, CodePart value) {
return new OperateImpl(part, operation, value);
}
// Throw Exceptions
public static ThrowException throwException(CodePart partToThrow) {
return throwException__Factory(partToThrow);
}
public static ThrowException throwException(CodeType exceptionType, CodeArgument... arguments) {
return throwException__Factory(exceptionType, arguments);
}
//Class
public static ThrowException throwException(Class<?> exceptionType, CodeArgument... arguments) {
return throwException__Factory(toCodeType(exceptionType), arguments);
}
// Factory
private static ThrowException throwException__Factory(CodePart partToThrow) {
return Helper.throwException(partToThrow);
}
private static ThrowException throwException__Factory(CodeType exceptionType, CodeArgument... arguments) {
MethodInvocation invoke = Helper.invoke(InvokeType.INVOKE_SPECIAL, exceptionType, exceptionType, new MethodSpecImpl(null, Arrays.asList(arguments), (CodeType) null, MethodType.CONSTRUCTOR));
return throwException__Factory(invoke);
}
// Annotations
public static Annotation overrideAnnotation() {
return CodeAPI.annotation(PredefinedTypes.OVERRIDE);
}
// CodeType
/**
* Create an annotation that is not visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @return A runtime invisible annotation.
*/
public static Annotation annotation(CodeType annotationType) {
return annotation__Factory(false, annotationType, Collections.emptyMap());
}
/**
* Create an annotation.
*
* @param annotationType Type of annotation
* @param isVisible Is annotation visible at runtime (only affects bytecode generation).
* @return A runtime invisible annotation.
*/
public static Annotation annotation(boolean isVisible, CodeType annotationType) {
return annotation__Factory(isVisible, annotationType, Collections.emptyMap());
}
/**
* Create an annotation that is visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @return A visible annotation
*/
public static Annotation visibleAnnotation(CodeType annotationType) {
return annotation__Factory(true, annotationType, Collections.emptyMap());
}
/**
* Create an annotation that is not visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @param values The Annotation values must be: {@link Byte}, {@link Boolean}, {@link
* Character}, {@link Short}, {@link Integer}, {@link Long}, {@link
* Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return A runtime invisible annotation.
*/
public static Annotation annotation(CodeType annotationType, Map<String, Object> values) {
return annotation__Factory(false, annotationType, values);
}
/**
* Create an annotation that is visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @param values The Annotation values must be: {@link Byte}, {@link Boolean}, {@link
* Character}, {@link Short}, {@link Integer}, {@link Long}, {@link
* Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return A visible annotation
*/
public static Annotation visibleAnnotation(CodeType annotationType, Map<String, Object> values) {
return annotation__Factory(true, annotationType, values);
}
/**
* Create an annotation.
*
* @param annotationType Type of annotation
* @param isVisible Is annotation visible at runtime (only affects bytecode generation).
* @param values The Annotation values must be: {@link Byte}, {@link Boolean}, {@link
* Character}, {@link Short}, {@link Integer}, {@link Long}, {@link
* Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return A runtime invisible annotation.
*/
public static Annotation annotation(boolean isVisible, CodeType annotationType, Map<String, Object> values) {
return annotation__Factory(isVisible, annotationType, values);
}
// Class
/**
* Create an annotation that is not visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @return A runtime invisible annotation.
*/
public static Annotation annotation(Class<?> annotationType) {
return annotation__Factory(false, CodeAPI.toCodeType(annotationType), Collections.emptyMap());
}
/**
* Create an annotation.
*
* @param annotationType Type of annotation
* @param isVisible Is annotation visible at runtime (only affects bytecode generation).
* @return A runtime invisible annotation.
*/
public static Annotation annotation(boolean isVisible, Class<?> annotationType) {
return annotation__Factory(isVisible, CodeAPI.toCodeType(annotationType), Collections.emptyMap());
}
/**
* Create an annotation that is visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @return A visible annotation
*/
public static Annotation visibleAnnotation(Class<?> annotationType) {
return annotation__Factory(true, CodeAPI.toCodeType(annotationType), Collections.emptyMap());
}
/**
* Create an annotation that is not visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @param values The Annotation values must be: {@link Byte}, {@link Boolean}, {@link
* Character}, {@link Short}, {@link Integer}, {@link Long}, {@link
* Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return A runtime invisible annotation.
*/
public static Annotation annotation(Class<?> annotationType, Map<String, Object> values) {
return annotation__Factory(false, CodeAPI.toCodeType(annotationType), values);
}
/**
* Create an annotation that is visible at runtime (only affects bytecode generation).
*
* @param annotationType Type of annotation
* @param values The Annotation values must be: {@link Byte}, {@link Boolean}, {@link
* Character}, {@link Short}, {@link Integer}, {@link Long}, {@link
* Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return A visible annotation
*/
public static Annotation visibleAnnotation(Class<?> annotationType, Map<String, Object> values) {
return annotation__Factory(true, CodeAPI.toCodeType(annotationType), values);
}
/**
* Create an annotation.
*
* @param annotationType Type of annotation
* @param isVisible Is annotation visible at runtime (only affects bytecode generation).
* @param values The Annotation values must be: {@link Byte}, {@link Boolean}, {@link
* Character}, {@link Short}, {@link Integer}, {@link Long}, {@link
* Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return A runtime invisible annotation.
*/
public static Annotation annotation(boolean isVisible, Class<?> annotationType, Map<String, Object> values) {
return annotation__Factory(isVisible, CodeAPI.toCodeType(annotationType), values);
}
// Factory
/**
* Create an Annotation
*
* @param isVisible Is annotation visible at runtime.
* @param annotationType Type of annotation
* @param values The Annotation values must be: {@link Byte}, {@link Boolean}, {@link
* Character}, {@link Short}, {@link Integer}, {@link Long}, {@link
* Float}, {@link Double}, {@link String}, {@link CodeType}, OBJECT,
* ARRAY, {@link EnumValue} or other {@link Annotation}.
* @return Annotation
*/
private static Annotation annotation__Factory(boolean isVisible, CodeType annotationType, Map<String, Object> values) {
return new AnnotationImpl(annotationType, isVisible, values);
}
// Annotations & Case Enum Values
/**
* EnumValue of an Annotation property.
*
* @param enumType Type of enum
* @param entry Enum entry (aka Field)
* @return Enum value
*/
public static EnumValue enumValue(Class<?> enumType, String entry) {
return enumValue__factory(CodeAPI.toCodeType(enumType), entry);
}
/**
* EnumValue of an Annotation property.
*
* @param enumType Type of enum
* @param entry Enum entry (aka Field)
* @return Enum value
*/
public static EnumValue enumValue(CodeType enumType, String entry) {
return enumValue__factory(enumType, entry);
}
/**
* EnumValue in Case check.
*
* @param entry Enum entry (aka Field)
* @return Enum value
*/
public static EnumValue enumValue(String entry) {
return enumValue__factory(null, entry);
}
// Factory
private static EnumValue enumValue__factory(CodeType enumType, String entry) {
return new EnumValueImpl(enumType, entry);
}
// TypeSpec
/**
* Specification of a signature.
*
* @param returnType Return type.
* @return Specification of a signature.
*/
public static TypeSpec typeSpec(CodeType returnType) {
return typeSpec__factory(returnType, new CodeType[]{});
}
/**
* Specification of a signature.
*
* @param returnType Return type.
* @param parameterTypes Parameter types.
* @return Specification of a signature.
*/
public static TypeSpec typeSpec(CodeType returnType, CodeType... parameterTypes) {
return typeSpec__factory(returnType, parameterTypes);
}
/**
* Specification of a constructor signature.
*
* @param parameterTypes Parameter types.
* @return Specification of a signature.
*/
public static TypeSpec constructorTypeSpec(CodeType... parameterTypes) {
return typeSpec__factory(PredefinedTypes.VOID, parameterTypes);
}
// Class
/**
* Specification of a signature.
*
* @param returnType Return type.
* @return Specification of a signature.
*/
public static TypeSpec typeSpec(Class<?> returnType) {
return typeSpec__factory(toCodeType(returnType), new CodeType[]{});
}
/**
* Specification of a signature.
*
* @param returnType Return type.
* @param parameterTypes Parameter types.
* @return Specification of a signature.
*/
public static TypeSpec typeSpec(Class<?> returnType, Class<?>... parameterTypes) {
return typeSpec__factory(toCodeType(returnType), toCodeType(parameterTypes));
}
/**
* Specification of a constructor signature.
*
* @param parameterTypes Parameter types.
* @return Specification of a signature.
*/
public static TypeSpec constructorTypeSpec(Class<?>... parameterTypes) {
return typeSpec__factory(PredefinedTypes.VOID, toCodeType(parameterTypes));
}
// Factory
private static TypeSpec typeSpec__factory(CodeType returnType, CodeType[] parameterTypes) {
return new TypeSpec(returnType, parameterTypes);
}
// Cast
/**
* Cast an element from a type to another type.
*
* @param fromType From type.
* @param toType Target type to cast.
* @param partToCast Part to cast.
* @return Cast of element.
*/
public static Casted cast(CodeType fromType, CodeType toType, CodePart partToCast) {
return cast__Factory(fromType, toType, partToCast);
}
// Class
/**
* Cast an element from a type to another type.
*
* @param fromType From type.
* @param toType Target type to cast.
* @param partToCast Part to cast.
* @return Cast of element.
*/
public static Casted cast(Class<?> fromType, Class<?> toType, CodePart partToCast) {
return cast__Factory(toCodeType(fromType), toCodeType(toType), partToCast);
}
// Factory
private static Casted cast__Factory(CodeType fromType, CodeType toType, CodePart partToCast) {
return Helper.cast(fromType, toType, partToCast);
}
// If block
/**
* Create a if statement.
*
* @param groups Expressions.
* @param body Body of the if.
* @param elseBlock Else block of the if.
* @return If statement.
*/
public static IfBlock ifBlock(BiMultiVal<CodePart, IfExpr, Operator> groups, CodeSource body, ElseBlock elseBlock) {
return ifBlock__Factory(groups, body, elseBlock);
}
/**
* Create a if statement.
*
* @param groups Expressions.
* @param body Body of the if.
* @return If statement.
*/
public static IfBlock ifBlock(BiMultiVal<CodePart, IfExpr, Operator> groups, CodeSource body) {
return ifBlock__Factory(groups, body, null);
}
/**
* Create a if statement.
*
* @param ifExpr Expression.
* @param body Body of the if.
* @param elseBlock Else block of the if.
* @return If statement.
*/
public static IfBlock ifBlock(IfExpr ifExpr, CodeSource body, ElseBlock elseBlock) {
return ifBlock__Factory(CodeAPI.ifExprs(ifExpr), body, elseBlock);
}
/**
* Create a if statement.
*
* @param ifExpr Expression.
* @param body Body of the if.
* @return If statement.
*/
public static IfBlock ifBlock(IfExpr ifExpr, CodeSource body) {
return ifBlock__Factory(CodeAPI.ifExprs(ifExpr), body, null);
}
// Factory
private static IfBlock ifBlock__Factory(BiMultiVal<CodePart, IfExpr, Operator> groups, CodeSource body, ElseBlock elseBlock) {
return Helper.ifExpression(groups, body, elseBlock);
}
// If Checks
/**
* Check if a part is not null.
*
* @param part Part to check.
* @return The verification part.
*/
public static IfExpr checkNotNull(CodePart part) {
return Helper.checkNotNull(part);
}
/**
* Check if a part is null.
*
* @param part Part to check.
* @return The verification part.
*/
public static IfExpr checkNull(CodePart part) {
return Helper.checkNull(part);
}
/**
* Check if a expression is true.
*
* @param part Part to check.
* @return The verification part.
*/
public static IfExpr checkTrue(CodePart part) {
return Helper.check(part, Operators.EQUAL_TO, Literals.BOOLEAN(true));
}
/**
* Check if a expression is false.
*
* @param part Part to check.
* @return The verification part.
*/
public static IfExpr checkFalse(CodePart part) {
return Helper.check(part, Operators.EQUAL_TO, Literals.BOOLEAN(false));
}
/**
* Create a check condition.
*
* @param part1 Part 1.
* @param operator Operation to do over two values.
* @param part2 Part2.
* @return The verification part.
*/
public static IfExpr check(CodePart part1, Operator operator, CodePart part2) {
return Helper.check(part1, operator, part2);
}
// Else block
/**
* Else statement.
*
* @param body Body of else statement.
* @return Else statement.
*/
public static ElseBlock elseBlock(CodeSource body) {
return elseBlock__Factory(body);
}
/**
* Else statement.
*
* @param parts {@link CodePart}s in the body of else statement.
* @return Else statement.
*/
public static ElseBlock elseBlock(CodePart... parts) {
return elseBlock__Factory(sourceOfParts(parts));
}
// Factory
private static ElseBlock elseBlock__Factory(CodeSource body) {
return Helper.elseExpression(body);
}
// Break and Continue
public static Break aBreak() {
return CodeAPI.break__Factory();
}
public static Continue aContinue() {
return CodeAPI.continue__Factory();
}
// Factory
private static Break break__Factory() {
return new BreakImpl();
}
private static Continue continue__Factory() {
return new ContinueImpl();
}
// Instance Of
/**
* Check if {@link CodePart part} is instance of {@link CodeType type}.
*
* @param part Part.
* @param type Type.
* @return The verification part.
*/
public static InstanceOf isInstanceOf(CodePart part, CodeType type) {
return isInstanceOf__Factory(part, type);
}
// Class
/**
* Check if {@link CodePart part} is instance of {@link Class type}.
*
* @param part Part.
* @param type Type.
* @return The verification part.
*/
public static InstanceOf isInstanceOf(CodePart part, Class<?> type) {
return isInstanceOf__Factory(part, toCodeType(type));
}
// Factory
private static InstanceOf isInstanceOf__Factory(CodePart part, CodeType type) {
return Helper.isInstanceOf(part, type);
}
// Try block
/**
* Create a try-catch-finally statement.
*
* @param toSurround Code to surround.
* @param catchBlocks Catch blocks.
* @param finallySource Finally statement.
* @return Try-Catch-Finally statement.
*/
public static TryBlock tryBlock(CodeSource toSurround, List<CatchBlock> catchBlocks, CodeSource finallySource) {
return tryBlock__Factory(toSurround, catchBlocks, finallySource);
}
/**
* Create a try-catch-finally statement.
*
* @param toSurround Code to surround.
* @param catchBlock Catch block.
* @param finallySource Finally statement.
* @return Try-Catch-Finally statement.
*/
public static TryBlock tryBlock(CodeSource toSurround, CatchBlock catchBlock, CodeSource finallySource) {
return tryBlock__Factory(toSurround, Collections.singletonList(catchBlock), finallySource);
}
/**
* Create a try-catch statement.
*
* @param toSurround Code to surround.
* @param catchBlocks Catch blocks.
* @return Try-Catch statement.
*/
public static TryBlock tryBlock(CodeSource toSurround, List<CatchBlock> catchBlocks) {
return tryBlock__Factory(toSurround, catchBlocks, null);
}
/**
* Create a try-catch statement.
*
* @param toSurround Code to surround.
* @param catchBlock Catch block.
* @return Try-Catch statement.
*/
public static TryBlock tryBlock(CodeSource toSurround, CatchBlock catchBlock) {
return tryBlock__Factory(toSurround, Collections.singletonList(catchBlock), null);
}
// Factory
private static TryBlock tryBlock__Factory(CodeSource toSurround, List<CatchBlock> catchBlocks, CodeSource finallySource) {
return Helper.surround(toSurround, catchBlocks, finallySource);
}
// Try With resources block
/**
* Create a try-with-resources block.
*
* @param variable Resource variable
* @param toSurround Code to surround.
* @param catchBlocks Catch blocks.
* @param finallySource Finally statement.
* @return Try-with-resources block.
*/
public static TryBlock tryWithResources(VariableDeclaration variable, CodeSource toSurround, List<CatchBlock> catchBlocks, CodeSource finallySource) {
return tryWithResources__Factory(variable, toSurround, catchBlocks, finallySource);
}
/**
* Create a try-with-resources block.
*
* @param variable Resource variable
* @param toSurround Code to surround.
* @param catchBlock Catch block.
* @param finallySource Finally statement.
* @return Try-with-resources block.
*/
public static TryBlock tryWithResources(VariableDeclaration variable, CodeSource toSurround, CatchBlock catchBlock, CodeSource finallySource) {
return tryWithResources__Factory(variable, toSurround, Collections.singletonList(catchBlock), finallySource);
}
/**
* Create a try-with-resources block.
*
* @param variable Resource variable
* @param toSurround Code to surround.
* @param finallySource Finally statement.
* @return Try-with-resources block.
*/
public static TryBlock tryWithResources(VariableDeclaration variable, CodeSource toSurround, CodeSource finallySource) {
return tryWithResources__Factory(variable, toSurround, Collections.emptyList(), finallySource);
}
* /**
* Create a try-with-resources block.
*
* @param variable Resource variable
* @param toSurround Code to surround.
* @param catchBlocks Catch blocks.
* @return Try-with-resources block.
*/
public static TryBlock tryWithResources(VariableDeclaration variable, CodeSource toSurround, List<CatchBlock> catchBlocks) {
return tryWithResources__Factory(variable, toSurround, catchBlocks, null);
}
* /**
* Create a try-with-resources block.
*
* @param variable Resource variable
* @param toSurround Code to surround.
* @param catchBlock Catch block.
* @return Try-with-resources block.
*/
public static TryBlock tryWithResources(VariableDeclaration variable, CodeSource toSurround, CatchBlock catchBlock) {
return tryWithResources__Factory(variable, toSurround, Collections.singletonList(catchBlock), null);
}
/**
* Create a try-with-resources block.
*
* @param variable Resource variable
* @param toSurround Code to surround.
* @return Try-with-resources block.
*/
public static TryBlock tryWithResources(VariableDeclaration variable, CodeSource toSurround) {
return tryWithResources__Factory(variable, toSurround, Collections.emptyList(), null);
}
// Factory
private static TryWithResources tryWithResources__Factory(VariableDeclaration variable, CodeSource toSurround, List<CatchBlock> catchBlocks, CodeSource finallySource) {
return Helper.tryWithResources(variable, toSurround, catchBlocks, finallySource);
}
// WhileBlock
public static WhileBlock whileBlock(BiMultiVal<CodePart, IfExpr, Operator> parts, CodeSource source) {
return whileBlock__Factory(parts, source);
}
// Factory
private static WhileBlock whileBlock__Factory(BiMultiVal<CodePart, IfExpr, Operator> parts, CodeSource source) {
return Helper.createWhile(parts, source);
}
// DoWhileBlock
/**
* Create a do-while statement.
*
* @param parts Expression.
* @param source Source.
* @return Do-while statement.
*/
public static DoWhileBlock doWhileBlock(BiMultiVal<CodePart, IfExpr, Operator> parts, CodeSource source) {
return doWhileBlock__Factory(source, parts);
}
// Factory
private static DoWhileBlock doWhileBlock__Factory(CodeSource source, BiMultiVal<CodePart, IfExpr, Operator> parts) {
return Helper.createDoWhile(source, parts);
}
// ForBlock
/**
* Create a for statement.
*
* @param initialization For initialization.
* @param condition Condition.
* @param update For Update
* @param body For body.
* @return For statement.
*/
public static ForBlock forBlock(CodePart initialization, BiMultiVal<CodePart, IfExpr, Operator> condition, CodePart update, CodeSource body) {
return forBlock__Factory(initialization, condition, update, body);
}
// Factory
private static ForBlock forBlock__Factory(CodePart initialization, BiMultiVal<CodePart, IfExpr, Operator> condition, CodePart update, CodeSource body) {
return Helper.createFor(initialization, condition, update, body);
}
// ForeachBlock
/**
* Create a ForEach statement.
*
* <pre>{@code
* forEachBlock(field IterationType expression) body
* }</pre>
*
* @param field Field to store values.
* @param iterationType Iteration type (constants: {@link IterationTypes}).
* @param expression Expression.
* @param body For each block.
* @return ForEach statement.
*/
public static ForEachBlock forEachBlock(FieldDeclaration field, IterationType iterationType, CodePart expression, CodeSource body) {
return forEachBlock__Factory(field, iterationType, expression, body);
}
/**
* ForEach statement iterating an array.
*
* <pre>{@code
* forEachBlock(field : expression) body
* }</pre>
*
* @param field Field to store values.
* @param expression Expression (the array).
* @param body ForEach body.
* @return ForEach statement iterating an array.
*/
public static ForEachBlock forEachArray(FieldDeclaration field, CodePart expression, CodeSource body) {
return forEachBlock__Factory(field, IterationTypes.ARRAY, expression, body);
}
/**
* ForEach statement iterating an iterable element.
*
* <pre>{@code
* forEachBlock(field : expression) body
* }</pre>
*
* @param field Field to store values.
* @param expression Expression (the iterable object).
* @param body ForEach body.
* @return ForEach statement iterating an iterable element.
*/
public static ForEachBlock forEachIterable(FieldDeclaration field, CodePart expression, CodeSource body) {
return forEachBlock__Factory(field, IterationTypes.ITERABLE_ELEMENT, expression, body);
}
// Factory
private static ForEachBlock forEachBlock__Factory(FieldDeclaration field, IterationType iterationType, CodePart expression, CodeSource body) {
return Helper.createForEach(field, iterationType, expression, body);
}
// Method Spec
/**
* Specification of a method.
*
* @param location Localization of method.
* @param returnType Return type of the method.
* @param methodName Name of the method.
* @param parameterTypes Parameter types of the method.
* @return Specification of a method.
*/
public static FullMethodSpec fullMethodSpec(CodeType location, CodeType returnType, String methodName, CodeType... parameterTypes) {
return fullMethodSpec__factory(location, returnType, methodName, parameterTypes);
}
/**
* Specification of a method.
*
* @param location Localization of method.
* @param returnType Return type of the method.
* @param methodName Name of the method.
* @param parameterTypes Parameter types of the method.
* @return Specification of a method.
*/
public static FullMethodSpec fullMethodSpec(Class<?> location, Class<?> returnType, String methodName, Class<?>... parameterTypes) {
return fullMethodSpec__factory(toCodeType(location), toCodeType(returnType), methodName, toCodeType(parameterTypes));
}
// Factory
private static FullMethodSpec fullMethodSpec__factory(CodeType location, CodeType returnType, String methodName, CodeType... parameterTypes) {
return new FullMethodSpec(location, returnType, methodName, parameterTypes);
}
// Invoke Spec
/**
* Specification of a method to invoke.
*
* @param invokeType Invocation type.
* @param location Localization of method.
* @param returnType Return type of the method.
* @param methodName Name of the method.
* @param parameterTypes Parameter types of the method.
* @return Specification of a method.
*/
public static FullInvokeSpec fullInvokeSpec(InvokeType invokeType, CodeType location, CodeType returnType, String methodName, CodeType... parameterTypes) {
return fullInvokeSpec__factory(invokeType, location, returnType, methodName, parameterTypes);
}
/**
* Specification of a method to invoke.
*
* @param invokeType Invocation type.
* @param location Localization of method.
* @param returnType Return type of the method.
* @param methodName Name of the method.
* @param parameterTypes Parameter types of the method.
* @return Specification of a method.
*/
public static FullInvokeSpec fullInvokeSpec(InvokeType invokeType, Class<?> location, Class<?> returnType, String methodName, Class<?>... parameterTypes) {
return fullInvokeSpec__factory(invokeType, toCodeType(location), toCodeType(returnType), methodName, toCodeType(parameterTypes));
}
// Factory
private static FullInvokeSpec fullInvokeSpec__factory(InvokeType invokeType, CodeType location, CodeType returnType, String methodName, CodeType... parameterTypes) {
return new FullInvokeSpec(invokeType, location, returnType, methodName, parameterTypes);
}
// Method fragment
/**
* Create a method fragment.
*
* @param codeInterface Code class to insert method.
* @param scope Scope of fragment.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param body Body of method.
* @return Method fragment.
*/
public static MethodFragment fragment(CodeInterface codeInterface, Scope scope, CodeType returnType, CodeParameter[] parameters, CodeArgument[] arguments, CodeSource body) {
return fragment__factory(codeInterface, scope, returnType, parameters, arguments, body);
}
/**
* Create a method fragment.
*
* @param codeInterface Code class to insert method.
* @param scope Scope of fragment.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param source Function that provide the method body.
* @return Method fragment.
*/
public static MethodFragment fragment(CodeInterface codeInterface, Scope scope, CodeType returnType, CodeParameter[] parameters, CodeArgument[] arguments, Function<MethodFragment, CodeSource> source) {
MethodFragment methodFragment = fragment__factory(codeInterface, scope, returnType, parameters, arguments, new CodeSource());
if (source != null)
return methodFragment.setMethod(methodFragment.getMethod().setBody(source.apply(methodFragment)));
return methodFragment;
}
/**
* Create a static method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param body Body of method.
* @return Method fragment.
*/
public static MethodFragment fragmentStatic(CodeInterface codeInterface, CodeType returnType, CodeParameter[] parameters, CodeArgument[] arguments, CodeSource body) {
return fragment__factory(codeInterface, Scope.STATIC, returnType, parameters, arguments, body);
}
/**
* Create a static method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param source Function that provide the method body.
* @return Method fragment.
*/
public static MethodFragment fragmentStatic(CodeInterface codeInterface, CodeType returnType, CodeParameter[] parameters, CodeArgument[] arguments, Function<MethodFragment, CodeSource> source) {
MethodFragment methodFragment = fragment__factory(codeInterface, Scope.STATIC, returnType, parameters, arguments, new CodeSource());
if (source != null)
return methodFragment.setMethod(methodFragment.getMethod().setBody(source.apply(methodFragment)));
return methodFragment;
}
/**
* Create a instance method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param body Body of method.
* @return Method fragment.
*/
public static MethodFragment fragmentInstance(CodeInterface codeInterface, CodeType returnType, CodeParameter[] parameters, CodeArgument[] arguments, CodeSource body) {
return fragment__factory(codeInterface, Scope.INSTANCE, returnType, parameters, arguments, body);
}
/**
* Create a instance method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param source Function that provide the method body.
* @return Method fragment.
*/
public static MethodFragment fragmentInstance(CodeInterface codeInterface, CodeType returnType, CodeParameter[] parameters, CodeArgument[] arguments, Function<MethodFragment, CodeSource> source) {
MethodFragment methodFragment = fragment__factory(codeInterface, Scope.INSTANCE, returnType, parameters, arguments, new CodeSource());
if (source != null)
return methodFragment.setMethod(methodFragment.getMethod().setBody(source.apply(methodFragment)));
return methodFragment;
}
// Class
/**
* Create a method fragment.
*
* @param codeInterface Code class to insert method.
* @param scope Scope of fragment.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param body Body of method.
* @return Method fragment.
*/
public static MethodFragment fragment(CodeInterface codeInterface, Scope scope, Class<?> returnType, CodeParameter[] parameters, CodeArgument[] arguments, CodeSource body) {
return fragment__factory(codeInterface, scope, toCodeType(returnType), parameters, arguments, body);
}
/**
* Create a method fragment.
*
* @param codeInterface Code class to insert method.
* @param scope Scope of fragment.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param source Function that provide the method body.
* @return Method fragment.
*/
public static MethodFragment fragment(CodeInterface codeInterface, Scope scope, Class<?> returnType, CodeParameter[] parameters, CodeArgument[] arguments, Function<MethodFragment, CodeSource> source) {
MethodFragment methodFragment = fragment__factory(codeInterface, scope, toCodeType(returnType), parameters, arguments, new CodeSource());
if (source != null)
return methodFragment.setMethod(methodFragment.getMethod().setBody(source.apply(methodFragment)));
return methodFragment;
}
/**
* Create a static method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param body Body of method.
* @return Method fragment.
*/
public static MethodFragment fragmentStatic(CodeInterface codeInterface, Class<?> returnType, CodeParameter[] parameters, CodeArgument[] arguments, CodeSource body) {
return fragment__factory(codeInterface, Scope.STATIC, toCodeType(returnType), parameters, arguments, body);
}
/**
* Create a static method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param source Function that provide the method body.
* @return Method fragment.
*/
public static MethodFragment fragmentStatic(CodeInterface codeInterface, Class<?> returnType, CodeParameter[] parameters, CodeArgument[] arguments, Function<MethodFragment, CodeSource> source) {
MethodFragment methodFragment = fragment__factory(codeInterface, Scope.STATIC, toCodeType(returnType), parameters, arguments, new CodeSource());
if (source != null)
return methodFragment.setMethod(methodFragment.getMethod().setBody(source.apply(methodFragment)));
return methodFragment;
}
/**
* Create a instance method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param body Body of method.
* @return Method fragment.
*/
public static MethodFragment fragmentInstance(CodeInterface codeInterface, Class<?> returnType, CodeParameter[] parameters, CodeArgument[] arguments, CodeSource body) {
return fragment__factory(codeInterface, Scope.INSTANCE, toCodeType(returnType), parameters, arguments, body);
}
/**
* Create a instance method fragment.
*
* @param codeInterface Code class to insert method.
* @param returnType Return type of method.
* @param parameters Parameters of the method.
* @param arguments Arguments to pass to method.
* @param source Function that provide the method body.
* @return Method fragment.
*/
public static MethodFragment fragmentInstance(CodeInterface codeInterface, Class<?> returnType, CodeParameter[] parameters, CodeArgument[] arguments, Function<MethodFragment, CodeSource> source) {
MethodFragment methodFragment = fragment__factory(codeInterface, Scope.INSTANCE, toCodeType(returnType), parameters, arguments, new CodeSource());
if (source != null)
return methodFragment.setMethod(methodFragment.getMethod().setBody(source.apply(methodFragment)));
return methodFragment;
}
// Factory
private static MethodFragment fragment__factory(CodeInterface codeInterface, Scope scope, CodeType returnType, CodeParameter[] parameters, CodeArgument[] arguments, CodeSource body) {
return Helper.methodFragment(codeInterface, scope, returnType, parameters, arguments, body);
}
// Switch & Case
public static Switch switchInt(Typed value, Case... cases) {
return switch__factory(SwitchTypes.NUMERIC, value, ArrayToList.toList(cases));
}
public static Switch switchString(Typed value, Case... cases) {
return switch__factory(SwitchTypes.STRING, value, ArrayToList.toList(cases));
}
public static Switch switchEnum(Typed value, Case... cases) {
return switch__factory(SwitchTypes.ENUM, value, ArrayToList.toList(cases));
}
public static Switch switchObject(Typed value, Case... cases) {
return switch__factory(SwitchTypes.OBJECT, value, ArrayToList.toList(cases));
}
public static Switch switchDefined(SwitchType switchType, Typed value, Case... cases) {
return switch__factory(switchType, value, ArrayToList.toList(cases));
}
// Case
public static Case aCase(Typed value, CodeSource body) {
return case__factory(value, body);
}
public static Case caseDefault(CodeSource body) {
return case__factory(null, body);
}
// Factory
private static Switch switch__factory(SwitchType switchType, Typed value, List<Case> caseList) {
return Helper.aSwitch(switchType, value, caseList);
}
private static Case case__factory(Typed value, CodeSource body) {
return Helper.aCase(value, body);
}
// Utils
/**
* Access this {@link com.github.jonathanxd.codeapi.interfaces.TypeDeclaration}.
*
* Equivalent to Java {@code this}.
*
* @return Access this {@link com.github.jonathanxd.codeapi.interfaces.TypeDeclaration}.
*/
public static AccessThis accessThis() {
return Helper.accessThis();
}
/**
* Access super type of current {@link com.github.jonathanxd.codeapi.interfaces.TypeDeclaration}.
*
* Equivalent to Java {@code super}.
*
* @return Access super type of current {@link com.github.jonathanxd.codeapi.interfaces.TypeDeclaration}.
*/
public static AccessSuper accessSuper() {
return Helper.accessSuper();
}
/**
* Access enclosing class of current {@link com.github.jonathanxd.codeapi.interfaces.TypeDeclaration}.
*
* Equivalent to Java {@code CLASS.this}.
*
* @param localization Localization of outer class.
* @return Access enclosing class of current {@link com.github.jonathanxd.codeapi.interfaces.TypeDeclaration}.
*/
public static AccessOuter accessOuter(CodeType localization) {
return Helper.accessOuter(localization);
}
/**
* Plain code type.
*
* @param name Name of the type.
* @param isInterface Is the type an interface.
* @return {@link PlainCodeType Plain Code Type} representation.
*/
public static PlainCodeType plainType(String name, boolean isInterface) {
return new PlainCodeType(name, isInterface);
}
/**
* Plain interface code type.
*
* @param name Name of the type.
* @return {@link PlainCodeType Plain Code Type} representation.
*/
public static PlainCodeType plainInterfaceType(String name) {
return new PlainCodeType(name, true);
}
/**
* Plain class code type.
*
* @param name Name of the type.
* @return {@link PlainCodeType Plain Code Type} representation.
*/
public static PlainCodeType plainClassType(String name) {
return new PlainCodeType(name, false);
}
/**
* Convert Java {@link Class class} to CodeAPI {@link CodeType type}.
*
* @param aClass Class to convert.
* @return Converted type.
*/
private static CodeType toCodeType(Class<?> aClass) {
return Helper.getJavaType(aClass);
}
/**
* Convert Java {@link Class classes} to CodeAPI {@link CodeType types}.
*
* @param aClass Classes to convert.
* @return Converted types.
*/
private static CodeType[] toCodeType(Class<?>[] aClass) {
return Arrays.stream(aClass).map(Helper::getJavaType).toArray(CodeType[]::new);
}
/**
* Helper method to create if expressions.
*
* @param objects {@link IfExpr}s and {@link Operator}s.
* @return If multi values.
*/
public static BiMultiVal<CodePart, IfExpr, Operator> ifExprs(Object... objects) {
BiMultiVal.Adder<CodePart, IfExpr, Operator> adder = CodeAPI.ifExprs();
for (Object object : objects) {
if (object instanceof IfExpr) {
adder.add1((IfExpr) object);
} else if (object instanceof Operator) {
adder.add2((Operator) object);
} else {
throw new IllegalArgumentException("Illegal input object: '" + object + "'.");
}
}
return adder.make();
}
/**
* Helper method to create if expressions.
*
* @return If multi values adder.
*/
public static BiMultiVal.Adder<CodePart, IfExpr, Operator> ifExprs() {
return BiMultiVal.create(CodePart.class, IfExpr.class, Operator.class);
}
public static Annotation[] annotations(Annotation... annotations) {
return annotations;
}
public static CodeArgument[] arguments(CodeArgument... arguments) {
return arguments;
}
public static CodeParameter[] parameters(CodeParameter... parameters) {
return parameters;
}
public static CodeType[] types(CodeType... types) {
return types;
}
public static Class<?>[] types(Class<?>... types) {
return types;
}
public static ConcatHelper concatHelper() {
return ConcatHelper.builder();
}
public static ConcatHelper concatHelper(CodePart part) {
return ConcatHelper.builder(part);
}
public static ConcatHelper concatHelper(String str) {
return ConcatHelper.builder(str);
}
public static ConcatHelper concatHelper(CodePart... part) {
if(part.length == 0)
return ConcatHelper.builder();
ConcatHelper helper = ConcatHelper.builder(part[0]);
for (int i = 1; i < part.length; i++) {
helper = helper.concat(part[i]);
}
return helper;
}
public static ConcatHelper concatHelper(String... strs) {
if(strs.length == 0)
return ConcatHelper.builder();
ConcatHelper helper = ConcatHelper.builder(strs[0]);
for (int i = 1; i < strs.length; i++) {
helper = helper.concat(strs[i]);
}
return helper;
}
public static ConcatHelper concatHelperObj(Object... objs) {
if(objs.length == 0)
return ConcatHelper.builder();
ConcatHelper helper;
Object at0 = objs[0];
if(at0 instanceof CodePart) {
helper = ConcatHelper.builder((CodePart) at0);
} else if(at0 instanceof String) {
helper = ConcatHelper.builder((String) at0);
} else {
throw new IllegalArgumentException("Invalid element type at index 0 ("+at0+") in array: '"+Arrays.toString(objs)+"'! Acceptable types: String|CodePart");
}
for (int i = 1; i < objs.length; i++) {
Object atI = objs[i];
if(at0 instanceof CodePart) {
helper = helper.concat((CodePart) atI);
} else if(at0 instanceof String) {
helper = helper.concat((String) atI);
} else {
throw new IllegalArgumentException("Invalid element type at index "+i+" ("+atI+") in array: '"+Arrays.toString(objs)+"'! Acceptable types: String|CodePart");
}
}
return helper;
}
public static OperateHelper operateHelper(CodePart part) {
return OperateHelper.builder(part);
}
/**
* Helper method to create maps.
*
* @param objects Objects (Key and values).
* @return Map of keys and values.
*/
public static Map<String, Object> values(Object... objects) {
Map<String, Object> map = new HashMap<>();
if (objects.length % 2 != 0) {
throw new IllegalArgumentException("Input must be odd (Pair of String and Object)");
}
for (int i = 0; i < objects.length; i += 2) {
map.put((String) objects[i], objects[i + 1]);
}
return map;
}
/**
* Generator Specific features
*
* Not supported by Java Source Code generation. ({@link PlainSourceGenerator}).
*/
public static class Specific {
// Invoke Dynamic
/**
* Invoke dynamic method.
*
* @param invokeDynamic Dynamic invocation specification.
* @param methodInvocation Method to invoke dynamically.
* @return Dynamic invocation.
*/
public static MethodInvocation invokeDynamic(InvokeDynamic invokeDynamic, MethodInvocation methodInvocation) {
return Specific.invokeDynamic__factory(invokeDynamic, methodInvocation);
}
/**
* Invoke a {@link com.github.jonathanxd.codeapi.common.InvokeDynamic.LambdaFragment}
* dynamically.
*
* @param fragment Lambda Fragment.
* @return Invocation of lambda fragment.
*/
public static MethodInvocation invokeDynamicFragment(InvokeDynamic.LambdaFragment fragment) {
return Specific.invokeDynamic__factory(fragment);
}
// Factory
private static MethodInvocation invokeDynamic__factory(InvokeDynamic invokeDynamic, MethodInvocation methodInvocation) {
return Helper.invokeDynamic(invokeDynamic, methodInvocation);
}
private static MethodInvocation invokeDynamic__factory(InvokeDynamic.LambdaFragment fragment) {
return Helper.invokeDynamicFragment(fragment);
}
private static MethodInvocation invokeConstructor__factory(CodeType type, CodeArgument... arguments) {
return Helper.invokeConstructor(type, arguments);
}
// Utils
/**
* Invoke Bootstrap methods with bsm parameters
*
* @param invokeType Invocation Type.
* @param fullMethodSpec Bootstrap method.
* @param args BSM Arguments, must be an {@link String}, {@link Integer}, {@link
* Long}, {@link Float}, {@link Double}, {@link CodeType}, or {@link
* FullInvokeSpec}.
* @return Bootstrap specification.
*/
public static InvokeDynamic.Bootstrap bootstrap(InvokeType invokeType, FullMethodSpec fullMethodSpec, Object... args) {
return InvokeDynamic.invokeDynamicBootstrap(invokeType, fullMethodSpec, args);
}
/**
* Invoke a Bootstrap method.
*
* @param invokeType Invocation Type.
* @param fullMethodSpec Bootstrap method.
* @return Bootstrap specification.
*/
public static InvokeDynamic.Bootstrap bootstrap(InvokeType invokeType, FullMethodSpec fullMethodSpec) {
return InvokeDynamic.invokeDynamicBootstrap(invokeType, fullMethodSpec);
}
/**
* Invoke a lambda method reference.
*
* @param fullMethodSpec Method specification ({@link InvokeDynamic}).
* @param expectedTypes Expected types.
* @return Lambda Method Reference specification.
* @see InvokeDynamic
*/
public static InvokeDynamic.LambdaMethodReference lambda(FullMethodSpec fullMethodSpec, TypeSpec expectedTypes) {
return InvokeDynamic.invokeDynamicLambda(fullMethodSpec, expectedTypes);
}
/**
* Invoke a lambda code.
*
* @param fullMethodSpec Method specification ({@link InvokeDynamic}).
* @param expectedTypes Expected types.
* @param methodFragment Fragment to invoke.
* @return Lambda Method Reference specification.
* @see InvokeDynamic
*/
public static InvokeDynamic.LambdaMethodReference code(FullMethodSpec fullMethodSpec, TypeSpec expectedTypes, MethodFragment methodFragment) {
return InvokeDynamic.invokeDynamicLambdaFragment(fullMethodSpec, expectedTypes, methodFragment);
}
}
}
|
package org.spongepowered.api.entity;
import com.flowpowered.math.vector.Vector3d;
import com.google.common.base.Optional;
import org.spongepowered.api.service.persistence.data.DataHolder;
import org.spongepowered.api.util.Identifiable;
import org.spongepowered.api.util.RelativePositions;
import org.spongepowered.api.world.Location;
import org.spongepowered.api.world.World;
import java.util.EnumSet;
import javax.annotation.Nullable;
/**
* An entity is a Minecraft entity.
*
* <p>Examples of entities include:</p>
*
* <ul>
* <li>Zombies</li>
* <li>Sheep</li>
* <li>Players</li>
* <li>Dropped items</li>
* <li>Dropped experience points</li>
* <li>etc.</li>
* </ul>
*
* <p>Blocks and items (when they are in inventories) are not entities.</p>
*/
public interface Entity extends Identifiable, EntityState, DataHolder {
/**
* Gets the current world this entity resides in.
*
* @return The current world this entity resides in
*/
World getWorld();
/**
* Get the location of this entity.
*
* @return The location
*/
Location getLocation();
/**
* Sets the location of this entity. This is equivalent to a teleport,
* and also moves this entity's passengers.
*
* @param location The location to set
* @return True if the teleport was successful
*/
boolean setLocation(Location location);
/**
* Moves the entity to the specified location, and sets the rotation.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> yaw</code>, <code>y -> pitch</code>, <code>z -> roll
* </code></ul>
*
* @param location The location to set
* @param rotation The rotation to set
* @return True if the teleport was successful
*/
boolean setLocationAndRotation(Location location, Vector3d rotation);
/**
* Moves the entity to the specified location, and sets the rotation. {@link RelativePositions}
* listed inside the EnumSet are considered relative.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> yaw</code>, <code>y -> pitch</code>, <code>z -> roll
* </code></ul>
*
* @param location The location to set
* @param rotation The rotation to set
* @param relativePositions The coordinates to set relatively
* @return True if the teleport was successful
*/
boolean setLocationAndRotation(Location location, Vector3d rotation, EnumSet<RelativePositions> relativePositions);
/**
* Gets the rotation as a Vector3f.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> yaw</code>, <code>y -> pitch</code>, <code>z -> roll
* </code></ul>
*
* @return The rotation as a Vector3f
*/
Vector3d getRotation();
/**
* Sets the rotation of this entity.
*
* <p>The format of the rotation is represented by:</p>
*
* <ul><code>x -> yaw</code>, <code>y -> pitch</code>, <code>z -> roll
* </code></ul>
*
* @param rotation The rotation to set the entity to
*/
void setRotation(Vector3d rotation);
/**
* Gets the current velocity of this entity.
*
* @return The current velocity of this entity
*/
Vector3d getVelocity();
/**
* Sets the velocity of this entity.
*
* @param velocity The velocity to set this entity
*/
void setVelocity(Vector3d velocity);
/**
* Gets the entity passenger that rides this entity, if available.
*
* @return The passenger entity, if it exists
*/
Optional<Entity> getPassenger();
/**
* Gets the entity vehicle that this entity is riding, if available.
*
* @return The vehicle entity, if it exists
*/
Optional<Entity> getVehicle();
/**
* Gets the entity vehicle that is the base of what ever stack the current
* entity is a part of. This can be the current entity, if it is not riding any vehicle.
*
* <p>The returned entity can never ride another entity, that would make
* the ridden entity the base of the stack.</p>
*
* @return The vehicle entity
*/
Entity getBaseVehicle();
/**
* Sets the passenger entity(the entity that rides this one).
*
* @param entity The entity passenger, or null to eject
* @return True if the set was successful
*/
boolean setPassenger(@Nullable Entity entity);
/**
* Sets the vehicle entity(the entity that is ridden by this one).
*
* @param entity The entity vehicle, or null to dismount
* @return True if the set was successful
*/
boolean setVehicle(@Nullable Entity entity);
/**
* Gets the current x/z size of this entity.
*
* @return The width of this entity
*/
float getBase();
/**
* Gets the current y height of this entity.
*
* @return The current y height
*/
float getHeight();
/**
* Gets the current size scale of this entity.
*
* @return The current scale of the bounding box
*/
float getScale();
/**
* Returns whether this entity is on the ground (not in the air) or not.
*
* @return Whether this entity is on the ground or not
*/
boolean isOnGround();
/**
* Returns whether this entity has been removed.
*
* @return True if this entity has been removed
*/
boolean isRemoved();
/**
* Returns whether this entity is still loaded in a world/chunk.
*
* @return True if this entity is still loaded
*/
boolean isLoaded();
/**
* Mark this entity for removal in the very near future, preferably
* within one game tick.
*/
void remove();
/**
* Gets the ticks remaining of being lit on fire.
*
* @return The remaining fire ticks
*/
int getFireTicks();
/**
* Sets the remaining ticks of being lit on fire.
*
* @param ticks The ticks of being lit on fire
*/
void setFireTicks(int ticks);
/**
* Gets the delay in ticks before this entity will catch fire after being in a burning block.
*
* @return The delay before catching fire
*/
int getFireDelay();
/**
* Returns whether this entity will be persistent when no player is near.
*
* @return True if this entity is persistent
*/
boolean isPersistent();
/**
* Sets whether this entity will be persistent when no player is near.
*
* @param persistent Whether the entity will be persistent
*/
void setPersistent(boolean persistent);
/**
* Checks if this is a flowerpot.
*
* @return Whether this is a flowerpot
*/
boolean isFlowerPot();
}
|
import java.util.Random;
import java.util.Set;
import java.util.Vector;
public class QLearning {
private Grid q_table;
private int mNumThreads;
private class EpisodeRunner implements Runnable {
double mGamma;
double mAlpha;
Random generator;
EpisodeRunner(double alpha, double gamma) {
mAlpha = alpha;
mGamma = gamma;
generator = new Random(5);
}
@Override
public void run() {
int x;
int y;
int numEpisodes = 100000 / mNumThreads;
for(int i = 0; i < numEpisodes; ++i)
{
Position randomLocation;
do{
x = generator.nextInt(q_table.getNumColumns());
y = generator.nextInt(q_table.getNumRows());
randomLocation = new Position(y, x);
} while(q_table.locationIsWall(randomLocation) || q_table.getReward(randomLocation) > 99.999);
episode(q_table.getState(randomLocation), 0, mGamma, mAlpha);
}
}
}
public QLearning(Position start, Position goal, Grid.LockType lockType, int numThreads) {
mNumThreads = numThreads;
//q_table = new Grid("worldSmall.txt", goal);
q_table = new Grid("world.txt", goal, lockType);
double alpha = 1;
double gamma = 0.8;
q_table.printWorld();
q_table.printRewards();
long startTime = System.nanoTime();
Thread[] threads = new Thread[mNumThreads];
for (int i = 0; i < mNumThreads; ++i) {
Thread t = new Thread(new EpisodeRunner(alpha, gamma));
threads[i] = t;
t.start();
}
for (int i = 0; i < mNumThreads; ++i) {
try {
threads[i].join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
long endTime = System.nanoTime();
traverseGrid(start, goal);
System.out.println("Time to complete: " + ((endTime-startTime) * 1000.0));
}
// gets neighbors, updates the reward, and then moves to the next state
// returns if depth exceeded, goal reached, or an invalid state reached
private void episode(State state, int depth, double gamma, double alpha){
StatePair next_state;
double reward;
String direction;
if(depth > 150)
return;
if(state.getReward() > 99.999){
//System.out.println("reached the goal");
return;
}
// Figure out the next state to take based on the current state. This is chosen at random from the currents
// states neighbors that aren't walls.
next_state = nextState(state);
// Take the action so we can keep track of how many times a direction was taken from this state
state.takeTransitionAction(next_state.getDirection());
// Go through the possible actions for the next state and get their action reward values. We will use this to
// calculate the max action value for all possible actions from the next state
direction = next_state.getDirection();
reward = state.getTransitionActionReward(direction) + alpha *
(
next_state.getState().getReward() +
gamma * maxActionReward(next_state.getState()) -
state.getTransitionActionReward(direction)
);
// Set the new transaction reward. We set it based on the max of the current reward for the transition and the
// calculated reward. This is done to guarantee that the transition action reward value will only ever increase
// and no decrease.
state.setTransitionActionReward(direction,
Math.max(reward, state.getTransitionActionReward(direction)));
episode(next_state.getState(), depth + 1, gamma, alpha);
}
public double maxActionReward(State state){
double max = 0.0;
Set<String> actions = state.getActions();
for(String s : actions){
if(state.getTransitionActionReward(s) > max){
max = state.getTransitionActionReward(s);
}
}
return max;
}
static Random nextStateGenerator = new Random(5);
/**
* Provides the next state to explore given the current state. The current state must not be surrounded by walls
* @param state The current state
* @return A pair with the next direction and its corresponding state
*/
private StatePair nextState(State state) {
// Get a vector of the next possible states from the current state
Vector<StatePair> neighbors = q_table.getNeighbors(state);
// Choose a random direction to go next from the list of available directions
int index = nextStateGenerator.nextInt(neighbors.size());
// Return the random state chosen
return neighbors.elementAt(index);
}
public Vector<StatePair> traverseGrid(Position start, Position goal) {
Vector<StatePair> thePathTaken = new Vector<>();
Vector<StatePair> neighbors;
boolean reachedEnd = false;
// Traverse the grid until we reach our goal. QLearning will have created a path that leads us directly
// to the goal.
while(!reachedEnd){
// Check if we found the goal
if(start.equals(goal)){
System.out.println("Reached the goal");
reachedEnd = true;
}else{
// Else we haven't found the goal yet.
State curState = q_table.getState(start);
neighbors = q_table.getNeighbors(curState);
StatePair nextNeighbor = null;
System.out.println('(' + start.getX() + ',' + start.getY() + ')');
double maxReward = 0;
double reward;
for(StatePair neighbor : neighbors)
{
// Look at the reward values to transition to the next neighbor
reward = curState.getTransitionActionReward(neighbor.getDirection());
System.out.println("reward for " + neighbor.getDirection() + " is " + reward);
if(reward > maxReward)
{
maxReward = reward;
nextNeighbor = neighbor;
}
}
// If no neighbor was selected, this means all neighbors have a reward value of 0. So we select a
// random neighbor.
if (nextNeighbor == null) {
//Random generator = new Random();
//nextNeighbor = neighbors.get(generator.nextInt(neighbors.size()));
nextNeighbor = neighbors.get(0);
}
assert nextNeighbor != null;
System.out.println("Agent moves in direction: " + nextNeighbor.getDirection());
// Add state to vector representing the path taken
thePathTaken.add(nextNeighbor);
Position nextPosition = nextNeighbor.getState().getPosition();
System.out.println("Moved from " + '(' + start.getX() + ',' + start.getY() + ')'
+ " to " + '(' + nextPosition.getX() + ',' + nextPosition.getY() + ')');
// Set the start position to the next position that was just found
start = nextPosition;
}
}
return thePathTaken;
}
}
|
package org.vorthmann.zome.ui;
import static org.vorthmann.zome.ui.ApplicationUI.getLogFileName;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.FileDialog;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.ToolTipManager;
import org.vorthmann.j3d.J3dComponentFactory;
import org.vorthmann.j3d.Platform;
import org.vorthmann.ui.Controller;
import org.vorthmann.ui.ExclusiveAction;
import com.vzome.desktop.controller.ViewPlatformControlPanel;
public class DocumentFrame extends JFrame implements PropertyChangeListener, ControlActions
{
private static final long serialVersionUID = 1L;
protected final Controller mController, toolsController;
private final ModelPanel modelPanel;
private final JTabbedPane tabbedPane = new JTabbedPane();
private final ExclusiveAction.Excluder mExcluder = new ExclusiveAction.Excluder( this );
private boolean isEditor, fullPower, readerPreview, canSave;
private CardLayout modelArticleCardLayout;
private static final Logger logger = Logger.getLogger( "org.vorthmann.zome.ui" );
private LessonPanel lessonPanel;
private JFrame zomicFrame, pythonFrame;
private JButton snapshotButton;
private JRadioButton articleButton, modelButton;
private JPanel viewControl, modelArticleEditPanel;
private JLabel statusText;
private Controller viewPlatform;
private Controller lessonController;
private JDialog polytopesDialog;
private final boolean developerExtras;
private final ActionListener localActions;
private File mFile = null;
private final Controller.ErrorChannel errors;
private Snapshot2dFrame snapshot2dFrame;
private ControllerFileAction saveAsAction;
private PropertyChangeListener appUI;
public ExclusiveAction.Excluder getExcluder()
{
return mExcluder;
}
private void createLessonPanel()
{
if ( lessonPanel != null )
return;
lessonPanel = new LessonPanel( lessonController );
modelArticleEditPanel .add( lessonPanel, "article" );
}
void setAppUI( PropertyChangeListener appUI )
{
this .appUI = appUI;
}
public DocumentFrame( final Controller controller )
{
mController = controller;
mController .addPropertyListener( this );
toolsController = mController .getSubController( "tools" );
String path = mController .getProperty( "window.file" );
if ( path != null )
this .mFile = new File( path ); // this enables "save" in localActions
// TODO: compute these booleans once here, and don't recompute in DocumentMenuBar
this.readerPreview = mController .propertyIsTrue( "reader.preview" );
this.isEditor = mController .userHasEntitlement( "model.edit" ) && ! readerPreview;
this.canSave = mController .userHasEntitlement( "save.files" );
this.fullPower = isEditor ;//&& controller .userHasEntitlement( "all.tools" );
this.developerExtras = fullPower && mController .userHasEntitlement( "developer.extras" );
errors = new Controller.ErrorChannel()
{
@Override
public void reportError( String errorCode, Object[] arguments )
{
if ( Controller.USER_ERROR_CODE.equals( errorCode ) ) {
errorCode = ( (Exception) arguments[0] ).getMessage();
// don't want a stack trace for a user error
logger.log( Level.WARNING, errorCode );
} else if ( Controller.UNKNOWN_ERROR_CODE.equals( errorCode ) ) {
errorCode = ( (Exception) arguments[0] ).getMessage();
logger.log( Level.WARNING, "internal error: " + errorCode, ( (Exception) arguments[0] ) );
errorCode = "internal error, see the log file at " + getLogFileName();
} else {
logger.log( Level.WARNING, "reporting error: " + errorCode, arguments );
// TODO use resources
}
if ( statusText != null )
statusText .setText( errorCode );
else
JOptionPane .showMessageDialog( DocumentFrame.this, errorCode, "Command Failure", JOptionPane .ERROR_MESSAGE );
}
@Override
public void clearError()
{
if ( statusText != null )
statusText .setText( "" );
}
};
mController .setErrorChannel( errors );
final String initSystem = mController .getProperty( "symmetry" );
localActions = new ActionListener()
{
private String system = initSystem;
private final Map<String, JDialog> shapesDialogs = new HashMap<>();
private final Map<String, JDialog> directionsDialogs = new HashMap<>();
@Override
public void actionPerformed( ActionEvent e )
{
Controller delegate = mController;
String cmd = e.getActionCommand();
switch ( cmd ) {
case "close":
closeWindow();
break;
// case "openURL":
// String url = JOptionPane .showInputDialog( DocumentFrame.this, "Enter the URL for an online .vZome file.", "Open URL",
// JOptionPane.PLAIN_MESSAGE );
// try {
// mController .doAction( cmd, new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, url ) );
// } catch ( Exception ex )
// ex .printStackTrace();
// // TODO better error report
// errors .reportError( Controller.USER_ERROR_CODE, new Object[]{ ex } );
// break;
case "save":
if ( mFile == null ) {
saveAsAction .actionPerformed( e );
}
else {
mController .doFileAction( "save", mFile );
}
break;
case "saveDefault":
// this is basically "save a copy...", with a hard-coded file path.
String fieldName = mController.getProperty( "field.name" );
String fieldLabel = mController.getProperty( "field.label" );
File prototype = new File( Platform.getPreferencesFolder(), "Prototypes/" + fieldName + ".vZome" );
try {
String path = prototype.getCanonicalPath();
int response = JOptionPane.showConfirmDialog(
DocumentFrame.this,
"Save as the template for new models in the " + fieldLabel + " field?"
+ "\n\nTemplate file: " + path,
"Save Template?",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE );
if ( response == JOptionPane.YES_OPTION ) {
logger.config("Saving default template to " + path);
mController .doFileAction( "save", prototype );
}
else if ( prototype.exists() ) {
response = JOptionPane.showConfirmDialog(
DocumentFrame.this,
"Delete the existing template for new models in the " + fieldLabel + " field?"
+ "\n\nTemplate file: " + path,
"Delete Template?",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE );
if ( response == JOptionPane.YES_OPTION ) {
logger.config("Deleting default template at " + path);
prototype.delete();
}
}
} catch (IOException ex) {
errors .reportError( Controller.USER_ERROR_CODE, new Object[]{ ex } );
}
break;
case "snapshot.2d":
if ( snapshot2dFrame == null ) {
snapshot2dFrame = new Snapshot2dFrame( mController.getSubController( "snapshot.2d" ), new FileDialog( DocumentFrame.this ) );
}
snapshot2dFrame.setPanelSize( modelPanel .getRenderedSize() );
snapshot2dFrame.pack();
if ( ! snapshot2dFrame .isVisible() )
snapshot2dFrame.repaint();
snapshot2dFrame.setVisible( true );
break;
case "redoUntilEdit":
String number = JOptionPane.showInputDialog( null, "Enter the edit number.", "Set Edit Number",
JOptionPane.PLAIN_MESSAGE );
try {
mController .doAction( "redoUntilEdit." + number, new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "redoUntilEdit." + number ) );
} catch ( Exception e1 ) {
errors .reportError( Controller.USER_ERROR_CODE, new Object[]{ e1 } );
}
break;
case "showToolsPanel":
tabbedPane .setSelectedIndex( 1 ); // should be "tools" tab
break;
case "showPolytopesDialog":
Controller polytopesController = mController .getSubController( "polytopes" );
if ( polytopesDialog == null )
polytopesDialog = new PolytopesDialog( DocumentFrame.this, polytopesController );
try {
polytopesController .doAction( "setQuaternion", new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "setQuaternion" ) );
} catch ( Exception e1 ) {
errors .reportError( Controller.USER_ERROR_CODE, new Object[]{ e1 } );
}
polytopesDialog .setVisible( true );
break;
case "showPythonWindow":
if ( pythonFrame == null ) {
pythonFrame = new JFrame( "Python Scripting" );
pythonFrame .setContentPane( new PythonConsolePanel( pythonFrame, mController ) );
}
pythonFrame .pack();
pythonFrame .setVisible( true );
break;
case "showZomicWindow":
if ( zomicFrame == null ) {
zomicFrame = new JFrame( "Zomic Scripting" );
zomicFrame .setContentPane( new ZomicEditorPanel( zomicFrame, mController ) );
}
zomicFrame .pack();
zomicFrame .setVisible( true );
break;
case "setItemColor":
Color color = JColorChooser.showDialog( DocumentFrame.this, "Choose Object Color", null );
if ( color == null )
return;
int rgb = color .getRGB() & 0xffffff;
int alpha = color .getAlpha() & 0xff;
String command = "setItemColor/" + Integer.toHexString( ( rgb << 8 ) | alpha );
mController .actionPerformed( new ActionEvent( e .getSource(), e.getID(), command ) );
break;
case "setBackgroundColor":
color = JColorChooser.showDialog( DocumentFrame.this, "Choose Background Color", null );
if ( color != null )
mController .setProperty( "backgroundColor", Integer.toHexString( color.getRGB() & 0xffffff ) );
break;
case "usedOrbits":
mController .actionPerformed( e ); // TO DO exclusive
break;
case "rZomeOrbits":
case "predefinedOrbits":
case "setAllDirections":
delegate = mController .getSubController( "symmetry." + system );
delegate .actionPerformed( e );
break;
case "configureShapes":
JDialog shapesDialog = shapesDialogs.get( system );
if ( shapesDialog == null ) {
delegate = mController .getSubController( "symmetry." + system );
shapesDialog = new ShapesDialog( DocumentFrame.this, delegate );
shapesDialogs .put( system, shapesDialog );
}
shapesDialog .setVisible( true );
break;
case "configureDirections":
JDialog symmetryDialog = directionsDialogs.get( system );
if ( symmetryDialog == null ) {
delegate = mController .getSubController( "symmetry." + system );
symmetryDialog = new SymmetryDialog( DocumentFrame.this, delegate );
directionsDialogs .put( system, symmetryDialog );
}
symmetryDialog .setVisible( true );
break;
default:
if ( cmd .startsWith( "setSymmetry." ) )
{
system = cmd .substring( "setSymmetry.".length() );
mController .actionPerformed( e ); // TODO getExclusiveAction
}
else if ( cmd .startsWith( "addTool-" ) )
{
String group = cmd .substring( "addTool-" .length() );
String numStr = toolsController .getProperty( "next.tool.number" );
int toolNum = Integer .parseInt( numStr );
String toolId = group + "." + toolNum;
String toolName = (String) JOptionPane .showInputDialog( (Component) e .getSource(),
"Name the new tool:", "New Tool",
JOptionPane.PLAIN_MESSAGE, null, null, toolId );
if ( ( toolName == null ) || ( toolName .length() == 0 ) ) {
return;
}
mController .actionPerformed( new ActionEvent( e .getSource(), e.getID(), "newTool/" + toolId + "/" + toolName ) );
}
else if ( cmd .startsWith( "showProperties-" ) )
{
String key = cmd .substring( "showProperties-" .length() );
Controller subc = mController .getSubController( key + "Picking" );
JOptionPane .showMessageDialog( DocumentFrame.this, subc .getProperty( "objectProperties" ), "Object Properties",
JOptionPane.PLAIN_MESSAGE );
}
else
mController .actionPerformed( e );
break;
}
}
};
viewPlatform = mController .getSubController( "viewPlatform" );
lessonController = mController .getSubController( "lesson" );
lessonController .addPropertyListener( this );
// Now the component containment hierarchy
JPanel outerPanel = new JPanel( new BorderLayout() );
setContentPane( outerPanel );
{
JPanel leftCenterPanel = new JPanel( new BorderLayout() );
{
if ( this .isEditor )
{
JPanel modeAndStatusPanel = new JPanel( new BorderLayout() );
JPanel articleButtonsPanel = new JPanel();
modeAndStatusPanel .add( articleButtonsPanel, BorderLayout.LINE_START );
ButtonGroup group = new ButtonGroup();
modelButton = new JRadioButton( "Model" );
modelButton .setSelected( true );
articleButtonsPanel .add( modelButton );
group .add( modelButton );
modelButton .setActionCommand( "switchToModel" );
modelButton .addActionListener( mController );
snapshotButton = new JButton( "-> capture ->" );
// String imgLocation = "/icons/snapshot.png";
// URL imageURL = getClass().getResource( imgLocation );
// if ( imageURL != null ) {
// Icon icon = new ImageIcon( imageURL, "capture model snapshot" );
// snapshotButton .setIcon( icon );
// Dimension dim = new Dimension( 50, 36 );
// snapshotButton .setPreferredSize( dim );
// snapshotButton .setMaximumSize( dim );
articleButtonsPanel .add( snapshotButton );
snapshotButton .setActionCommand( "takeSnapshot" );
snapshotButton .addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
mController .actionPerformed( e ); // sends thumbnailChanged propertyChange, but no listener...
articleButton .doClick(); // switch to article mode, so now there's a listener
// now trigger the propertyChange again
lessonController .actionPerformed( new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "setView" ) );
}
} );
articleButton = new JRadioButton( "Article" );
articleButton .setEnabled( lessonController .propertyIsTrue( "has.pages" ) );
articleButton .setSelected( false );
articleButtonsPanel .add( articleButton );
group .add( articleButton );
articleButton .setActionCommand( "switchToArticle" );
articleButton .addActionListener( mController );
JPanel statusPanel = new JPanel( new BorderLayout() );
statusPanel .setBorder( BorderFactory .createEmptyBorder( 4, 4, 4, 4 ) );
statusText = new JLabel( "", JLabel.CENTER );
statusText .setBorder( BorderFactory .createLineBorder( Color.LIGHT_GRAY ) );
statusText .setForeground( Color .RED );
statusPanel .add( statusText );
modeAndStatusPanel .add( statusPanel, BorderLayout.CENTER );
leftCenterPanel .add( modeAndStatusPanel, BorderLayout.PAGE_START );
}
modelPanel = new ModelPanel( mController, this, this .isEditor, fullPower );
leftCenterPanel .add( modelPanel, BorderLayout.CENTER );
}
outerPanel.add( leftCenterPanel, BorderLayout.CENTER );
// String mag = props .getProperty( "default.magnification" );
// if ( mag != null ) {
// float magnification = Float .parseFloat( mag );
// // TODO this seems to work, but ought not to!
// viewControl .zoomAdjusted( (int) magnification );
JPanel rightPanel = new JPanel( new BorderLayout() );
{
Component trackballCanvas = ( (J3dComponentFactory) mController ) .createJ3dComponent( "controlViewer" );
viewControl = new ViewPlatformControlPanel( trackballCanvas, viewPlatform );
// this is probably moot for reader mode
rightPanel .add( viewControl, BorderLayout.PAGE_START );
modelArticleEditPanel = new JPanel();
modelArticleCardLayout = new CardLayout();
modelArticleEditPanel .setLayout( modelArticleCardLayout );
if ( this .isEditor )
{
JPanel buildPanel = new StrutBuilderPanel( DocumentFrame.this, mController .getProperty( "symmetry" ), mController, this );
if ( this .fullPower )
{
tabbedPane .addTab( "build", buildPanel );
if ( mController .propertyIsTrue( "original.tools" ) )
{
ToolsPanel toolsPanel = new ToolsPanel( DocumentFrame.this, toolsController );
tabbedPane .addTab( "tools", toolsPanel );
}
JPanel bomPanel = new PartsPanel( mController .getSubController( "parts" ) );
tabbedPane .addTab( "parts", bomPanel );
modelArticleEditPanel .add( tabbedPane, "model" );
}
else
modelArticleEditPanel .add( buildPanel, "model" );
}
if ( this .isEditor )
{
modelArticleCardLayout .show( modelArticleEditPanel, "model" );
modelArticleEditPanel .setMinimumSize( new Dimension( 300, 500 ) );
modelArticleEditPanel .setPreferredSize( new Dimension( 300, 800 ) );
}
else
{
createLessonPanel();
modelArticleCardLayout .show( modelArticleEditPanel, "article" );
modelArticleEditPanel .setMinimumSize( new Dimension( 400, 500 ) );
modelArticleEditPanel .setPreferredSize( new Dimension( 400, 800 ) );
}
rightPanel .add( modelArticleEditPanel, BorderLayout.CENTER );
}
outerPanel.add( rightPanel, BorderLayout.LINE_END );
}
JPopupMenu.setDefaultLightWeightPopupEnabled( false );
ToolTipManager ttm = ToolTipManager.sharedInstance();
ttm .setLightWeightPopupEnabled( false );
this .saveAsAction = new ControllerFileAction( new FileDialog( DocumentFrame.this ), false, "save", "vZome", mController )
{
// this happens at the very end, after choose, save, set type
@Override
protected void openApplication( File file )
{
mFile = file;
String newTitle = file .getAbsolutePath();
mController .setProperty( "name", newTitle );
setTitle( newTitle );
}
};
this .setJMenuBar( new DocumentMenuBar( mController, this ) );
this.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE );
this.addWindowListener( new WindowAdapter()
{
@Override
public void windowClosing( WindowEvent we )
{
closeWindow();
}
} );
// Find the screen with the largest area if this is a multi-monitor system.
// Set the frame size to just a bit smaller than the screen
// so the frame will fit on the screen if the user un-maximizes it.
// Default to opening the window as maximized on the selected (or default) monitor.
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
if(gs.length > 0) {
int bestIndex = 0;
GraphicsDevice bestDevice = gs[bestIndex];
DisplayMode bestMode = bestDevice.getDisplayMode();
int bestArea = bestMode.getHeight() * bestMode.getWidth();
for (int i = bestIndex+1; i < gs.length; i++) {
GraphicsDevice testDevice = gs[i];
DisplayMode testMode = testDevice.getDisplayMode();
int testArea = testMode.getHeight() * testMode.getWidth();
if(bestArea < testArea) {
bestArea = testArea;
bestMode = testMode;
bestDevice = testDevice;
}
}
Rectangle bounds = bestDevice.getDefaultConfiguration().getBounds();
this.setLocation(bounds.x, bounds.y);
int n = 15, d = n + 1; // set size to 15/16 of full screen size then maximize it
this.setSize(bestMode.getWidth() * n/d, bestMode.getHeight() * n/d);
}
this.setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
this.pack();
this.setVisible( true );
this.setFocusable( true );
new ExclusiveAction( this .getExcluder() )
{
@Override
protected void doAction( ActionEvent e ) throws Exception
{
mController .doAction( "finish.load", e );
String title = mController .getProperty( "window.title" );
boolean migrated = mController .propertyIsTrue( "migrated" );
boolean asTemplate = mController .propertyIsTrue( "as.template" );
URL url = null; // TODO
if ( ! mController .userHasEntitlement( "model.edit" ) )
{
mController .doAction( "switchToArticle", e );
if ( url != null )
title = url .toExternalForm();
migrated = false;
}
if ( ! asTemplate && migrated ) { // a migration
final String NL = System .getProperty( "line.separator" );
if ( mController .propertyIsTrue( "autoFormatConversion" ) )
{
if ( mController .propertyIsTrue( "formatIsSupported" ) )
JOptionPane .showMessageDialog( DocumentFrame.this,
"This document was created by an older version." + NL +
"If you save it now, it will be converted automatically" + NL +
"to the current format. It will no longer open using" + NL +
"the older version.",
"Automatic Conversion", JOptionPane.INFORMATION_MESSAGE );
else
{
title = null;
DocumentFrame.this .makeUnnamed();
JOptionPane .showMessageDialog( DocumentFrame.this,
"You have \"autoFormatConversion\" turned on," + NL +
"but the behavior is disabled until this version of vZome" + NL +
"is stable. This converted document is being opened as" + NL +
"a new document.",
"Automatic Conversion Disabled", JOptionPane.INFORMATION_MESSAGE );
}
}
else
{
title = null;
DocumentFrame.this .makeUnnamed();
JOptionPane .showMessageDialog( DocumentFrame.this,
"This document was created by an older version." + NL +
"It is being opened as a new document, so you can" + NL +
"still open the original using the older version.",
"Outdated Format", JOptionPane.INFORMATION_MESSAGE );
}
}
if ( title == null )
title = mController .getProperty( "untitled.title" );
DocumentFrame.this .setTitle( title );
}
@Override
protected void showError( Exception e )
{
JOptionPane .showMessageDialog( DocumentFrame.this,
e .getLocalizedMessage(),
"Error Loading Document", JOptionPane.ERROR_MESSAGE );
DocumentFrame.this .dispose();
}
} .actionPerformed( null );
}
private ExclusiveAction getExclusiveAction( final String action )
{
return new ExclusiveAction( getExcluder() )
{
@Override
protected void doAction( ActionEvent e ) throws Exception
{
mController.doAction( action, e );
}
@Override
protected void showError( Exception e )
{
JOptionPane.showMessageDialog( DocumentFrame.this, e.getMessage(), "Command failure", JOptionPane.ERROR_MESSAGE );
}
};
}
@Override
public AbstractButton setButtonAction( String command, AbstractButton control )
{
control .setActionCommand( command );
boolean enable = true;
switch ( command ) {
// TODO: find a better way to disable these... they are found in OrbitPanel.java
case "predefinedOrbits":
case "usedOrbits":
case "setAllDirections":
enable = fullPower;
break;
case "save":
case "saveAs":
case "saveDefault":
enable = this .canSave;
break;
default:
if ( command .startsWith( "export." ) ) {
enable = this .canSave;
}
}
control .setEnabled( enable );
if ( control .isEnabled() )
{
ActionListener actionListener = this .mController;
switch ( command ) {
// these can fall through to the ApplicationController
case "quit":
case "new":
case "new-rootTwo":
case "new-rootThree":
case "new-heptagon":
case "new-snubDodec":
case "openURL":
case "showAbout":
// these will be handled by the DocumentController
case "toggleWireframe":
case "toggleOrbitViews":
case "toggleStrutScales":
case "toggleFrameLabels":
case "toggleOutlines":
actionListener = this .mController;
break;
case "open":
case "newFromTemplate":
case "openDeferringRedo":
actionListener = new ControllerFileAction( new FileDialog( this ), true, command, "vZome", mController );
break;
case "import.vef":
actionListener = new ControllerFileAction( new FileDialog( this ), true, command, "vef", mController );
break;
case "saveAs":
actionListener = saveAsAction;
break;
case "save":
case "saveDefault":
case "close":
case "snapshot.2d":
case "showToolsPanel":
case "setItemColor":
case "setBackgroundColor":
case "showPolytopesDialog":
case "showZomicWindow":
case "showPythonWindow":
case "rZomeOrbits":
case "predefinedOrbits":
case "usedOrbits":
case "setAllDirections":
case "configureShapes":
case "configureDirections":
case "redoUntilEdit":
actionListener = this .localActions;
break;
case "capture-animation":
actionListener = new ControllerFileAction( new FileDialog( this ), false, command, "png", mController );
break;
default:
if ( command .startsWith( "openResource-" ) ) {
actionListener = this .mController;
}
else if ( command .startsWith( "setSymmetry." ) ) {
actionListener = this .localActions;
}
else if ( command .startsWith( "addTool-" ) ) {
actionListener = this .localActions;
}
else if ( command .startsWith( "showProperties-" ) ) {
actionListener = this .localActions;
}
else if ( command .startsWith( "capture." ) ) {
String ext = command .substring( "capture." .length() );
actionListener = new ControllerFileAction( new FileDialog( this ), false, command, ext, mController );
}
else if ( command .startsWith( "export." ) ) {
String ext = command .substring( "export." .length() );
switch ( ext ) {
case "vrml": ext = "wrl"; break;
case "size": ext = "txt"; break;
case "partslist": ext = "txt"; break;
case "partgeom": ext = "vef"; break;
default:
break;
}
actionListener = new ControllerFileAction( new FileDialog( this ), false, command, ext, mController );
}
else {
actionListener = getExclusiveAction( command );
this .mExcluder .addExcludable( control );
}
break;
}
control .addActionListener( actionListener );
}
return control;
}
@Override
public JMenuItem setMenuAction( String command, JMenuItem menuItem )
{
return (JMenuItem) this .setButtonAction( command, menuItem );
}
@Override
public void propertyChange( PropertyChangeEvent e )
{
switch ( e .getPropertyName() ) {
case "command.status":
if ( statusText != null && ! this .developerExtras )
statusText .setText( (String) e .getNewValue() );
break;
case "current.edit.xml":
if ( statusText != null && this .developerExtras )
statusText .setText( (String) e .getNewValue() );
break;
case "editor.mode":
String mode = (String) e .getNewValue();
int width = 0;
if ( "article" .equals( mode ) )
{
width = 400;
if ( snapshotButton != null ) // this gets called just once for the Reader
snapshotButton .setEnabled( false );
// viewControl .setVisible( false );
mExcluder .grab();
}
else
{
width = 300;
snapshotButton .setEnabled( true );
// viewControl .setVisible( true );
mExcluder .release();
}
createLessonPanel();
modelArticleCardLayout .show( modelArticleEditPanel, mode );
modelArticleEditPanel .setMinimumSize( new Dimension( width, 500 ) );
modelArticleEditPanel .setPreferredSize( new Dimension( width, 800 ) );
break;
case "has.pages":
if ( articleButton != null )
{
boolean enable = e .getNewValue() .toString() .equals( "true" );
articleButton .setEnabled( enable );
if ( ! enable )
modelButton .doClick();
}
break;
case "window.title":
this .setTitle( e .getNewValue() .toString() );
break;
case "visible":
if ( Boolean.TRUE .equals( e .getNewValue() ) ) {
this .appUI .propertyChange( e ); // remove this window from the UI's collection
this .setVisible( true );
}
break;
}
}
// called from ApplicationUI on quit
boolean closeWindow()
{
if ( "true".equals( mController.getProperty( "edited" ) ) && ( isEditor && canSave ) )
{
// TODO replace showConfirmDialog() with use of EscapeDialog, or something similar...
int response = JOptionPane.showConfirmDialog( DocumentFrame.this, "Do you want to save your changes?",
"file is changed", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE );
if ( response == JOptionPane.CANCEL_OPTION )
return false;
if ( response == JOptionPane.YES_OPTION )
try {
localActions .actionPerformed( new ActionEvent( DocumentFrame.this, ActionEvent.ACTION_PERFORMED, "save" ) );
return false;
} catch ( RuntimeException re ) {
logger.log( Level.WARNING, "did not save due to error", re );
return false;
}
}
dispose();
mController .setProperty( "visible", Boolean.FALSE );
return true;
}
public void makeUnnamed()
{
this .mFile = null;
}
}
|
package uk.ac.ebi.quickgo.annotation.controller;
import uk.ac.ebi.quickgo.annotation.AnnotationREST;
import uk.ac.ebi.quickgo.annotation.common.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker;
import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig;
import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore;
import java.util.Collections;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.apache.commons.lang.StringUtils;
import org.junit.Before;
import org.junit.ClassRule;
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.ResultActions;
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.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static uk.ac.ebi.quickgo.annotation.AnnotationParameters.*;
import static uk.ac.ebi.quickgo.annotation.IdGeneratorUtil.createGPId;
import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.*;
import static uk.ac.ebi.quickgo.annotation.controller.ResponseVerifier.ResponseItem.responseItem;
import static uk.ac.ebi.quickgo.annotation.model.AnnotationRequest.DEFAULT_ENTRIES_PER_PAGE;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {AnnotationREST.class})
@WebAppConfiguration
public class AnnotationControllerIT {
// temporary data store for solr's data, which is automatically cleaned on exit
@ClassRule
public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore();
//Test Data
private static final String MISSING_ASSIGNED_BY = "ZZZZZ";
private static final String RESOURCE_URL = "/annotation";
private static final String MISSING_GO_ID = "GO:0009871";
private static final String INVALID_GO_ID = "GO:1";
private static final String ECO_ID2 = "ECO:0000323";
private static final String MISSING_ECO_ID = "ECO:0000888";
private static final String WITH_FROM_PATH = "withFrom.*.connectedXrefs";
//Configuration
private static final int NUMBER_OF_GENERIC_DOCS = 3;
private MockMvc mockMvc;
private List<AnnotationDocument> genericDocs;
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private AnnotationRepository repository;
@Before
public void setup() {
repository.deleteAll();
mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext)
.build();
genericDocs = createGenericDocs(NUMBER_OF_GENERIC_DOCS);
repository.save(genericDocs);
}
//ASSIGNED BY
@Test
public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception {
String geneProductId = "P99999";
String assignedBy = "ASPGD";
AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy);
repository.save(document);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), assignedBy));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId));
}
@Test
public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception {
String geneProductId1 = "P99999";
String assignedBy1 = "ASPGD";
AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1);
repository.save(document1);
String geneProductId2 = "P99998";
String assignedBy2 = "BHF-UCL";
AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2);
repository.save(document2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), assignedBy1 + "," + assignedBy2));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(fieldsInAllResultsExist(2))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId2, geneProductId1));
}
@Test
public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception {
String geneProductId1 = "P99999";
String assignedBy1 = "ASPGD";
AnnotationDocument document1 = createDocWithAssignedBy(geneProductId1, assignedBy1);
repository.save(document1);
String geneProductId2 = "P99998";
String assignedBy2 = "BHF-UCL";
AnnotationDocument document2 = createDocWithAssignedBy(geneProductId2, assignedBy2);
repository.save(document2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(ASSIGNED_BY_PARAM.getName(), assignedBy1)
.param(ASSIGNED_BY_PARAM.getName(), assignedBy2));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(fieldsInAllResultsExist(2))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId2, geneProductId1));
}
@Test
public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), MISSING_ASSIGNED_BY));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception {
String geneProductId = "P99999";
String assignedBy = "ASPGD";
AnnotationDocument document = createDocWithAssignedBy(geneProductId, assignedBy);
repository.save(document);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), MISSING_ASSIGNED_BY + ","
+ assignedBy));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId));
}
@Test
public void invalidAssignedByThrowsAnError() throws Exception {
String invalidAssignedBy = "_ASPGD";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM.getName(), invalidAssignedBy));
response.andDo(print())
.andExpect(status().isBadRequest());
}
//TAXON ID
@Test
public void lookupAnnotationFilterByTaxonIdSuccessfully() throws Exception {
String geneProductId = "P99999";
int taxonId = 2;
AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId);
repository.save(document);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM.getName(), Integer.toString(taxonId)));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(valuesOccursInField(TAXON_ID_FIELD, taxonId))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId));
}
@Test
public void lookupAnnotationFilterByMultipleTaxonIdsSuccessfully() throws Exception {
String geneProductId1 = "P99999";
int taxonId1 = 2;
AnnotationDocument document1 = createDocWithTaxonId(geneProductId1, taxonId1);
repository.save(document1);
String geneProductId2 = "P99998";
int taxonId2 = 3;
AnnotationDocument document2 = createDocWithTaxonId(geneProductId2, taxonId2);
repository.save(document2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(TAXON_ID_PARAM.getName(), Integer.toString(taxonId1))
.param(TAXON_ID_PARAM.getName(), Integer.toString(taxonId2)));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(fieldsInAllResultsExist(2))
.andExpect(valuesOccursInField(TAXON_ID_FIELD, taxonId2, taxonId1))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId2, geneProductId1));
}
@Test
public void lookupWhereTaxonIdIsZeroWillNotShowTaxonIdBecauseThisMeansInvalid() throws Exception {
String geneProductId = "P99999";
int taxonId = 0;
AnnotationDocument document = createDocWithTaxonId(geneProductId, taxonId);
repository.save(document);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldDoesNotExist(TAXON_ID_FIELD))
.andExpect(valuesOccurInField(GENEPRODUCT_ID_FIELD, geneProductId));
}
@Test
public void invalidTaxIdThrowsError() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(TAXON_ID_PARAM.getName(), "-2"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void filterAnnotationsByGoEvidenceCodeSuccessfully() throws Exception {
String goEvidenceCode = "IEA";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), goEvidenceCode));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode));
}
@Test
public void filterAnnotationsByLowercaseGoEvidenceCodeSuccessfully() throws Exception {
String goEvidenceCode = "iea";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), goEvidenceCode));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(atLeastOneResultHasItem(GO_EVIDENCE_FIELD, goEvidenceCode.toUpperCase()));
}
@Test
public void filterAnnotationsByNonExistentGoEvidenceCodeReturnsNothing() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), "ZZZ"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterAnnotationsUsingMultipleGoEvidenceCodesSuccessfully() throws Exception {
String goEvidenceCode = "IEA";
String goEvidenceCode1 = "BSS";
AnnotationDocument annoDoc1 = AnnotationDocMocker.createAnnotationDoc(createGPId(999));
annoDoc1.goEvidence = goEvidenceCode1;
repository.save(annoDoc1);
String goEvidenceCode2 = "AWE";
AnnotationDocument annoDoc2 = AnnotationDocMocker.createAnnotationDoc(createGPId(998));
annoDoc2.goEvidence = goEvidenceCode2;
repository.save(annoDoc2);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), "IEA,BSS,AWE,PEG"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode1, 1))
.andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode2, 1))
.andExpect(itemExistsExpectedTimes(GO_EVIDENCE_FIELD, goEvidenceCode, NUMBER_OF_GENERIC_DOCS));
}
@Test
public void invalidGoEvidenceThrowsException() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_EVIDENCE_PARAM.getName(), "BlahBlah"));
response.andExpect(status().isBadRequest())
.andExpect(contentTypeToBeJson());
}
@Test
public void successfullyLookupAnnotationsByQualifier() throws Exception {
String qualifier = "enables";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM.getName(), qualifier));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(valueOccursInField(QUALIFIER_FIELD, qualifier));
}
@Test
public void successfullyLookupAnnotationsByNegatedQualifier() throws Exception {
String qualifier = "not|enables";
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.qualifier = qualifier;
repository.save(doc);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM.getName(), qualifier));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(valueOccursInField(QUALIFIER_FIELD, qualifier));
}
@Test
public void failToFindAnnotationsWhenQualifierDoesntExist() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(QUALIFIER_PARAM.getName(), "peeled"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterByGeneProductIDSuccessfully() throws Exception {
String geneProductId = "A1E959";
String fullGeneProductId = "UniProtKB:" + geneProductId;
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(fullGeneProductId);
repository.save(doc);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, fullGeneProductId, 1));
}
@Test
public void filterByFullyQualifiedUniProtGeneProductIDSuccessfully() throws Exception {
String geneProductId = "UniProtKB:A1E959";
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId);
repository.save(doc);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, geneProductId, 1));
}
@Test
public void filterByUniProtKBAndIntactAndRNACentralGeneProductIDSuccessfully() throws Exception {
repository.deleteAll();
String uniprotGp = "A1E959";
String intactGp = "EBI-10043081";
String rnaGp = "URS00000064B1_559292";
repository.save(AnnotationDocMocker.createAnnotationDoc(uniprotGp));
repository.save(AnnotationDocMocker.createAnnotationDoc(intactGp));
repository.save(AnnotationDocMocker.createAnnotationDoc(rnaGp));
StringJoiner sj = new StringJoiner(",");
sj.add(uniprotGp).add(intactGp).add(rnaGp);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), sj.toString()));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(3))
.andExpect(fieldsInAllResultsExist(3))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, uniprotGp, 1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, intactGp, 1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, rnaGp, 1));
}
@Test
public void filterByUniProtKBAndIntactAndRNACentralGeneProductIDCaseInsensitiveSuccessfully() throws Exception {
repository.deleteAll();
String uniprotGp = "A1E959".toLowerCase();
String intactGp = "EBI-10043081".toLowerCase();
String rnaGp = "URS00000064B1_559292".toLowerCase();
repository.save(AnnotationDocMocker.createAnnotationDoc(uniprotGp));
repository.save(AnnotationDocMocker.createAnnotationDoc(intactGp));
repository.save(AnnotationDocMocker.createAnnotationDoc(rnaGp));
StringJoiner sj = new StringJoiner(",");
sj.add(uniprotGp).add(intactGp).add(rnaGp);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), sj.toString()));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(3))
.andExpect(fieldsInAllResultsExist(3))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, uniprotGp, 1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, intactGp, 1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, rnaGp, 1));
}
@Test
public void filterByGeneProductUsingInvalidIDFailsValidation() throws Exception {
String invalidGeneProductID = "99999";
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(invalidGeneProductID);
repository.save(doc);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), invalidGeneProductID));
response.andExpect(status().isBadRequest());
}
@Test
public void filterByValidIdThatDoesNotExistExpectZeroResultsButNoError() throws Exception {
String geneProductId = "Z0Z000";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterByThreeGeneProductIdsTwoOfWhichExistToEnsureTheyAreReturned() throws Exception {
String geneProductId = "Z0Z000";
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GENE_PRODUCT_ID_PARAM.getName(), geneProductId)
.param(GENE_PRODUCT_ID_PARAM.getName(), genericDocs.get(0).geneProductId)
.param(GENE_PRODUCT_ID_PARAM.getName(), genericDocs.get(1).geneProductId));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(2))
.andExpect(fieldsInAllResultsExist(2))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, genericDocs.get(0).geneProductId, 1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, genericDocs.get(1).geneProductId, 1));
}
@Test
public void filterByGeneProductIDAndAssignedBySuccessfully() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(GENE_PRODUCT_ID_PARAM.getName(), genericDocs.get(0).geneProductId)
.param(ASSIGNED_BY_PARAM.getName(), genericDocs.get(0).assignedBy));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(itemExistsExpectedTimes(GENEPRODUCT_ID_FIELD, genericDocs.get(0).geneProductId, 1))
.andExpect(itemExistsExpectedTimes(ASSIGNED_BY_FIELD, genericDocs.get(1).assignedBy, 1));
}
@Test
public void successfullyLookupAnnotationsByGoId() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ID_PARAM.getName(), AnnotationDocMocker.GO_ID));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(GO_ID_FIELD, AnnotationDocMocker.GO_ID, NUMBER_OF_GENERIC_DOCS));
}
@Test
public void successfullyLookupAnnotationsByGoIdCaseInsensitive() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ID_PARAM.getName(), AnnotationDocMocker.GO_ID.toLowerCase()));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(GO_ID_FIELD, AnnotationDocMocker.GO_ID, NUMBER_OF_GENERIC_DOCS));
}
@Test
public void failToFindAnnotationsWhenGoIdDoesntExist() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ID_PARAM.getName(), MISSING_GO_ID));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void incorrectFormattedGoIdCausesError() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ID_PARAM.getName(), INVALID_GO_ID));
response.andExpect(status().isBadRequest())
.andExpect(contentTypeToBeJson());
}
@Test
public void filterAnnotationsUsingSingleEvidenceCodeReturnsResults() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(atLeastOneResultHasItem(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID));
}
@Test
public void filterAnnotationsUsingMultipleEvidenceCodesInSingleParameterProducesMixedResults() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("B0A000");
doc.evidenceCode = ECO_ID2;
repository.save(doc);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID + ","
+ doc.evidenceCode + "," + MISSING_ECO_ID));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 1))
.andExpect(fieldsInAllResultsExist(4))
.andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID,
NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), doc.evidenceCode, 1))
.andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID, 0));
}
@Test
public void filterAnnotationsUsingMultipleEvidenceCodesAsIndependentParametersProducesMixedResults()
throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("B0A000");
doc.evidenceCode = ECO_ID2;
repository.save(doc);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID)
.param(EVIDENCE_CODE_PARAM.getName(), doc.evidenceCode)
.param(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 1))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 1))
.andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), AnnotationDocMocker.ECO_ID,
NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), doc.evidenceCode, 1))
.andExpect(itemExistsExpectedTimes(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID, 0));
}
@Test
public void filterByNonExistentEvidenceCodeReturnsZeroResults() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(EVIDENCE_CODE_PARAM.getName(), MISSING_ECO_ID));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void retrievesSecondPageOfAllEntriesRequest() throws Exception {
int totalEntries = 60;
repository.deleteAll();
repository.save(createGenericDocs(totalEntries));
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(PAGE_PARAM.getName(), "2"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(totalEntries))
.andExpect(resultsInPage(DEFAULT_ENTRIES_PER_PAGE))
.andExpect(
pageInfoMatches(
2,
totalPages(totalEntries, DEFAULT_ENTRIES_PER_PAGE),
DEFAULT_ENTRIES_PER_PAGE)
);
}
@Test
public void pageRequestEqualToAvailablePagesReturns200() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(PAGE_PARAM.getName(), "1"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(
pageInfoMatches(
1,
totalPages(NUMBER_OF_GENERIC_DOCS, DEFAULT_ENTRIES_PER_PAGE),
DEFAULT_ENTRIES_PER_PAGE)
);
}
@Test
public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(PAGE_PARAM.getName(), "0"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void pageRequestHigherThanAvailablePagesReturns400() throws Exception {
repository.deleteAll();
int existingPages = 4;
createGenericDocs(SearchServiceConfig.MAX_PAGE_RESULTS * existingPages);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(PAGE_PARAM.getName(), String.valueOf(existingPages + 1)));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void successfulLookupWithFromForSingleId() throws Exception {
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "InterPro:IPR015421"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(valueOccursInFieldList(WITH_FROM_PATH,
responseItem()
.withAttribute("db", "InterPro")
.withAttribute("id", "IPR015421").build()));
}
@Test
public void successfulLookupWithFromForMultipleValues() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(),
"InterPro:IPR015421,InterPro:IPR015422"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem()
.withAttribute("db", "InterPro")
.withAttribute("id", "IPR015421").build()))
.andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem()
.withAttribute("db", "InterPro")
.withAttribute("id", "IPR015422").build()));
}
@Test
public void searchingForUnknownWithFromBringsBackNoResults() throws Exception {
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "XXX:54321"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void successfulLookupWithFromUsingDatabaseNameOnly() throws Exception {
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "InterPro"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem()
.withAttribute("db", "InterPro")
.withAttribute("id", "IPR015421").build()))
.andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem()
.withAttribute("db", "InterPro")
.withAttribute("id", "IPR015422").build()));
}
@Test
public void successfulLookupWithFromUsingDatabaseIdOnly() throws Exception {
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM.getName(), "IPR015421"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(valueOccursInFieldList(WITH_FROM_PATH, responseItem()
.withAttribute("db", "InterPro")
.withAttribute("id", "IPR015421").build()));
}
@Test
public void limitForPageExceedsMaximumAllowed() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search")
.param(LIMIT_PARAM.getName(), "101"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void limitForPageWithinMaximumAllowed() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(LIMIT_PARAM.getName(), "100"));
response.andExpect(status().isOk())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(pageInfoMatches(1, 1, 100));
}
@Test
public void limitForPageThrowsErrorWhenNegative() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search")
.param(LIMIT_PARAM.getName(), "-20"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
private AnnotationDocument createDocWithAssignedBy(String geneProductId, String assignedBy) {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId);
doc.assignedBy = assignedBy;
return doc;
}
private AnnotationDocument createDocWithTaxonId(String geneProductId, int taxonId) {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc(geneProductId);
doc.taxonId = taxonId;
return doc;
}
@Test
public void filterBySingleReferenceReturnsDocumentsThatContainTheReference() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(),
AnnotationDocMocker.REFERENCE));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS));
}
@Test
public void filterBySingleReferenceReturnsOnlyDocumentsThatContainTheReferenceWhenOthersExists() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.reference = "PMID:0000002";
repository.save(doc);
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), doc.reference));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, doc.reference, 1));
}
@Test
public void filterByThreeReferencesReturnsDocumentsThatContainThoseReferences() throws Exception {
AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123");
docA.reference = "PMID:0000002";
repository.save(docA);
AnnotationDocument docB = AnnotationDocMocker.createAnnotationDoc("A0A124");
docB.reference = "PMID:0000003";
repository.save(docB);
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(),
AnnotationDocMocker.REFERENCE + "," + docA.reference + "," + docB.reference));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docB.reference, 1));
}
@Test
public void filterByThreeIndependentReferencesReturnsDocumentsThatContainThoseReferences() throws Exception {
AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123");
docA.reference = "PMID:0000002";
repository.save(docA);
AnnotationDocument docB = AnnotationDocMocker.createAnnotationDoc("A0A124");
docB.reference = "PMID:0000003";
repository.save(docB);
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(),
AnnotationDocMocker.REFERENCE).param(REF_PARAM.getName(), docA.reference)
.param(REF_PARAM.getName(), docB.reference));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docB.reference, 1));
}
@Test
public void filterByReferenceDbOnlyReturnsDocumentsWithReferencesThatStartWithThatDb() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "GO_REF"));
//This one shouldn't be found
AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123");
docA.reference = "PMID:0000002";
repository.save(docA);
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS));
}
@Test
public void filterByReferenceDbNotAvailableInDocumentsReturnsZeroResults() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "GO_LEFT"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterBySingleReferenceIdReturnsDocumentsThatContainTheReferenceId() throws Exception {
AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123");
docA.reference = "PMID:0000002";
repository.save(docA);
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "0000002"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 1))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 1))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1));
}
@Test
public void filterByMultipleReferenceIdReturnsDocumentsThatContainTheReferenceId() throws Exception {
AnnotationDocument docA = AnnotationDocMocker.createAnnotationDoc("A0A123");
docA.reference = "PMID:0000002";
repository.save(docA);
AnnotationDocument docB = AnnotationDocMocker.createAnnotationDoc("A0A124");
docB.reference = "PMID:0000003";
repository.save(docB);
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "0000002")
.param(REF_PARAM.getName(), "0000003"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS + 2))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, AnnotationDocMocker.REFERENCE, NUMBER_OF_GENERIC_DOCS))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docA.reference, 1))
.andExpect(itemExistsExpectedTimes(REFERENCE_FIELD, docB.reference, 1));
}
@Test
public void filterByUnknownReferenceIdIsUnsuccessful() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(REF_PARAM.getName(), "999999"));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterByGeneProductTypeReturnsMatchingDocuments() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(),
"protein"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS));
}
@Test
public void filterBySingleGeneProductTypeOfRnaReturnsMatchingDocument() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.geneProductType = "miRNA";
repository.save(doc);
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(), "miRNA"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1));
}
@Test
public void filterAnnotationsByTwoGeneProductTypesAsOneParameterReturnsMatchingDocuments() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.geneProductType = "complex";
repository.save(doc);
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(),
"protein,complex"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(4))
.andExpect(fieldsInAllResultsExist(4));
}
@Test
public void filterAnnotationsByTwoGeneProductTypesAsTwoParametersReturnsMatchingDocuments() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.geneProductType = "complex";
repository.save(doc);
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(),
"protein").param(GENE_PRODUCT_TYPE_PARAM.getName(), "complex"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(4))
.andExpect(fieldsInAllResultsExist(4));
}
@Test
public void filterByNonExistentGeneProductTypeReturnsNothing() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.geneProductType = "complex";
repository.save(doc);
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(GENE_PRODUCT_TYPE_PARAM.getName(), "miRNA"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterByTargetSetReturnsMatchingDocuments() throws Exception {
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "KRUK"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS));
}
@Test
public void filterByTwoTargetSetValuesReturnsMatchingDocuments() throws Exception {
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "KRUK,BHF-UCL"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS));
}
@Test
public void filterByNewTargetSetValueReturnsMatchingDocuments() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.targetSets = Collections.singletonList("Parkinsons");
repository.save(doc);
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "Parkinsons"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1));
}
@Test
public void filterByTargetSetCaseInsensitiveReturnsMatchingDocuments() throws Exception {
AnnotationDocument doc = AnnotationDocMocker.createAnnotationDoc("A0A123");
doc.targetSets = Collections.singletonList("parkinsons");
repository.save(doc);
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "PARKINSONS"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1));
}
@Test
public void filterByNonExistentTargetSetReturnsNoDocuments() throws Exception {
ResultActions response =
mockMvc.perform(get(RESOURCE_URL + "/search").param(TARGET_SET_PARAM.getName(), "CLAP"));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(0));
}
@Test
public void filterAnnotationsByGoAspectSuccessfully() throws Exception {
String goAspect = AnnotationDocMocker.GO_ASPECT;
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), goAspect));
response.andDo(print())
.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS));
}
@Test
public void filterAnnotationsByInvertedCaseGoAspectSuccessfully() throws Exception {
String goAspect = StringUtils.swapCase(AnnotationDocMocker.GO_ASPECT);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), goAspect));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(NUMBER_OF_GENERIC_DOCS))
.andExpect(fieldsInAllResultsExist(NUMBER_OF_GENERIC_DOCS));
}
@Test
public void filterAnnotationsByInvalidGoAspectReturnsError() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), "ZZZ"));
response.andExpect(status().isBadRequest());
}
@Test
public void filterWithAspectMolecularFunctionReturnsAnnotationsWithMolecularFunction() throws Exception {
String goAspect = "molecular_function";
AnnotationDocument annoDoc1 = AnnotationDocMocker.createAnnotationDoc(createGPId(999));
annoDoc1.goAspect = goAspect;
repository.save(annoDoc1);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(GO_ASPECT_PARAM.getName(), goAspect));
response.andExpect(status().isOk())
.andExpect(contentTypeToBeJson())
.andExpect(totalNumOfResults(1))
.andExpect(fieldsInAllResultsExist(1));
}
private List<AnnotationDocument> createGenericDocs(int n) {
return IntStream.range(0, n)
.mapToObj(i -> AnnotationDocMocker.createAnnotationDoc(createGPId(i))).collect
(Collectors.toList());
}
private int totalPages(int totalEntries, int resultsPerPage) {
return (int) Math.ceil(totalEntries / resultsPerPage) + 1;
}
}
|
package scrum.client.workspace;
import ilarkesto.core.scope.Scope;
import ilarkesto.gwt.client.DropdownMenuButtonWidget;
import ilarkesto.gwt.client.Gwt;
import ilarkesto.gwt.client.HyperlinkWidget;
import ilarkesto.gwt.client.SwitchingNavigatorWidget.SwitchAction;
import ilarkesto.gwt.client.TableBuilder;
import ilarkesto.gwt.client.undo.UndoButtonWidget;
import java.util.Collections;
import java.util.List;
import scrum.client.ApplicationInfo;
import scrum.client.ScrumScopeManager;
import scrum.client.admin.LogoutAction;
import scrum.client.common.AScrumAction;
import scrum.client.common.AScrumWidget;
import scrum.client.img.Img;
import scrum.client.project.ChangeProjectAction;
import scrum.client.project.Project;
import scrum.client.search.SearchInputWidget;
import scrum.client.undo.Undo;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
public class HeaderWidget extends AScrumWidget {
private SimplePanel wrapper;
private Label title;
private UndoButtonWidget undoButton;
private DropdownMenuButtonWidget switchProjectButton;
private SearchInputWidget search;
private CommunicationIndicatorWidget status;
private HTML feedback;
@Override
protected Widget onInitialization() {
setHeight100();
title = new Label("");
title.setStyleName("HeaderWidget-title");
status = new CommunicationIndicatorWidget();
undoButton = new UndoButtonWidget();
switchProjectButton = new DropdownMenuButtonWidget();
switchProjectButton.setLabel("Switch Project");
search = new SearchInputWidget();
feedback = new HTML("<a href='http://kunagi.org/support.html' target='blank'>Support/Feedback</a>");
wrapper = Gwt.createDiv("HeaderWidget", title);
return wrapper;
}
@Override
protected void onUpdate() {
boolean projectOpen = ScrumScopeManager.isProjectScope();
undoButton.setUndoManager(null);
ApplicationInfo applicationInfo = getApp().getApplicationInfo();
if (applicationInfo != null) {
title.setText(applicationInfo.getName());
title.setTitle(applicationInfo.getVersionDescription());
}
if (projectOpen) {
switchProjectButton.clear();
switchProjectButton.addAction("ProjectSelectorLink", new AScrumAction() {
@Override
public String getLabel() {
return "Project Selector";
}
@Override
protected void onExecute() {
getNavigator().gotoProjectSelector();
}
});
switchProjectButton.addSeparator();
List<Project> projects = getDao().getProjects();
Collections.sort(projects, Project.LAST_OPENED_COMPARATOR);
for (Project p : projects) {
if (p == getCurrentProject()) continue;
switchProjectButton.addAction("QuickLinks", new ChangeProjectAction(p));
}
}
TableBuilder tb = new TableBuilder();
tb.setCellPadding(2);
tb.setColumnWidths("70px", "", "", "", "200px", "60px", "100px", "50px");
Widget searchWidget = projectOpen ? search : Gwt.createEmptyDiv();
Widget undoWidget = projectOpen ? undoButton : Gwt.createEmptyDiv();
// Widget changeProjectWidget = projectOpen ? new HyperlinkWidget(new ChangeProjectAction()) : Gwt
// .createEmptyDiv();
Widget changeProjectWidget = projectOpen ? switchProjectButton : Gwt.createEmptyDiv();
tb.add(createLogo(), status, createCurrentUserWidget(), searchWidget, feedback, undoWidget,
changeProjectWidget, new HyperlinkWidget(new LogoutAction()));
wrapper.setWidget(tb.createTable());
super.onUpdate();
}
private Widget createCurrentUserWidget() {
boolean loggedIn = getAuth().isUserLoggedIn();
if (!loggedIn) return Gwt.createEmptyDiv();
ProjectWorkspaceWidgets widgets = Scope.get().getComponent(ProjectWorkspaceWidgets.class);
if (!ScrumScopeManager.isProjectScope()) return new Label(createCurrentUserText());
SwitchAction action = widgets.getSidebar().getNavigator().createSwitchAction(widgets.getProjectUserConfig());
action.setLabel(createCurrentUserText());
return new HyperlinkWidget(action);
}
private String createCurrentUserText() {
boolean loggedIn = getAuth().isUserLoggedIn();
StringBuilder text = new StringBuilder();
if (loggedIn) {
text.append(getCurrentUser().getName());
if (ScrumScopeManager.isProjectScope()) {
text.append(getCurrentProject().getUsersRolesAsString(getCurrentUser(), " (", ")"));
text.append(" @ " + getCurrentProject().getLabel());
undoButton.setUndoManager(Scope.get().getComponent(Undo.class).getManager());
}
}
return text.toString();
}
private Widget createLogo() {
SimplePanel div = Gwt.createDiv("HeaderWidget-logo", Img.bundle.logo25().createImage());
ApplicationInfo applicationInfo = getApp().getApplicationInfo();
if (applicationInfo != null) div.setTitle(applicationInfo.getVersionDescription());
return div;
}
}
|
package uk.ac.ebi.quickgo.annotation.controller;
import uk.ac.ebi.quickgo.annotation.AnnotationREST;
import uk.ac.ebi.quickgo.annotation.common.AnnotationRepository;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocMocker;
import uk.ac.ebi.quickgo.annotation.common.document.AnnotationDocument;
import uk.ac.ebi.quickgo.annotation.model.AnnotationRequest;
import uk.ac.ebi.quickgo.annotation.service.search.SearchServiceConfig;
import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.ClassRule;
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.http.MediaType;
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.ResultActions;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasSize;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {AnnotationREST.class})
@WebAppConfiguration
public class AnnotationControllerIT {
// temporary data store for solr's data, which is automatically cleaned on exit
@ClassRule
public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore();
private static final String UNAVAILABLE_ASSIGNED_BY = "ZZZZZ";
private static final String ASSIGNED_BY_PARAM = "assignedBy";
private static final String PAGE_PARAM = "page";
private static final String LIMIT_PARAM = "limit";
private static final String WITHFROM_PARAM= "withFrom";
private static final List<String> VALID_ASSIGNED_BY_PARMS = Arrays.asList("ASPGD", "ASPGD,Agbase", "ASPGD_,Agbase",
"ASPGD,Agbase_", "ASPGD,Agbase", "BHF-UCL,Agbase", "Roslin_Institute,BHF-UCL,Agbase");
private static final List<String> INVALID_ASSIGNED_BY_PARMS =
Arrays.asList("_ASPGD", "ASPGD,_Agbase", "5555,Agbase",
"ASPGD,5555,", "4444,5555,");
private MockMvc mockMvc;
private String savedAssignedBy;
private List<AnnotationDocument> basicDocs;
private static final String RESOURCE_URL = "/QuickGO/services/annotation";
@Autowired
protected WebApplicationContext webApplicationContext;
@Autowired
protected AnnotationRepository annotationRepository;
@Before
public void setup() {
annotationRepository.deleteAll();
mockMvc = MockMvcBuilders.
webAppContextSetup(webApplicationContext)
.build();
basicDocs = createBasicDocs();
assertThat(basicDocs.size(), is(greaterThan(1)));
savedAssignedBy = basicDocs.get(0).assignedBy;
annotationRepository.save(basicDocs);
}
@Test
public void lookupAnnotationFilterByAssignedBySuccessfully() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(1))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void lookupAnnotationFilterByMultipleAssignedBySuccessfully() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, basicDocs.get(0).assignedBy + ","
+ basicDocs.get(1).assignedBy));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(2))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void lookupAnnotationFilterByRepetitionOfParmsSuccessfully() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, basicDocs.get(0).assignedBy)
.param(ASSIGNED_BY_PARAM, basicDocs.get(1).assignedBy)
.param(ASSIGNED_BY_PARAM, basicDocs.get(3).assignedBy));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(3))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void lookupAnnotationFilterByInvalidAssignedBy() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(0))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void lookupAnnotationFilterByMultipleAssignedByOneCorrectAndOneUnavailable() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, UNAVAILABLE_ASSIGNED_BY + ","
+ basicDocs.get(1).assignedBy));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(1))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void allTheseValuesForAssignedShouldNotThrowAnError() throws Exception {
for (String validAssignedBy : VALID_ASSIGNED_BY_PARMS) {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, validAssignedBy));
expectResultsInfoExists(response)
.andExpect(status().isOk());
}
}
@Test
public void allTheseValuesForAssignedShouldThrowAnError() throws Exception {
for (String inValidAssignedBy : INVALID_ASSIGNED_BY_PARMS) {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, inValidAssignedBy));
response.andDo(print())
.andExpect(status().isBadRequest());
}
}
@Test
public void retrievesSecondPageOfAllEntriesRequest() throws Exception {
annotationRepository.deleteAll();
annotationRepository.save(createAndSaveDocs(60));
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy)
.param(PAGE_PARAM, "2"));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.results").isArray())
.andExpect(jsonPath("$.results", hasSize(AnnotationRequest.DEFAULT_ENTRIES_PER_PAGE)));
}
@Test
public void pageRequestEqualToAvailablePagesReturns200() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy).param(PAGE_PARAM, "1"));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(1))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void pageRequestOfZeroAndResultsAvailableReturns400() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy).param(PAGE_PARAM, "0"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void pageRequestHigherThanAvailablePagesReturns400() throws Exception {
annotationRepository.deleteAll();
int existingPages = 4;
createAndSaveDocs(SearchServiceConfig.MAX_PAGE_RESULTS * existingPages);
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy)
.param(PAGE_PARAM, String.valueOf(existingPages + 1)));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void successfulLookupWithFromForSingleId()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM, "InterPro:IPR015421"));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(basicDocs.size()))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void successfulLookupWithFromForMultipleValues()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM,
"InterPro:IPR015421,InterPro:IPR015422"));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(basicDocs.size()))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void searchingForUnknownWithFromBringsBackNoResults()throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(WITHFROM_PARAM, "XXX:54321"));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(0))
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void limitForPageExceedsMaximumAllowed() throws Exception {
annotationRepository.deleteAll();
annotationRepository.save(createAndSaveDocs(60));
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy)
.param(LIMIT_PARAM, "101"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
@Test
public void limitForPageWithinMaximumAllowed() throws Exception {
ResultActions response = mockMvc.perform(
get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy).param(LIMIT_PARAM, "100"));
expectResultsInfoExists(response)
.andExpect(jsonPath("$.numberOfHits").value(1))
.andExpect(jsonPath("$.results.*").exists())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(status().isOk());
}
@Test
public void limitForPageThrowsErrorWhenNegative() throws Exception {
ResultActions response = mockMvc.perform(get(RESOURCE_URL + "/search").param(ASSIGNED_BY_PARAM, savedAssignedBy)
.param(LIMIT_PARAM, "-20"));
response.andDo(print())
.andExpect(status().isBadRequest());
}
/**
* TESTING RESULTS
*/
private ResultActions expectResultsInfoExists(ResultActions result) throws Exception {
return expectFieldsInResults(result)
.andDo(print())
.andExpect(status().isOk())
.andExpect(jsonPath("$.pageInfo").exists())
.andExpect(jsonPath("$.pageInfo.resultsPerPage").exists())
.andExpect(jsonPath("$.pageInfo.total").exists())
.andExpect(jsonPath("$.pageInfo.current").exists());
}
private ResultActions expectFieldsInResults(ResultActions result) throws Exception {
int index = 0;
for (int i = 0; i > basicDocs.size(); i++) {
expectFields(result, "$.results[" + index++ + "].");
}
return result;
}
private void expectFields(ResultActions result, String path) throws Exception {
result
.andExpect(jsonPath(path + "id").exists())
.andExpect(jsonPath(path + "geneProductId").exists())
.andExpect(jsonPath(path + "qualifier").exists())
.andExpect(jsonPath(path + "goId").exists())
.andExpect(jsonPath(path + "goEvidence").exists())
.andExpect(jsonPath(path + "ecoId").exists())
.andExpect(jsonPath(path + "reference").exists())
.andExpect(jsonPath(path + "withFrom").exists())
.andExpect(jsonPath(path + "taxonId").exists())
.andExpect(jsonPath(path + "assignedBy").exists())
.andExpect(jsonPath(path + "extension").exists());
}
/**
* Create some
*/
private List<AnnotationDocument> createBasicDocs() {
return Arrays.asList(
AnnotationDocMocker.createAnnotationDoc("A0A000"),
AnnotationDocMocker.createAnnotationDoc("A0A001", "ASPGD"),
AnnotationDocMocker.createAnnotationDoc("A0A001", "BHF-UCL"),
AnnotationDocMocker.createAnnotationDoc("A0A002", "AGPRD"));
}
private List<AnnotationDocument> createAndSaveDocs(int n) {
return IntStream.range(0, n)
.mapToObj(i -> AnnotationDocMocker.createAnnotationDoc(createId(i))).collect
(Collectors.toList());
}
private String createId(int idNum) {
return String.format("A0A%03d", idNum);
}
}
|
package com.google.sps.data;
import java.util.List;
import java.util.LinkedList;
import java.util.Arrays;
import java.io.Serializable;
import java.net.URL;
import java.util.logging.Logger;
import com.google.maps.GeoApiContext;
import com.google.maps.PlacesApi;
import com.google.maps.NearbySearchRequest;
import com.google.maps.model.LatLng;
import com.google.maps.model.LocationType;
import com.google.maps.model.Photo;
import com.google.maps.model.PlaceType;
import com.google.maps.model.RankBy;
import com.google.maps.model.Geometry;
import com.google.maps.model.PlacesSearchResponse;
import com.google.maps.model.PlacesSearchResult;
import java.util.logging.Logger;
import java.util.Iterator;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.SortDirection;
/** BusinessesService object representing all businesses
* components of the webapp.
**/
public class BusinessesService {
private List<Listing> smallBusinesses;
private final String KEY = "REDACTED";
private final static Logger LOGGER =
Logger.getLogger(BusinessesService.class.getName());
private final int ALLOWED_SEARCH_REQUESTS = 3;
/** Create a new Businesses instance
* @param smallBusinesses businesses from SmallCityService
**/
public BusinessesService(List<Listing> smallBusinesses) {
this.smallBusinesses = smallBusinesses;
}
public PreparedQuery getBigBusinessFromDatabase(){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query query = new Query("BigBusinesses");
PreparedQuery queryOfDatabase = datastore.prepare(query);
return queryOfDatabase;
}
public List<Listing> removeBigBusinessesFromResults(PreparedQuery queryOfDatabase){
Iterator<Listing> businesses = smallBusinesses.iterator();
Entity entity;
String businessName;
while (businesses.hasNext()) {
Listing currentBusiness = businesses.next();
Iterator<Entity> bigBusinessEntities = queryOfDatabase.asIterator();
while(bigBusinessEntities.hasNext()) {
entity = bigBusinessEntities.next();
businessName = (String) entity.getProperty("business");
if(businessName.equals(currentBusiness.getName())) {
businesses.remove();
}
}
}
return smallBusinesses;
}
public void setAllBusinesses(List<Listing> allBusinesses) {
smallBusinesses = allBusinesses;
}
public List<Listing> getBusinessesFromPlacesApi(User user) {
LatLng latLng =
new LatLng(user.getGeolocation().lat, user.getGeolocation().lng);
final GeoApiContext context = new GeoApiContext.Builder()
.apiKey(KEY)
.build();
NearbySearchRequest request = PlacesApi.nearbySearchQuery(context, latLng);
try {
PlacesSearchResponse response = request.type(PlaceType.STORE)
.rankby(RankBy.DISTANCE)
.await();
for (int i=0; i<ALLOWED_SEARCH_REQUESTS; i++) {
for(PlacesSearchResult place : response.results) {
addListingToBusinesses(place);
}
Thread.sleep(2000); // Required delay before next API request
response = PlacesApi
.nearbySearchNextPage(context, response.nextPageToken).await();
}
} catch(Exception e) {
LOGGER.warning(e.getMessage());
}
return smallBusinesses;
}
private void addListingToBusinesses(PlacesSearchResult place) {
String name = place.name;
String formattedAddress = place.vicinity;
Geometry geometry = place.geometry;
MapLocation placeLocation =
new MapLocation(geometry.location.lat, geometry.location.lng);
double rating = place.rating;
Photo photos[] = place.photos;
String types[] = place.types;
smallBusinesses.add(new Listing(name, formattedAddress,
placeLocation, rating, photos, types));
}
}
|
package com.gallatinsystems.device.dao;
import java.util.Date;
import java.util.logging.Logger;
import com.gallatinsystems.device.domain.Device;
import com.gallatinsystems.device.domain.Device.DeviceType;
import com.gallatinsystems.framework.dao.BaseDAO;
/**
* data access object for devices.
*
* @author Christopher Fagiani
*
*/
public class DeviceDAO extends BaseDAO<Device> {
private static final String NO_IMEI = "NO_IMEI";
@SuppressWarnings("unused")
private static final Logger log = Logger.getLogger(DeviceDAO.class
.getName());
public DeviceDAO() {
super(Device.class);
}
/**
* gets a single device by phoneNumber. If phone number is not unique (this
* shouldn't happen), it returns the first instance found.
*
* @param phoneNumber
* @return
*/
public Device get(String phoneNumber) {
return super.findByProperty("phoneNumber", phoneNumber, STRING_TYPE);
}
/**
* gets a single device by imei/esn. If phone number is not unique (this
* shouldn't happen), it returns the first instance found.
*
* @param imei
* @return
*/
public Device getByImei(String imei) {
if (NO_IMEI.equals(imei)) {
// WiFi only devices could have "NO_IMEI" as value
// We want to fall back to search by `phoneNumber` (MAC address)
return null;
}
return super.findByProperty("esn", imei, STRING_TYPE);
}
/**
* updates the device's last known position
*
* @param phoneNumber
* @param lat
* @param lon
* @param accuracy
* @param version
* @param deviceIdentifier
* @param imei
*/
public void updateDeviceLocation(String phoneNumber, Double lat,
Double lon, Double accuracy, String version,
String deviceIdentifier, String imei, String osVersion) {
Device d = null;
if (imei != null) { // New Apps from 1.10.0 and on provide IMEI/ESN
d = getByImei(imei);
}
if (d == null) {
d = get(phoneNumber); // Fall back to less-stable ID
}
if (d == null) {
// if device is null, we have to create it
d = new Device();
d.setCreatedDateTime(new Date());
d.setDeviceType(DeviceType.CELL_PHONE_ANDROID);
d.setPhoneNumber(phoneNumber);
}
if (lat != null && lon != null) {
d.setLastKnownLat(lat);
d.setLastKnownLon(lon);
d.setLastKnownAccuracy(accuracy);
}
if (deviceIdentifier != null) {
d.setDeviceIdentifier(deviceIdentifier);
}
if (imei != null && !NO_IMEI.equals(imei)) {
d.setEsn(imei);
}
if (osVersion != null) {
d.setOsVersion(osVersion);
}
d.setLastLocationBeaconTime(new Date());
d.setGallatinSoftwareManifest(version);
save(d);
}
}
|
package skyhussars.engine.plane;
import skyhussars.engine.weapons.Bullet;
import skyhussars.engine.weapons.ProjectileManager;
import com.jme3.math.Quaternion;
import com.jme3.math.Ring;
import com.jme3.math.Vector3f;
import java.util.Random;
public class GunLocation {
private int rounds;
private ProjectileManager projectileManager;
private final Random random;
private final Vector3f location;
private final float muzzleVelocity;
private final float spread;
private final float rof;
public GunLocation(GunLocationDescriptor gunLocationDescriptor, int rounds, ProjectileManager projectileManager) {
/*should check if rounnds > maxRounds*/
this.rounds = rounds;
this.projectileManager = projectileManager;
this.random = new Random();
this.location = gunLocationDescriptor.getLocation();
this.muzzleVelocity = gunLocationDescriptor.getGunDescriptor().getMuzzleVelocity();
this.spread = gunLocationDescriptor.getGunDescriptor().getSpread();
this.rof = gunLocationDescriptor.getGunDescriptor().getRateOfFire();
}
public Vector3f addSpread(Vector3f vVelocity) {
float locSpread = spread * (float) random.nextGaussian() * vVelocity.length() / 100f;
return new Ring(vVelocity, vVelocity.normalize(), locSpread, locSpread).random();
}
public void firing(boolean firing, Vector3f vLocation, Vector3f vVelocity, Quaternion vOrientation) {
if (firing) {
Vector3f vBulletLocation = vLocation.add(vOrientation.mult(location));
Vector3f vMuzzleVelocity = vOrientation.mult(Vector3f.UNIT_Z).mult(muzzleVelocity);
Vector3f vBulletVelocity = addSpread(vVelocity.add(vMuzzleVelocity));
Bullet bullet = new Bullet(vBulletLocation, vBulletVelocity);
projectileManager.addProjectile(bullet);
}
}
}
|
package de.nebur97.git.gw2api.manager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
/**
* This class provides features to manage items and recipes.
* @author NeBuR97
**/
public abstract class Manager<T> implements Serializable
{
private static final long serialVersionUID = 1958428812706515101L;
protected HashMap<Integer, T> entryIDs = new HashMap<Integer, T>();
protected transient int finishedThreads = 0;
protected transient int idsToLoad;
protected transient boolean isLoading = false;
protected transient int neededThreads = 0;
protected transient int threadCount = (int) Math.pow(2, Runtime.getRuntime().availableProcessors());
/**
* Adds an entry.
* @param obj
*/
public synchronized void add(T obj)
{
entryIDs.put(((EntryWithID) obj ).getID(), obj);
}
/**
* Get an element via it's id. Returns null if no element is present (although the map may contain a null value, I believe recipes and items will never be null, thus making null a definitive return type).
* @param id
* @return The entry with the given id or null if no such element is present.
*/
public synchronized T get(int id)
{
return entryIDs.get(id);
}
/**
* Gets a list of all entries.
* @return an arraylist of all entries.
*/
public synchronized ArrayList<T> getEntryList()
{
return new ArrayList<T>(entryIDs.values());
}
public int getFinishedThreads()
{
return finishedThreads;
}
/**
* Get the threadcount
* @return this manager's threadcount
*/
public int getThreadCount()
{
return threadCount;
}
/**
* Checks if the map contains this id (contained in the map = loaded).
* @param id
* @return true if the entry is present and loaded.
* @see #isLoaded(Object)
*/
public synchronized boolean isLoaded(int id)
{
return entryIDs.containsKey(id);
}
/**
* Checks, if an object is already in the entry map (contained in the map = loaded).
* @param obj
* @return true if the entry is loaded
*/
public boolean isLoaded(T obj)
{
return entryIDs.containsValue(obj);
}
/**
* Check if this manager is loading.
* @return isLoading
*/
public boolean isLoading()
{
synchronized(this) {
return isLoading;
}
}
/**
* Load the ids contained in the collection. This method is non-blocking because it utilizes threads to load the entries.<br>
* The amount of threads is specified by {@link #setThreadCount(int)} or defaults to 2^{@link Runtime#availableProcessors()}
* @param ids - The collection containing the ids to load.
*/
abstract public void load(Collection<Integer> ids);
/**
* Set the amount of threads to use.
* @param threads
* @throws Exception - When threads are currently running
*/
public void setThreadCount(int threads) throws Exception
{
if( !isLoading()) {
threadCount = threads;
} else {
throw new Exception("You cannot change the threadcount while threads are running!");
}
}
}
|
package sm.tools.veda_client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class VedaConnection
{
public static final int STORAGE = 1;
public static final int ACL = 2;
public static final int FULL_TEXT_INDEXER = 4;
public static final int FANOUT_EMAIL = 8;
public static final int SCRIPTS = 16;
public static final int FANOUT_SQL = 32;
public static final int USER_MODULES_TOOL = 64;
public VedaConnection(String _url, String user, String pass) throws IOException
{
jp = new JSONParser();
destination = _url;
vedaTicket = getVedaTicket(user, pass);
if ((vedaTicket == null) || (vedaTicket.length() < 1))
{
System.out.println("Destination.Veda.Login filed");
_isOk = false;
} else {
_isOk = true;
}
}
public boolean isOk()
{
return _isOk;
}
String destination;
String vedaTicket;
boolean _isOk = false;
JSONParser jp;
public long count_put = 0;
public int setIndividual(Individual indv, boolean isPrepareEvent, int assignedSubsystems) throws InterruptedException
{
String jsn = indv.toJsonStr();
String ijsn = "{\"@\":\"" + indv.getUri() + "\"," + jsn + "}";
int res = setJson(ijsn, isPrepareEvent, assignedSubsystems);
return res;
}
private int setJson(String jsn, boolean isPrepareEvent, int assignedSubsystems) throws InterruptedException
{
if (jsn.indexOf("\\") >= 0)
{
int len = jsn.length();
StringBuffer new_str_buff = new StringBuffer();
for (int idx = 0; idx < jsn.length(); idx++)
{
char ch1 = jsn.charAt(idx);
new_str_buff.append(ch1);
if (ch1 == '\\')
{
char ch2 = 0;
if (idx < len - 1)
ch2 = jsn.charAt(idx + 1);
if (ch2 != 'n' && ch2 != 'b' && ch2 != '"' && ch2 != '\\')
{
new_str_buff.append('\\');
}
if (ch2 == '\\')
{
new_str_buff.append(ch2);
idx++;
}
}
}
jsn = new_str_buff.toString();
}
int res = 429;
int count_wait = 0;
while (res == 429)
{
//String query = "{\"ticket\":\"" + vedaTicket + "\", \"individual\":" + jsn + ", \"prepare_events\":" + isPrepareEvent
// + ", \"event_id\":\"\", " + "\"transaction_id\":\"\" }";
// String query=String.format("{\"ticket\":\"%s\", \"individual\":%s, \"prepare_events\": %b, \"event_id\":\"\", \"transaction_id\":\"\","
// + "\"assigned_subsystems\":%d }", vedaTicket, jsn, isPrepareEvent, assignedSubsystems);
String query=String.format("{\"individual\":%s, \"prepare_events\": %b, \"event_id\":\"\", \"transaction_id\":\"\","
+ "\"assigned_subsystems\":%d }", jsn, isPrepareEvent, assignedSubsystems);
// System.out.println(query);
res = util.excutePut(destination + "/set_in_individual?ticket=" + vedaTicket, query);
if (res != 200)
{
if (res == 429)
{
Thread.sleep(10);
count_wait++;
}
} else
{
count_put++;
}
if (count_wait == 1)
System.out.print(".");
}
return res;
}
public int putIndividual(Individual indv, boolean isPrepareEvent, int assignedSubsystems) throws InterruptedException
{
String jsn = indv.toJsonStr();
String ijsn = "{\"@\":\"" + indv.getUri() + "\"," + jsn + "}";
int res = putJson(ijsn, isPrepareEvent, assignedSubsystems);
return res;
}
public int putJson(String jsn, boolean isPrepareEvent, int assignedSubsystems) throws InterruptedException
{
if (jsn.indexOf("\\") >= 0)
{
int len = jsn.length();
StringBuffer new_str_buff = new StringBuffer();
for (int idx = 0; idx < jsn.length(); idx++)
{
char ch1 = jsn.charAt(idx);
new_str_buff.append(ch1);
if (ch1 == '\\')
{
char ch2 = 0;
if (idx < len - 1)
ch2 = jsn.charAt(idx + 1);
if (ch2 != 'n' && ch2 != 'b' && ch2 != '"' && ch2 != '\\')
{
new_str_buff.append('\\');
}
if (ch2 == '\\')
{
new_str_buff.append(ch2);
idx++;
}
}
}
jsn = new_str_buff.toString();
}
int res = 429;
int count_wait = 0;
while (res == 429)
{
//String query = "{\"ticket\":\"" + vedaTicket + "\", \"individual\":" + jsn + ", \"prepare_events\":" + isPrepareEvent
// + ", \"event_id\":\"\", " + "\"transaction_id\":\"\" }";
// String query=String.format("{\"ticket\":\"%s\", \"individual\":%s, \"prepare_events\": %b, \"event_id\":\"\", \"transaction_id\":\"\","
// + "\"assigned_subsystems\":%d }", vedaTicket, jsn, isPrepareEvent, assignedSubsystems);
String query=String.format("{\"individual\":%s, \"prepare_events\": %b, \"event_id\":\"\", \"transaction_id\":\"\","
+ "\"assigned_subsystems\":%d }", jsn, isPrepareEvent, assignedSubsystems);
// System.out.println(query);
res = util.excutePut(destination + "/put_individual?ticket=" + vedaTicket, query);
if (res != 200)
{
if (res == 429)
{
Thread.sleep(10);
count_wait++;
}
} else
{
count_put++;
}
if (count_wait == 1)
System.out.print(".");
}
return res;
}
public String uploadFile(byte[] data, String path, String fileName) throws ClientProtocolException, IOException {
String uri = DigestUtils.shaHex(data);
CloseableHttpClient httpClient = null;
try {
httpClient = HttpClients.createDefault();
BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("ticket", vedaTicket);
cookieStore.addCookie(cookie);
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
HttpPost uploadFile = new HttpPost(destination+"/files");
uploadFile.addHeader("accept-encoding", "identity");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("file", data, ContentType.DEFAULT_BINARY, fileName);
builder.addTextBody("uri", uri, ContentType.TEXT_PLAIN);
builder.addTextBody("path", path, ContentType.TEXT_PLAIN);
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
System.out.println("uploadFile: "+uploadFile.getURI());
CloseableHttpResponse response = httpClient.execute(uploadFile, context);
System.out.println("response: "+response.toString());
HttpEntity responseEntity = response.getEntity();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
String line = null;
while((line = reader.readLine()) != null) {
System.out.println("UPLOAD FILE: " + line);
}
} finally {
if (reader != null) {
reader.close();
}
}
} finally {
if (httpClient != null) {
httpClient.close();
}
}
return uri;
}
public String getVedaTicket(String user, String pass) throws IOException
{
String query = destination + "/authenticate?login=" + user + "&password=" + pass;
System.out.println("ticketQuery="+query);
String res = util.excuteGet(query);
System.out.println(res);
try
{
JSONObject oo = (JSONObject) jp.parse(res);
return (String) oo.get("id");
} catch (Exception ex)
{
//ex.printStackTrace();
}
return null;
}
public String[] query(String query, String param) throws UnsupportedEncodingException, Exception {
String[] res_arr;
String res = util.excuteGet(destination + "/query?ticket=" + vedaTicket + "&"+param+"&query=" + URLEncoder.encode(query,"UTF-8"));
// System.out.println(res);
try
{
Object oo_res = jp.parse(res);
if (oo_res instanceof JSONObject)
{
Object oo = ((JSONObject) oo_res).get("result");
if (oo instanceof JSONArray)
{
JSONArray arr = (JSONArray) oo;
res_arr = new String[arr.size()];
arr.toArray(res_arr);
return res_arr;
}
}
return null;
} catch (Exception ex)
{
//ex.printStackTrace();
}
return null;
}
public String[] query(String query) throws IOException
{
String[] res_arr;
String res = util.excuteGet(destination + "/query?ticket=" + vedaTicket + "&query=" + URLEncoder.encode(query,"UTF-8"));
// System.out.println(res);
try
{
Object oo_res = jp.parse(res);
if (oo_res instanceof JSONObject)
{
Object oo = ((JSONObject) oo_res).get("result");
if (oo instanceof JSONArray)
{
JSONArray arr = (JSONArray) oo;
res_arr = new String[arr.size()];
arr.toArray(res_arr);
return res_arr;
}
}
return null;
} catch (Exception ex)
{
//ex.printStackTrace();
}
return null;
}
public Individual getIndividual(String uri) throws IOException
{
String res = util.excuteGet(destination + "/get_individual?ticket=" + vedaTicket + "&uri=" + uri);
if (res == null)
return null;
// System.out.println(res);
try
{
JSONObject oo = (JSONObject) jp.parse(res);
return new Individual(oo);
} catch (Exception ex)
{
//ex.printStackTrace();
}
return null;
}
public static void copy(Individual src, Individual dest, String field_name, int new_type)
{
Resources rsz = src.getResources(field_name);
if (rsz != null)
{
for (Resource rs : rsz.resources)
{
if (new_type > 0)
dest.addProperty(field_name, rs.getData(), new_type);
else
dest.addProperty(field_name, rs.getData(), rs.getType());
}
}
}
}
|
package com.touchableheroes.drafts.spacerx.spacerx.examples.step2;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.touchableheroes.drafts.db.cupboard.xt.loader.ContractLoaderCallback;
import com.touchableheroes.drafts.db.cupboard.xt.loader.impl.SimpleContractLoader;
import com.touchableheroes.drafts.spacerx.spacerx.R;
import com.touchableheroes.drafts.spacerx.spacerx.examples.step1.ExampleAppStateKey;
import com.touchableheroes.drafts.spacerx.spacerx.examples.step2.model.ContentProviderApiContract;
import com.touchableheroes.drafts.spacerx.ui.FragmentBinder;
import com.touchableheroes.drafts.spacerx.ui.UIUpdater;
import java.io.Serializable;
public class GameItemFragment
extends Fragment {
private final Binder binder;
private final GameItemRecyclerViewAdapter adapter;
private SimpleContractLoader loaderMgr;
class Binder extends FragmentBinder {
public Binder(final Fragment src) {
super(src);
}
@Override
public void bind() {
/*
bind(R.id.gamez_list)
.value( ExampleAppStateKey.LOADER_ALL_GAMEZ_COUNT )
.updater(new UIUpdater() {
@Override
public void update(final View view,
final Serializable serializable) {
}
});
*/
}
@Override
public void init(final Context context) {
;
}
};
public GameItemFragment() {
adapter = new GameItemRecyclerViewAdapter();
binder = new Binder(this);
}
@Override
public View onCreateView(
final LayoutInflater inflater,
final ViewGroup container,
final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_game_item_list, container, false);
// Set the adapter
if (view instanceof RecyclerView) {
Context context = view.getContext();
RecyclerView recyclerView = (RecyclerView) view;
recyclerView.setAdapter( adapter );
}
return view;
}
@Override
public void onViewCreated(
final View view, @Nullable
final Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
this.loaderMgr = new SimpleContractLoader(
getLoaderManager(),
this.getContext());
final String[] args = null;
loaderMgr.load(
new ContractLoaderCallback(
ContentProviderApiContract.All_GAMEZ,
args) {
@Override
public void onLoadFinished(
final Object data) {
updateListData( (Cursor) data );
}
});
binder.bind();
}
protected void updateListData(final Cursor data) {
System.out.println( ">>> update cursor data in view..." );
adapter.updateData( new GameItemRecyclerViewAdapter.ListImpl(data) );
}
}
|
package com.googlecode.jsu.util;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericEntityException;
import org.ofbiz.core.entity.GenericValue;
import com.atlassian.core.user.GroupUtils;
import com.atlassian.core.user.UserUtils;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.ManagerFactory;
import com.atlassian.jira.config.properties.APKeys;
import com.atlassian.jira.config.properties.ApplicationProperties;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.IssueConstant;
import com.atlassian.jira.issue.IssueFieldConstants;
import com.atlassian.jira.issue.IssueRelationConstants;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.customfields.CustomFieldType;
import com.atlassian.jira.issue.customfields.view.CustomFieldParams;
import com.atlassian.jira.issue.customfields.view.CustomFieldParamsImpl;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.fields.Field;
import com.atlassian.jira.issue.fields.FieldManager;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutItem;
import com.atlassian.jira.issue.fields.layout.field.FieldLayoutStorageException;
import com.atlassian.jira.issue.fields.screen.FieldScreen;
import com.atlassian.jira.issue.resolution.Resolution;
import com.atlassian.jira.issue.status.Status;
import com.atlassian.jira.issue.util.IssueChangeHolder;
import com.atlassian.jira.issue.worklog.WorkRatio;
import com.atlassian.jira.project.version.Version;
import com.atlassian.jira.project.version.VersionManager;
import com.atlassian.jira.workflow.WorkflowActionsBean;
import com.opensymphony.user.EntityNotFoundException;
import com.opensymphony.user.Group;
import com.opensymphony.user.User;
import com.opensymphony.workflow.loader.ActionDescriptor;
/**
* @author Gustavo Martin.
*
* This utils class exposes common methods to custom workflow objects.
*
*/
public class WorkflowUtils {
public static final String SPLITTER = "@@";
public static final String CONDITION_MAJOR = ">";
public static final String CONDITION_MAJOR_EQUAL = ">=";
public static final String CONDITION_EQUAL = "=";
public static final String CONDITION_MINOR_EQUAL = "<=";
public static final String CONDITION_MINOR = "<";
public static final String CONDITION_DIFFERENT = "!=";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String COMPARISON_TYPE_STRING = "String";
public static final String COMPARISON_TYPE_NUMBER = "Number";
public static final String COMPARISON_TYPE_DATE = "Date";
private static final WorkflowActionsBean workflowActionsBean = new WorkflowActionsBean();
public static final String CASCADING_SELECT_TYPE = "com.atlassian.jira.plugin.system.customfieldtypes:cascadingselect";
private static final Logger log = Logger.getLogger(WorkflowUtils.class);
/**
* @return a list of boolean values.
*/
public static List<String> getBooleanList() {
List<String> booleanList = new ArrayList<String>();
booleanList.add(BOOLEAN_YES);
booleanList.add(BOOLEAN_NO);
return booleanList;
}
/**
* @return a list of comparison types.
*/
public static List<String> getComparisonList() {
List<String> comparisonList = new ArrayList<String>();
comparisonList.add(COMPARISON_TYPE_STRING);
comparisonList.add(COMPARISON_TYPE_NUMBER);
// Not implemented yet.
//comparisonList.add(COMPARISON_TYPE_DATE);
return comparisonList;
}
/**
* @return a list of conditions types.
*/
public static List<String> getConditionList() {
List<String> conditionList = new ArrayList<String>();
conditionList.add(CONDITION_MAJOR);
conditionList.add(CONDITION_MAJOR_EQUAL);
conditionList.add(CONDITION_EQUAL);
conditionList.add(CONDITION_MINOR_EQUAL);
conditionList.add(CONDITION_MINOR);
conditionList.add(CONDITION_DIFFERENT);
return conditionList;
}
/**
* @param condition
* @return a String with the description from given condition.
*/
public static String getConditionString(String condition) {
String retVal = null;
if (condition.equals(CONDITION_MINOR))
retVal = "minor to";
if (condition.equals(CONDITION_MINOR_EQUAL))
retVal = "minor or equal to";
if (condition.equals(CONDITION_EQUAL))
retVal = "equal to";
if (condition.equals(CONDITION_MAJOR_EQUAL))
retVal = "greater or equal than";
if (condition.equals(CONDITION_MAJOR))
retVal = "greater than";
if (condition.equals(CONDITION_DIFFERENT))
retVal = "different to";
return retVal;
}
/**
* @param key
* @return a String with the field name from given key.
*/
public static String getFieldNameFromKey(String key) {
return getFieldFromKey(key).getName();
}
/**
* @param key
* @return a Field object from given key. (Field or Custom Field).
*/
public static Field getFieldFromKey(String key) {
FieldManager fieldManager = ManagerFactory.getFieldManager();
Field field;
if (fieldManager.isCustomField(key)) {
field = fieldManager.getCustomField(key);
} else {
field = fieldManager.getField(key);
}
if (field == null) {
throw new IllegalArgumentException("Unable to find field '" + key + "'");
}
return field;
}
/**
* @param issue
* an issue object.
* @param field
* a field object. (May be a Custom Field)
* @return an Object
*
* It returns the value of a field within issue object. May be a Collection,
* a List, a Strong, or any FildType within JIRA.
*
*/
public static Object getFieldValueFromIssue(Issue issue, Field field) {
FieldManager fldManager = ManagerFactory.getFieldManager();
Object retVal = null;
try {
if (fldManager.isCustomField(field)) {
// Return the CustomField value. It could be any object.
CustomField customField = (CustomField) field;
Object value = issue.getCustomFieldValue(customField);
// TODO Maybe for cascade we have to create separate manager
if (CASCADING_SELECT_TYPE.equals(customField.getCustomFieldType().getKey())) {
CustomFieldParams params = (CustomFieldParams) value;
if (params != null) {
Object parent = params.getFirstValueForNullKey();
Object child = params.getFirstValueForKey("1");
if (parent != null) {
retVal = child.toString();
}
}
} else {
retVal = value;
}
log.debug(
"Get field value [object=" +
retVal +
";class=" +
((retVal != null) ? retVal.getClass() : "") +
"]"
);
} else {
String fieldId = field.getId();
Collection retCollection = null;
boolean isEmpty = false;
// Special treatment of fields.
if (fieldId.equals(IssueFieldConstants.ATTACHMENT)) {
// return a collection with the attachments associated to given issue.
retCollection = (Collection) issue.getExternalFieldValue(fieldId);
if (retCollection == null || retCollection.isEmpty()) {
isEmpty = true;
} else {
retVal = retCollection;
}
} else if (fieldId.equals(IssueFieldConstants.AFFECTED_VERSIONS)) {
retCollection = issue.getAffectedVersions();
if (retCollection == null || retCollection.isEmpty()) {
isEmpty = true;
} else {
retVal = retCollection;
}
} else if (fieldId.equals(IssueFieldConstants.COMMENT)) {
// return a list with the comments of a given issue.
try {
retCollection = ManagerFactory.getIssueManager().getEntitiesByIssue(IssueRelationConstants.COMMENTS, issue.getGenericValue());
if (retCollection == null || retCollection.isEmpty()) {
isEmpty = true;
} else {
retVal = retCollection;
}
} catch (GenericEntityException e) {
retVal = null;
}
} else if (fieldId.equals(IssueFieldConstants.COMPONENTS)) {
retCollection = issue.getComponents();
if (retCollection == null || retCollection.isEmpty()) {
isEmpty = true;
} else {
retVal = retCollection;
}
} else if (fieldId.equals(IssueFieldConstants.FIX_FOR_VERSIONS)) {
retCollection = issue.getFixVersions();
if (retCollection == null || retCollection.isEmpty()) {
isEmpty = true;
} else {
retVal = retCollection;
}
} else if (fieldId.equals(IssueFieldConstants.THUMBNAIL)) {
// Not implemented, yet.
isEmpty = true;
} else if (fieldId.equals(IssueFieldConstants.ISSUE_TYPE)) {
retVal = issue.getIssueTypeObject();
} else if (fieldId.equals(IssueFieldConstants.TIMETRACKING)) {
// Not implemented, yet.
isEmpty = true;
} else if (fieldId.equals(IssueFieldConstants.ISSUE_LINKS)) {
retVal = ComponentManager.getInstance().getIssueLinkManager().getIssueLinks(issue.getId());
} else if (fieldId.equals(IssueFieldConstants.WORKRATIO)) {
retVal = String.valueOf(WorkRatio.getWorkRatio(issue));
} else if (fieldId.equals(IssueFieldConstants.ISSUE_KEY)) {
retVal = issue.getKey();
} else if (fieldId.equals(IssueFieldConstants.SUBTASKS)) {
retCollection = issue.getSubTasks();
if (retCollection == null || retCollection.isEmpty()) {
isEmpty = true;
} else {
retVal = retCollection;
}
} else if (fieldId.equals(IssueFieldConstants.PRIORITY)) {
retVal = issue.getPriorityObject();
} else if (fieldId.equals(IssueFieldConstants.RESOLUTION)) {
retVal = issue.getResolutionObject();
} else if (fieldId.equals(IssueFieldConstants.STATUS)) {
retVal = issue.getStatusObject();
} else if (fieldId.equals(IssueFieldConstants.PROJECT)) {
retVal = issue.getProject();
} else if (fieldId.equals(IssueFieldConstants.SECURITY)) {
retVal = issue.getSecurityLevel();
} else if (fieldId.equals(IssueFieldConstants.TIME_ESTIMATE)) {
retVal = issue.getEstimate();
} else if (fieldId.equals(IssueFieldConstants.TIME_SPENT)) {
retVal = issue.getTimeSpent();
} else if (fieldId.equals(IssueFieldConstants.ASSIGNEE)) {
retVal = issue.getAssignee();
} else if (fieldId.equals(IssueFieldConstants.REPORTER)) {
retVal = issue.getReporter();
} else if (fieldId.equals(IssueFieldConstants.DESCRIPTION)) {
retVal = issue.getDescription();
} else if (fieldId.equals(IssueFieldConstants.ENVIRONMENT)) {
retVal = issue.getEnvironment();
} else if (fieldId.equals(IssueFieldConstants.SUMMARY)) {
retVal = issue.getSummary();
} else if (fieldId.equals(IssueFieldConstants.DUE_DATE)) {
retVal = issue.getDueDate();
} else {
LogUtils.getGeneral().error("Issue field \"" + fieldId + "\" is not supported.");
GenericValue gvIssue = issue.getGenericValue();
if (gvIssue != null) {
retVal = gvIssue.get(fieldId);
}
}
}
} catch (NullPointerException e) {
retVal = null;
LogUtils.getGeneral().error("Unable to get field \"" + field.getId() + "\" value", e);
}
return retVal;
}
/**
* Sets specified value to the field for the issue.
*
* @param issue
* @param field
* @param value
*/
public static void setFieldValue(MutableIssue issue, Field field, Object value, IssueChangeHolder changeHolder) {
FieldManager fldManager = ManagerFactory.getFieldManager();
if (fldManager.isCustomField(field)) {
CustomField customField = (CustomField) field;
Object oldValue = issue.getCustomFieldValue(customField);
FieldLayoutItem fieldLayoutItem;
CustomFieldType cfType = customField.getCustomFieldType();
try {
fieldLayoutItem = CommonPluginUtils.getFieldLayoutItem(issue, field);
} catch (FieldLayoutStorageException e) {
LogUtils.getGeneral().error("Unable to get field layout item", e);
throw new IllegalStateException(e);
}
Object newValue = value;
if (value instanceof IssueConstant) {
newValue = ((IssueConstant) value).getName();
} else if (value instanceof User) {
newValue = ((User) value).getName();
}
if ((newValue instanceof String) || (newValue instanceof Collection)) {
//convert from string to Object
CustomFieldParams fieldParams = new CustomFieldParamsImpl(customField, newValue);
newValue = cfType.getValueFromCustomFieldParams(fieldParams);
}
// Updating internal custom field value
issue.setCustomFieldValue(customField, newValue);
customField.updateValue(
fieldLayoutItem, issue,
new ModifiedValue(oldValue, newValue), changeHolder
);
if (log.isDebugEnabled()) {
log.debug(
"Issue [" +
issue +
"] got modfied fields - [" +
issue.getModifiedFields() +
"]"
);
}
// Not new
if (issue.getKey() != null) {
// Remove duplicated issue update
if (issue.getModifiedFields().containsKey(field.getId())) {
issue.getModifiedFields().remove(field.getId());
}
}
} else {
final String fieldId = field.getId();
// Special treatment of fields.
if (fieldId.equals(IssueFieldConstants.ATTACHMENT)) {
throw new UnsupportedOperationException("Not implemented");
// // return a collection with the attachments associated to given issue.
// retCollection = (Collection)issue.getExternalFieldValue(fieldId);
// if(retCollection==null || retCollection.isEmpty()){
// isEmpty = true;
// }else{
// retVal = retCollection;
} else if (fieldId.equals(IssueFieldConstants.AFFECTED_VERSIONS)) {
if (value == null) {
issue.setAffectedVersions(Collections.EMPTY_SET);
} else if (value instanceof String) {
VersionManager versionManager = ComponentManager.getInstance().getVersionManager();
Version v = versionManager.getVersion(issue.getProjectObject().getId(), (String) value);
if (v != null) {
issue.setAffectedVersions(Arrays.asList(v));
} else {
throw new IllegalArgumentException("Wrong affected version value");
}
} else if (value instanceof Version) {
issue.setAffectedVersions(Arrays.asList((Version) value));
} else if (value instanceof Collection) {
issue.setAffectedVersions((Collection) value);
} else {
throw new IllegalArgumentException("Wrong affected version value");
}
} else if (fieldId.equals(IssueFieldConstants.COMMENT)) {
throw new UnsupportedOperationException("Not implemented");
// // return a list with the comments of a given issue.
// try {
// retCollection = ManagerFactory.getIssueManager().getEntitiesByIssue(IssueRelationConstants.COMMENTS, issue.getGenericValue());
// if(retCollection==null || retCollection.isEmpty()){
// isEmpty = true;
// }else{
// retVal = retCollection;
// } catch (GenericEntityException e) {
// retVal = null;
} else if (fieldId.equals(IssueFieldConstants.COMPONENTS)) {
throw new UnsupportedOperationException("Not implemented");
// retCollection = issue.getComponents();
// if(retCollection==null || retCollection.isEmpty()){
// isEmpty = true;
// }else{
// retVal = retCollection;
} else if (fieldId.equals(IssueFieldConstants.FIX_FOR_VERSIONS)) {
if (value == null) {
issue.setFixVersions(Collections.EMPTY_SET);
} else if (value instanceof String) {
VersionManager versionManager = ComponentManager.getInstance().getVersionManager();
Version v = versionManager.getVersion(issue.getProjectObject().getId(), (String) value);
if (v != null) {
issue.setFixVersions(Arrays.asList(v));
}
} else if (value instanceof Version) {
issue.setFixVersions(Arrays.asList((Version) value));
} else if (value instanceof Collection) {
issue.setFixVersions((Collection) value);
} else {
throw new IllegalArgumentException("Wrong fix version value");
}
} else if (fieldId.equals(IssueFieldConstants.THUMBNAIL)) {
throw new UnsupportedOperationException("Not implemented");
// // Not implemented, yet.
// isEmpty = true;
} else if (fieldId.equals(IssueFieldConstants.ISSUE_TYPE)) {
throw new UnsupportedOperationException("Not implemented");
// retVal = issue.getIssueTypeObject();
} else if (fieldId.equals(IssueFieldConstants.TIMETRACKING)) {
throw new UnsupportedOperationException("Not implemented");
// // Not implemented, yet.
// isEmpty = true;
} else if (fieldId.equals(IssueFieldConstants.ISSUE_LINKS)) {
throw new UnsupportedOperationException("Not implemented");
// retVal = ComponentManager.getInstance().getIssueLinkManager().getIssueLinks(issue.getId());
} else if (fieldId.equals(IssueFieldConstants.WORKRATIO)) {
throw new UnsupportedOperationException("Not implemented");
// retVal = String.valueOf(WorkRatio.getWorkRatio(issue));
} else if (fieldId.equals(IssueFieldConstants.ISSUE_KEY)) {
throw new UnsupportedOperationException("Not implemented");
// retVal = issue.getKey();
} else if (fieldId.equals(IssueFieldConstants.SUBTASKS)) {
throw new UnsupportedOperationException("Not implemented");
// retCollection = issue.getSubTasks();
// if(retCollection==null || retCollection.isEmpty()){
// isEmpty = true;
// }else{
// retVal = retCollection;
} else if (fieldId.equals(IssueFieldConstants.PRIORITY)) {
if (value == null) {
issue.setPriority(null);
} else {
throw new UnsupportedOperationException("Not implemented");
}
} else if (fieldId.equals(IssueFieldConstants.RESOLUTION)) {
if (value == null) {
issue.setResolution(null);
} else if (value instanceof GenericValue) {
issue.setResolution((GenericValue) value);
} else if (value instanceof Resolution) {
issue.setResolutionId(((Resolution) value).getId());
} else if (value instanceof String) {
Collection<Resolution> resolutions = ManagerFactory.getConstantsManager().getResolutionObjects();
Resolution resolution = null;
String s = ((String) value).trim();
for (Resolution r : resolutions) {
if (r.getName().equalsIgnoreCase(s)) {
resolution = r;
break;
}
}
if (resolution != null) {
issue.setResolutionId(resolution.getId());
} else {
throw new IllegalArgumentException("Unable to find resolution with name \"" + value + "\"");
}
} else {
throw new UnsupportedOperationException("Not implemented");
}
} else if (fieldId.equals(IssueFieldConstants.STATUS)) {
if (value == null) {
issue.setStatus(null);
} else if (value instanceof GenericValue) {
issue.setStatus((GenericValue) value);
} else if (value instanceof Status) {
issue.setStatusId(((Status) value).getId());
} else if (value instanceof String) {
Status status = ManagerFactory.getConstantsManager().getStatusByName((String) value);
if (status != null) {
issue.setStatusId(status.getId());
} else {
throw new IllegalArgumentException("Unable to find status with name \"" + value + "\"");
}
} else {
throw new UnsupportedOperationException("Not implemented");
}
} else if (fieldId.equals(IssueFieldConstants.PROJECT)) {
if (value == null) {
issue.setProject(null);
} else {
throw new UnsupportedOperationException("Not implemented");
}
} else if (fieldId.equals(IssueFieldConstants.SECURITY)) {
if (value == null) {
issue.setSecurityLevel(null);
} else {
throw new UnsupportedOperationException("Not implemented");
}
} else if (fieldId.equals(IssueFieldConstants.ASSIGNEE)) {
if (value == null) {
issue.setAssignee(null);
} else if (value instanceof User) {
issue.setAssignee((User) value);
} else if (value instanceof String) {
try {
User user = UserUtils.getUser((String) value);
if (null != user) {
issue.setAssignee(user);
}
} catch (EntityNotFoundException e) {
throw new IllegalArgumentException(String.format("User \"%s\" not found", value));
}
}
} else if (fieldId.equals(IssueFieldConstants.DUE_DATE)) {
if (value == null) {
issue.setDueDate(null);
}
if (value instanceof Timestamp) {
issue.setDueDate((Timestamp) value);
} else if (value instanceof String) {
ApplicationProperties properties = ManagerFactory.getApplicationProperties();
SimpleDateFormat formatter = new SimpleDateFormat(
properties.getDefaultString(APKeys.JIRA_DATE_TIME_PICKER_JAVA_FORMAT)
);
try {
Date date = formatter.parse((String) value);
if (date != null) {
issue.setDueDate(new Timestamp(date.getTime()));
} else {
issue.setDueDate(null);
}
} catch (ParseException e) {
throw new IllegalArgumentException("Wrong date format exception for \"" + value + "\"");
}
}
}
}
}
/**
* Method sets value for issue field. Field was defined as string
*
* @param issue
* Muttable issue for changing
* @param fieldKey
* Field name
* @param value
* Value for setting
*/
public static void setFieldValue(
MutableIssue issue, String fieldKey, Object value,
IssueChangeHolder changeHolder
) {
final Field field = (Field) WorkflowUtils.getFieldFromKey(fieldKey);
setFieldValue(issue, field, value, changeHolder);
}
/**
* @param issue
* an issue object.
* @param field
* a field object. (May be a Custom Field)
* @return an String.
*
* It returns the value of a field within issue object as String. Instead
* null, it will return an empty String ( "" ).
*
*/
public static String getFieldValueFromIssueAsString(Issue issue, Field field) throws UnsupportedOperationException {
FieldManager fldManager = ManagerFactory.getFieldManager();
String retVal = null;
try {
if (fldManager.isCustomField(field)) {
CustomField customField = (CustomField) field;
if (issue.getCustomFieldValue(customField) != null) {
retVal = issue.getCustomFieldValue(customField).toString();
} else {
retVal = "";
}
} else {
String fieldId = field.getId();
// Unsupported fields as single String value.
if (fieldId.equals("versions")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("attachment")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("comment")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("components")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("fixVersions")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("thumbnail")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("issuelinks")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("subtasks")) {
throw new UnsupportedOperationException();
}
if (fieldId.equals("timetracking")) {
throw new UnsupportedOperationException();
}
// Special treatment of fields.
if (fieldId.equals("issuetype")) {
if (issue.getIssueTypeObject() != null) {
retVal = issue.getIssueTypeObject().getNameTranslation();
} else {
retVal = "";
}
}
if (fieldId.equals("workratio")) {
retVal = String.valueOf(WorkRatio.getWorkRatio(issue));
}
if (fieldId.equals("priority")) {
if (issue.getPriorityObject() != null) {
retVal = issue.getPriorityObject().getNameTranslation();
} else {
retVal = "";
}
}
if (fieldId.equals("project")) {
if (issue.getProjectObject() != null) {
retVal = issue.getProjectObject().getName();
} else {
retVal = "";
}
}
if (fieldId.equals("resolution")) {
if (issue.getResolutionObject() != null) {
retVal = issue.getResolutionObject().getNameTranslation();
} else {
retVal = "";
}
}
if (fieldId.equals("status")) {
if (issue.getStatusObject() != null) {
retVal = issue.getStatusObject().getNameTranslation();
} else {
retVal = "";
}
}
if (fieldId.equals("security")) {
if (issue.getSecurityLevel() != null) {
retVal = issue.getSecurityLevel().getString("name");
} else {
retVal = "";
}
}
if (fieldId.equals("issuekey")) {
retVal = issue.getKey();
}
if (fieldId.equals(IssueFieldConstants.ASSIGNEE)) {
retVal = issue.getAssigneeId();
}
if (fieldId.equals(IssueFieldConstants.REPORTER)) {
retVal = issue.getReporterId();
}
// Get the value from the Generic Value of Issue.
if (retVal == null) {
GenericValue gvIssue = issue.getGenericValue();
if (gvIssue.get(fieldId) != null) {
retVal = gvIssue.get(fieldId).toString();
if((fieldId.equals("timeoriginalestimate")) ||
(fieldId.equals("timeestimate")) ||
(fieldId.equals("timespent"))){
retVal = String.valueOf(new Long(retVal).longValue() / 60);
}
} else {
retVal = "";
}
}
}
} catch (NullPointerException e) {
retVal = null;
}
return retVal;
}
/**
* @param strGroups
* @param splitter
* @return a List of Group
*
* Get Groups from a string.
*
*/
public static List<Group> getGroups(String strGroups, String splitter) {
String[] groups = strGroups.split("\\Q" + splitter + "\\E");
List<Group> groupList = new ArrayList<Group>(groups.length);
for (String s : groups) {
Group group = GroupUtils.getGroup(s);
groupList.add(group);
}
return groupList;
}
/**
* @param group
* @param splitter
* @return a String with the groups selected.
*
* Get Groups as String.
*
*/
public static String getStringGroup(Collection<Group> groups, String splitter) {
StringBuilder sb = new StringBuilder();
for (Group g : groups) {
sb.append(g.getName()).append(splitter);
}
return sb.toString();
}
/**
* @param strFields
* @param splitter
* @return a List of Field
*
* Get Fields from a string.
*
*/
public static List<Field> getFields(String strFields, String splitter) {
String[] fields = strFields.split("\\Q" + splitter + "\\E");
List<Field> fieldList = new ArrayList<Field>(fields.length);
for (String s : fields) {
Field field = ManagerFactory.getFieldManager().getField(s);
fieldList.add(field);
}
return CommonPluginUtils.sortFields(fieldList);
}
/**
* @param fields
* @param splitter
* @return a String with the fields selected.
*
* Get Fields as String.
*
*/
public static String getStringField(Collection<Field> fields, String splitter) {
StringBuilder sb = new StringBuilder();
for (Field f : fields) {
sb.append(f.getId()).append(splitter);
}
return sb.toString();
}
/**
* @param actionDescriptor
* @return the FieldScreen of the transition. Or null, if the transition
* hasn't a screen asociated.
*
* It obtains the fieldscreen for a transition, if it have one.
*
*/
public static FieldScreen getFieldScreen(ActionDescriptor actionDescriptor) {
return workflowActionsBean.getFieldScreenForView(actionDescriptor);
}
}
|
package sparqles.core.discovery;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sparqles.utils.LogFormater;
import sparqles.utils.QueryManager;
import com.hp.hpl.jena.query.QueryExecution;
import com.hp.hpl.jena.query.ResultSet;
import com.hp.hpl.jena.query.ResultSetFactory;
import com.hp.hpl.jena.query.ResultSetRewindable;
import com.hp.hpl.jena.rdf.model.RDFNode;
import sparqles.core.Endpoint;
import sparqles.core.EndpointFactory;
public class DGetVoidRun extends DRun<VoidResult>{
private static final Logger log = LoggerFactory.getLogger(DGetVoidRun.class);
private boolean _self;
private final static String voidStore="http://void.rkbexplorer.com/sparql/";
private static Endpoint VOIDSTORE=null;
public DGetVoidRun(Endpoint ep, boolean self) {
super(ep);
_self = self;
if(VOIDSTORE==null)
try {
VOIDSTORE = EndpointFactory.newEndpoint(new URI(voidStore));
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private final static String query = "" +
"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns
"PREFIX void: <http://rdfs.org/ns/void
"SELECT DISTINCT * \n"+
"WHERE {\n"+
"?ds a void:Dataset .\n"+
"?ds void:sparqlEndpoint %%s .\n"+
"?ds ?p ?o .\n"+
"}";
public VoidResult execute() {
VoidResult res = new VoidResult();
String queryString = query.replaceAll("%%s", "<"+_ep.getUri()+">");
ArrayList<CharSequence> voidA = new ArrayList<CharSequence>();
res.setVoidFile(voidA);
// initializing queryExecution factory with remote service.
// **this actually was the main problem I couldn't figure out.**
QueryExecution qexec = null;
try {
if(_self)
qexec = QueryManager.getExecution(_ep, queryString);
else
qexec = QueryManager.getExecution(VOIDSTORE, queryString);
boolean results = false;
//after it goes standard query execution and result processing which can
// be found in almost any Jena/SPARQL tutorial.
ResultSet resSet = qexec.execSelect();
ResultSetRewindable reswind = ResultSetFactory.makeRewindable(resSet);
while(reswind.hasNext()){
RDFNode dataset = reswind.next().get("ds");
voidA.add(dataset.toString());
}
log.info("Found {} results",reswind.getRowNumber());
} catch (Exception e1) {
res.setException(LogFormater.toString(e1));
}
finally {
if(qexec!=null)qexec.close();
}
return res;
}
}
|
package com.googlecode.lightity;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* Factory of {@link Entity}.
*
* @author Koba, Masafumi
*/
public final class EntityFactory {
/**
* Create an empty entity.
* <p>
* The entity to be created is the default implementation of {@link Entity}.
*
* @return an empty entity
*/
public static Entity create() {
return new EntityImpl();
}
private static class PropertyValuePair {
final EntityProperty<?> property;
final Object value;
PropertyValuePair(final EntityProperty<?> property, final Object value) {
this.property = property;
this.value = value;
assert (this.property != null);
}
}
private static class EntityImpl implements Entity {
private static String getKey(final EntityProperty<?> property) {
return property.getName();
}
private final Map<String, PropertyValuePair> propertyValuePairs = new LinkedHashMap<String, EntityFactory.PropertyValuePair>();
@Override
public <T> Entity set(final EntityProperty<T> property, final T value) {
if (property == null) {
throw new NullPointerException("required property");
}
propertyValuePairs.put(getKey(property), new PropertyValuePair(
property, value));
return this;
}
@Override
public <T> T get(final EntityProperty<T> property)
throws NoSuchEntityPropertyException {
final String key = getKey(property);
if (!propertyValuePairs.containsKey(key)) {
throw new NoSuchEntityPropertyException(property);
}
return property.getType().cast(propertyValuePairs.get(key).value);
}
@Override
public void remove(final EntityProperty<?> property) {
propertyValuePairs.remove(getKey(property));
}
@Override
public boolean exists(final EntityProperty<?> property) {
return propertyValuePairs.containsKey(getKey(property));
}
@Override
public int count() {
return propertyValuePairs.size();
}
@Override
public Iterator<EntityProperty<?>> iterator() {
final List<EntityProperty<?>> properties = new ArrayList<EntityProperty<?>>(
count());
for (final PropertyValuePair pair : propertyValuePairs.values()) {
properties.add(pair.property);
}
return properties.iterator();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append('{');
for (final PropertyValuePair pair : propertyValuePairs.values()) {
if (sb.length() > 1) {
sb.append(", ");
}
sb.append(pair.property.getName());
sb.append(':').append(pair.property.getType().getName());
sb.append('=');
sb.append(pair.value);
}
sb.append('}');
return sb.toString();
}
}
private EntityFactory() {
super();
}
}
|
package team.unstudio.udpl.util;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import javax.annotation.Nonnull;
import org.apache.commons.lang.Validate;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
public final class PluginUtils {
private PluginUtils() {}
public static void saveDirectory(@Nonnull JavaPlugin plugin,@Nonnull String resourcePath,boolean replace){
Validate.notNull(plugin);
Validate.notEmpty(resourcePath);
resourcePath = resourcePath.replace('\\', '/');
plugin.getLogger().info("Plugin save directory. Path: " + resourcePath);
URL url = plugin.getClass().getClassLoader().getResource(resourcePath);
if(url == null)
throw new IllegalArgumentException("Directory isn't found. Path: "+resourcePath);
JarURLConnection jarConn;
try {
jarConn = (JarURLConnection) url.openConnection();
JarFile jarFile = jarConn.getJarFile();
Enumeration<JarEntry> entrys = jarFile.entries();
while(entrys.hasMoreElements()){
JarEntry entry = entrys.nextElement();
if(entry.getName().startsWith(resourcePath)&&!entry.isDirectory())
plugin.saveResource(entry.getName(), replace);
}
} catch (IOException e) {
plugin.getLogger().warning("Plugin save directory failed. Path: " + resourcePath);
e.printStackTrace();
}
}
public static void registerEvent(Listener listener,Plugin plugin){
Bukkit.getPluginManager().registerEvents(listener, plugin);
}
}
|
package info.nightscout.androidaps.plugins.IobCobCalculator;
import android.os.Handler;
import android.os.HandlerThread;
import android.support.annotation.Nullable;
import android.support.v4.util.LongSparseArray;
import com.squareup.otto.Subscribe;
import org.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import info.nightscout.androidaps.Config;
import info.nightscout.androidaps.Constants;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.data.IobTotal;
import info.nightscout.androidaps.data.Profile;
import info.nightscout.androidaps.db.BgReading;
import info.nightscout.androidaps.db.TemporaryBasal;
import info.nightscout.androidaps.db.Treatment;
import info.nightscout.androidaps.events.EventConfigBuilderChange;
import info.nightscout.androidaps.events.EventNewBG;
import info.nightscout.androidaps.events.EventNewBasalProfile;
import info.nightscout.androidaps.events.EventPreferenceChange;
import info.nightscout.androidaps.interfaces.PluginBase;
import info.nightscout.androidaps.plugins.ConfigBuilder.ConfigBuilderPlugin;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.BasalData;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventAutosensCalculationFinished;
import info.nightscout.androidaps.plugins.IobCobCalculator.events.EventNewHistoryData;
public class IobCobCalculatorPlugin implements PluginBase {
private static Logger log = LoggerFactory.getLogger(IobCobCalculatorPlugin.class);
private static LongSparseArray<IobTotal> iobTable = new LongSparseArray<>(); // oldest at index 0
private static LongSparseArray<AutosensData> autosensDataTable = new LongSparseArray<>(); // oldest at index 0
private static LongSparseArray<BasalData> basalDataTable = new LongSparseArray<>(); // oldest at index 0
private static volatile List<BgReading> bgReadings = null; // newest at index 0
private static volatile List<BgReading> bucketed_data = null;
private static double dia = Constants.defaultDIA;
private static Handler sHandler = null;
private static HandlerThread sHandlerThread = null;
private static final Object dataLock = new Object();
private static IobCobCalculatorPlugin plugin = null;
public static IobCobCalculatorPlugin getPlugin() {
if (plugin == null)
plugin = new IobCobCalculatorPlugin();
return plugin;
}
public static LongSparseArray<AutosensData> getAutosensDataTable() {
return autosensDataTable;
}
public static List<BgReading> getBucketedData() {
return bucketed_data;
}
@Override
public int getType() {
return GENERAL;
}
@Override
public String getFragmentClass() {
return null;
}
@Override
public String getName() {
return "IOB COB Calculator";
}
@Override
public String getNameShort() {
return "IOC";
}
@Override
public boolean isEnabled(int type) {
return type == GENERAL;
}
@Override
public boolean isVisibleInTabs(int type) {
return false;
}
@Override
public boolean canBeHidden(int type) {
return false;
}
@Override
public boolean hasFragment() {
return false;
}
@Override
public boolean showInList(int type) {
return false;
}
@Override
public void setFragmentEnabled(int type, boolean fragmentEnabled) {
}
@Override
public void setFragmentVisible(int type, boolean fragmentVisible) {
}
IobCobCalculatorPlugin() {
MainApp.bus().register(this);
if (sHandlerThread == null) {
sHandlerThread = new HandlerThread(IobCobCalculatorPlugin.class.getSimpleName());
sHandlerThread.start();
sHandler = new Handler(sHandlerThread.getLooper());
}
onNewBg(new EventNewBG());
}
@Nullable
public static List<BgReading> getBucketedData(long fromTime) {
//log.debug("Locking getBucketedData");
synchronized (dataLock) {
if (bucketed_data == null) {
log.debug("No bucketed data available");
return null;
}
int index = indexNewerThan(fromTime);
if (index > -1) {
List<BgReading> part = bucketed_data.subList(0, index);
log.debug("Bucketed data striped off: " + part.size() + "/" + bucketed_data.size());
return part;
}
}
//log.debug("Releasing getBucketedData");
return null;
}
private static int indexNewerThan(long time) {
for (int index = 0; index < bucketed_data.size(); index++) {
if (bucketed_data.get(index).date < time)
return index - 1;
}
return -1;
}
public static long roundUpTime(long time) {
if (time % 60000 == 0)
return time;
long rouded = (time / 60000 + 1) * 60000;
return rouded;
}
private void loadBgData() {
//log.debug("Locking loadBgData");
synchronized (dataLock) {
onNewProfile(null);
bgReadings = MainApp.getDbHelper().getBgreadingsDataFromTime((long) (System.currentTimeMillis() - 60 * 60 * 1000L * (24 + dia)), false);
log.debug("BG data loaded. Size: " + bgReadings.size());
}
//log.debug("Releasing loadBgData");
}
private boolean isAbout5minData() {
synchronized (dataLock) {
if (bgReadings == null || bgReadings.size() < 3) {
return true;
}
long totalDiff = 0;
for (int i = 1; i < bgReadings.size(); ++i) {
long bgTime = bgReadings.get(i).date;
long lastbgTime = bgReadings.get(i - 1).date;
long diff = lastbgTime - bgTime;
totalDiff += diff;
if (diff > 30 * 1000 && diff < 270 * 1000) { // 0:30 - 4:30
log.debug("Interval detection: values: " + bgReadings.size() + " diff: " + (diff / 1000) + "sec is5minData: " + false);
return false;
}
}
double intervals = totalDiff / (5 * 60 * 1000d);
double variability = Math.abs(intervals - Math.round(intervals));
boolean is5mindata = variability < 0.02;
log.debug("Interval detection: values: " + bgReadings.size() + " variability: " + variability + " is5minData: " + is5mindata);
return is5mindata;
}
}
private void createBucketedData() {
if (isAbout5minData())
createBucketedData5min();
else
createBucketedDataRecalculated();
}
@Nullable
private BgReading findNewer(long time) {
BgReading lastFound = bgReadings.get(0);
if (lastFound.date < time) return null;
for (int i = 1; i < bgReadings.size(); ++i) {
if (bgReadings.get(i).date > time) continue;
lastFound = bgReadings.get(i);
if (bgReadings.get(i).date < time) break;
}
return lastFound;
}
@Nullable
private BgReading findOlder(long time) {
BgReading lastFound = bgReadings.get(bgReadings.size() - 1);
if (lastFound.date > time) return null;
for (int i = bgReadings.size() - 2; i >=0 ; --i) {
if (bgReadings.get(i).date < time) continue;
lastFound = bgReadings.get(i);
if (bgReadings.get(i).date > time) break;
}
return lastFound;
}
private void createBucketedDataRecalculated() {
synchronized (dataLock) {
if (bgReadings == null || bgReadings.size() < 3) {
bucketed_data = null;
return;
}
bucketed_data = new ArrayList<>();
long currentTime = bgReadings.get(0).date + 5 * 60 * 1000 - bgReadings.get(0).date % (5 * 60 * 1000) - 5 * 60 * 1000L;
//log.debug("First reading: " + new Date(currentTime).toLocaleString());
while (true) {
// test if current value is older than current time
BgReading newer = findNewer(currentTime);
BgReading older = findOlder(currentTime);
if (newer == null || older == null)
break;
double bgDelta = newer.value - older.value;
long timeDiffToNew = newer.date - currentTime;
double currentBg = newer.value - (double) timeDiffToNew / (newer.date - older.date) * bgDelta;
BgReading newBgreading = new BgReading();
newBgreading.date = currentTime;
newBgreading.value = Math.round(currentBg);
bucketed_data.add(newBgreading);
//log.debug("BG: " + newBgreading.value + " (" + new Date(newBgreading.date).toLocaleString() + ") Prev: " + older.value + " (" + new Date(older.date).toLocaleString() + ") Newer: " + newer.value + " (" + new Date(newer.date).toLocaleString() + ")");
currentTime -= 5 * 60 * 1000L;
}
}
}
public void createBucketedData5min() {
//log.debug("Locking createBucketedData");
synchronized (dataLock) {
if (bgReadings == null || bgReadings.size() < 3) {
bucketed_data = null;
return;
}
bucketed_data = new ArrayList<>();
bucketed_data.add(bgReadings.get(0));
int j = 0;
for (int i = 1; i < bgReadings.size(); ++i) {
long bgTime = bgReadings.get(i).date;
long lastbgTime = bgReadings.get(i - 1).date;
//log.error("Processing " + i + ": " + new Date(bgTime).toString() + " " + bgReadings.get(i).value + " Previous: " + new Date(lastbgTime).toString() + " " + bgReadings.get(i - 1).value);
if (bgReadings.get(i).value < 39 || bgReadings.get(i - 1).value < 39) {
continue;
}
long elapsed_minutes = (bgTime - lastbgTime) / (60 * 1000);
if (Math.abs(elapsed_minutes) > 8) {
// interpolate missing data points
double lastbg = bgReadings.get(i - 1).value;
elapsed_minutes = Math.abs(elapsed_minutes);
//console.error(elapsed_minutes);
long nextbgTime;
while (elapsed_minutes > 5) {
nextbgTime = lastbgTime - 5 * 60 * 1000;
j++;
BgReading newBgreading = new BgReading();
newBgreading.date = nextbgTime;
double gapDelta = bgReadings.get(i).value - lastbg;
//console.error(gapDelta, lastbg, elapsed_minutes);
double nextbg = lastbg + (5d / elapsed_minutes * gapDelta);
newBgreading.value = Math.round(nextbg);
//console.error("Interpolated", bucketed_data[j]);
bucketed_data.add(newBgreading);
elapsed_minutes = elapsed_minutes - 5;
lastbg = nextbg;
lastbgTime = nextbgTime;
}
j++;
BgReading newBgreading = new BgReading();
newBgreading.value = bgReadings.get(i).value;
newBgreading.date = bgTime;
bucketed_data.add(newBgreading);
} else if (Math.abs(elapsed_minutes) > 2) {
j++;
BgReading newBgreading = new BgReading();
newBgreading.value = bgReadings.get(i).value;
newBgreading.date = bgTime;
bucketed_data.add(newBgreading);
} else {
bucketed_data.get(j).value = (bucketed_data.get(j).value + bgReadings.get(i).value) / 2;
}
}
log.debug("Bucketed data created. Size: " + bucketed_data.size());
}
//log.debug("Releasing createBucketedData");
}
private void calculateSensitivityData() {
if (MainApp.getConfigBuilder() == null)
return; // app still initializing
if (MainApp.getConfigBuilder().getProfile() == null)
return; // app still initializing
//log.debug("Locking calculateSensitivityData");
long oldestTimeWithData = oldestDataAvailable();
synchronized (dataLock) {
if (bucketed_data == null || bucketed_data.size() < 3) {
log.debug("calculateSensitivityData: No bucketed data available");
return;
}
long prevDataTime = roundUpTime(bucketed_data.get(bucketed_data.size() - 3).date);
log.debug("Prev data time: " + new Date(prevDataTime).toLocaleString());
AutosensData previous = autosensDataTable.get(prevDataTime);
// start from oldest to be able sub cob
for (int i = bucketed_data.size() - 4; i >= 0; i
// check if data already exists
long bgTime = bucketed_data.get(i).date;
bgTime = roundUpTime(bgTime);
Profile profile = MainApp.getConfigBuilder().getProfile(bgTime);
AutosensData existing;
if ((existing = autosensDataTable.get(bgTime)) != null) {
previous = existing;
continue;
}
if (profile.getIsf(bgTime) == null)
return; // profile not set yet
double sens = Profile.toMgdl(profile.getIsf(bgTime), profile.getUnits());
AutosensData autosensData = new AutosensData();
autosensData.time = bgTime;
if (previous != null)
autosensData.activeCarbsList = new ArrayList<>(previous.activeCarbsList);
else
autosensData.activeCarbsList = new ArrayList<>();
//console.error(bgTime , bucketed_data[i].glucose);
double bg;
double avgDelta;
double delta;
bg = bucketed_data.get(i).value;
if (bg < 39 || bucketed_data.get(i + 3).value < 39) {
log.error("! value < 39");
continue;
}
delta = (bg - bucketed_data.get(i + 1).value);
IobTotal iob = calculateFromTreatmentsAndTemps(bgTime);
double bgi = -iob.activity * sens * 5;
double deviation = delta - bgi;
List<Treatment> recentTreatments = MainApp.getConfigBuilder().getTreatments5MinBackFromHistory(bgTime);
for (int ir = 0; ir < recentTreatments.size(); ir++) {
autosensData.carbsFromBolus += recentTreatments.get(ir).carbs;
autosensData.activeCarbsList.add(new AutosensData.CarbsInPast(recentTreatments.get(ir)));
}
// if we are absorbing carbs
if (previous != null && previous.cob > 0) {
// calculate sum of min carb impact from all active treatments
double totalMinCarbsImpact = 0d;
for (int ii = 0; ii < autosensData.activeCarbsList.size(); ++ii) {
AutosensData.CarbsInPast c = autosensData.activeCarbsList.get(ii);
totalMinCarbsImpact += c.min5minCarbImpact;
}
// figure out how many carbs that represents
// but always assume at least 3mg/dL/5m (default) absorption per active treatment
double ci = Math.max(deviation, totalMinCarbsImpact);
autosensData.absorbed = ci * profile.getIc(bgTime) / sens;
// and add that to the running total carbsAbsorbed
autosensData.cob = Math.max(previous.cob - autosensData.absorbed, 0d);
autosensData.substractAbosorbedCarbs();
}
autosensData.removeOldCarbs(bgTime);
autosensData.cob += autosensData.carbsFromBolus;
autosensData.deviation = deviation;
autosensData.bgi = bgi;
autosensData.delta = delta;
// calculate autosens only without COB
if (autosensData.cob <= 0) {
if (Math.abs(deviation) < Constants.DEVIATION_TO_BE_EQUAL) {
autosensData.pastSensitivity += "=";
autosensData.nonEqualDeviation = true;
} else if (deviation > 0) {
autosensData.pastSensitivity += "+";
autosensData.nonEqualDeviation = true;
} else {
autosensData.pastSensitivity += "-";
autosensData.nonEqualDeviation = true;
}
autosensData.nonCarbsDeviation = true;
} else {
autosensData.pastSensitivity += "C";
}
//log.debug("TIME: " + new Date(bgTime).toString() + " BG: " + bg + " SENS: " + sens + " DELTA: " + delta + " AVGDELTA: " + avgDelta + " IOB: " + iob.iob + " ACTIVITY: " + iob.activity + " BGI: " + bgi + " DEVIATION: " + deviation);
previous = autosensData;
autosensDataTable.put(bgTime, autosensData);
autosensData.autosensRatio = detectSensitivity(oldestTimeWithData, bgTime).ratio;
if (Config.logAutosensData)
log.debug(autosensData.log(bgTime));
}
}
MainApp.bus().post(new EventAutosensCalculationFinished());
//log.debug("Releasing calculateSensitivityData");
}
public static long oldestDataAvailable() {
long now = System.currentTimeMillis();
long oldestDataAvailable = MainApp.getConfigBuilder().oldestDataAvailable();
long getBGDataFrom = Math.max(oldestDataAvailable, (long) (now - 60 * 60 * 1000L * (24 + MainApp.getConfigBuilder().getProfile().getDia())));
log.debug("Limiting data to oldest available temps: " + new Date(oldestDataAvailable).toString());
return getBGDataFrom;
}
public static IobTotal calculateFromTreatmentsAndTempsSynchronized(long time) {
synchronized (dataLock) {
return calculateFromTreatmentsAndTemps(time);
}
}
public static IobTotal calculateFromTreatmentsAndTemps(long time) {
long now = System.currentTimeMillis();
time = roundUpTime(time);
if (time < now && iobTable.get(time) != null) {
//og.debug(">>> calculateFromTreatmentsAndTemps Cache hit " + new Date(time).toLocaleString());
return iobTable.get(time);
} else {
//log.debug(">>> calculateFromTreatmentsAndTemps Cache miss " + new Date(time).toLocaleString());
}
IobTotal bolusIob = MainApp.getConfigBuilder().getCalculationToTimeTreatments(time).round();
IobTotal basalIob = MainApp.getConfigBuilder().getCalculationToTimeTempBasals(time).round();
IobTotal iobTotal = IobTotal.combine(bolusIob, basalIob).round();
if (time < System.currentTimeMillis()) {
iobTable.put(time, iobTotal);
}
return iobTotal;
}
@Nullable
private static Long findPreviousTimeFromBucketedData(long time) {
if (bucketed_data == null)
return null;
for (int index = 0; index < bucketed_data.size(); index++) {
if (bucketed_data.get(index).date < time)
return bucketed_data.get(index).date;
}
return null;
}
public static BasalData getBasalData(long time) {
long now = System.currentTimeMillis();
time = roundUpTime(time);
BasalData retval = basalDataTable.get(time);
if (retval == null) {
retval = new BasalData();
TemporaryBasal tb = MainApp.getConfigBuilder().getTempBasalFromHistory(time);
retval.basal = MainApp.getConfigBuilder().getProfile(time).getBasal(time);
if (tb != null) {
retval.isTempBasalRunning = true;
retval.tempBasalAbsolute = tb.tempBasalConvertedToAbsolute(time);
} else {
retval.isTempBasalRunning = false;
retval.tempBasalAbsolute = retval.basal;
}
if (time < now) {
basalDataTable.append(time, retval);
}
//log.debug(">>> getBasalData Cache miss " + new Date(time).toLocaleString());
} else {
//log.debug(">>> getBasalData Cache hit " + new Date(time).toLocaleString());
}
return retval;
}
@Nullable
public static AutosensData getAutosensData(long time) {
synchronized (dataLock) {
long now = System.currentTimeMillis();
if (time > now)
return null;
Long previous = findPreviousTimeFromBucketedData(time);
if (previous == null)
return null;
time = roundUpTime(previous);
AutosensData data = autosensDataTable.get(time);
if (data != null) {
//log.debug(">>> getAutosensData Cache hit " + data.log(time));
return data;
} else {
//log.debug(">>> getAutosensData Cache miss " + new Date(time).toLocaleString());
return null;
}
}
}
@Nullable
public static AutosensData getLastAutosensData() {
if (autosensDataTable.size() < 1)
return null;
AutosensData data = autosensDataTable.valueAt(autosensDataTable.size() - 1);
if (data.time < System.currentTimeMillis() - 5 * 60 * 1000) {
return null;
} else {
return data;
}
}
public static IobTotal[] calculateIobArrayInDia() {
Profile profile = MainApp.getConfigBuilder().getProfile();
// predict IOB out to DIA plus 30m
long time = System.currentTimeMillis();
time = roundUpTime(time);
int len = (int) ((profile.getDia() * 60 + 30) / 5);
IobTotal[] array = new IobTotal[len];
int pos = 0;
for (int i = 0; i < len; i++) {
long t = time + i * 5 * 60000;
IobTotal iob = calculateFromTreatmentsAndTempsSynchronized(t);
array[pos] = iob;
pos++;
}
return array;
}
public static AutosensResult detectSensitivityWithLock(long fromTime, long toTime) {
synchronized (dataLock) {
return detectSensitivity(fromTime, toTime);
}
}
private static AutosensResult detectSensitivity(long fromTime, long toTime) {
return ConfigBuilderPlugin.getActiveSensitivity().detectSensitivity(fromTime, toTime);
}
public static JSONArray convertToJSONArray(IobTotal[] iobArray) {
JSONArray array = new JSONArray();
for (int i = 0; i < iobArray.length; i++) {
array.put(iobArray[i].determineBasalJson());
}
return array;
}
@Subscribe
public void onNewBg(EventNewBG ev) {
sHandler.post(new Runnable() {
@Override
public void run() {
loadBgData();
createBucketedData();
calculateSensitivityData();
}
});
}
@Subscribe
public void onNewProfile(EventNewBasalProfile ev) {
if (MainApp.getConfigBuilder() == null)
return; // app still initializing
Profile profile = MainApp.getConfigBuilder().getProfile();
if (profile == null)
return; // app still initializing
dia = profile.getDia();
if (ev == null) { // on init no need of reset
return;
}
synchronized (dataLock) {
log.debug("Invalidating cached data because of new profile. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}
sHandler.post(new Runnable() {
@Override
public void run() {
calculateSensitivityData();
}
});
}
@Subscribe
public void onStatusEvent(EventPreferenceChange ev) {
if (ev.isChanged(R.string.key_openapsama_autosens_period) ||
ev.isChanged(R.string.key_age) ||
ev.isChanged(R.string.key_absorption_maxtime)
) {
synchronized (dataLock) {
log.debug("Invalidating cached data because of preference change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}
sHandler.post(new Runnable() {
@Override
public void run() {
calculateSensitivityData();
}
});
}
}
@Subscribe
public void onStatusEvent(EventConfigBuilderChange ev) {
synchronized (dataLock) {
log.debug("Invalidating cached data because of configuration change. IOB: " + iobTable.size() + " Autosens: " + autosensDataTable.size() + " records");
iobTable = new LongSparseArray<>();
autosensDataTable = new LongSparseArray<>();
}
sHandler.post(new Runnable() {
@Override
public void run() {
calculateSensitivityData();
}
});
}
// When historical data is changed (comming from NS etc) finished calculations after this date must be invalidated
@Subscribe
public void onNewHistoryData(EventNewHistoryData ev) {
//log.debug("Locking onNewHistoryData");
synchronized (dataLock) {
long time = ev.time;
log.debug("Invalidating cached data to: " + new Date(time).toLocaleString());
for (int index = iobTable.size() - 1; index >= 0; index
if (iobTable.keyAt(index) > time) {
if (Config.logAutosensData)
if (Config.logAutosensData)
log.debug("Removing from iobTable: " + new Date(iobTable.keyAt(index)).toLocaleString());
iobTable.removeAt(index);
} else {
break;
}
}
for (int index = autosensDataTable.size() - 1; index >= 0; index
if (autosensDataTable.keyAt(index) > time) {
if (Config.logAutosensData)
log.debug("Removing from autosensDataTable: " + new Date(autosensDataTable.keyAt(index)).toLocaleString());
autosensDataTable.removeAt(index);
} else {
break;
}
}
for (int index = basalDataTable.size() - 1; index >= 0; index
if (basalDataTable.keyAt(index) > time) {
if (Config.logAutosensData)
log.debug("Removing from basalDataTable: " + new Date(basalDataTable.keyAt(index)).toLocaleString());
basalDataTable.removeAt(index);
} else {
break;
}
}
}
sHandler.post(new Runnable() {
@Override
public void run() {
calculateSensitivityData();
}
});
//log.debug("Releasing onNewHistoryData");
}
// Returns the value at a given percentile in a sorted numeric array.
// "Linear interpolation between closest ranks" method
public static double percentile(Double[] arr, double p) {
if (arr.length == 0) return 0;
if (p <= 0) return arr[0];
if (p >= 1) return arr[arr.length - 1];
double index = arr.length * p,
lower = Math.floor(index),
upper = lower + 1,
weight = index % 1;
if (upper >= arr.length) return arr[(int) lower];
return arr[(int) lower] * (1 - weight) + arr[(int) upper] * weight;
}
}
|
package imj2.tools;
import static imj2.tools.IMJTools.a8gray888;
import static imj2.tools.IMJTools.a8r8g8b8;
import static imj2.tools.IMJTools.uint8;
import static java.awt.event.InputEvent.SHIFT_DOWN_MASK;
import static java.awt.event.KeyEvent.VK_BACK_SPACE;
import static java.awt.event.KeyEvent.VK_DELETE;
import static java.lang.Integer.parseInt;
import static java.lang.Math.abs;
import static java.lang.Math.max;
import static java.util.Arrays.copyOfRange;
import static net.sourceforge.aprog.swing.SwingTools.horizontalBox;
import static net.sourceforge.aprog.swing.SwingTools.horizontalSplit;
import static net.sourceforge.aprog.swing.SwingTools.scrollable;
import static net.sourceforge.aprog.swing.SwingTools.show;
import static net.sourceforge.aprog.swing.SwingTools.verticalBox;
import static net.sourceforge.aprog.tools.Tools.array;
import static net.sourceforge.aprog.tools.Tools.debugPrint;
import static net.sourceforge.aprog.tools.Tools.getOrCreate;
import static pixel3d.PolygonTools.X;
import static pixel3d.PolygonTools.Y;
import static pixel3d.PolygonTools.Z;
import imj2.tools.ColorSeparationTest.RGBTransformer;
import imj2.tools.Image2DComponent.Painter;
import imj2.tools.PaletteBasedSegmentationTest.HistogramView.PointsUpdatedEvent;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import java.util.BitSet;
import java.util.Collection;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.AbstractAction;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import jgencode.primitivelists.DoubleList;
import jgencode.primitivelists.IntList;
import net.sourceforge.aprog.events.EventManager;
import net.sourceforge.aprog.events.EventManager.Event.Listener;
import net.sourceforge.aprog.swing.SwingTools;
import net.sourceforge.aprog.tools.Factory;
import net.sourceforge.aprog.tools.TicToc;
import org.junit.Test;
import pixel3d.MouseHandler;
import pixel3d.OrbiterMouseHandler;
import pixel3d.OrbiterMouseHandler.OrbiterParameters;
import pixel3d.OrthographicRenderer;
import pixel3d.Renderer;
import pixel3d.TiledRenderer;
/**
* @author codistmonk (creation 2014-04-23)
*/
public final class PaletteBasedSegmentationTest {
@Test
public final void test() {
SwingTools.useSystemLookAndFeel();
SwingTools.setCheckAWT(false);
final SimpleImageView imageView = new SimpleImageView();
final HistogramView histogramView = new HistogramView();
final JComboBox<? extends RGBTransformer> transformerSelector = new JComboBox<>(array(
RGBTransformer.Predefined.ID, new NearestNeighborRGBQuantizer()));
final JCheckBox segmentCheckBox = new JCheckBox("Segment");
final JSplitPane splitPane = horizontalSplit(imageView, verticalBox(
horizontalBox(transformerSelector, segmentCheckBox), scrollable(histogramView)));
SwingTools.setCheckAWT(true);
final ActionListener updateImageViewActionListener = new ActionListener() {
@Override
public final void actionPerformed(final ActionEvent event) {
imageView.refreshBuffer();
}
};
transformerSelector.addActionListener(updateImageViewActionListener);
segmentCheckBox.addActionListener(updateImageViewActionListener);
EventManager.getInstance().addListener(histogramView, PointsUpdatedEvent.class, new Serializable() {
@Listener
public final void segmentsUpdated(final PointsUpdatedEvent event) {
final Map<Integer, Collection<Integer>> clusters = ((NearestNeighborRGBQuantizer) transformerSelector.getItemAt(1)).getClusters();
clusters.clear();
final double[] points = histogramView.getUserPoints().toArray();
final double tx = +128.0;
final double ty = +128.0;
final double tz = -128.0;
final int n = points.length;
for (int i = 0; i < n; i += 3) {
final Integer rgb = a8r8g8b8(0xFF
, uint8(points[i + X] - tx), uint8(points[i + Y] - ty), uint8(points[i + Z] - tz));
getOrCreate((Map) clusters, rgb, Factory.DefaultFactory.TREE_SET_FACTORY).add(rgb);
}
final DefaultComboBoxModel<RGBTransformer> transformers = (DefaultComboBoxModel<RGBTransformer>) transformerSelector.getModel();
final int selectedIndex = transformerSelector.getSelectedIndex();
while (2 < transformers.getSize()) {
transformers.removeElementAt(2);
}
for (final Integer clusterRGB : clusters.keySet()) {
transformers.addElement(new NearestNeighborRGBLinearizer(clusters, clusterRGB));
}
transformerSelector.setSelectedIndex(selectedIndex < transformers.getSize() ? selectedIndex : 0);
imageView.refreshBuffer();
}
/**
* {@value}.
*/
private static final long serialVersionUID = -7179884216164528584L;
});
imageView.getPainters().add(new Painter<SimpleImageView>() {
private final Canvas labels = new Canvas();
@Override
public final void paint(final Graphics2D g, final SimpleImageView component,
final int width, final int height) {
final RGBTransformer transformer = (RGBTransformer) transformerSelector.getSelectedItem();
final BufferedImage image = imageView.getImage();
final BufferedImage buffer = imageView.getBufferImage();
if (segmentCheckBox.isSelected()) {
imageView.getBufferGraphics().drawImage(image, 0, 0, null);
this.labels.setFormat(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB);
this.labels.clear(Color.BLACK);
if (transformer instanceof NearestNeighborRGBLinearizer) {
RGBTransformer.Tools.filter(image, transformer, this.labels.getImage());
} else {
RGBTransformer.Tools.transform(image, transformer, this.labels.getImage());
}
RGBTransformer.Tools.drawSegmentContours(this.labels.getImage(), 0xFF00FF00, buffer);
} else {
RGBTransformer.Tools.transform(image, transformer, buffer);
}
histogramView.refresh(image);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 646058874106526093L;
});
show(splitPane, this.getClass().getSimpleName(), true);
}
public static final int distance1(final int rgb1, final int rgb2) {
int result = 0;
result += abs(((rgb1 >> 16) & 0xFF) - ((rgb2 >> 16) & 0xFF));
result += abs(((rgb1 >> 8) & 0xFF) - ((rgb2 >> 8) & 0xFF));
result += abs(((rgb1 >> 0) & 0xFF) - ((rgb2 >> 0) & 0xFF));
return result;
}
public static final Map<Integer, Collection<Integer>> getClusters(final GenericTree clustersEditor) {
final Map<Integer, Collection<Integer>> result = new TreeMap<Integer, Collection<Integer>>();
final DefaultTreeModel model = clustersEditor.getModel();
final Object root = model.getRoot();
for (int i = 0; i < model.getChildCount(root); ++i) {
final Object cluster = model.getChild(root, i);
final Integer clusterRGB = stringsToRGB(cluster);
for (int j = 0; j < model.getChildCount(cluster); ++j) {
getOrCreate((Map) result, clusterRGB, Factory.DefaultFactory.TREE_SET_FACTORY)
.add(stringsToRGB(model.getChild(cluster, j)));
}
}
return result;
}
public static final int stringsToRGB(final Object object) {
final String[] strings = object.toString().split("\\s+");
return 0xFF000000 | ((parseInt(strings[0]) & 0xFF) << 16) | ((parseInt(strings[1]) & 0xFF) << 8) | ((parseInt(strings[2]) & 0xFF) << 0);
}
/**
* @author codistmonk (creation 2014-04-23)
*/
public static final class GenericTree extends JTree {
public GenericTree(final Object rootData) {
super(new DefaultMutableTreeNode(rootData));
this.setEditable(true);
this.addMouseListener(new MouseAdapter() {
@Override
public final void mousePressed(final MouseEvent event) {
this.mousePressedOrReleased(event);
}
@Override
public final void mouseReleased(final MouseEvent event) {
this.mousePressedOrReleased(event);
}
final void mousePressedOrReleased(final MouseEvent event) {
if (event.isPopupTrigger()) {
final int row = GenericTree.this.getRowForLocation(event.getX(), event.getY());
if (row < 0) {
return;
}
GenericTree.this.setSelectionRow(row);
final DefaultMutableTreeNode node = (DefaultMutableTreeNode) GenericTree.this.getSelectionPath().getLastPathComponent();
final JPopupMenu popup = new JPopupMenu();
popup.add(new AbstractAction("Add...") {
@Override
public final void actionPerformed(final ActionEvent event) {
final Object childData = JOptionPane.showInputDialog("New child:");
if (childData != null) {
GenericTree.this.getModel().insertNodeInto(new DefaultMutableTreeNode(childData), node, node.getChildCount());
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = 3476173857535861284L;
});
if (0 < row) {
popup.addSeparator();
popup.add(new AbstractAction("Remove") {
@Override
public final void actionPerformed(final ActionEvent event) {
GenericTree.this.getModel().removeNodeFromParent(node);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 7037260191035026652L;
});
}
popup.show(event.getComponent(), event.getX(), event.getY());
}
}
});
}
public GenericTree() {
this("");
}
@Override
public DefaultTreeModel getModel() {
return (DefaultTreeModel) super.getModel();
}
@Override
public final void setModel(final TreeModel newModel) {
super.setModel((DefaultTreeModel) newModel);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 2264597555092857049L;
}
/**
* @author codistmonk (creation 2014-04-28)
*/
public static final class HistogramView extends JLabel {
private final Canvas canvas;
private final Canvas idCanvas;
private final BitSet histogram;
private double[] histogramPoints;
private int[] histogramARGBs;
private final Renderer histogramRenderer;
private final Renderer idRenderer;
private final OrbiterMouseHandler orbiter;
private final Graphics3D histogramGraphics;
private final Graphics3D idGraphics;
private final DoubleList userPoints;
private final IntList userSegments;
private BufferedImage oldImage;
private final int[] idUnderMouse;
private final int[] lastTouchedId;
public HistogramView() {
this.setFocusable(true);
this.addKeyListener(new KeyAdapter() {
@Override
public final void keyPressed(final KeyEvent event) {
switch (event.getKeyCode()) {
case VK_DELETE:
case VK_BACK_SPACE:
final int idToRemove = lastTouchedId[0];
if (0 < idToRemove) {
lastTouchedId[0] = 0;
if (idUnderMouse[0] == idToRemove) {
idUnderMouse[0] = 0;
}
{
final int n = userSegments.size();
int i = 0;
for (int j = 0; j < n; j += 2) {
final int id1 = userSegments.get(j);
final int id2 = userSegments.get(j + 1);
if (idToRemove != id1 && idToRemove != id2) {
userSegments.set(i, id1);
userSegments.set(++i, id2);
++i;
}
}
userSegments.resize(i);
EventManager.getInstance().dispatch(HistogramView.this.new SegmentsUpdatedEvent());
}
{
final int n = userPoints.size();
final int offset = idToRemove * 3;
System.arraycopy(userPoints.toArray(), offset, userPoints.toArray(), offset - 3, n - offset);
userPoints.resize(n - 3);
EventManager.getInstance().dispatch(HistogramView.this.new PointsUpdatedEvent());
}
HistogramView.this.refresh();
}
break;
}
}
});
new MouseHandler(null) {
private final Point lastMouseLocation = new Point();
@Override
public final void mousePressed(final MouseEvent event) {
HistogramView.this.requestFocusInWindow();
idUnderMouse[0] = idCanvas.getImage().getRGB(event.getX(), event.getY()) & 0x00FFFFFF;
this.maybeAddUserSegment(event);
this.lastMouseLocation.setLocation(event.getPoint());
if (0 < idUnderMouse[0]) {
lastTouchedId[0] = idUnderMouse[0];
}
HistogramView.this.refresh();
}
@Override
public final void mouseClicked(final MouseEvent event) {
if (event.getButton() == 1 && event.getClickCount() == 2) {
userPoints.addAll(this.getPoint(event, 0.0));
idUnderMouse[0] = userPoints.size() / 3;
EventManager.getInstance().dispatch(HistogramView.this.new PointsUpdatedEvent());
this.maybeAddUserSegment(event);
this.lastMouseLocation.setLocation(event.getPoint());
lastTouchedId[0] = idUnderMouse[0];
HistogramView.this.refresh();
}
}
@Override
public final void mouseDragged(final MouseEvent event) {
if (0 < idUnderMouse[0]) {
final int offset = (idUnderMouse[0] - 1) * 3;
final double[] tmp = copyOfRange(userPoints.toArray(), offset, offset + 3);
orbiter.transform(tmp);
System.arraycopy(this.getPoint(event, tmp[Z]), 0, userPoints.toArray(), offset, 3);
event.consume();
EventManager.getInstance().dispatch(HistogramView.this.new PointsUpdatedEvent());
{
boolean segmentsUpdated = false;
for (final int id : userSegments.toArray()) {
if (id == idUnderMouse[0]) {
segmentsUpdated = true;
break;
}
}
if (segmentsUpdated) {
EventManager.getInstance().dispatch(HistogramView.this.new SegmentsUpdatedEvent());
}
}
}
}
@Override
public final void mouseMoved(final MouseEvent event) {
final int x = event.getX();
final int y = event.getY();
idUnderMouse[0] = x < 0 || idCanvas.getWidth() <= x || y < 0 || idCanvas.getHeight() <= y ? 0
: idCanvas.getImage().getRGB(x, y) & 0x00FFFFFF;
HistogramView.this.refresh();
}
public final double[] getPoint(final MouseEvent event, final double z) {
final double[] result = { event.getX(), (canvas.getHeight() - 1 - event.getY()), z };
orbiter.inverseTransform(result);
return result;
}
private final void maybeAddUserSegment(final MouseEvent event) {
if (event.getButton() == 1 && (event.getModifiersEx() & SHIFT_DOWN_MASK) == SHIFT_DOWN_MASK
&& 0 < lastTouchedId[0] && 0 < idUnderMouse[0] && lastTouchedId[0] != idUnderMouse[0]) {
userSegments.addAll(lastTouchedId[0], idUnderMouse[0]);
EventManager.getInstance().dispatch(HistogramView.this.new SegmentsUpdatedEvent());
}
}
/**
* {@value}.
*/
private static final long serialVersionUID = 2866844463835255393L;
}.addTo(this);
this.orbiter = new OrbiterMouseHandler(null).addTo(this);
new MouseHandler(null) {
@Override
public final void mouseWheelMoved(final MouseWheelEvent event) {
HistogramView.this.refresh();
}
@Override
public final void mouseDragged(final MouseEvent event) {
HistogramView.this.refresh();
}
/**
* {@value}.
*/
private static final long serialVersionUID = 465287425693150361L;
}.addTo(this);
this.canvas = new Canvas().setFormat(512, 512, BufferedImage.TYPE_INT_ARGB);
this.idCanvas = new Canvas().setFormat(this.canvas.getWidth(), this.canvas.getHeight(), BufferedImage.TYPE_INT_ARGB);
this.histogram = new BitSet(0x00FFFFFF);
this.histogramRenderer = new TiledRenderer(OrthographicRenderer.FACTORY).setCanvas(this.canvas.getImage());
this.idRenderer = new TiledRenderer(OrthographicRenderer.FACTORY).setCanvas(this.idCanvas.getImage());
this.histogramGraphics = new Graphics3D(this.histogramRenderer).setOrbiterParameters(this.orbiter.getParameters());
this.idGraphics = new Graphics3D(this.idRenderer).setOrbiterParameters(this.orbiter.getParameters());
this.userPoints = new DoubleList();
this.userSegments = new IntList();
this.idUnderMouse = new int[1];
this.lastTouchedId = new int[1];
this.setIcon(new ImageIcon(this.canvas.getImage()));
}
public final DoubleList getUserPoints() {
return this.userPoints;
}
public final IntList getUserSegments() {
return this.userSegments;
}
public final void refresh() {
this.refresh(this.oldImage);
}
public final void refresh(final BufferedImage image) {
if (image == null) {
this.oldImage = null;
return;
}
final double x0 = this.canvas.getWidth() / 2;
final double y0 = this.canvas.getHeight() / 2;
final double z0 = 0.0;
final double tx = x0 - 128.0;
final double ty = y0 - 128.0;
final double tz = z0 - 128.0;
final TicToc timer = new TicToc();
final DoubleList times = new DoubleList();
this.histogramGraphics.getOrbiterParameters().setCenterX(x0).setCenterY(y0);
timer.tic();
if (this.oldImage != image) {
this.oldImage = image;
final int w = image.getWidth();
final int h = image.getHeight();
this.histogram.clear();
for (int y = 0; y < h; ++y) {
for (int x = 0; x < w; ++x) {
this.histogram.set(image.getRGB(x, y) & 0x00FFFFFF);
}
}
final int n = this.histogram.cardinality();
debugPrint(n);
this.histogramPoints = new double[n * 3];
this.histogramARGBs = new int[n];
for (int rgb = 0x00000000, i = 0, j = 0; rgb <= 0x00FFFFFF; ++rgb) {
if (this.histogram.get(rgb)) {
this.histogramPoints[i++] = ((rgb >> 16) & 0xFF) + tx;
this.histogramPoints[i++] = ((rgb >> 8) & 0xFF) + ty;
this.histogramPoints[i++] = ((rgb >> 0) & 0xFF) + tz;
this.histogramARGBs[j++] = 0x60000000 | rgb;
}
}
}
times.add(tocTic(timer));
this.histogramRenderer.clear();
this.idRenderer.clear();
this.histogramGraphics.setPointSize(0).transformAndDrawPoints(
this.histogramPoints.clone(), this.histogramARGBs);
times.add(tocTic(timer));
this.drawBox(tx, ty, tz);
times.add(tocTic(timer));
{
final double[] userPoints = this.userPoints.toArray();
final int n = userPoints.length;
this.histogramGraphics.setPointSize(2);
this.idGraphics.setPointSize(2);
for (int i = 0, id = 1; i < n; i += 3, ++id) {
final double x = userPoints[i + X];
final double y = userPoints[i + Y];
final double z = userPoints[i + Z];
this.histogramGraphics.drawPoint(x, y, z, idUnderMouse[0] == id ? 0xFFFFFF00
: lastTouchedId[0] == id ? 0xFF00FFFF : 0xFF0000FF);
this.idGraphics.drawPoint(x, y, z, 0xFF000000 | id);
}
}
{
final double[] userPoints = this.userPoints.toArray();
final int[] userSegments = this.userSegments.toArray();
final int n = userSegments.length;
for (int i = 0; i < n; i += 2) {
final int i1 = (userSegments[i + 0] - 1) * 3;
final int i2 = (userSegments[i + 1] - 1) * 3;
final double x1 = userPoints[i1 + X];
final double y1 = userPoints[i1 + Y];
final double z1 = userPoints[i1 + Z];
final double x2 = userPoints[i2 + X];
final double y2 = userPoints[i2 + Y];
final double z2 = userPoints[i2 + Z];
this.histogramGraphics.drawSegment(x1, y1, z1, x2, y2, z2, 0xFF00FFFF);
}
}
times.add(tocTic(timer));
this.canvas.clear(Color.GRAY);
this.idCanvas.clear(Color.BLACK);
this.histogramRenderer.render();
this.idRenderer.render();
times.add(tocTic(timer));
if (false) {
debugPrint(times);
}
this.repaint();
}
private final void drawBox(final double tx, final double ty, final double tz) {
this.histogramGraphics.drawSegment(
0.0 + tx, 0.0 + ty, 0.0 + tz,
255.0 + tx, 0.0 + ty, 0.0 + tz,
0xFFFF0000);
this.histogramGraphics.drawSegment(
0.0 + tx, 0.0 + ty, 0.0 + tz,
0.0 + tx, 255.0 + ty, 0.0 + tz,
0xFF00FF00);
this.histogramGraphics.drawSegment(
0.0 + tx, 0.0 + ty, 0.0 + tz,
0.0 + tx, 0.0 + ty, 255.0 + tz,
0xFF0000FF);
this.histogramGraphics.drawSegment(
0.0 + tx, 255.0 + ty, 255.0 + tz,
255.0 + tx, 255.0 + ty, 255.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
255.0 + tx, 0.0 + ty, 255.0 + tz,
255.0 + tx, 255.0 + ty, 255.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
255.0 + tx, 255.0 + ty, 0.0 + tz,
255.0 + tx, 255.0 + ty, 255.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
0.0 + tx, 0.0 + ty, 255.0 + tz,
255.0 + tx, 0.0 + ty, 255.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
0.0 + tx, 0.0 + ty, 255.0 + tz,
0.0 + tx, 255.0 + ty, 255.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
0.0 + tx, 255.0 + ty, 0.0 + tz,
255.0 + tx, 255.0 + ty, 0.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
0.0 + tx, 255.0 + ty, 0.0 + tz,
0.0 + tx, 255.0 + ty, 255.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
255.0 + tx, 0.0 + ty, 0.0 + tz,
255.0 + tx, 255.0 + ty, 0.0 + tz,
0xFFFFFFFF);
this.histogramGraphics.drawSegment(
255.0 + tx, 0.0 + ty, 0.0 + tz,
255.0 + tx, 0.0 + ty, 255.0 + tz,
0xFFFFFFFF);
}
/**
* @author codistmonk (creation 2014-05-01)
*/
public abstract class AbstractEvent extends EventManager.AbstractEvent<HistogramView> {
protected AbstractEvent() {
super(HistogramView.this);
}
/**
* {@value}.
*/
private static final long serialVersionUID = -7134443307604095575L;
}
/**
* @author codistmonk (creation 2014-05-01)
*/
public final class PointsUpdatedEvent extends AbstractEvent {
/**
* {@value}.
*/
private static final long serialVersionUID = 563741454550991000L;
}
/**
* @author codistmonk (creation 2014-04-30)
*/
public final class SegmentsUpdatedEvent extends AbstractEvent {
/**
* {@value}.
*/
private static final long serialVersionUID = 9008919825085028206L;
}
/**
* {@value}.
*/
private static final long serialVersionUID = 8150020673886684998L;
public static final long tocTic(final TicToc timer) {
final long result = timer.toc();
timer.tic();
return result;
}
}
/**
* @author codistmonk (creation 2014-04-29)
*/
public static final class Graphics3D implements Serializable {
private final Renderer renderer;
private OrbiterParameters orbiterParameters;
private int pointSize;
public Graphics3D(final Renderer renderer) {
this.renderer = renderer;
this.orbiterParameters = new OrbiterParameters();
}
public final OrbiterParameters getOrbiterParameters() {
return this.orbiterParameters;
}
public final Graphics3D setOrbiterParameters(final OrbiterParameters orbiterParameters) {
this.orbiterParameters = orbiterParameters;
return this;
}
public final int getPointSize() {
return this.pointSize;
}
public final Graphics3D setPointSize(final int pointSize) {
this.pointSize = pointSize;
return this;
}
public final Graphics3D drawSegment(final double x1, final double y1, final double z1,
final double x2, final double y2, final double z2, final int argb) {
final double[] extremities = { x1, y1, z1, x2, y2, z2 };
this.transform(extremities);
final double dx = extremities[3 + X] - extremities[0 + X];
final double dy = extremities[3 + Y] - extremities[0 + Y];
final double dz = extremities[3 + Z] - extremities[0 + Z];
final int d = 1 + (int) max(abs(dx), abs(dy));
for (int i = 0; i < d; ++i) {
this.renderer.addPixel(
extremities[0 + X] + i * dx / d,
extremities[0 + Y] + i * dy / d,
extremities[0 + Z] + i * dz / d,
argb);
}
return this;
}
public final Graphics3D transformAndDrawPoints(final double[] points, final int[] argbs) {
this.transform(points);
for (int i = 0, j = 0; i < points.length; i += 3, ++j) {
for (int ty = -this.pointSize; ty <= this.pointSize; ++ty) {
for (int tx = -this.pointSize; tx <= this.pointSize; ++tx) {
this.renderer.addPixel(points[i + X] + tx, points[i + Y] + ty, points[i + Z], argbs[j]);
}
}
}
return this;
}
public final Graphics3D drawPoint(final double x, final double y, final double z, final int argb) {
return this.transformAndDrawPoints(new double[] { x, y, z }, new int[] { argb });
}
public final Graphics3D transform(final double... points) {
OrbiterMouseHandler.transform(points, this.getOrbiterParameters());
return this;
}
/**
* {@value}.
*/
private static final long serialVersionUID = -1033925831595591034L;
}
/**
* @author codistmonk (creation 2014-04-23)
*/
public static abstract class UpdaterTreeModelListener implements TreeModelListener, Serializable {
@Override
public final void treeNodesChanged(final TreeModelEvent event) {
this.update(event);
}
@Override
public final void treeNodesInserted(final TreeModelEvent event) {
this.update(event);
}
@Override
public final void treeNodesRemoved(final TreeModelEvent event) {
this.update(event);
}
@Override
public final void treeStructureChanged(final TreeModelEvent event) {
this.update(event);
}
public abstract void update(TreeModelEvent event);
/**
* {@value}.
*/
private static final long serialVersionUID = -1429045406856434520L;
}
/**
* @author codistmonk (creation 2014-05-01)
*/
public static final class NearestNeighborRGBQuantizer implements RGBTransformer {
private final Map<Integer, Collection<Integer>> clusters = new TreeMap<>();
public final Map<Integer, Collection<Integer>> getClusters() {
return this.clusters;
}
@Override
public final int transform(final int rgb) {
int result = rgb;
int bestDistance = Integer.MAX_VALUE;
for (final Map.Entry<Integer, Collection<Integer>> entry : this.clusters.entrySet()) {
for (final Integer prototype : entry.getValue()) {
final int distance = distance1(rgb, prototype);
if (distance < bestDistance) {
bestDistance = distance;
result = entry.getKey();
}
}
}
return result;
}
@Override
public final String toString() {
return this.getClass().getSimpleName();
}
/**
* {@value}.
*/
private static final long serialVersionUID = 7849106863112337513L;
}
/**
* @author codistmonk (creation 2014-05-01)
*/
public static final class NearestNeighborRGBLinearizer implements RGBTransformer {
private final Map<Integer, Collection<Integer>> clusters;
private final Integer clusterRGB;
public NearestNeighborRGBLinearizer(final Map<Integer, Collection<Integer>> clusters, final Integer clusterRGB) {
this.clusters = clusters;
this.clusterRGB = clusterRGB;
}
@Override
public final int transform(final int rgb) {
final Integer[] bestClusters = { this.clusterRGB, this.clusterRGB };
final double[] bestDistances = { Double.POSITIVE_INFINITY, Double.POSITIVE_INFINITY };
for (final Map.Entry<Integer, Collection<Integer>> entry : this.clusters.entrySet()) {
for (final Integer prototype : entry.getValue()) {
final int distance = distance1(rgb, prototype);
if (distance < bestDistances[0]) {
bestClusters[1] = bestClusters[0];
bestDistances[1] = bestDistances[0];
bestDistances[0] = distance;
bestClusters[0] = entry.getKey();
} else if (distance < bestDistances[1]) {
bestDistances[1] = distance;
bestClusters[1] = entry.getKey();
}
}
}
if (bestClusters[0] != this.clusterRGB) {
return 0xFF000000;
}
if (bestClusters[0] == bestClusters[1] || bestDistances[0] == 0.0) {
return 0xFFFFFFFF;
}
return a8gray888(0xFF, uint8(
255.0 * (1.0 - 2.0 * bestDistances[0] / (bestDistances[0] + bestDistances[1]))));
}
@Override
public final String toString() {
return Integer.toHexString(this.clusterRGB);
}
/**
* {@value}.
*/
private static final long serialVersionUID = 405532606002207460L;
}
}
|
package com.dineshsunny.fingershare;
import java.util.Locale;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends ActionBarActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {@link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
* Yipee ... Dinesh Sunny's project!!
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent loginIntent = new Intent(this, LoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// YOU CAN ALSO WRITE loginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
// | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
|
package ve.com.abicelis.creditcardexpensemanager.app.fragments;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.github.clans.fab.FloatingActionButton;
import com.github.clans.fab.FloatingActionMenu;
import java.util.ArrayList;
import java.util.List;
import ve.com.abicelis.creditcardexpensemanager.R;
import ve.com.abicelis.creditcardexpensemanager.app.activities.OcrCreateExpenseActivity;
import ve.com.abicelis.creditcardexpensemanager.app.adapters.ExpensesAdapter;
import ve.com.abicelis.creditcardexpensemanager.app.dialogs.CreateOrEditExpenseDialogFragment;
import ve.com.abicelis.creditcardexpensemanager.app.holders.ExpensesViewHolder;
import ve.com.abicelis.creditcardexpensemanager.app.utils.Constants;
import ve.com.abicelis.creditcardexpensemanager.app.utils.SharedPreferencesUtils;
import ve.com.abicelis.creditcardexpensemanager.database.ExpenseManagerDAO;
import ve.com.abicelis.creditcardexpensemanager.exceptions.CouldNotDeleteDataException;
import ve.com.abicelis.creditcardexpensemanager.exceptions.CreditCardNotFoundException;
import ve.com.abicelis.creditcardexpensemanager.exceptions.CreditPeriodNotFoundException;
import ve.com.abicelis.creditcardexpensemanager.exceptions.SharedPreferenceNotFoundException;
import ve.com.abicelis.creditcardexpensemanager.model.CreditCard;
import ve.com.abicelis.creditcardexpensemanager.model.Expense;
public class ExpenseListFragment extends Fragment {
//Data
int activeCreditCardId = -1;
CreditCard activeCreditCard = null;
List<Expense> creditCardExpenses = new ArrayList<>();
ExpenseManagerDAO mDao;
RecyclerView recyclerViewExpenses;
LinearLayoutManager mLayoutManager;
ExpensesAdapter mAdapter;
FloatingActionMenu fabMenu;
FloatingActionButton fabNewExpense;
FloatingActionButton fabNewExpenseCamera;
SwipeRefreshLayout swipeRefreshLayout;
RelativeLayout noCCContainer;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.fragment_name_expense_list));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadDao();
try {
activeCreditCardId = SharedPreferencesUtils.getInt(getContext(), Constants.ACTIVE_CC_ID);
try {
refreshData();
}catch (CreditCardNotFoundException e ) {
Toast.makeText(getActivity(), getResources().getString(R.string.err_problem_loading_card_or_no_card_exists), Toast.LENGTH_SHORT).show();
}catch (CreditPeriodNotFoundException e) {
Toast.makeText(getActivity(), getResources().getString(R.string.err_problem_loading_credit_period), Toast.LENGTH_SHORT).show();
}
}catch(SharedPreferenceNotFoundException e) {
//This shouldn't happen
}
}
@Override
public void onResume() {
refreshRecyclerView();
super.onResume();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_expense_list, container, false);
recyclerViewExpenses = (RecyclerView) rootView.findViewById(R.id.home_recycler_expenses);
noCCContainer = (RelativeLayout) rootView.findViewById(R.id.home_err_no_cc_container);
swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.home_swipe_refresh);
fabMenu = (FloatingActionMenu) rootView.findViewById(R.id.home_fab_menu);
fabNewExpense = (FloatingActionButton) rootView.findViewById(R.id.home_fab_new_expense);
fabNewExpenseCamera = (FloatingActionButton) rootView.findViewById(R.id.home_fab_new_expense_camera);
// final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) rootView.findViewById(R.id.home_collapsing);
// AppBarLayout appBarLayout = (AppBarLayout) rootView.findViewById(R.id.home_appbar);
// toolbar = (Toolbar) rootView.findViewById(R.id.home_toolbar);
if(activeCreditCard != null) {
setUpRecyclerView(rootView);
setUpSwipeRefresh(rootView);
//setUpToolbar(rootView);
setUpFab(rootView);
}
else {
noCCContainer.setVisibility(View.VISIBLE);
swipeRefreshLayout.setVisibility(View.GONE);
fabMenu.setVisibility(View.GONE);
}
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// view.post(new Runnable() {
// @Override
// public void run() {
// chartFragment = (ChartExpenseFragment) getFragmentManager().findFragmentById(R.id.home_chart_container);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//If coming back from expenseDetailActivity and data was edited/deleted, refresh.
if (requestCode == Constants.EXPENSE_DETAIL_ACTIVITY_REQUEST_CODE && resultCode == Constants.RESULT_REFRESH_DATA) {
//Toast.makeText(getActivity(), "Refreshing Expenses!", Toast.LENGTH_SHORT).show();
//refreshChart();
refreshRecyclerView();
}
}
// @Override
// public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// super.onCreateOptionsMenu(menu, inflater);
// inflater.inflate(R.menu.menu_overview, menu);
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// switch(id) {
// case R.id.overview_menu_add_card:
// Toast.makeText(getActivity(), "oaiwjdoiwd", Toast.LENGTH_SHORT).show();
// break;
// return true;
private void loadDao() {
if(mDao == null)
mDao = new ExpenseManagerDAO(getActivity().getApplicationContext());
}
private void setUpRecyclerView(View rootView) {
ExpensesViewHolder.ExpenseDeletedListener listener = new ExpensesViewHolder.ExpenseDeletedListener() {
@Override
public void OnExpenseDeleted(int position) {
try {
mDao.deleteExpense(creditCardExpenses.get(position).getId());
creditCardExpenses.remove(position);
mAdapter.notifyItemRemoved(position);
mAdapter.notifyItemRangeChanged(position, mAdapter.getItemCount());
//refreshChart();
}catch (CouldNotDeleteDataException e) {
Toast.makeText(getActivity(), "There was an error deleting the expense!", Toast.LENGTH_SHORT).show();
}
}
};
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
mAdapter = new ExpensesAdapter(this, creditCardExpenses, activeCreditCard.getCreditPeriods().get(0).getId(), listener);
DividerItemDecoration itemDecoration = new DividerItemDecoration(recyclerViewExpenses.getContext(), mLayoutManager.getOrientation());
itemDecoration.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.item_decoration_half_line));
recyclerViewExpenses.addItemDecoration(itemDecoration);
recyclerViewExpenses.setLayoutManager(mLayoutManager);
recyclerViewExpenses.setAdapter(mAdapter);
}
private void setUpSwipeRefresh(View rootView) {
swipeRefreshLayout.setColorSchemeResources(R.color.swipe_refresh_green, R.color.swipe_refresh_red, R.color.swipe_refresh_yellow);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshRecyclerView();
//refreshChart();
swipeRefreshLayout.setRefreshing(false);
}
}
);
}
// private void setUpToolbar(View rootView) {
// appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
// boolean isShow = false;
// int scrollRange = -1;
// @Override
// public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
// if (scrollRange == -1) {
// scrollRange = appBarLayout.getTotalScrollRange();
// if (scrollRange + verticalOffset == 0) {
// collapsingToolbarLayout.setTitle(getResources().getString(R.string.app_name));
// isShow = true;
// } else if(isShow) {
// collapsingToolbarLayout.setTitle(" ");//carefull there should a space between double quote otherwise it wont work
// isShow = false;
private void setUpFab(View rootView) {
fabMenu.setClosedOnTouchOutside(true);
fabNewExpense.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fabMenu.close(true);
showCreateExpenseDialog();
}
});
fabNewExpenseCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fabMenu.close(true);
Intent intent = new Intent(getActivity(), OcrCreateExpenseActivity.class);
intent.putExtra(OcrCreateExpenseActivity.TAG_EXTRA_PERIOD_ID, activeCreditCard.getCreditPeriods().get(0).getId());
intent.putExtra(OcrCreateExpenseActivity.TAG_EXTRA_CURRENCY, activeCreditCard.getCurrency());
startActivity(intent);
}
});
}
public void refreshData() throws CreditCardNotFoundException, CreditPeriodNotFoundException {
activeCreditCard = mDao.getCreditCardWithCreditPeriod(activeCreditCardId, 0);
//Clear the list and refresh it with new data, this must be done so the mAdapter
// doesn't lose track of creditCardExpenses object when overwriting
// activeCreditCard.getCreditPeriods().get(0).getExpenses();
creditCardExpenses.clear();
creditCardExpenses.addAll(activeCreditCard.getCreditPeriods().get(0).getExpenses());
}
public void refreshRecyclerView() {
if(activeCreditCard != null) {
loadDao();
int oldExpensesCount = creditCardExpenses.size();
try {
refreshData();
}catch (CreditCardNotFoundException e ) {
Toast.makeText(getActivity(), getResources().getString(R.string.err_problem_loading_card_or_no_card_exists), Toast.LENGTH_SHORT).show();
return;
}catch (CreditPeriodNotFoundException e) {
Toast.makeText(getActivity(), getResources().getString(R.string.err_problem_loading_credit_period), Toast.LENGTH_SHORT).show();
return;
}
int newExpensesCount = creditCardExpenses.size();
//TODO: in the future, expenses wont necessarily be added with date=now,
//TODO: meaning they wont always be added on recyclerview position = 0
//If a new expense was added
if(newExpensesCount == oldExpensesCount+1) {
mAdapter.notifyItemInserted(0);
mAdapter.notifyItemRangeChanged(1, activeCreditCard.getCreditPeriods().get(0).getExpenses().size()-1);
mLayoutManager.scrollToPosition(0);
} else {
mAdapter.notifyDataSetChanged();
}
}
}
// private void refreshChart(){
// //TODO: this is probably a hack.. maybe a listener is needed here?
// //Refresh chartFragment
// if(chartFragment != null)
// chartFragment.refreshData();
// else
// Toast.makeText(getActivity(), "Error on onDismiss, chartFragment == null!", Toast.LENGTH_SHORT).show();
private void showCreateExpenseDialog() {
FragmentManager fm = getFragmentManager();
CreateOrEditExpenseDialogFragment dialog = CreateOrEditExpenseDialogFragment.newInstance(
mDao,
activeCreditCard.getCreditPeriods().get(0).getId(),
activeCreditCard.getCurrency(),
null);
dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
refreshRecyclerView();
//refreshChart();
}
});
dialog.show(fm, "fragment_dialog_create_expense");
}
}
|
package com.hyperwallet.clientsdk;
import com.fasterxml.jackson.core.type.TypeReference;
import com.hyperwallet.clientsdk.model.*;
import com.hyperwallet.clientsdk.util.HyperwalletApiClient;
import com.hyperwallet.clientsdk.util.HyperwalletEncryption;
import com.hyperwallet.clientsdk.util.HyperwalletJsonUtil;
import org.apache.commons.lang3.StringUtils;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.TimeZone;
/**
* The Hyperwallet Client
*/
public class Hyperwallet {
public static final String VERSION = "1.4.2";
private final HyperwalletApiClient apiClient;
private final String programToken;
private final String url;
/**
* Create Hyperwallet SDK instance
*
* @param username API key assigned
* @param password API Password assigned
* @param programToken API program token
* @param server API server url
* @param hyperwalletEncryption API encryption data
*/
public Hyperwallet(final String username, final String password, final String programToken, final String server,
final HyperwalletEncryption hyperwalletEncryption) {
apiClient = new HyperwalletApiClient(username, password, VERSION, hyperwalletEncryption);
this.programToken = programToken;
this.url = StringUtils.isEmpty(server) ? "https://api.sandbox.hyperwallet.com/rest/v4" : server + "/rest/v4";
}
/**
* Create Hyperwallet SDK instance
*
* @param username API key assigned
* @param password API Password assigned
* @param programToken API program token
* @param server API serer url
*/
public Hyperwallet(final String username, final String password, final String programToken, final String server) {
this(username, password, programToken, server, null);
}
/**
* Create Hyperwallet SDK instance
*
* @param username API key assigned
* @param password API password
* @param programToken API program token assigned
*/
public Hyperwallet(final String username, final String password, final String programToken) {
this(username, password, programToken, null, null);
}
/**
* Create Hyperwallet SDK instance
*
* @param username API key assigned
* @param password API password
* @param programToken API program token assigned
* @param hyperwalletEncryption API encryption data
*/
public Hyperwallet(final String username, final String password, final String programToken,
final HyperwalletEncryption hyperwalletEncryption) {
this(username, password, programToken, null, hyperwalletEncryption);
}
/**
* Create Hyperwallet SDK instance
*
* @param username API key assigned
* @param password API password
*/
public Hyperwallet(final String username, final String password) {
this(username, password, null);
}
// Users
/**
* Create a User
*
* @param user Hyperwallet user representation
* @return HyperwalletUser created User
*/
public HyperwalletUser createUser(HyperwalletUser user) {
if (user == null) {
throw new HyperwalletException("User is required");
}
if (!StringUtils.isEmpty(user.getToken())) {
throw new HyperwalletException("User token may not be present");
}
user = copy(user);
user.setStatus(null);
user.setCreatedOn(null);
return apiClient.post(url + "/users", user, HyperwalletUser.class);
}
/**
* Get User
*
* @param token user account token
* @return HyperwalletUser retreived user
*/
public HyperwalletUser getUser(String token) {
if (StringUtils.isEmpty(token)) {
throw new HyperwalletException("User token is required");
}
return apiClient.get(url + "/users/" + token, HyperwalletUser.class);
}
/**
* Update User
*
* @param user Hyperwallet User representation object
* @return HyperwalletUser updated user object
*/
public HyperwalletUser updateUser(HyperwalletUser user) {
if (user == null) {
throw new HyperwalletException("User is required");
}
if (StringUtils.isEmpty(user.getToken())) {
throw new HyperwalletException("User token is required");
}
return apiClient.put(url + "/users/" + user.getToken(), user, HyperwalletUser.class);
}
/**
* List Users
*
* @return HyperwalletList of HyperwalletUser
*/
public HyperwalletList<HyperwalletUser> listUsers() {
return listUsers(null);
}
/**
* List Users
*
* @param options List filter option
* @return HyperwalletList of HyperwalletUser
*/
public HyperwalletList<HyperwalletUser> listUsers(HyperwalletPaginationOptions options) {
String url = paginate(this.url + "/users", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletUser>>() {
});
}
/**
* Get User Status Transition
*
* @param userToken User token
* @param statusTransitionToken Status transition token
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition listgetUserStatusTransition(String userToken, String statusTransitionToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(statusTransitionToken)) {
throw new HyperwalletException("Transition token is required");
}
return apiClient.get(url + "/users/" + userToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class);
}
/**
* Create Business Stakeholder
*
* @param stakeholder Hyperwallet Stakeholder representation
* @param userToken String
* @return HyperwalletBusinessStakeholder created Stakeholder
*/
public HyperwalletBusinessStakeholder createBusinessStakeholder(String userToken, HyperwalletBusinessStakeholder stakeholder) {
System.out.println("--Business Stakeholder - create");
if (stakeholder == null) {
throw new HyperwalletException("Stakeholder is required");
}
if (userToken == null) {
throw new HyperwalletException("User token may not be present");
}
stakeholder = copy(stakeholder);
// stakeholder.setStatus(null);
// stakeholder.setCreatedOn(null);
return apiClient.post(url + "/users/"+ userToken + "/business-stakeholders", stakeholder, HyperwalletBusinessStakeholder.class);
}
/**
* Update User
*
* @param user Hyperwallet User representation object
* @return HyperwalletUser updated user object
*/
// public HyperwalletUser updateBusinessStakeholder(HyperwalletBusinessStakeholder stakeholder) {
// if (stakeholder == null) {
// throw new HyperwalletException("User is required");
// if (StringUtils.isEmpty(stakeholder.getToken())) {
// throw new HyperwalletException("User token is required");
// return apiClient.put(url + "/users/" + user.getToken(), user, HyperwalletUser.class);
/**
* Get Authentication Token
*
* @param token user account token
* @return HyperwalletAuthenticationToken retreived authentication token
*/
public HyperwalletAuthenticationToken getAuthenticationToken(String token) {
if (StringUtils.isEmpty(token)) {
throw new HyperwalletException("User token is required");
}
String urlString = url + "/users/" + token + "/authentication-token";
return apiClient.post(urlString, null, HyperwalletAuthenticationToken.class);
}
/**
* Get User Status Transition
*
* @param userToken User token
* @param statusTransitionToken Status transition token
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition getUserStatusTransition(String userToken, String statusTransitionToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(statusTransitionToken)) {
throw new HyperwalletException("Transition token is required");
}
return apiClient.get(url + "/users/" + userToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class);
}
/**
* List All User Status Transition information
*
* @param userToken User token
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listUserStatusTransitions(String userToken) {
return listUserStatusTransitions(userToken, null);
}
/**
* List Prepaid Card Status Transition information
*
* @param userToken User token
* @param options List filter option
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listUserStatusTransitions(String userToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/status-transitions", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() {
});
}
// Prepaid Cards
/**
* Create Prepaid Card
*
* @param prepaidCard Prepaid Card object to create
* @return HyperwalletPrepaidCard Prepaid Card object created
*/
public HyperwalletPrepaidCard createPrepaidCard(HyperwalletPrepaidCard prepaidCard) {
if (prepaidCard == null) {
throw new HyperwalletException("Prepaid Card is required");
}
if (StringUtils.isEmpty(prepaidCard.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (!StringUtils.isEmpty(prepaidCard.getToken())) {
throw new HyperwalletException("Prepaid Card token may not be present");
}
if (prepaidCard.getType() == null) {
prepaidCard.setType(HyperwalletTransferMethod.Type.PREPAID_CARD);
}
prepaidCard = copy(prepaidCard);
prepaidCard.setStatus(null);
prepaidCard.setCardType(null);
prepaidCard.setCreatedOn(null);
prepaidCard.setTransferMethodCountry(null);
prepaidCard.setTransferMethodCurrency(null);
prepaidCard.setCardNumber(null);
prepaidCard.setCardBrand(null);
prepaidCard.setDateOfExpiry(null);
return apiClient.post(url + "/users/" + prepaidCard.getUserToken() + "/prepaid-cards", prepaidCard, HyperwalletPrepaidCard.class);
}
/**
* Get Prepaid Card
*
* @param userToken User token assigned
* @param prepaidCardToken Prepaid Card token
* @return HyperwalletPrepaidCard Prepaid Card
*/
public HyperwalletPrepaidCard getPrepaidCard(String userToken, String prepaidCardToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(prepaidCardToken)) {
throw new HyperwalletException("Prepaid Card token is required");
}
return apiClient.get(url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken, HyperwalletPrepaidCard.class);
}
/**
* Update Prepaid Card
*
* @param prepaidCard Prepaid Card object to create
* @return HyperwalletPrepaidCard Prepaid Card object created
*/
public HyperwalletPrepaidCard updatePrepaidCard(HyperwalletPrepaidCard prepaidCard) {
if (prepaidCard == null) {
throw new HyperwalletException("Prepaid Card is required");
}
if (StringUtils.isEmpty(prepaidCard.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(prepaidCard.getToken())) {
throw new HyperwalletException("Prepaid Card token is required");
}
return apiClient.put(url + "/users/" + prepaidCard.getUserToken() + "/prepaid-cards/" + prepaidCard.getToken(),
prepaidCard,
HyperwalletPrepaidCard.class);
}
/**
* List User's Prepaid Card
*
* @param userToken User token assigned
* @return HyperwalletList of HyperwalletPrepaidCard
*/
public HyperwalletList<HyperwalletPrepaidCard> listPrepaidCards(String userToken) {
return listPrepaidCards(userToken, null);
}
/**
* List User's Prepaid Card
*
* @param userToken User token assigned
* @param options List filter option
* @return HyperwalletList of HyperwalletPrepaidCard
*/
public HyperwalletList<HyperwalletPrepaidCard> listPrepaidCards(String userToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/prepaid-cards", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPrepaidCard>>() {
});
}
/**
* Suspend a prepaid card
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @return The status transition
*/
public HyperwalletStatusTransition suspendPrepaidCard(String userToken, String prepaidCardToken) {
return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.SUSPENDED));
}
/**
* Unsuspend a prepaid card
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @return The status transition
*/
public HyperwalletStatusTransition unsuspendPrepaidCard(String userToken, String prepaidCardToken) {
return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.UNSUSPENDED));
}
/**
* Mark a prepaid card as lost or stolen
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @return The status transition
*/
public HyperwalletStatusTransition lostOrStolenPrepaidCard(String userToken, String prepaidCardToken) {
return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.LOST_OR_STOLEN));
}
/**
* Deactivate a prepaid card
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @return The status transition
*/
public HyperwalletStatusTransition deactivatePrepaidCard(String userToken, String prepaidCardToken) {
return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED));
}
/**
* Lock a prepaid card
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @return The status transition
*/
public HyperwalletStatusTransition lockPrepaidCard(String userToken, String prepaidCardToken) {
return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.LOCKED));
}
/**
* Unlock a prepaid card
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @return The status transition
*/
public HyperwalletStatusTransition unlockPrepaidCard(String userToken, String prepaidCardToken) {
return createPrepaidCardStatusTransition(userToken, prepaidCardToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.UNLOCKED));
}
/**
* Create Prepaid Card Status Transition
*
* @param userToken User token
* @param prepaidCardToken Prepaid Card token
* @param transition Status transition information
* @return HyperwalletStatusTransition new status for Prepaid Card
*/
public HyperwalletStatusTransition createPrepaidCardStatusTransition(String userToken, String prepaidCardToken, HyperwalletStatusTransition transition) {
if (transition == null) {
throw new HyperwalletException("Transition is required");
}
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(prepaidCardToken)) {
throw new HyperwalletException("Prepaid Card token is required");
}
if (!StringUtils.isEmpty(transition.getToken())) {
throw new HyperwalletException("Status Transition token may not be present");
}
transition = copy(transition);
transition.setCreatedOn(null);
transition.setFromStatus(null);
transition.setToStatus(null);
return apiClient.post(url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/status-transitions", transition, HyperwalletStatusTransition.class);
}
/**
* Get Prepaid Card Status Transition
*
* @param userToken User token
* @param prepaidCardToken Prepaid Card token
* @param statusTransitionToken Status transition token
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition getPrepaidCardStatusTransition(String userToken, String prepaidCardToken, String statusTransitionToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(prepaidCardToken)) {
throw new HyperwalletException("Prepaid Card token is required");
}
if (StringUtils.isEmpty(statusTransitionToken)) {
throw new HyperwalletException("Transition token is required");
}
return apiClient.get(url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class);
}
/**
* List All Prepaid Card Status Transition information
*
* @param userToken User token
* @param prepaidCardToken Prepaid Card token
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPrepaidCardStatusTransitions(String userToken, String prepaidCardToken) {
return listPrepaidCardStatusTransitions(userToken, prepaidCardToken, null);
}
/**
* List Prepaid Card Status Transition information
*
* @param userToken User token
* @param prepaidCardToken Prepaid Card token
* @param options List filter option
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPrepaidCardStatusTransitions(String userToken, String prepaidCardToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(prepaidCardToken)) {
throw new HyperwalletException("Prepaid Card token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/status-transitions", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() {
});
}
// Bank Cards
/**
* Create Bank Card
*
* @param bankCard Bank Card object to create
* @return HyperwalletBankCard Bank Card object created
*/
public HyperwalletBankCard createBankCard(HyperwalletBankCard bankCard) {
if (bankCard == null) {
throw new HyperwalletException("Bank Card is required");
}
if (StringUtils.isEmpty(bankCard.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (!StringUtils.isEmpty(bankCard.getToken())) {
throw new HyperwalletException("Bank Card token may not be present");
}
if (bankCard.getType() == null) {
bankCard.setType(HyperwalletTransferMethod.Type.BANK_CARD);
}
bankCard = copy(bankCard);
bankCard.setStatus(null);
bankCard.setCardType(null);
bankCard.setCreatedOn(null);
bankCard.setCardBrand(null);
return apiClient.post(url + "/users/" + bankCard.getUserToken() + "/bank-cards", bankCard, HyperwalletBankCard.class);
}
/**
* Get Bank Card
*
* @param userToken User token assigned
* @param bankCardToken Bank Card token
* @return HyperwalletBankCard Bank Card
*/
public HyperwalletBankCard getBankCard(String userToken, String bankCardToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankCardToken)) {
throw new HyperwalletException("Bank Card token is required");
}
return apiClient.get(url + "/users/" + userToken + "/bank-cards/" + bankCardToken, HyperwalletBankCard.class);
}
/**
* Update Bank Card
*
* @param bankCard Bank Card object to create
* @return HyperwalletBankCard Bank Card object created
*/
public HyperwalletBankCard updateBankCard(HyperwalletBankCard bankCard) {
if (bankCard == null) {
throw new HyperwalletException("Bank Card is required");
}
if (StringUtils.isEmpty(bankCard.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankCard.getToken())) {
throw new HyperwalletException("Bank Card token is required");
}
return apiClient.put(url + "/users/" + bankCard.getUserToken() + "/bank-cards/" + bankCard.getToken(), bankCard, HyperwalletBankCard.class);
}
/**
* List User's Bank Card
*
* @param userToken User token assigned
* @return HyperwalletList of HyperwalletBankCard
*/
public HyperwalletList<HyperwalletBankCard> listBankCards(String userToken) {
return listBankCards(userToken, null);
}
/**
* List User's Bank Card
*
* @param userToken User token assigned
* @param options List filter option
* @return HyperwalletList of HyperwalletBankCard
*/
public HyperwalletList<HyperwalletBankCard> listBankCards(String userToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/bank-cards", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBankCard>>() {
});
}
/**
* Deactivate a bank card
*
* @param userToken User token
* @param bankCardToken Bank card token
* @return The status transition
*/
public HyperwalletStatusTransition deactivateBankCard(String userToken, String bankCardToken) {
return deactivateBankCard(userToken, bankCardToken, null);
}
/**
* Deactivate a bank card
*
* @param userToken User token
* @param bankCardToken Bank card token
* @param notes Comments regarding the status change
* @return The status transition
*/
public HyperwalletStatusTransition deactivateBankCard(String userToken, String bankCardToken, String notes) {
return createBankCardStatusTransition(userToken,
bankCardToken,
new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED).notes(notes));
}
/**
* Create Bank Card Status Transition
*
* @param userToken User token
* @param bankCardToken Bank Card token
* @param transition Status transition information
* @return HyperwalletStatusTransition new status for Bank Card
*/
public HyperwalletStatusTransition createBankCardStatusTransition(String userToken, String bankCardToken, HyperwalletStatusTransition transition) {
if (transition == null) {
throw new HyperwalletException("Transition is required");
}
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankCardToken)) {
throw new HyperwalletException("Bank Card token is required");
}
if (!StringUtils.isEmpty(transition.getToken())) {
throw new HyperwalletException("Status Transition token may not be present");
}
transition = copy(transition);
transition.setCreatedOn(null);
transition.setFromStatus(null);
transition.setToStatus(null);
return apiClient.post(url + "/users/" + userToken + "/bank-cards/" + bankCardToken + "/status-transitions", transition, HyperwalletStatusTransition.class);
}
/**
* Get Bank Card Status Transition
*
* @param userToken User token
* @param bankCardToken Bank Card token
* @param statusTransitionToken Status transition token
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition getBankCardStatusTransition(String userToken, String bankCardToken, String statusTransitionToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankCardToken)) {
throw new HyperwalletException("Bank Card token is required");
}
if (StringUtils.isEmpty(statusTransitionToken)) {
throw new HyperwalletException("Transition token is required");
}
return apiClient.get(url + "/users/" + userToken + "/bank-cards/" + bankCardToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class);
}
/**
* List All Bank Card Status Transition information
*
* @param userToken User token
* @param bankCardToken Bank Card token
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listBankCardStatusTransitions(String userToken, String bankCardToken) {
return listBankCardStatusTransitions(userToken, bankCardToken, null);
}
/**
* List Bank Card Status Transition information
*
* @param userToken User token
* @param bankCardToken Bank Card token
* @param options List filter option
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listBankCardStatusTransitions(String userToken, String bankCardToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankCardToken)) {
throw new HyperwalletException("Bank Card token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/bank-cards/" + bankCardToken + "/status-transitions", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() {
});
}
// Paper Checks
/**
* Create Paper Check
*
* @param paperCheck Paper Check object to create
* @return HyperwalletPaperCheck Paper Check object created
*/
public HyperwalletPaperCheck createPaperCheck(HyperwalletPaperCheck paperCheck) {
if (paperCheck == null) {
throw new HyperwalletException("Paper Check is required");
}
if (StringUtils.isEmpty(paperCheck.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (!StringUtils.isEmpty(paperCheck.getToken())) {
throw new HyperwalletException("Paper Check token may not be present");
}
if (paperCheck.getType() == null) {
paperCheck.setType(HyperwalletTransferMethod.Type.PAPER_CHECK);
}
paperCheck = copy(paperCheck);
paperCheck.setStatus(null);
paperCheck.setCreatedOn(null);
return apiClient.post(url + "/users/" + paperCheck.getUserToken() + "/paper-checks", paperCheck, HyperwalletPaperCheck.class);
}
/**
* Get Paper Check
*
* @param userToken User token assigned
* @param paperCheckToken Paper Check token
* @return HyperwalletPaperCheck Paper Check
*/
public HyperwalletPaperCheck getPaperCheck(String userToken, String paperCheckToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(paperCheckToken)) {
throw new HyperwalletException("Paper Check token is required");
}
return apiClient.get(url + "/users/" + userToken + "/paper-checks/" + paperCheckToken, HyperwalletPaperCheck.class);
}
/**
* Update Paper Check
*
* @param paperCheck Paper Check object to create
* @return HyperwalletPaperCheck Paper Check object created
*/
public HyperwalletPaperCheck updatePaperCheck(HyperwalletPaperCheck paperCheck) {
if (paperCheck == null) {
throw new HyperwalletException("Paper Check is required");
}
if (StringUtils.isEmpty(paperCheck.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(paperCheck.getToken())) {
throw new HyperwalletException("Paper Check token is required");
}
return apiClient.put(url + "/users/" + paperCheck.getUserToken() + "/paper-checks/" + paperCheck.getToken(), paperCheck, HyperwalletPaperCheck.class);
}
/**
* List User's Paper Check
*
* @param userToken User token assigned
* @return HyperwalletList of HyperwalletPaperCheck
*/
public HyperwalletList<HyperwalletPaperCheck> listPaperChecks(String userToken) {
return listPaperChecks(userToken, null);
}
/**
* List User's Paper Check
*
* @param userToken User token assigned
* @param options List filter option
* @return HyperwalletList of HyperwalletPaperCheck
*/
public HyperwalletList<HyperwalletPaperCheck> listPaperChecks(String userToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/paper-checks", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPaperCheck>>() {
});
}
/**
* Deactivate a Paper Check
*
* @param userToken User token
* @param paperCheckToken Paper Check token
* @return The status transition
*/
public HyperwalletStatusTransition deactivatePaperCheck(String userToken, String paperCheckToken) {
return deactivatePaperCheck(userToken, paperCheckToken, null);
}
/**
* Deactivate a Paper Check
*
* @param userToken User token
* @param paperCheckToken Paper Check token
* @return The status transition
*/
public HyperwalletStatusTransition deactivatePaperCheck(String userToken, String paperCheckToken, String notes) {
return createPaperCheckStatusTransition(userToken,
paperCheckToken,
new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED).notes(notes));
}
/**
* Create Paper Check Status Transition
*
* @param userToken User token
* @param paperCheckToken Paper Check token
* @param transition Status transition information
* @return HyperwalletStatusTransition new status for Paper Check
*/
public HyperwalletStatusTransition createPaperCheckStatusTransition(String userToken, String paperCheckToken, HyperwalletStatusTransition transition) {
if (transition == null) {
throw new HyperwalletException("Transition is required");
}
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(paperCheckToken)) {
throw new HyperwalletException("Paper Check token is required");
}
if (!StringUtils.isEmpty(transition.getToken())) {
throw new HyperwalletException("Status Transition token may not be present");
}
transition = copy(transition);
transition.setCreatedOn(null);
transition.setFromStatus(null);
transition.setToStatus(null);
return apiClient.post(url + "/users/" + userToken + "/paper-checks/" + paperCheckToken + "/status-transitions", transition, HyperwalletStatusTransition.class);
}
/**
* Get Paper Check Status Transition
*
* @param userToken User token
* @param paperCheckToken Paper Check token
* @param statusTransitionToken Status transition token
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition getPaperCheckStatusTransition(String userToken, String paperCheckToken, String statusTransitionToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(paperCheckToken)) {
throw new HyperwalletException("Paper Check token is required");
}
if (StringUtils.isEmpty(statusTransitionToken)) {
throw new HyperwalletException("Transition token is required");
}
return apiClient.get(url + "/users/" + userToken + "/paper-checks/" + paperCheckToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class);
}
/**
* List All Paper Check Status Transition information
*
* @param userToken User token
* @param paperCheckToken Paper Check token
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPaperCheckStatusTransitions(String userToken, String paperCheckToken) {
return listPaperCheckStatusTransitions(userToken, paperCheckToken, null);
}
/**
* List Paper Check Status Transition information
*
* @param userToken User token
* @param paperCheckToken Paper Check token
* @param options List filter option
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPaperCheckStatusTransitions(String userToken, String paperCheckToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(paperCheckToken)) {
throw new HyperwalletException("Paper Check token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/paper-checks/" + paperCheckToken + "/status-transitions", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() {
});
}
// Transfers
/**
* Create Transfer Request
*
* @param transfer HyperwalletTransfer object to create
* @return HyperwalletTransfer Transfer object created
*/
public HyperwalletTransfer createTransfer(HyperwalletTransfer transfer) {
if (transfer == null) {
throw new HyperwalletException("Transfer is required");
}
if (StringUtils.isEmpty(transfer.getSourceToken())) {
throw new HyperwalletException("Source token is required");
}
if (StringUtils.isEmpty(transfer.getDestinationToken())) {
throw new HyperwalletException("Destination token is required");
}
if (StringUtils.isEmpty(transfer.getClientTransferId())) {
throw new HyperwalletException("ClientTransferId is required");
}
transfer = copy(transfer);
transfer.setStatus(null);
transfer.setCreatedOn(null);
transfer.setExpiresOn(null);
return apiClient.post(url + "/transfers", transfer, HyperwalletTransfer.class);
}
/**
* Get Transfer Request
*
* @param transferToken Transfer token assigned
* @return HyperwalletTransfer Transfer
*/
public HyperwalletTransfer getTransfer(String transferToken) {
if (StringUtils.isEmpty(transferToken)) {
throw new HyperwalletException("Transfer token is required");
}
return apiClient.get(url + "/transfers/" + transferToken, HyperwalletTransfer.class);
}
/**
* List Transfer Requests
*
* @param options List filter option
* @return HyperwalletList of HyperwalletTransfer
*/
public HyperwalletList<HyperwalletTransfer> listTransfers(HyperwalletTransferListOptions options) {
String url = paginate(this.url + "/transfers", options);
if (options != null) {
url = addParameter(url, "sourceToken", options.getSourceToken());
url = addParameter(url, "destinationToken", options.getDestinationToken());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletTransfer>>() {
});
}
/**
* List Transfer Requests
*
* @return HyperwalletList of HyperwalletTransfer
*/
public HyperwalletList<HyperwalletTransfer> listTransfers() {
return listTransfers(null);
}
/**
* Create Transfer Status Transition
*
* @param transferToken Transfer token assigned
* @return HyperwalletStatusTransition new status for Transfer Request
*/
public HyperwalletStatusTransition createTransferStatusTransition(String transferToken, HyperwalletStatusTransition transition) {
if (transition == null) {
throw new HyperwalletException("Transition is required");
}
if (StringUtils.isEmpty(transferToken)) {
throw new HyperwalletException("Transfer token is required");
}
if (!StringUtils.isEmpty(transition.getToken())) {
throw new HyperwalletException("Status Transition token may not be present");
}
transition = copy(transition);
transition.setCreatedOn(null);
transition.setFromStatus(null);
transition.setToStatus(null);
return apiClient.post(url + "/transfers/" + transferToken + "/status-transitions", transition, HyperwalletStatusTransition.class);
}
// PayPal Accounts
/**
* Create PayPal Account Request
*
* @param payPalAccount HyperwalletPayPalAccount object to create
* @return HyperwalletPayPalAccount created PayPal account for the specified user
*/
public HyperwalletPayPalAccount createPayPalAccount(HyperwalletPayPalAccount payPalAccount) {
if (payPalAccount == null) {
throw new HyperwalletException("PayPal Account is required");
}
if (StringUtils.isEmpty(payPalAccount.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(payPalAccount.getTransferMethodCountry())) {
throw new HyperwalletException("Transfer Method Country is required");
}
if (StringUtils.isEmpty(payPalAccount.getTransferMethodCurrency())) {
throw new HyperwalletException("Transfer Method Currency is required");
}
if (StringUtils.isEmpty(payPalAccount.getEmail())) {
throw new HyperwalletException("Email is required");
}
if (!StringUtils.isEmpty(payPalAccount.getToken())) {
throw new HyperwalletException("PayPal Account token may not be present");
}
if (payPalAccount.getType() == null) {
payPalAccount.setType(HyperwalletTransferMethod.Type.PAYPAL_ACCOUNT);
}
payPalAccount = copy(payPalAccount);
payPalAccount.setStatus(null);
payPalAccount.setCreatedOn(null);
return apiClient.post(url + "/users/" + payPalAccount.getUserToken() + "/paypal-accounts", payPalAccount, HyperwalletPayPalAccount.class);
}
/**
* Get PayPal Account Request
*
* @param userToken User token assigned
* @param payPalAccountToken PayPal Account token assigned
* @return HyperwalletPayPalAccount PayPal Account
*/
public HyperwalletPayPalAccount getPayPalAccount(String userToken, String payPalAccountToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(payPalAccountToken)) {
throw new HyperwalletException("PayPal Account token is required");
}
return apiClient.get(url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken, HyperwalletPayPalAccount.class);
}
/**
* List PayPal Accounts
*
* @param userToken User token assigned
* @param options List filter option
* @return HyperwalletList of HyperwalletPayPalAccount
*/
public HyperwalletList<HyperwalletPayPalAccount> listPayPalAccounts(String userToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/paypal-accounts", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPayPalAccount>>() {
});
}
/**
* List PayPal Accounts
*
* @param userToken User token assigned
* @return HyperwalletList of HyperwalletPayPalAccount
*/
public HyperwalletList<HyperwalletPayPalAccount> listPayPalAccounts(String userToken) {
return listPayPalAccounts(userToken, null);
}
/**
* Deactivate PayPal Account
*
* @param userToken User token
* @param payPalAccountToken PayPal Account token
* @return HyperwalletStatusTransition deactivated PayPal account
*/
public HyperwalletStatusTransition deactivatePayPalAccount(String userToken, String payPalAccountToken) {
return deactivatePayPalAccount(userToken, payPalAccountToken, null);
}
/**
* Deactivate PayPal Account
*
* @param userToken User token
* @param payPalAccountToken PayPal Account token
* @param notes Comments regarding the status change
* @return HyperwalletStatusTransition deactivated PayPal account
*/
public HyperwalletStatusTransition deactivatePayPalAccount(String userToken, String payPalAccountToken, String notes) {
return createPayPalAccountStatusTransition(userToken,
payPalAccountToken,
new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED).notes(notes));
}
/**
* Create PayPal Account Status Transition
*
* @param userToken User token
* @param payPalAccountToken PayPal Account token
* @param transition Status transition information
* @return HyperwalletStatusTransition new status for PayPal Account
*/
public HyperwalletStatusTransition createPayPalAccountStatusTransition(String userToken, String payPalAccountToken, HyperwalletStatusTransition transition) {
if (transition == null) {
throw new HyperwalletException("Transition is required");
}
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(payPalAccountToken)) {
throw new HyperwalletException("PayPal Account token is required");
}
if (!StringUtils.isEmpty(transition.getToken())) {
throw new HyperwalletException("Status Transition token may not be present");
}
transition = copy(transition);
transition.setCreatedOn(null);
transition.setFromStatus(null);
transition.setToStatus(null);
return apiClient.post(url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken + "/status-transitions", transition, HyperwalletStatusTransition.class);
}
/**
* Get PayPal Account Status Transition
*
* @param userToken User token
* @param payPalAccountToken PayPal Account token
* @param statusTransitionToken Status transition token
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition getPayPalAccountStatusTransition(String userToken, String payPalAccountToken, String statusTransitionToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(payPalAccountToken)) {
throw new HyperwalletException("PayPal Account token is required");
}
if (StringUtils.isEmpty(statusTransitionToken)) {
throw new HyperwalletException("Transition token is required");
}
return apiClient.get(url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class);
}
/**
* List All PayPal Account Status Transition information
*
* @param userToken User token
* @param payPalAccountToken PayPal Account token
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPayPalAccountStatusTransitions(String userToken, String payPalAccountToken) {
return listPayPalAccountStatusTransitions(userToken, payPalAccountToken, null);
}
/**
* List PayPal Account Status Transition information
*
* @param userToken User token
* @param payPalAccountToken PayPal Account token
* @param options List filter option
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPayPalAccountStatusTransitions(String userToken, String payPalAccountToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(payPalAccountToken)) {
throw new HyperwalletException("PayPal Account token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/paypal-accounts/" + payPalAccountToken + "/status-transitions", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() {
});
}
// Bank Accounts
/**
* Create Bank Account
*
* @param bankAccount bank account representation
* @return HyperwalletBankAccount created bank account for the specicic user
*/
public HyperwalletBankAccount createBankAccount(HyperwalletBankAccount bankAccount) {
if (bankAccount == null) {
throw new HyperwalletException("Bank Account is required");
}
if (StringUtils.isEmpty(bankAccount.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (!StringUtils.isEmpty(bankAccount.getToken())) {
throw new HyperwalletException("Bank Account token may not be present");
}
bankAccount = copy(bankAccount);
bankAccount.createdOn(null);
bankAccount.setStatus(null);
return apiClient.post(url + "/users/" + bankAccount.getUserToken() + "/bank-accounts", bankAccount, HyperwalletBankAccount.class);
}
/**
* Get Bank Account
*
* @param userToken User token assigned
* @param transferMethodToken Bank account token assigned
* @return HyperwalletBankAccount bank account information
*/
public HyperwalletBankAccount getBankAccount(String userToken, String transferMethodToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(transferMethodToken)) {
throw new HyperwalletException("Bank Account token is required");
}
return apiClient.get(url + "/users/" + userToken + "/bank-accounts/" + transferMethodToken, HyperwalletBankAccount.class);
}
/**
* Update Bank Account
*
* @param bankAccount Bank Account to update.
* @return HyperwalletBankAccount updated Bank Account
*/
public HyperwalletBankAccount updateBankAccount(HyperwalletBankAccount bankAccount) {
if (bankAccount == null) {
throw new HyperwalletException("Bank Account is required");
}
if (StringUtils.isEmpty(bankAccount.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankAccount.getToken())) {
throw new HyperwalletException("Bank Account token is required");
}
return apiClient.put(url + "/users/" + bankAccount.getUserToken() + "/bank-accounts/" + bankAccount.getToken(), bankAccount, HyperwalletBankAccount.class);
}
/**
* List Bank Accounts
*
* @param userToken User token assigned
* @return HyperwalletList of HyperwalletBankAccount
*/
public HyperwalletList<HyperwalletBankAccount> listBankAccounts(String userToken) {
return listBankAccounts(userToken, null);
}
/**
* List Bank Accounts
*
* @param userToken User token assigned
* @param options List filter option
* @return HyperwalletList of HyperwalletBankAccount
*/
public HyperwalletList<HyperwalletBankAccount> listBankAccounts(String userToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/bank-accounts", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBankAccount>>() {
});
}
/**
* Deactivate Bank Account
*
* @param userToken User token
* @param bankAccountToken Bank Account token
* @return HyperwalletStatusTransition deactivated bank account
*/
public HyperwalletStatusTransition deactivateBankAccount(String userToken, String bankAccountToken) {
return createBankAccountStatusTransition(userToken, bankAccountToken, new HyperwalletStatusTransition(HyperwalletStatusTransition.Status.DE_ACTIVATED));
}
/**
* Create Bank Account Status Transition
*
* @param userToken User token
* @param bankAccountToken Bank Account token
* @param transition Status transition information
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition createBankAccountStatusTransition(String userToken, String bankAccountToken, HyperwalletStatusTransition transition) {
if (transition == null) {
throw new HyperwalletException("Transition is required");
}
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankAccountToken)) {
throw new HyperwalletException("Bank Account token is required");
}
if (!StringUtils.isEmpty(transition.getToken())) {
throw new HyperwalletException("Status Transition token may not be present");
}
transition = copy(transition);
transition.setCreatedOn(null);
transition.setFromStatus(null);
transition.setToStatus(null);
return apiClient.post(url + "/users/" + userToken + "/bank-accounts/" + bankAccountToken + "/status-transitions", transition, HyperwalletStatusTransition.class);
}
/**
* List All Bank Account Status Transition
*
* @param userToken User token
* @param bankAccountToken Bank Account token
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listBankAccountStatusTransitions(String userToken, String bankAccountToken) {
return listBankAccountStatusTransitions(userToken, bankAccountToken, null);
}
/**
* List Bank Account Status Transition
*
* @param userToken User token
* @param bankAccountToken Bank Account token
* @param options List filter option
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listBankAccountStatusTransitions(String userToken, String bankAccountToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(bankAccountToken)) {
throw new HyperwalletException("Bank Account token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/bank-accounts/" + bankAccountToken + "/status-transitions", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() {
});
}
// Balances
/**
* List all User's Balances
*
* @param userToken User token assigned
* @return HyperwalletList of HyperwalletBalance
*/
public HyperwalletList<HyperwalletBalance> listBalancesForUser(String userToken) {
return listBalancesForUser(userToken, null);
}
/**
* List all User's Balances
*
* @param userToken User token assigned
* @param options List filter option
* @return HyperwalletList list of HyperwalletBalance
*/
public HyperwalletList<HyperwalletBalance> listBalancesForUser(String userToken, HyperwalletBalanceListOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = this.url + "/users/" + userToken + "/balances";
if (options != null) {
url = addParameter(url, "currency", options.getCurrency());
url = addParameter(url, "sortBy", options.getSortBy());
url = addParameter(url, "offset", options.getOffset());
url = addParameter(url, "limit", options.getLimit());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBalance>>() {
});
}
/**
* List all Program account balances
*
* @param accountToken Account token assigned
* @param programToken Program token assigned
* @return HyperwalletList of HyperwalletBalance
*/
public HyperwalletList<HyperwalletBalance> listBalancesForAccount(String programToken, String accountToken) {
return listBalancesForAccount(programToken, accountToken, null);
}
/**
* List all Program account balances
*
* @param accountToken Account token assigned
* @param programToken Program token assigned
* @param options List filter option
* @return HyperwalletList list of HyperwalletBalance
*/
public HyperwalletList<HyperwalletBalance> listBalancesForAccount(String programToken, String accountToken, HyperwalletBalanceListOptions options) {
if (StringUtils.isEmpty(programToken)) {
throw new HyperwalletException("Program token is required");
}
if (StringUtils.isEmpty(accountToken)) {
throw new HyperwalletException("Account token is required");
}
String url = this.url + "/programs/" + programToken + "/accounts/" + accountToken + "/balances";
if (options != null) {
url = addParameter(url, "currency", options.getCurrency());
url = addParameter(url, "sortBy", options.getSortBy());
url = addParameter(url, "offset", options.getOffset());
url = addParameter(url, "limit", options.getLimit());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBalance>>() {
});
}
/**
* List all User's Prepaid Card Balances
*
* @param userToken User token assigned
* @param prepaidCardToken Prepaid Card token assigned from User's Prepaid Card
* @return HyperwalletList of HyperwalletBalances
*/
public HyperwalletList<HyperwalletBalance> listBalancesForPrepaidCard(String userToken, String prepaidCardToken) {
return listBalancesForPrepaidCard(userToken, prepaidCardToken, null);
}
/**
* List all User's Prepaid Card Balances
*
* @param userToken User token assigned
* @param prepaidCardToken Prepaid Card token assigned from User's Prepaid Card
* @param options List filter option
* @return HyperwalletList of HyperwalletBalances
*/
public HyperwalletList<HyperwalletBalance> listBalancesForPrepaidCard(String userToken, String prepaidCardToken, HyperwalletBalanceListOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(prepaidCardToken)) {
throw new HyperwalletException("Prepaid Card token is required");
}
String url = this.url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/balances";
if (options != null) {
url = addParameter(url, "sortBy", options.getSortBy());
url = addParameter(url, "offset", options.getOffset());
url = addParameter(url, "limit", options.getLimit());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletBalance>>() {
});
}
// Payments
/**
* Create Payment
*
* @param payment Payment
* @return HyperwalletPayment created payment information
*/
public HyperwalletPayment createPayment(HyperwalletPayment payment) {
if (payment == null) {
throw new HyperwalletException("Payment is required");
}
if (!StringUtils.isEmpty(payment.getToken())) {
throw new HyperwalletException("Payment token may not be present");
}
payment = copy(payment);
payment.setCreatedOn(null);
return apiClient.post(url + "/payments", payment, HyperwalletPayment.class);
}
/**
* Get Payment
*
* @param paymentToken Payment token
* @return HyperwalletPayment
*/
public HyperwalletPayment getPayment(String paymentToken) {
if (StringUtils.isEmpty(paymentToken)) {
throw new HyperwalletException("Payment token is required");
}
return apiClient.get(url + "/payments/" + paymentToken, HyperwalletPayment.class);
}
/**
* List all Payments
*
* @return HyperwalletList of HyperwalletPayment
*/
public HyperwalletList<HyperwalletPayment> listPayments() {
return listPayments(null);
}
/**
* List all Payments
*
* @param options List filter option
* @return HyperwalletList of HyperwalletPayment
*/
public HyperwalletList<HyperwalletPayment> listPayments(HyperwalletPaymentListOptions options) {
String url = paginate(this.url + "/payments", options);
if (options != null) {
url = addParameter(url, "releasedOn", convert(options.getReleasedOn()));
url = addParameter(url, "currency", options.getCurrency());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletPayment>>() {
});
}
/**
* Create Payment Status Transition
*
* @param paymentToken Payment token
* @param transition Status transition information
* @return HyperwalletStatusTransition new status for Payment
*/
public HyperwalletStatusTransition createPaymentStatusTransition(String paymentToken, HyperwalletStatusTransition transition) {
if (transition == null) {
throw new HyperwalletException("Transition is required");
}
if (StringUtils.isEmpty(paymentToken)) {
throw new HyperwalletException("Payment token is required");
}
if (!StringUtils.isEmpty(transition.getToken())) {
throw new HyperwalletException("Status Transition token may not be present");
}
transition = copy(transition);
transition.setCreatedOn(null);
transition.setFromStatus(null);
transition.setToStatus(null);
return apiClient.post(url + "/payments/" + paymentToken + "/status-transitions", transition, HyperwalletStatusTransition.class);
}
/**
* Get Payment Status Transition
*
* @param paymentToken Payment token
* @param statusTransitionToken Status transition token
* @return HyperwalletStatusTransition
*/
public HyperwalletStatusTransition getPaymentStatusTransition(String paymentToken, String statusTransitionToken) {
if (StringUtils.isEmpty(paymentToken)) {
throw new HyperwalletException("Payment token is required");
}
if (StringUtils.isEmpty(statusTransitionToken)) {
throw new HyperwalletException("Transition token is required");
}
return apiClient.get(url + "/payments/" + paymentToken + "/status-transitions/" + statusTransitionToken, HyperwalletStatusTransition.class);
}
/**
* List All Payment Status Transition information
*
* @param paymentToken Payment token
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPaymentStatusTransitions( String paymentToken) {
return listPaymentStatusTransitions(paymentToken, null);
}
/**
* List Payment Status Transition information
*
* @param paymentToken Payment token
* @param options List filter option
* @return HyperwalletList of HyperwalletStatusTransition
*/
public HyperwalletList<HyperwalletStatusTransition> listPaymentStatusTransitions(String paymentToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(paymentToken)) {
throw new HyperwalletException("Payment token is required");
}
String url = paginate(this.url + "/payments/" + paymentToken + "/status-transitions", options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletStatusTransition>>() {
});
}
// Programs
/**
* Get Program
*
* @param programToken Program token
* @return HyperwalletProgram
*/
public HyperwalletProgram getProgram(String programToken) {
if (StringUtils.isEmpty(programToken)) {
throw new HyperwalletException("Program token is required");
}
return apiClient.get(url + "/programs/" + programToken, HyperwalletProgram.class);
}
// Program Accounts
/**
* Get Programs Account
*
* @param programToken Program token
* @param accountToken Program account token
* @return HyperwalletAccount
*/
public HyperwalletAccount getProgramAccount(String programToken, String accountToken) {
if (StringUtils.isEmpty(programToken)) {
throw new HyperwalletException("Program token is required");
}
if (StringUtils.isEmpty(accountToken)) {
throw new HyperwalletException("Account token is required");
}
return apiClient.get(url + "/programs/" + programToken + "/accounts/" + accountToken, HyperwalletAccount.class);
}
// Transfer Method Configurations
/**
* Get Transfer Method Configuration
*
* @param userToken User token
* @param country Country
* @param currency Currency
* @param type Type of Transfer Method to retrieve
* @param profileType Type of User profile
* @return HyperwalletTransferMethodConfiguration
*/
public HyperwalletTransferMethodConfiguration getTransferMethodConfiguration(String userToken, String country, String currency, HyperwalletTransferMethod.Type type, HyperwalletUser.ProfileType profileType) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(country)) {
throw new HyperwalletException("Country is required");
}
if (StringUtils.isEmpty(currency)) {
throw new HyperwalletException("Currency is required");
}
if (type == null) {
throw new HyperwalletException("Type is required");
}
if (profileType == null) {
throw new HyperwalletException("Profile Type is required");
}
return apiClient.get(url + "/transfer-method-configurations"
+ "?userToken=" + userToken
+ "&country=" + country
+ "¤cy=" + currency
+ "&type=" + type.name()
+ "&profileType=" + profileType.name(),
HyperwalletTransferMethodConfiguration.class);
}
/**
* List all Transfer Method Configuration associated with User
*
* @param userToken User token
* @return HyperwalletList of HyperwalletTransferMethodConfiguration
*/
public HyperwalletList<HyperwalletTransferMethodConfiguration> listTransferMethodConfigurations(String userToken) {
return listTransferMethodConfigurations(userToken, null);
}
/**
* List all Transfer Method Configuration associated with User
*
* @param userToken User token
* @param options List filter options
* @return HyperwalletList of HyperwalletTransferMethodConfiguration
*/
public HyperwalletList<HyperwalletTransferMethodConfiguration> listTransferMethodConfigurations(String userToken, HyperwalletPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/transfer-method-configurations?userToken=" + userToken, options);
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletTransferMethodConfiguration>>() {
});
}
// Receipts
/**
* List all program account receipts
*
* @param programToken Program token
* @param accountToken Program account token
* @return HyperwalletList of HyperwalletReceipt
*/
public HyperwalletList<HyperwalletReceipt> listReceiptsForProgramAccount(String programToken, String accountToken) {
return listReceiptsForProgramAccount(programToken, accountToken, null);
}
/**
* List all program account receipts
*
* @param programToken Program token
* @param accountToken Program account token
* @param options List filter options
* @return HyperwalletList of HyperwalletReceipt
*/
public HyperwalletList<HyperwalletReceipt> listReceiptsForProgramAccount(String programToken, String accountToken, HyperwalletReceiptPaginationOptions options) {
if (StringUtils.isEmpty(programToken)) {
throw new HyperwalletException("Program token is required");
}
if (StringUtils.isEmpty(accountToken)) {
throw new HyperwalletException("Account token is required");
}
String url = paginate(this.url + "/programs/" + programToken + "/accounts/" + accountToken + "/receipts", options);
if (options != null && options.getType() != null) {
url = addParameter(url, "type", options.getType().name());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletReceipt>>() {
});
}
/**
* List all user receipts
*
* @param userToken User token
* @return HyperwalletList of HyperwalletReceipt
*/
public HyperwalletList<HyperwalletReceipt> listReceiptsForUser(String userToken) {
return listReceiptsForUser(userToken, null);
}
/**
* List all user receipts
*
* @param userToken Program token
* @param options List filter options
* @return HyperwalletList of HyperwalletReceipt
*/
public HyperwalletList<HyperwalletReceipt> listReceiptsForUser(String userToken, HyperwalletReceiptPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/receipts", options);
if (options != null && options.getType() != null) {
url = addParameter(url, "type", options.getType().name());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletReceipt>>() {
});
}
/**
* List all prepaid card receipts
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @return HyperwalletList of HyperwalletReceipt
*/
public HyperwalletList<HyperwalletReceipt> listReceiptsForPrepaidCard(String userToken, String prepaidCardToken) {
return listReceiptsForPrepaidCard(userToken, prepaidCardToken, null);
}
/**
* List all prepaid card receipts
*
* @param userToken User token
* @param prepaidCardToken Prepaid card token
* @param options List filter options
* @return HyperwalletList of HyperwalletReceipt
*/
public HyperwalletList<HyperwalletReceipt> listReceiptsForPrepaidCard(String userToken, String prepaidCardToken, HyperwalletReceiptPaginationOptions options) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(prepaidCardToken)) {
throw new HyperwalletException("Prepaid card token is required");
}
String url = paginate(this.url + "/users/" + userToken + "/prepaid-cards/" + prepaidCardToken + "/receipts", options);
if (options != null && options.getType() != null) {
url = addParameter(url, "type", options.getType().name());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletReceipt>>() {
});
}
// Webhook Notification
/**
* Retrieve webhook event notification
*
* @param webhookToken Webhook token
* @return HyperwalletWebhookNotification
* */
public HyperwalletWebhookNotification getWebhookEvent(String webhookToken) {
if (StringUtils.isEmpty(webhookToken)) {
throw new HyperwalletException("Webhook token is required");
}
return apiClient.get(url + "/webhook-notifications/" + webhookToken, HyperwalletWebhookNotification.class);
}
/**
* List all webhook event notifications
*
* @return HyperwalletList of HyperwalletWebhookNotification
* */
public HyperwalletList<HyperwalletWebhookNotification> listWebhookEvents() {
return listWebhookEvents(null);
}
/**
* List all webhook event notifications
*
* @param options List filter options
* @return HyperwalletList of HyperwalletWebhookNotification
* */
public HyperwalletList<HyperwalletWebhookNotification> listWebhookEvents(HyperwalletWebhookNotificationPaginationOptions options) {
String url = paginate(this.url + "/webhook-notifications", options);
if (options != null && options.getType() != null) {
url = addParameter(url, "type", options.getType());
}
return apiClient.get(url, new TypeReference<HyperwalletList<HyperwalletWebhookNotification>>() {});
}
// Transfer Methods
/**
* Create a Transfer Method
*
* @param jsonCacheToken String JSON cache token
* @param transferMethod TransferMethod object to create
* @return HyperwalletTransferMethod Transfer Method object created
*/
public HyperwalletTransferMethod createTransferMethod(String jsonCacheToken, HyperwalletTransferMethod transferMethod) {
if (transferMethod == null || StringUtils.isEmpty(transferMethod.getUserToken())) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(jsonCacheToken)) {
throw new HyperwalletException("JSON token is required");
}
transferMethod = copy(transferMethod);
transferMethod.setToken(null);
transferMethod.setStatus(null);
transferMethod.setCreatedOn(null);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Json-Cache-Token", jsonCacheToken);
return apiClient.post(url + "/users/" + transferMethod.getUserToken() + "/transfer-methods", transferMethod, HyperwalletTransferMethod.class, headers);
}
/**
* Create a Transfer Method
*
* @param jsonCacheToken String JSON cache token
* @param userToken String user token
* @return HyperwalletTransferMethod Transfer Method object created
*/
public HyperwalletTransferMethod createTransferMethod(String jsonCacheToken, String userToken) {
if (StringUtils.isEmpty(userToken)) {
throw new HyperwalletException("User token is required");
}
if (StringUtils.isEmpty(jsonCacheToken)) {
throw new HyperwalletException("JSON token is required");
}
HyperwalletTransferMethod transferMethod = new HyperwalletTransferMethod();
transferMethod.setUserToken(userToken);
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Json-Cache-Token", jsonCacheToken);
return apiClient.post(url + "/users/" + transferMethod.getUserToken() + "/transfer-methods", transferMethod, HyperwalletTransferMethod.class, headers);
}
// Internal utils
private String paginate(String url, HyperwalletPaginationOptions options) {
if (options == null) {
return url;
}
url = addParameter(url, "createdAfter", convert(options.getCreatedAfter()));
url = addParameter(url, "createdBefore", convert(options.getCreatedBefore()));
url = addParameter(url, "sortBy", options.getSortBy());
url = addParameter(url, "offset", options.getOffset());
url = addParameter(url, "limit", options.getLimit());
return url;
}
private String addParameter(String url, String key, Object value) {
if (url == null || key == null || value == null) {
return url;
}
return url + (url.indexOf("?") == -1 ? "?" : "&") + key + "=" + value;
}
private String convert(Date in) {
if (in == null) {
return null;
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
return dateFormat.format(in);
}
private void setProgramToken(HyperwalletUser user) {
if (user != null && user.getProgramToken() == null) {
user.setProgramToken(this.programToken);
}
}
private void setProgramToken(HyperwalletPayment payment) {
if (payment != null && payment.getProgramToken() == null) {
payment.setProgramToken(this.programToken);
}
}
private HyperwalletUser copy(HyperwalletUser user) {
user = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(user), HyperwalletUser.class);
setProgramToken(user);
return user;
}
private HyperwalletPayment copy(HyperwalletPayment payment) {
payment = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(payment), HyperwalletPayment.class);
setProgramToken(payment);
return payment;
}
private HyperwalletPrepaidCard copy(HyperwalletPrepaidCard method) {
method = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(method), HyperwalletPrepaidCard.class);
return method;
}
private HyperwalletBusinessStakeholder copy(HyperwalletBusinessStakeholder method) {
method = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(method), HyperwalletBusinessStakeholder.class);
return method;
}
private HyperwalletBankCard copy(HyperwalletBankCard card) {
card = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(card), HyperwalletBankCard.class);
return card;
}
private HyperwalletPaperCheck copy(HyperwalletPaperCheck check) {
check = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(check), HyperwalletPaperCheck.class);
return check;
}
private HyperwalletBankAccount copy(HyperwalletBankAccount method) {
method = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(method), HyperwalletBankAccount.class);
return method;
}
private HyperwalletStatusTransition copy(HyperwalletStatusTransition statusTransition) {
statusTransition = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(statusTransition), HyperwalletStatusTransition.class);
return statusTransition;
}
private HyperwalletTransferMethod copy(HyperwalletTransferMethod transferMethod) {
transferMethod = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(transferMethod), HyperwalletTransferMethod.class);
return transferMethod;
}
private HyperwalletTransfer copy(HyperwalletTransfer transfer) {
transfer = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(transfer), HyperwalletTransfer.class);
return transfer;
}
private HyperwalletPayPalAccount copy(HyperwalletPayPalAccount payPalAccount) {
payPalAccount = HyperwalletJsonUtil.fromJson(HyperwalletJsonUtil.toJson(payPalAccount), HyperwalletPayPalAccount.class);
return payPalAccount;
}
}
|
package the_fireplace.ias.gui;
import java.io.IOException;
import org.lwjgl.input.Keyboard;
import com.github.mrebhan.ingameaccountswitcher.tools.alt.AccountData;
import com.github.mrebhan.ingameaccountswitcher.tools.alt.AltDatabase;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.GuiTextField;
import net.minecraft.util.StatCollector;
/**
* The GUI where the alt is added
* @author The_Fireplace
*/
public class GuiAddAccount extends GuiScreen {
private String user = "", pass = "", cover = "";
private GuiTextField username;
private GuiTextField password;
private GuiButton addaccount;
@Override
public void initGui() {
Keyboard.enableRepeatEvents(true);
this.buttonList.clear();
this.buttonList.add(addaccount = new GuiButton(2, this.width / 2 - 152, this.height - 28, 150, 20, StatCollector.translateToLocal("ias.addaccount")));
this.buttonList.add(new GuiButton(3, this.width / 2 + 2, this.height - 28, 150, 20, StatCollector.translateToLocal("gui.cancel")));
username = new GuiTextField(0, this.fontRendererObj, this.width / 2 - 100, 60, 200, 20);
username.setFocused(true);
username.setText(user);
password = new GuiTextField(1, this.fontRendererObj, this.width / 2 - 100, 90, 200, 20);
password.setText(pass);
addaccount.enabled = username.getText().length() > 0;
}
@Override
public void drawScreen(int par1, int par2, float par3) {
this.drawDefaultBackground();
this.drawCenteredString(fontRendererObj, StatCollector.translateToLocal("ias.addaccount"), this.width / 2, 7, -1);
this.drawCenteredString(fontRendererObj, StatCollector.translateToLocal("ias.username"), this.width / 2 - 130, 66, -1);
this.drawCenteredString(fontRendererObj, StatCollector.translateToLocal("ias.password"), this.width / 2 - 130, 96, -1);
username.drawTextBox();
password.drawTextBox();
super.drawScreen(par1, par2, par3);
}
@Override
protected void keyTyped(char character, int keyIndex) {
if (keyIndex == Keyboard.KEY_ESCAPE) {
escape();
} else if (keyIndex == Keyboard.KEY_RETURN) {
if(username.isFocused()){
username.setFocused(false);
password.setFocused(true);
}else if(password.isFocused()){
addAccount();
}
} else if (keyIndex == Keyboard.KEY_BACK) {
if (username.isFocused() && user.length() > 0) {
user = user.substring(0, user.length() - 1);
} else if (password.isFocused() && pass.length() > 0) {
pass = pass.substring(0, pass.length() - 1);
cover = cover.substring(0, cover.length() - 1);
}
updateText();
} else if(keyIndex == Keyboard.KEY_TAB){
if(username.isFocused()){
username.setFocused(false);
password.setFocused(true);
}else if(password.isFocused()){
username.setFocused(true);
password.setFocused(false);
}
} else if (character != 0) {
if (username.isFocused()) {
user += character;
} else if (password.isFocused()) {
pass += character;
cover += '*';
}
updateText();
}
}
@Override
public void updateScreen()
{
this.username.updateCursorCounter();
this.password.updateCursorCounter();
addaccount.enabled = username.getText().length() > 0;
updateText();
}
@Override
protected void actionPerformed(GuiButton button){
if (button.enabled)
{
if(button.id == 2){
addAccount();
}else if(button.id == 3){
escape();
}
}
}
@Override
protected void mouseClicked(int mouseX, int mouseY, int mouseButton) throws IOException
{
super.mouseClicked(mouseX, mouseY, mouseButton);
username.mouseClicked(mouseX, mouseY, mouseButton);
password.mouseClicked(mouseX, mouseY, mouseButton);
}
@Override
public void onGuiClosed()
{
Keyboard.enableRepeatEvents(false);
}
/**
* Return to the Account Selector
*/
private void escape(){
mc.displayGuiScreen(new GuiAccountSelector());
}
/**
* Add account and return to account selector
*/
private void addAccount(){
AltDatabase.getInstance().getAlts().add(new AccountData(user, pass, user));
mc.displayGuiScreen(new GuiAccountSelector());
}
/**
* Updates the username and password
*/
private void updateText(){
username.setText(user);
password.setText(cover);
}
}
|
package com.instructure.canvasapi.api;
import android.content.Context;
import android.util.Log;
import com.instructure.canvasapi.model.Attachment;
import com.instructure.canvasapi.model.CanvasContext;
import com.instructure.canvasapi.model.CanvasColor;
import com.instructure.canvasapi.model.Enrollment;
import com.instructure.canvasapi.model.FileUploadParams;
import com.instructure.canvasapi.model.User;
import com.instructure.canvasapi.utilities.*;
import java.io.File;
import java.util.LinkedHashMap;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.http.*;
import retrofit.mime.TypedFile;
public class UserAPI {
public enum ENROLLMENT_TYPE {STUDENT, TEACHER, TA, OBSERVER, DESIGNER}
private static String getSelfEnrollmentsCacheFilename(){
return "/users/self/enrollments";
}
private static String getUserByIdCacheFilename(long userId){
return "/search/recipients/"+userId;
}
private static String getFirstPagePeopleCacheFilename(CanvasContext canvasContext){
return canvasContext.toAPIString() + "/users";
}
private static String getFirstPagePeopleCacheFilename(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type){
return canvasContext + "/users/"+enrollment_type;
}
private static String getCourseUserListCacheFilename(CanvasContext canvasContext){
return canvasContext.toAPIString() + "/users/all";
}
private static String getColorCacheFilename(){
return "/users/colors";
}
private static String getSelfWithPermissionsCacheFileName(){
return "/users/self";
}
interface UsersInterface {
@GET("/users/self/profile")
void getSelf(Callback<User> callback);
// TODO: We probably need to create a helper that does each of these individually
@GET("/users/self/enrollments?state[]=active&state[]=invited&state[]=completed")
void getSelfEnrollments(Callback<Enrollment[]> callback);
@GET("/users/self")
void getSelfWithPermission(CanvasCallback<User> callback);
@PUT("/users/self")
void updateShortName(@Query("user[short_name]") String shortName, Callback<User> callback);
@GET("/users/{userid}/profile")
void getUserById(@Path("userid")long userId, Callback<User> userCallback);
@GET("/{context_id}/users/{userId}?include[]=avatar_url&include[]=user_id&include[]=email&include[]=bio")
void getUserById(@Path("context_id") long context_id, @Path("userId")long userId, Callback<User> userCallback);
@GET("/{context_id}/users?include[]=enrollments&include[]=avatar_url&include[]=user_id&include[]=email&include[]=bio")
void getFirstPagePeopleList(@Path("context_id") long context_id, Callback<User[]> callback);
@GET("/{context_id}/users?include[]=enrollments&include[]=avatar_url&include[]=user_id&include[]=email")
void getFirstPagePeopleListWithEnrollmentType(@Path("context_id") long context_id, @Query("enrollment_type") String enrollmentType, Callback<User[]> callback);
@GET("/{next}")
void getNextPagePeopleList(@Path(value = "next", encode = false) String nextURL, Callback<User[]> callback);
@POST("/users/self/file")
void uploadUserFileURL( @Query("url") String fileURL, @Query("name") String fileName, @Query("size") long size, @Query("content_type") String content_type, @Query("parent_folder_path") String parentFolderPath, Callback<String> callback);
@POST("/users/self/files")
FileUploadParams getFileUploadParams( @Query("size") long size, @Query("name") String fileName, @Query("content_type") String content_type, @Query("parent_folder_id") Long parentFolderId);
@Multipart
@POST("/")
Attachment uploadUserFile(@PartMap LinkedHashMap<String, String> params, @Part("file") TypedFile file);
//Colors
@GET("/users/self/colors")
void getColors(CanvasCallback<CanvasColor> callback);
@PUT("/users/self/colors/{context_id}")
void setColor(@Path("context_id") String context_id, @Query(value = "hexcode", encodeValue = false) String color, CanvasCallback<CanvasColor> callback);
}
// Build Interface Helpers
private static UsersInterface buildInterface(CanvasCallback callback, CanvasContext canvasContext) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(callback, canvasContext);
return restAdapter.create(UsersInterface.class);
}
private static UsersInterface buildInterface(CanvasCallback callback, CanvasContext canvasContext, boolean perPageQueryParam) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(callback, canvasContext, perPageQueryParam);
return restAdapter.create(UsersInterface.class);
}
private static UsersInterface buildInterface(Context context) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(context);
return restAdapter.create(UsersInterface.class);
}
private static UsersInterface buildInterface(Context context, boolean perPageQueryParam) {
RestAdapter restAdapter = CanvasRestAdapter.buildAdapter(context, perPageQueryParam);
return restAdapter.create(UsersInterface.class);
}
private static UsersInterface buildUploadInterface(String hostURL) {
RestAdapter restAdapter = CanvasRestAdapter.getGenericHostAdapter(hostURL);
return restAdapter.create(UsersInterface.class);
}
// API Calls
public static void getSelf(UserCallback callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
//Read cache
callback.cache(APIHelpers.getCacheUser(callback.getContext()));
//Don't allow this API call to be made while masquerading.
//It causes the current user to be overriden with the masqueraded one.
if (Masquerading.isMasquerading(callback.getContext())) {
Log.w(APIHelpers.LOG_TAG,"No API call for /users/self/profile can be made while masquerading.");
return;
}
buildInterface(callback, null).getSelf(callback);
}
public static void getSelfWithPermissions(CanvasCallback<User> callback) {
if (APIHelpers.paramIsNull(callback)) { return; }
//Don't allow this API call to be made while masquerading.
//It causes the current user to be overriden with the masqueraded one.
if (Masquerading.isMasquerading(callback.getContext())) {
Log.w(APIHelpers.LOG_TAG,"No API call for /users/self can be made while masquerading.");
return;
}
callback.readFromCache(getSelfWithPermissionsCacheFileName());
buildInterface(callback, null).getSelfWithPermission(callback);
}
public static void getSelfEnrollments(CanvasCallback<Enrollment[]> callback) {
if(APIHelpers.paramIsNull(callback)) return;
callback.readFromCache(getSelfEnrollmentsCacheFilename());
buildInterface(callback, null).getSelfEnrollments(callback);
}
public static void updateShortName(String shortName, CanvasCallback<User> callback) {
if (APIHelpers.paramIsNull(callback, shortName)) { return; }
buildInterface(callback, null).updateShortName(shortName, callback);
}
public static void getUserById(long userId, CanvasCallback<User> userCanvasCallback){
if(APIHelpers.paramIsNull(userCanvasCallback)){return;}
userCanvasCallback.readFromCache(getUserByIdCacheFilename(userId));
//Passing UserCallback here will break OUR cache.
if(userCanvasCallback instanceof UserCallback){
Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self..");
return;
}
buildInterface(userCanvasCallback, null).getUserById(userId, userCanvasCallback);
}
public static void getCourseUserById(CanvasContext canvasContext, long userId, CanvasCallback<User> userCanvasCallback){
if(APIHelpers.paramIsNull(userCanvasCallback)){return;}
userCanvasCallback.readFromCache(getUserByIdCacheFilename(userId));
//Passing UserCallback here will break OUR cache.
if(userCanvasCallback instanceof UserCallback){
Log.e(APIHelpers.LOG_TAG, "You cannot pass a User Call back here. It'll break cache for users/self..");
return;
}
buildInterface(userCanvasCallback, canvasContext).getUserById(canvasContext.getId(), userId, userCanvasCallback);
}
public static void getFirstPagePeople(CanvasContext canvasContext, CanvasCallback<User[]> callback) {
if (APIHelpers.paramIsNull(callback, canvasContext)) { return; }
callback.readFromCache(getFirstPagePeopleCacheFilename(canvasContext));
buildInterface(callback, canvasContext).getFirstPagePeopleList(canvasContext.getId(), callback);
}
public static void getNextPagePeople(String nextURL, CanvasCallback<User[]> callback){
if (APIHelpers.paramIsNull(callback, nextURL)) { return; }
callback.setIsNextPage(true);
buildInterface(callback, null).getNextPagePeopleList(nextURL, callback);
}
public static void getAllUsersForCourseByEnrollmentType(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, CanvasCallback<User[]> callback){
if(APIHelpers.paramIsNull(callback, canvasContext)){return;}
CanvasCallback<User[]> bridge = new ExhaustiveBridgeCallback<>(callback, new ExhaustiveBridgeCallback.ExhaustiveBridgeEvents() {
@Override
public void performApiCallWithExhaustiveCallback(CanvasCallback callback, String nextURL) {
UserAPI.getNextPagePeople(nextURL, callback);
}
@Override
public Class classType() {
return User.class;
}
});
callback.readFromCache(getCourseUserListCacheFilename(canvasContext));
buildInterface(callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), bridge);
}
public static void getFirstPagePeople(CanvasContext canvasContext, ENROLLMENT_TYPE enrollment_type, CanvasCallback<User[]> callback) {
if (APIHelpers.paramIsNull(callback, canvasContext)) { return; }
callback.readFromCache(getFirstPagePeopleCacheFilename(canvasContext, enrollment_type));
buildInterface(callback, canvasContext).getFirstPagePeopleListWithEnrollmentType(canvasContext.getId(), getEnrollmentTypeString(enrollment_type), callback);
}
public static void getColors(Context context, CanvasCallback<CanvasColor> callback) {
callback.readFromCache(getColorCacheFilename());
buildInterface(context, false).getColors(callback);
}
public static void setColor(Context context, CanvasContext canvasContext, String hexColor, CanvasCallback<CanvasColor> callback) {
if (APIHelpers.paramIsNull(context, canvasContext, hexColor, callback)) { return; }
setColor(context, canvasContext.getContextId(), hexColor, callback);
}
public static void setColor(Context context, String context_id, String hexColor, CanvasCallback<CanvasColor> callback) {
if (APIHelpers.paramIsNull(context, context_id, hexColor, callback)) { return; }
buildInterface(context, false).setColor(context_id, hexColor, callback);
}
// Synchronous Calls
public static FileUploadParams getFileUploadParams(Context context, String fileName, long size, String contentType, Long parentFolderId){
return buildInterface(context).getFileUploadParams(size, fileName, contentType, parentFolderId);
}
public static Attachment uploadUserFile(Context context, String uploadUrl, LinkedHashMap<String,String> uploadParams, String mimeType, File file){
return buildUploadInterface(uploadUrl).uploadUserFile(uploadParams, new TypedFile(mimeType, file));
}
// Helpers
private static String getEnrollmentTypeString(ENROLLMENT_TYPE enrollment_type){
String enrollmentType = "";
switch (enrollment_type){
case DESIGNER:
enrollmentType = "designer";
break;
case OBSERVER:
enrollmentType = "observer";
break;
case STUDENT:
enrollmentType = "student";
break;
case TA:
enrollmentType = "ta";
break;
case TEACHER:
enrollmentType = "teacher";
break;
}
return enrollmentType;
}
}
|
package tigase.server.filters;
import java.util.Arrays;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import tigase.server.Packet;
import tigase.server.PacketFilterIfc;
import tigase.server.QueueType;
import tigase.stats.StatisticsList;
import tigase.xml.Element;
/**
* Created: Jun 8, 2009 1:47:31 PM
*
* @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a>
* @version $Rev$
*/
public class PacketCounter implements PacketFilterIfc {
private Logger log = Logger.getLogger(this.getClass().getName());
private QueueType qType = null;
private String name = null;
private long msgCounter = 0;
private long presCounter = 0;
private ConcurrentSkipListMap<String, Integer> iqCounterIdx =
new ConcurrentSkipListMap<String, Integer>();
private long[] iqCounters = new long[1];
private int lastNodeNo = -1;
@Override
public boolean filter(Packet packet) {
if (packet.getElemName() == "message") {
++msgCounter;
}
if (packet.getElemName() == "presence") {
++presCounter;
}
if (packet.getElemName() == "iq") {
String xmlns = packet.getIQXMLNS();
incIQCounter(xmlns != null ? xmlns : packet.getIQChildName());
}
// TESTING ONLY START
// try {
// String node_name = null;
// List<Element> children = packet.getElemChildren("/iq/pubsub");
// if (children != null) {
// for (Element elem : children) {
// node_name = elem.getAttribute("node");
// if (node_name != null) {
// break;
// if (node_name != null) {
// String node_no = node_name.substring("node-".length());
// int no = Integer.parseInt(node_no);
// if ((lastNodeNo + 1 != no) && (lastNodeNo != no)) {
// log.warning(name + ":" + qType.name() +
// ": Incorrect node number, lastNodeNo = " + lastNodeNo +
// ", current number: " + no + ", or packet: " + packet.toString());
// lastNodeNo = no;
// } catch (Exception e) {
// //e.printStackTrace();
// TESTING ONLY END
return false;
}
private synchronized void incIQCounter(String xmlns) {
if (xmlns == null) {
++iqCounters[0];
} else {
Integer idx = iqCounterIdx.get(xmlns);
if (idx == null) {
iqCounters = Arrays.copyOf(iqCounters, iqCounters.length+1);
idx = iqCounters.length - 1;
iqCounterIdx.put(xmlns, idx);
}
++iqCounters[idx];
}
}
@Override
public void init(String name, QueueType qType) {
this.name = name;
this.qType = qType;
}
@Override
public void getStatistics(StatisticsList list) {
list.add(name, qType.name() + " messages", msgCounter, Level.FINER);
list.add(name, qType.name() + " presences", presCounter, Level.FINER);
list.add(name, qType.name() + " IQ no XMLNS", iqCounters[0], Level.FINEST);
for (Entry<String, Integer> iqCounter : iqCounterIdx.entrySet()) {
list.add(name, qType.name() + " IQ " + iqCounter.getKey(),
iqCounters[iqCounter.getValue()], Level.FINEST);
}
}
}
|
package uk.co.skyem.projects.emuZ80.cpu;
import javafx.scene.transform.Rotate;
import uk.co.skyem.projects.emuZ80.cpu.Register.Register16;
import uk.co.skyem.projects.emuZ80.cpu.Register.Register8;
public class ALU {
/**
* Rotates a long.
*
* @param data The long to be rotated.
* @param amount The amount to rotate the byte by, if greater than 0, rotate right, if less than 0, rotate left.
* @param dataLength The length of the data. If 0, assumes long length (65 bits).
* @return The rotated byte.
*/
// TODO: optimise?
public static long rotate(long data, int dataLength, int amount) {
if (dataLength == 0) dataLength = Long.SIZE;
if (amount > 0) {
// Rotate Right
// Shift the whole thing right.
long rotated = data >>> amount;
// Get the chopped off bits and move them.
long removed = data << dataLength - amount;
// stick the chopped off bits back on.
rotated = rotated | removed;
return rotated;
} else if (amount < 0) {
amount = Math.abs(amount);
// Rotate Left
// Shift the whole thing left.
long rotated = data << amount;
// Get the chopped off bits and move them.
long removed = data >>> dataLength - amount;
// stick the chopped off bits back on.
rotated = rotated | removed;
return rotated;
} else {
// No Rotation
return data;
}
}
/**
* Rotates an integer.
*
* @param data The integer to be rotated.
* @param amount The amount to rotate the byte by, if greater than 0, rotate right, if less than 0, rotate left.
* @param dataLength The length of the data. If 0, assumes integer length (32 bits).
* @return The rotated byte.
*/
public static int rotate(int data, int dataLength, int amount) {
if (dataLength == 0) dataLength = Integer.SIZE;
if (amount > 0) {
return (data >>> amount) | (data << dataLength - amount);
} else if (amount < 0) {
amount = Math.abs(amount);
return (data << amount) | (data >>> dataLength - amount);
} else {
// No Rotation
return data;
}
}
/**
* Rotates a short.
*
* @param data The integer to be rotated.
* @param amount The amount to rotate the byte by, if greater than 0, rotate right, if less than 0, rotate left.
* @param dataLength The length of the data. If 0, assumes short length (16 bits).
* @return The rotated byte.
*/
public static short rotate(short data, int dataLength, int amount) {
if (dataLength == 0) dataLength = Short.SIZE;
if (amount > 0) {
return (short)((data >>> amount) | (data << dataLength - amount));
} else if (amount < 0) {
amount = Math.abs(amount);
return (short)((data << amount) | (data >>> dataLength - amount));
} else {
// No Rotation
return data;
}
}
/**
* Rotates a byte.
*
* @param data The integer to be rotated.
* @param amount The amount to rotate the byte by, if greater than 0, rotate right, if less than 0, rotate left.
* @param dataLength The length of the data. If 0, assumes byte length (8 bits).
* @return The rotated byte.
*/
public static byte rotate(byte data, int dataLength, int amount) {
if (dataLength == 0) dataLength = Byte.SIZE;
if (amount > 0) {
return (byte)((data >>> amount) | (data << dataLength - amount));
} else if (amount < 0) {
amount = Math.abs(amount);
return (byte)((data << amount) | (data >>> dataLength - amount));
} else {
// No Rotation
return data;
}
}
Registers registers;
Core core;
public ALU(Core core){
this.core = core;
this.registers = core.registers;
}
private Register8 getFlags() {
return registers.flags;
}
/** Check if number is bigger than 16 bits. **/
private boolean checkCarry16(int result) {
return result > 0xFFFF;
}
/** Check if number is bigger than 8 bits. **/
private boolean checkCarry8(short result) {
return result > 0xFF;
}
/** Check if number is bigger than 8 bits. **/
private boolean checkCarry8(int result) {
return result > 0xFF;
}
/** Check if a number is bigger than 4 bits. **/
private boolean checkCarry4(int result) {
return result > 0xF;
}
/** Check if a number is bigger than 4 bits. **/
private boolean checkCarry4(byte result) {
return result > 0xF;
}
private byte getByte(long number, int byteNumber) {
return (byte)((number << (8 * byteNumber)) & 0xFF);
}
private byte getByte(int number, int byteNumber) {
return (byte)((number << (8 * byteNumber) & 0xFF));
}
private boolean getBit(long number, int bitNumber) {
return ((number << bitNumber) & 0b1) == 1;
}
private boolean getBit(int number, int bitNumber) {
return ((number << bitNumber) & 0b1) == 1;
}
private boolean getBit(byte number, int bitNumber) {
return ((number << bitNumber) & 0b1) == 1;
}
private boolean betweenInclusive(int x, int min, int max) {
return x>=min && x<=max;
}
/** Adds two registers together. **/
public void add16Register (Register16 a, Register16 b) {
Register8 flags = getFlags();
// get the result
int result = a.getData() + b.getData();
// check and set the carry flag
flags.setFlag(Flags.CARRY, checkCarry16(result));
// set the addition / subtraction flag
flags.setFlag(Flags.ADD_SUB, false);
// set the X_5 and X_3 flags
byte upper = getByte(result, 2);
flags.setFlag(Flags.X_3, getBit(upper, 3));
flags.setFlag(Flags.X_5, getBit(upper, 5));
// set the H flag
flags.setFlag(Flags.HALF_CARRY, checkCarry4(upper));
// finally, set the register with the result.
a.setData((short) result);
}
/** Sets a register to a 16 bit immediate value **/
public void load16(Register16 register, short data) {
register.setData(data);
}
public void increment16(Register16 register) {
register.increment();
}
public void decrement16(Register16 register) {
register.decrement();
}
private byte incDec8SetFlags(int result) {
Register8 flags = getFlags();
// Check to see if there is an overflow
// TODO: Is this correct?
flags.setFlag(Flags.PARITY_OVERFLOW, checkCarry8(result));
// set the addition / subtraction flag
flags.setFlag(Flags.ADD_SUB, false);
// set the X_5 and X_3 flags
flags.setFlag(Flags.X_3, getBit(result, 3));
flags.setFlag(Flags.X_5, getBit(result, 5));
// set the H flag
flags.setFlag(Flags.HALF_CARRY, checkCarry4(result));
// set the Z flag
flags.setFlag(Flags.ZERO, result == 0);
byte resultByte = (byte)result;
// set the S flag
flags.setFlag(Flags.SIGN, resultByte < 0);
return resultByte;
}
public void increment8(Register8 register) {
int result = register.getData() + 1;
// set the register with the result after setting flags
register.setData(incDec8SetFlags(result));
}
public void decrement8(Register8 register) {
int result = register.getData() - 1;
// set the register with the result after setting flags
register.setData(incDec8SetFlags(result));
}
public void load8(Register8 register, byte data) {
register.setData(data);
}
/** Loads a register with a value from a memory address **/
public void indirectLoad8(Register8 register, short address) {
register.setData(core.memoryBuffer.getByte(address));
}
/** Load contents of register into memory location **/
public void memoryLoad8(short address, Register8 register) {
core.memoryBuffer.putByte(address, register.getData());
}
/** Loads a register with a value from a memory address **/
public void indirectLoad16(Register16 register, short address) {
register.setData(core.memoryBuffer.getWord(address));
}
/** Load contents of register into memory location **/
public void memoryLoad16(short address, Register16 register) {
core.memoryBuffer.putWord(address, register.getData());
}
/** Rotate register one bit to the left **/
public void rotateRegisterLeft(Register register) {
// These flags are reset.
getFlags().setFlag(Flags.HALF_CARRY, false);
getFlags().setFlag(Flags.ADD_SUB, false);
register.rotateLeft(1);
}
/** Rotate register one bit to the right **/
public void rotateRegisterRight(Register register) {
// These flags are reset.
getFlags().setFlag(Flags.HALF_CARRY, false);
getFlags().setFlag(Flags.ADD_SUB, false);
register.rotateRight(1);
}
/** Set the carry flag to the LSB and rotate the register one bit to the right. **/
public void rotateRegisterRightCarry(Register register) {
// Get the LSB and put it into the carry flag.
getFlags().setFlag(Flags.CARRY, (register.getData().byteValue() & 0b1) == 0b1);
// Rotate the register
rotateRegisterRight(register);
}
/** Set the carry flag to the LSB and rotate the register one bit to the right. **/
public void rotateRegisterLeftCarry(Register register) {
// Get the MSB and put it into the carry flag.
// TODO: Does this work?
getFlags().setFlag(Flags.CARRY, (register.getData().longValue() & (0b1L << (register.getSize() - 1))) == 0b1);
// Rotate the register
rotateRegisterLeft(register);
}
/** Rotate a register right though carry. The carry flag is used as an extra bit. **/
public void rotateRegisterRightThroughCarry(Register register) {
// Get the previous contents of the carry flag
boolean oldCarry = getFlags().getFlag(Flags.CARRY);
// Get the LSB and put it into the carry flag.
getFlags().setFlag(Flags.CARRY, (register.getData().byteValue() & 0b1) == 0b1);
// Rotate the register
rotateRegisterRight(register);
// Copy the flag into the register.
// TODO: Does this work?
register.setFlag(0b1 << (register.getSize() - 1), oldCarry);
}
/** Rotate a register left though carry. The carry flag is used as an extra bit. **/
public void rotateRegisterLeftThroughCarry(Register register) {
// Get the previous contents of the carry flag
boolean oldCarry = getFlags().getFlag(Flags.CARRY);
// Get the MSB and put it into the carry flag.
// TODO: Does this work?
getFlags().setFlag(Flags.CARRY, (register.getData().longValue() & (0b1L << (register.getSize() - 1))) == 0b1);
// Rotate the register
rotateRegisterLeft(register);
// Copy the flag into the register.
register.setFlag(0b1, oldCarry);
}
/** Edits the accumulator after an operation with BCD input (ADD / SUB, etc...), to make the result BCD. **/
public void bcdAdjust(Register8 toAdjust) {
// Get the flags register
Register8 flags = getFlags();
// Get the data in the register
int data = toAdjust.getData();
// Get the lower nibble
int lower = data & 0x0F;
// Get the upper nibble
int upper = (data >>> 4) & 0x0F;
// Get the H flag
boolean flagH = flags.getFlag(Flags.HALF_CARRY);
// Get the C flag
boolean flagC = flags.getFlag(Flags.CARRY);
// Get the N flag
boolean flagN = flags.getFlag(Flags.ADD_SUB);
// Set the C flag
if (!flagC) {
if (betweenInclusive(upper, 0x09, 0x0F) && betweenInclusive(lower, 0x0A, 0x0F)) {
flags.setFlag(Flags.CARRY, true);
} else if (betweenInclusive(upper, 0x0A, 0x0F) && betweenInclusive(lower, 0x00, 0x09)) {
flags.setFlag(Flags.CARRY, true);
}
}
// Set the H flag
if (!flagN) {
if (betweenInclusive(lower, 0x00, 0x09)) {
flags.setFlag(Flags.HALF_CARRY, false);
} else if (betweenInclusive(lower, 0x0A, 0x0F)) {
flags.setFlag(Flags.HALF_CARRY, true);
}
} else {
if (flagH) {
if (betweenInclusive(lower, 0x06, 0x0F)) {
flags.setFlag(Flags.HALF_CARRY, false);
}
if (betweenInclusive(lower, 0x00, 0x05)) {
flags.setFlag(Flags.HALF_CARRY, true);
}
}
}
// If the lower nibble is greater than 9 or there is a half carry, add 0x06 to the register
if (lower > 0x09 && flagH)
data += 0x06;
// If the upper nibble is greater than 9 or there is a carry, add 0x60 to the register
else if(upper > 0x09 && flagC)
data += 0x60;
// Set the S flag if the MSB is true
flags.setFlag(Flags.SIGN, getBit(data, 7));
// Set the Z flag if the result is 0
if (data == 0) flags.setFlag(Flags.ZERO, true);
else flags.setFlag(Flags.ZERO, false);
// Set the P flag if the result is even
flags.setFlag(Flags.PARITY_OVERFLOW, getBit(data, 0));
// Set the other flags
flags.setFlag(Flags.X_3, getBit(data, 3));
flags.setFlag(Flags.X_5, getBit(data, 5));
toAdjust.setData((byte) data);
}
/** Invert register **/
public void complement(Register8 register) {
int data = ~register.getData() & 0xFF;
register.setData((byte) data);
Register8 flags = getFlags();
flags.setFlag(Flags.HALF_CARRY, true);
flags.setFlag(Flags.ADD_SUB, true);
flags.setFlag(Flags.X_3, getBit(data, 3));
flags.setFlag(Flags.X_5, getBit(data, 5));
}
/** Sets the carry flag and some other flags **/
public void setCarry() {
Register8 flags = getFlags();
flags.setFlag(Flags.CARRY, true);
flags.setFlag(Flags.HALF_CARRY, false);
flags.setFlag(Flags.ADD_SUB, false);
byte regA = registers.REG_A.getData();
flags.setFlag(Flags.X_3, getBit(regA, 3));
flags.setFlag(Flags.X_5, getBit(regA, 5));
}
/** Invert the carry flag **/
public void invertCarry() {
Register8 flags = getFlags();
flags.setFlag(Flags.HALF_CARRY, flags.getFlag(Flags.CARRY));
flags.toggleFlag(Flags.CARRY);
flags.setFlag(Flags.ADD_SUB, false);
byte regA = registers.REG_A.getData();
flags.setFlag(Flags.X_3, getBit(regA, 3));
flags.setFlag(Flags.X_5, getBit(regA, 5));
}
}
|
package uk.kihira.tails.client;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL30;
import uk.kihira.gltf.Model;
import java.nio.FloatBuffer;
import java.util.ArrayDeque;
import java.util.HashMap;
/**
* The main class for handling rendering of parts
*/
public class PartRenderer {
private final Shader shader;
private final FloatBuffer modelViewMatrixWorld;
private final FloatBuffer tintBuffer;
private final ArrayDeque<FloatBuffer> bufferPool;
private final HashMap<OutfitPart, FloatBuffer> renders;
public PartRenderer() {
modelViewMatrixWorld = BufferUtils.createFloatBuffer(16);
tintBuffer = BufferUtils.createFloatBuffer(9);
bufferPool = new ArrayDeque<>();
renders = new HashMap<>(16);
shader = new Shader("threetint_vert", "threetint_frag");
shader.registerUniform("tints");
}
/**
* Gets a {@link FloatBuffer} from the pool. If there is none left, creates a new one
*
* @return
*/
private FloatBuffer getFloatBuffer() {
if (bufferPool.size() == 0) {
return BufferUtils.createFloatBuffer(16);
} else return bufferPool.pop();
}
/**
* Returns a {@link FloatBuffer} back to the pool
*/
private void freeFloatBuffer(FloatBuffer buffer) {
bufferPool.add(buffer);
}
/**
* Queues up a part to be rendered
*/
public void render(OutfitPart part) {
GL11.glPushMatrix();
GlStateManager.translate(part.mountOffset[0], part.mountOffset[1], part.mountOffset[2]);
GlStateManager.rotate(part.rotation[0], 1f, 0f, 0f);
GlStateManager.rotate(part.rotation[1], 0f, 1f, 0f);
GlStateManager.rotate(part.rotation[2], 0f, 0f, 1f);
GlStateManager.scale(part.scale[0], part.scale[1], part.scale[2]);
FloatBuffer fb = getFloatBuffer();
GL11.glGetFloat(GL11.GL_MODELVIEW_MATRIX, fb);
GL11.glPopMatrix();
renders.put(part, fb);
}
/**
* Renders the entire queue of parts
*/
public void doRender() {
if (renders.size() == 0) return;
RenderHelper.enableStandardItemLighting();
GlStateManager.enableDepth();
GL11.glFrontFace(GL11.GL_CW); // TODO need to see why it faces are defined CW not CCW
GlStateManager.color(1f, 1f, 1f);
GlStateManager.getFloat(GL11.GL_MODELVIEW_MATRIX, modelViewMatrixWorld);
shader.use();
for (HashMap.Entry<OutfitPart, FloatBuffer> entry : renders.entrySet()) {
OutfitPart outfitPart = entry.getKey();
Part basePart = outfitPart.getPart();
if (basePart == null) continue;
Model model = basePart.getModel();
if (model == null) continue;
// Set tint colors
tintBuffer.put(outfitPart.tint[0]);
tintBuffer.put(outfitPart.tint[1]);
tintBuffer.put(outfitPart.tint[2]);
tintBuffer.flip();
OpenGlHelper.glUniform3(shader.getUniform("tints"), tintBuffer);
// todo load texture
Minecraft.getMinecraft().getTextureManager().bindTexture(new ResourceLocation("tails", "blah"));
GL11.glLoadMatrix(entry.getValue());
GlStateManager.scale(1, -1, 1); // Seems y is flipped, quick and cheap solution for now
model.render();
freeFloatBuffer(entry.getValue());
tintBuffer.clear();
}
renders.clear();
// Unbind everything
OpenGlHelper.glUseProgram(0);
glBindVertexArray(0);
OpenGlHelper.glBindBuffer(OpenGlHelper.GL_ARRAY_BUFFER, 0);
GL11.glFrontFace(GL11.GL_CCW);
GlStateManager.disableDepth();
RenderHelper.disableStandardItemLighting();
GL11.glLoadMatrix(modelViewMatrixWorld);
}
/*
Caching for vertex array binding
*/
private static int vertexArray = 0;
public static void glBindVertexArray(int vao) {
if (vao != vertexArray) {
GL30.glBindVertexArray(vao);
vertexArray = vao;
}
}
}
|
package com.hilton.gitatouille;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorSet;
import com.nineoldandroids.animation.ObjectAnimator;
import com.nineoldandroids.view.ViewHelper;
public class ProgitListAdapter extends BaseExpandableListAdapter {
private static final int ANIMATION_DEFAULT_DURATION = 400;
private static final int ANIMATION_DEFAULT_DELAY = 100;
private static final String TAG = ProgitListAdapter.class.getName();
private List<ProGitChapter> mProGitChapters;
private Context mContext;
private LayoutInflater mViewFactory;
public ProgitListAdapter(Context ctx) {
mContext = ctx;
mProGitChapters = ProGit.getChapters();
mViewFactory = LayoutInflater.from(ctx);
}
@Override
public ProGitSection getChild(int groupPosition, int childPosition) {
return mProGitChapters.get(groupPosition).getSection(childPosition);
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public View getChildView(int groupPosition, int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
TextView name = null;
if (convertView == null) {
name = (TextView) mViewFactory.inflate(R.layout.progit_child_item, null, false);
} else {
name = (TextView) convertView;
}
name.setText(getChild(groupPosition, childPosition).mName);
return name;
}
@Override
public int getChildrenCount(int groupPosition) {
return mProGitChapters.get(groupPosition).getSectionCount();
}
@Override
public ProGitChapter getGroup(int groupPosition) {
return mProGitChapters.get(groupPosition);
}
@Override
public int getGroupCount() {
return mProGitChapters.size();
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
View root = null;
if (convertView == null) {
root = mViewFactory.inflate(R.layout.progit_group_item, null, false);
Animator flyIn = ObjectAnimator.ofFloat(root, "translationY", 500, 0);
setupAnimation(groupPosition, root, parent, flyIn);
} else {
root = convertView;
}
TextView textView = (TextView) root.findViewById(R.id.name);
textView.setText(getGroup(groupPosition).mName);
ImageView indicator = (ImageView) root.findViewById(R.id.indicator);
indicator.setImageResource(isExpanded ? R.drawable.button_tab_to_close : R.drawable.button_tab_to_open);
return root;
}
private void setupAnimation(int position, View view, ViewGroup parent, Animator flyIn) {
Log.e(TAG, "setupAnimation position " + position);
ViewHelper.setAlpha(view, 0);
Animator alpha = ObjectAnimator.ofFloat(view, "alpha", 0, 1);
AnimatorSet set = new AnimatorSet();
set.playTogether(flyIn, alpha);
int delay = ANIMATION_DEFAULT_DELAY;
set.setStartDelay(position * delay);
set.setDuration(ANIMATION_DEFAULT_DURATION);
set.start();
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
|
package com.jasoncabot.gardenpath.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import static com.jasoncabot.gardenpath.model.Game.NUMBER_OF_FENCE_POSTS;
import static com.jasoncabot.gardenpath.model.Game.NUMBER_OF_SQUARES;
import static com.jasoncabot.gardenpath.model.Game.TOTAL_FENCE_POSTS;
public class Fence
{
public static final int LENGTH = 2;
private int startIndex = -1;
private int endIndex = -1;
public static Fence get(int id)
{
// convert our unique id back into start and end indexes
int s = id % TOTAL_FENCE_POSTS;
int e = id / TOTAL_FENCE_POSTS % TOTAL_FENCE_POSTS;
return Fence.get(s, e);
}
public static Fence get(int start, int end)
{
final Fence fence = new Fence();
// ensure start always smaller than end
if (start < end)
{
fence.startIndex = start;
fence.endIndex = end;
}
else
{
fence.startIndex = end;
fence.endIndex = start;
}
return fence;
}
public static boolean blocks(final Fence one, final Fence two)
{
if (one.isHorizontal())
{
if (two.isVertical())
{
// we can only interfere in 1 place
return one.startIndex == two.startIndex + NUMBER_OF_SQUARES;
}
else
{
// 3 possible interferences
return (two.startIndex == one.startIndex) ||
(two.startIndex + 1 == one.startIndex) ||
(two.startIndex - 1 == one.startIndex);
}
}
else
{
if (two.isHorizontal())
{
// we can only interfere in 1 place
return one.startIndex + NUMBER_OF_SQUARES == two.startIndex;
}
else
{
// 3 possible interferences
return (two.startIndex == one.startIndex) ||
(two.startIndex + NUMBER_OF_FENCE_POSTS == one.startIndex) ||
(two.startIndex - NUMBER_OF_FENCE_POSTS == one.startIndex);
}
}
}
@JsonProperty("start")
public int getStartIndex()
{
return startIndex;
}
@JsonProperty("end")
public int getEndIndex()
{
return endIndex;
}
@JsonIgnore
public int getMidpointIndex()
{
return (startIndex + endIndex) / 2;
}
@JsonIgnore
public boolean isVertical()
{
return startIndex + 20 == endIndex;
}
@JsonIgnore
public boolean isHorizontal()
{
return startIndex + 2 == endIndex;
}
@JsonIgnore
public boolean isValid()
{
// start will always be less then end, this is ensured when we construct this fence
if (startIndex == endIndex)
{
return false;
}
// basic validation
if (!(startIndex == (endIndex - (NUMBER_OF_FENCE_POSTS * LENGTH)) || startIndex == (endIndex - LENGTH)))
{
return false;
}
if (isVertical())
{
// we cannot be on the left or right wall
if (((startIndex % NUMBER_OF_FENCE_POSTS) == 0) || ((startIndex + 1) % NUMBER_OF_FENCE_POSTS) == 0)
{
return false;
}
}
else if (isHorizontal())
{
// we cannot be on the top or bottom wall
// if our fence is on the top wall and we horizontal
if (startIndex < NUMBER_OF_FENCE_POSTS || startIndex >= (NUMBER_OF_FENCE_POSTS * NUMBER_OF_SQUARES))
{
return false;
}
// we cannot span/loop over the right hand wall
for (int i = 1; i <= LENGTH; i++)
{
if (((startIndex + i) % NUMBER_OF_FENCE_POSTS) == 0)
{
return false;
}
}
}
return true;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Fence fence = (Fence) o;
return new EqualsBuilder()
.append(startIndex, fence.startIndex)
.append(endIndex, fence.endIndex)
.isEquals();
}
public boolean blocksFence(final Fence other)
{
return blocks(this, other);
}
public boolean blocksMove(final int start, final int end)
{
int fenceStartRowNum = startIndex / NUMBER_OF_FENCE_POSTS;
int a = start > end ? end : start;
int b = start > end ? start : end;
if (b - a == NUMBER_OF_SQUARES && !isVertical())
{
if (a == ((startIndex - fenceStartRowNum) - NUMBER_OF_SQUARES) && (b == startIndex - fenceStartRowNum))
{
return true;
}
if (a == (((startIndex - fenceStartRowNum) - NUMBER_OF_SQUARES) + 1) && (b == (startIndex - fenceStartRowNum) + 1))
{
return true;
}
}
else if (b - a == 1 && !isHorizontal())
{
if (a == (startIndex - (fenceStartRowNum + 1)) && (b == (startIndex - fenceStartRowNum)))
{
return true;
}
if (a == ((startIndex - (fenceStartRowNum + 1)) + NUMBER_OF_SQUARES) && (b == (startIndex - fenceStartRowNum) + NUMBER_OF_SQUARES))
{
return true;
}
}
return false;
}
@Override
public int hashCode()
{
return (startIndex * TOTAL_FENCE_POSTS) + endIndex;
}
@Override
public String toString()
{
return new ToStringBuilder(this)
.append("id", hashCode())
.append("startIndex", startIndex)
.append("endIndex", endIndex)
.toString();
}
}
|
package us.aaronweiss.pkgnx.util;
import us.aaronweiss.pkgnx.NXException;
import us.aaronweiss.pkgnx.format.NXHeader;
import us.aaronweiss.pkgnx.format.NXNode;
import us.aaronweiss.pkgnx.format.NXTables;
import us.aaronweiss.pkgnx.format.nodes.*;
/**
* A basic utility to parse data into an {@code NXNode}.
*
* @author Aaron Weiss
* @version 1.0.0
* @since 5/27/13
*/
public class NodeParser {
/**
* Parses the next {@code NXNode} from the supplied data.
*
* @param header the header of the file
* @param slea the {@code SeekableLittleEndianAccessor} to read the node from
* @return the newly parsed node
*/
public static NXNode parseNode(NXHeader header, NXTables tables, SeekableLittleEndianAccessor slea) {
String name = tables.getString(slea.getUnsignedInt());
long childIndex = slea.getUnsignedInt();
int childCount = slea.getUnsignedShort();
int type = slea.getUnsignedShort();
switch (type) {
case 0:
return new NXNullNode(name, header.getFile(), childIndex, childCount, slea);
case 1:
return new NXLongNode(name, header.getFile(), childIndex, childCount, slea);
case 2:
return new NXDoubleNode(name, header.getFile(), childIndex, childCount, slea);
case 3:
return new NXStringNode(name, header.getFile(), childIndex, childCount, slea);
case 4:
return new NXPointNode(name, header.getFile(), childIndex, childCount, slea);
case 5:
return new NXBitmapNode(name, header.getFile(), childIndex, childCount, slea);
case 6:
return new NXAudioNode(name, header.getFile(), childIndex, childCount, slea);
default:
throw new NXException("Failed to parse nodes. Encountered invalid node type (" + type + ") in file.");
}
}
}
|
package com.kovaciny.linemonitorbot;
import java.util.ArrayList;
import java.util.Locale;
import android.app.ActionBar;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
MenuItem mJobPicker;
MenuItem mLinePicker;
MenuItem mDebugDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
//instantiate database.
new PopulateMenusTask().execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mJobPicker = (MenuItem) menu.findItem(R.id.action_pick_job);
mLinePicker = (MenuItem) menu.findItem(R.id.action_pick_line);
mDebugDisplay = (MenuItem) menu.findItem(R.id.debug_display);
mDebugDisplay.setVisible(false);
//populate the line picker with lines
Menu pickLineSubMenu = mLinePicker.getSubMenu();
pickLineSubMenu.clear();
String lineList[] = getResources().getStringArray(R.array.line_list);
for (int i=0; i<lineList.length; i++) {
pickLineSubMenu.add(lineList[i]);
}
//populate the job picker with jobs
Menu pickJobSubMenu = mJobPicker.getSubMenu();
pickJobSubMenu.clear();
String jobList[]= {"Wo #1", "Wo #2"};
int jobListGroup = 0;
for (int i=0; i<jobList.length; i++) {
int menuId = i;
pickJobSubMenu.add(jobListGroup, menuId, Menu.FLAG_APPEND_TO_GROUP, jobList[i]);
}
int jobOptionsGroup = 1;
pickJobSubMenu.add(jobOptionsGroup, R.id.new_wo, Menu.FLAG_APPEND_TO_GROUP, "+ New");
pickJobSubMenu.add(jobOptionsGroup, R.id.clear_wos, Menu.FLAG_APPEND_TO_GROUP, "Clear");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_wo:
item.setTitle("new wo");
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a SectionFragment with the page number as its lone argument.
Fragment fragment;
switch(position){
case 0:
fragment = new SkidTimesFragment();
break;
case 1:
fragment = new RatesFragment();
break;
case 2:
fragment = new DrainingFragment();
break;
default:
fragment = new SectionFragment();
}
Bundle args = new Bundle();
args.putInt(SectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
public class PopulateMenusTask extends AsyncTask<Void,Void,Void> {
ArrayList<String> mLineList = new ArrayList<String>();
//Date mserviceStart;
public PopulateMenusTask() {
super();
}
@Override
protected Void doInBackground(Void... arg0) {
DataHelper dh = new DataHelper(getBaseContext());
String Status = (String) dh.getCode("appState","safetyDisabled");
//mserviceStart = (Date) dh.getCode("serviceStartTime",null);
for (int i=0; i<20; i++) {
String ii = Integer.toString(i);
String lineii = "Line " + ii;
dh.setCode(ii, lineii, "String");
}
//dh.setCode("key", "value", "String");
for (int i=0; i<20; i++) {
mLineList.add(i, (String) dh.getCode(Integer.toString(i), "default"));
}
mLineList.get(7);
dh.close();
dh = null;
/* // Gets the data repository in write mode
PrimexSQLiteOpenHelper mDbHelper = new PrimexSQLiteOpenHelper(getApplicationContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(PrimexDatabaseSchema.PrimexLines.COLUMN_NAME_ENTRY_ID, id);
values.put(PrimexDatabaseSchema.PrimexLines.COLUMN_NAME_LINE_NUMBER, title);
values.put(PrimexDatabaseSchema.PrimexLines.COLUMN_NAME_CONTENT, content);
// Insert the new row, returning the primary key value of the new row
long newRowId;
newRowId = db.insert(
PrimexDatabaseSchema.PrimexLines.TABLE_NAME,
null,
values);*/
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Menu pickLineSubMenu = mLinePicker.getSubMenu();
pickLineSubMenu.clear();
//String lineList[] = getResources().getStringArray(R.array.line_list);
for (int i=0; i<mLineList.size(); i++) {
pickLineSubMenu.add(mLineList.get(i));
}
//showDummyDialog(mStatus);
}
}
void showDummyDialog(String text) {
// Create the fragment and show it as a dialog.
DialogFragment newFragment = MyDialogFragment.newInstance(text);
newFragment.show(getFragmentManager(), "dialog");
}
}
|
package com.krux.kafka.producer;
import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
public class KafkaProducer {
private Producer<String, String> _producer;
public KafkaProducer(Properties props) {
// Properties props = new Properties();
// // all the below properties are set in TCPStreamListenerServer after
// // parsing the command line options
// props.put("metadata.broker.list", System.getProperty("metadata.broker.list", "localhost:9092"));
// props.put("serializer.class", System.getProperty("serializer.class", "kafka.serializer.StringEncoder"));
// props.put("partitioner.class",
// System.getProperty("partitioner.class", "com.krux.beacon.listener.kafka.producer.SimplePartitioner"));
// props.put("request.required.acks", System.getProperty("request.required.acks", "1"));
// props.put("producer.type", System.getProperty("producer.type", "async"));
// props.put("request.timeout.ms", System.getProperty("request.timeout.ms", "10000"));
// props.put("compression.codec", System.getProperty("compression.codec", "none"));
// props.put("message.send.max.retries", System.getProperty("message.send.max.retries", "3"));
// props.put("retry.backoff.ms", System.getProperty("retry.backoff.ms", "100"));
// props.put("queue.buffering.max.ms", System.getProperty("queue.buffering.max.ms", "5000"));
// props.put("queue.buffering.max.messages", System.getProperty("queue.buffering.max.messages", "10000"));
// props.put("queue.enqueue.timeout.ms", System.getProperty("queue.enqueue.timeout.ms", "-1"));
// props.put("batch.num.messages", System.getProperty("batch.num.messages", "200"));
// props.put("client.id", System.getProperty("client.id", ""));
// props.put("send.buffer.bytes", System.getProperty("send.buffer.bytes", String.valueOf(100 * 1024)));
ProducerConfig config = new ProducerConfig(props);
_producer = new Producer<String, String>(config);
}
public void send(String topic, String message) {
KeyedMessage<String, String> data = new KeyedMessage<String, String>(topic, "", message);
_producer.send(data);
}
}
|
package com.lenis0012.bukkit.ls;
import org.apache.commons.lang.RandomStringUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerPreLoginEvent;
import org.bukkit.event.player.PlayerPreLoginEvent.Result;
import org.bukkit.event.player.PlayerQuitEvent;
import com.lenis0012.bukkit.ls.util.StringUtil;
@SuppressWarnings("deprecation")
public class LoginListener implements Listener {
private LoginSecurity plugin;
public LoginListener(LoginSecurity i) { this.plugin = i; }
@EventHandler (priority = EventPriority.MONITOR)
public void onPlayerJoin(PlayerJoinEvent event) {
final Player player = event.getPlayer();
final String name = player.getName().toLowerCase();
if(!player.getName().equals(StringUtil.cleanString(player.getName()))) {
player.kickPlayer("Invalid username!");
return;
}
plugin.playerJoinPrompt(player, name);
}
@EventHandler (priority = EventPriority.LOWEST)
public void onPlayerPreLogin(PlayerPreLoginEvent event) {
String name = event.getName();
//Check if the player is already online
for(Player player : Bukkit.getServer().getOnlinePlayers()) {
String pname = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(pname))
continue;
if(pname.equalsIgnoreCase(name)) {
event.setResult(Result.KICK_OTHER);
event.setKickMessage("A player with this name is already online!");
}
}
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
String ip = player.getAddress().getAddress().toString();
if(!plugin.data.isRegistered(name))
plugin.data.updateIp(name, ip);
if(plugin.sesUse && !plugin.AuthList.containsKey(name) && plugin.data.isRegistered(name))
plugin.thread.getSession().put(name, plugin.sesDelay);
}
@EventHandler
public void onPlayerMove(PlayerMoveEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(name))
player.teleport(event.getFrom());
}
@EventHandler
public void onBlockPlace(BlockPlaceEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(name))
event.setCancelled(true);
}
@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(name))
event.setCancelled(true);
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(name))
event.setCancelled(true);
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(name))
event.setCancelled(true);
}
@EventHandler
public void onPlayerChat(PlayerChatEvent chat){
Player player = chat.getPlayer();
String pname = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(pname)){
chat.setCancelled(true);
}
}
@EventHandler
public void OnHealthRegain(EntityRegainHealthEvent event) {
Entity entity = event.getEntity();
if(!(entity instanceof Player))
return;
Player player = (Player)entity;
String pname = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(pname)) {
event.setCancelled(true);
}
}
@EventHandler
public void OnFoodLevelChange(FoodLevelChangeEvent event) {
Entity entity = event.getEntity();
if(!(entity instanceof Player))
return;
Player player = (Player)entity;
String pname = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(pname)) {
event.setCancelled(true);
}
}
@EventHandler
public void onInventoryClick(InventoryClickEvent event) {
Entity entity = event.getWhoClicked();
if(!(entity instanceof Player))
return;
Player player = (Player)entity;
String pname = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(pname)) {
event.setCancelled(true);
}
}
@EventHandler
public void onEntityDamageByEntity(EntityDamageByEntityEvent event) {
Entity defender = event.getEntity();
Entity damager = event.getDamager();
if(defender instanceof Player) {
Player p1 = (Player) defender;
String n1 = p1.getName().toLowerCase();
if(plugin.AuthList.containsKey(n1)) {
event.setCancelled(true);
return;
}
if(damager instanceof Player) {
Player p2 = (Player) damager;
String n2 = p2.getName().toLowerCase();
if(plugin.AuthList.containsKey(n2))
event.setCancelled(true);
}
}
}
@EventHandler(priority=EventPriority.LOWEST)
public void onPlayerCommandPreprocess(PlayerCommandPreprocessEvent event) {
Player player = event.getPlayer();
String name = player.getName().toLowerCase();
if(plugin.AuthList.containsKey(name)){
if(!event.getMessage().startsWith("/login") && !event.getMessage().startsWith("/register")) {
//faction fix start
if(event.getMessage().startsWith("/f"))
event.setMessage("/" + RandomStringUtils.randomAscii(name.length())); //this command does not exist :P
//faction fix end
event.setCancelled(true);
}
}
}
}
|
package com.microsoft.sqlserver.jdbc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.nio.Buffer;
final class TDS {
// TDS protocol versions
static final int VER_DENALI = 0x74000004; // TDS 7.4
static final int VER_KATMAI = 0x730B0003; // TDS 7.3B(includes null bit compression)
static final int VER_YUKON = 0x72090002; // TDS 7.2
static final int VER_UNKNOWN = 0x00000000; // Unknown/uninitialized
static final int TDS_RET_STAT = 0x79;
static final int TDS_COLMETADATA = 0x81;
static final int TDS_TABNAME = 0xA4;
static final int TDS_COLINFO = 0xA5;
static final int TDS_ORDER = 0xA9;
static final int TDS_ERR = 0xAA;
static final int TDS_MSG = 0xAB;
static final int TDS_RETURN_VALUE = 0xAC;
static final int TDS_LOGIN_ACK = 0xAD;
static final int TDS_FEATURE_EXTENSION_ACK = 0xAE;
static final int TDS_ROW = 0xD1;
static final int TDS_NBCROW = 0xD2;
static final int TDS_ENV_CHG = 0xE3;
static final int TDS_SSPI = 0xED;
static final int TDS_DONE = 0xFD;
static final int TDS_DONEPROC = 0xFE;
static final int TDS_DONEINPROC = 0xFF;
static final int TDS_FEDAUTHINFO = 0xEE;
// FedAuth
static final int TDS_FEATURE_EXT_FEDAUTH = 0x02;
static final int TDS_FEDAUTH_LIBRARY_SECURITYTOKEN = 0x01;
static final int TDS_FEDAUTH_LIBRARY_ADAL = 0x02;
static final int TDS_FEDAUTH_LIBRARY_RESERVED = 0x7F;
static final byte ADALWORKFLOW_ACTIVEDIRECTORYPASSWORD = 0x01;
static final byte ADALWORKFLOW_ACTIVEDIRECTORYINTEGRATED = 0x02;
static final byte FEDAUTH_INFO_ID_STSURL = 0x01; // FedAuthInfoData is token endpoint URL from which to acquire fed auth token
static final byte FEDAUTH_INFO_ID_SPN = 0x02; // FedAuthInfoData is the SPN to use for acquiring fed auth token
// AE constants
static final int TDS_FEATURE_EXT_AE = 0x04;
static final int MAX_SUPPORTED_TCE_VERSION = 0x01; // max version
static final int CUSTOM_CIPHER_ALGORITHM_ID = 0; // max version
static final int AES_256_CBC = 1;
static final int AEAD_AES_256_CBC_HMAC_SHA256 = 2;
static final int AE_METADATA = 0x08;
static final int TDS_TVP = 0xF3;
static final int TVP_ROW = 0x01;
static final int TVP_NULL_TOKEN = 0xFFFF;
static final int TVP_STATUS_DEFAULT = 0x02;
static final int TVP_ORDER_UNIQUE_TOKEN = 0x10;
// TVP_ORDER_UNIQUE_TOKEN flags
static final byte TVP_ORDERASC_FLAG = 0x1;
static final byte TVP_ORDERDESC_FLAG = 0x2;
static final byte TVP_UNIQUE_FLAG = 0x4;
// TVP flags, may be used in other places
static final int FLAG_NULLABLE = 0x01;
static final int FLAG_TVP_DEFAULT_COLUMN = 0x200;
static final int FEATURE_EXT_TERMINATOR = -1;
// Sql_variant length
static final int SQL_VARIANT_LENGTH = 8009;
static final String getTokenName(int tdsTokenType) {
switch (tdsTokenType) {
case TDS_RET_STAT:
return "TDS_RET_STAT (0x79)";
case TDS_COLMETADATA:
return "TDS_COLMETADATA (0x81)";
case TDS_TABNAME:
return "TDS_TABNAME (0xA4)";
case TDS_COLINFO:
return "TDS_COLINFO (0xA5)";
case TDS_ORDER:
return "TDS_ORDER (0xA9)";
case TDS_ERR:
return "TDS_ERR (0xAA)";
case TDS_MSG:
return "TDS_MSG (0xAB)";
case TDS_RETURN_VALUE:
return "TDS_RETURN_VALUE (0xAC)";
case TDS_LOGIN_ACK:
return "TDS_LOGIN_ACK (0xAD)";
case TDS_FEATURE_EXTENSION_ACK:
return "TDS_FEATURE_EXTENSION_ACK (0xAE)";
case TDS_ROW:
return "TDS_ROW (0xD1)";
case TDS_NBCROW:
return "TDS_NBCROW (0xD2)";
case TDS_ENV_CHG:
return "TDS_ENV_CHG (0xE3)";
case TDS_SSPI:
return "TDS_SSPI (0xED)";
case TDS_DONE:
return "TDS_DONE (0xFD)";
case TDS_DONEPROC:
return "TDS_DONEPROC (0xFE)";
case TDS_DONEINPROC:
return "TDS_DONEINPROC (0xFF)";
case TDS_FEDAUTHINFO:
return "TDS_FEDAUTHINFO (0xEE)";
default:
return "unknown token (0x" + Integer.toHexString(tdsTokenType).toUpperCase() + ")";
}
}
// RPC ProcIDs for use with RPCRequest (PKT_RPC) calls
static final short PROCID_SP_CURSOR = 1;
static final short PROCID_SP_CURSOROPEN = 2;
static final short PROCID_SP_CURSORPREPARE = 3;
static final short PROCID_SP_CURSOREXECUTE = 4;
static final short PROCID_SP_CURSORPREPEXEC = 5;
static final short PROCID_SP_CURSORUNPREPARE = 6;
static final short PROCID_SP_CURSORFETCH = 7;
static final short PROCID_SP_CURSOROPTION = 8;
static final short PROCID_SP_CURSORCLOSE = 9;
static final short PROCID_SP_EXECUTESQL = 10;
static final short PROCID_SP_PREPARE = 11;
static final short PROCID_SP_EXECUTE = 12;
static final short PROCID_SP_PREPEXEC = 13;
static final short PROCID_SP_PREPEXECRPC = 14;
static final short PROCID_SP_UNPREPARE = 15;
// Constants for use with cursor RPCs
static final short SP_CURSOR_OP_UPDATE = 1;
static final short SP_CURSOR_OP_DELETE = 2;
static final short SP_CURSOR_OP_INSERT = 4;
static final short SP_CURSOR_OP_REFRESH = 8;
static final short SP_CURSOR_OP_LOCK = 16;
static final short SP_CURSOR_OP_SETPOSITION = 32;
static final short SP_CURSOR_OP_ABSOLUTE = 64;
// Constants for server-cursored result sets.
// See the Engine Cursors Functional Specification for details.
static final int FETCH_FIRST = 1;
static final int FETCH_NEXT = 2;
static final int FETCH_PREV = 4;
static final int FETCH_LAST = 8;
static final int FETCH_ABSOLUTE = 16;
static final int FETCH_RELATIVE = 32;
static final int FETCH_REFRESH = 128;
static final int FETCH_INFO = 256;
static final int FETCH_PREV_NOADJUST = 512;
static final byte RPC_OPTION_NO_METADATA = (byte) 0x02;
// Transaction manager request types
static final short TM_GET_DTC_ADDRESS = 0;
static final short TM_PROPAGATE_XACT = 1;
static final short TM_BEGIN_XACT = 5;
static final short TM_PROMOTE_PROMOTABLE_XACT = 6;
static final short TM_COMMIT_XACT = 7;
static final short TM_ROLLBACK_XACT = 8;
static final short TM_SAVE_XACT = 9;
static final byte PKT_QUERY = 1;
static final byte PKT_RPC = 3;
static final byte PKT_REPLY = 4;
static final byte PKT_CANCEL_REQ = 6;
static final byte PKT_BULK = 7;
static final byte PKT_DTC = 14;
static final byte PKT_LOGON70 = 16; // 0x10
static final byte PKT_SSPI = 17;
static final byte PKT_PRELOGIN = 18; // 0x12
static final byte PKT_FEDAUTH_TOKEN_MESSAGE = 8; // Authentication token for federated authentication
static final byte STATUS_NORMAL = 0x00;
static final byte STATUS_BIT_EOM = 0x01;
static final byte STATUS_BIT_ATTENTION = 0x02;// this is called ignore bit in TDS spec
static final byte STATUS_BIT_RESET_CONN = 0x08;
// Various TDS packet size constants
static final int INVALID_PACKET_SIZE = -1;
static final int INITIAL_PACKET_SIZE = 4096;
static final int MIN_PACKET_SIZE = 512;
static final int MAX_PACKET_SIZE = 32767;
static final int DEFAULT_PACKET_SIZE = 8000;
static final int SERVER_PACKET_SIZE = 0; // Accept server's configured packet size
// TDS packet header size and offsets
static final int PACKET_HEADER_SIZE = 8;
static final int PACKET_HEADER_MESSAGE_TYPE = 0;
static final int PACKET_HEADER_MESSAGE_STATUS = 1;
static final int PACKET_HEADER_MESSAGE_LENGTH = 2;
static final int PACKET_HEADER_SPID = 4;
static final int PACKET_HEADER_SEQUENCE_NUM = 6;
static final int PACKET_HEADER_WINDOW = 7; // Reserved/Not used
// MARS header length:
// 2 byte header type
// 8 byte transaction descriptor
// 4 byte outstanding request count
static final int MARS_HEADER_LENGTH = 18; // 2 byte header type, 8 byte transaction descriptor,
static final int TRACE_HEADER_LENGTH = 26; // header length (4) + header type (2) + guid (16) + Sequence number size (4)
static final short HEADERTYPE_TRACE = 3; // trace header type
// Message header length
static final int MESSAGE_HEADER_LENGTH = MARS_HEADER_LENGTH + 4; // length includes message header itself
static final byte B_PRELOGIN_OPTION_VERSION = 0x00;
static final byte B_PRELOGIN_OPTION_ENCRYPTION = 0x01;
static final byte B_PRELOGIN_OPTION_INSTOPT = 0x02;
static final byte B_PRELOGIN_OPTION_THREADID = 0x03;
static final byte B_PRELOGIN_OPTION_MARS = 0x04;
static final byte B_PRELOGIN_OPTION_TRACEID = 0x05;
static final byte B_PRELOGIN_OPTION_FEDAUTHREQUIRED = 0x06;
static final byte B_PRELOGIN_OPTION_TERMINATOR = (byte) 0xFF;
// Login option byte 1
static final byte LOGIN_OPTION1_ORDER_X86 = 0x00;
static final byte LOGIN_OPTION1_ORDER_6800 = 0x01;
static final byte LOGIN_OPTION1_CHARSET_ASCII = 0x00;
static final byte LOGIN_OPTION1_CHARSET_EBCDIC = 0x02;
static final byte LOGIN_OPTION1_FLOAT_IEEE_754 = 0x00;
static final byte LOGIN_OPTION1_FLOAT_VAX = 0x04;
static final byte LOGIN_OPTION1_FLOAT_ND5000 = 0x08;
static final byte LOGIN_OPTION1_DUMPLOAD_ON = 0x00;
static final byte LOGIN_OPTION1_DUMPLOAD_OFF = 0x10;
static final byte LOGIN_OPTION1_USE_DB_ON = 0x00;
static final byte LOGIN_OPTION1_USE_DB_OFF = 0x20;
static final byte LOGIN_OPTION1_INIT_DB_WARN = 0x00;
static final byte LOGIN_OPTION1_INIT_DB_FATAL = 0x40;
static final byte LOGIN_OPTION1_SET_LANG_OFF = 0x00;
static final byte LOGIN_OPTION1_SET_LANG_ON = (byte) 0x80;
// Login option byte 2
static final byte LOGIN_OPTION2_INIT_LANG_WARN = 0x00;
static final byte LOGIN_OPTION2_INIT_LANG_FATAL = 0x01;
static final byte LOGIN_OPTION2_ODBC_OFF = 0x00;
static final byte LOGIN_OPTION2_ODBC_ON = 0x02;
static final byte LOGIN_OPTION2_TRAN_BOUNDARY_OFF = 0x00;
static final byte LOGIN_OPTION2_TRAN_BOUNDARY_ON = 0x04;
static final byte LOGIN_OPTION2_CACHE_CONNECTION_OFF = 0x00;
static final byte LOGIN_OPTION2_CACHE_CONNECTION_ON = 0x08;
static final byte LOGIN_OPTION2_USER_NORMAL = 0x00;
static final byte LOGIN_OPTION2_USER_SERVER = 0x10;
static final byte LOGIN_OPTION2_USER_REMUSER = 0x20;
static final byte LOGIN_OPTION2_USER_SQLREPL = 0x30;
static final byte LOGIN_OPTION2_INTEGRATED_SECURITY_OFF = 0x00;
static final byte LOGIN_OPTION2_INTEGRATED_SECURITY_ON = (byte) 0x80;
// Login option byte 3
static final byte LOGIN_OPTION3_DEFAULT = 0x00;
static final byte LOGIN_OPTION3_CHANGE_PASSWORD = 0x01;
static final byte LOGIN_OPTION3_SEND_YUKON_BINARY_XML = 0x02;
static final byte LOGIN_OPTION3_USER_INSTANCE = 0x04;
static final byte LOGIN_OPTION3_UNKNOWN_COLLATION_HANDLING = 0x08;
static final byte LOGIN_OPTION3_FEATURE_EXTENSION = 0x10;
// Login type flag (bits 5 - 7 reserved for future use)
static final byte LOGIN_SQLTYPE_DEFAULT = 0x00;
static final byte LOGIN_SQLTYPE_TSQL = 0x01;
static final byte LOGIN_SQLTYPE_ANSI_V1 = 0x02;
static final byte LOGIN_SQLTYPE_ANSI89_L1 = 0x03;
static final byte LOGIN_SQLTYPE_ANSI89_L2 = 0x04;
static final byte LOGIN_SQLTYPE_ANSI89_IEF = 0x05;
static final byte LOGIN_SQLTYPE_ANSI89_ENTRY = 0x06;
static final byte LOGIN_SQLTYPE_ANSI89_TRANS = 0x07;
static final byte LOGIN_SQLTYPE_ANSI89_INTER = 0x08;
static final byte LOGIN_SQLTYPE_ANSI89_FULL = 0x09;
static final byte LOGIN_OLEDB_OFF = 0x00;
static final byte LOGIN_OLEDB_ON = 0x10;
static final byte LOGIN_READ_ONLY_INTENT = 0x20;
static final byte LOGIN_READ_WRITE_INTENT = 0x00;
static final byte ENCRYPT_OFF = 0x00;
static final byte ENCRYPT_ON = 0x01;
static final byte ENCRYPT_NOT_SUP = 0x02;
static final byte ENCRYPT_REQ = 0x03;
static final byte ENCRYPT_INVALID = (byte) 0xFF;
static final String getEncryptionLevel(int level) {
switch (level) {
case ENCRYPT_OFF:
return "OFF";
case ENCRYPT_ON:
return "ON";
case ENCRYPT_NOT_SUP:
return "NOT SUPPORTED";
case ENCRYPT_REQ:
return "REQUIRED";
default:
return "unknown encryption level (0x" + Integer.toHexString(level).toUpperCase() + ")";
}
}
// Prelogin packet length, including the tds header,
// version, encrpytion, and traceid data sessions.
// For detailed info, please check the definition of
// preloginRequest in Prelogin function.
static final byte B_PRELOGIN_MESSAGE_LENGTH = 67;
static final byte B_PRELOGIN_MESSAGE_LENGTH_WITH_FEDAUTH = 73;
// Scroll options and concurrency options lifted out
// of the the Yukon cursors spec for sp_cursoropen.
final static int SCROLLOPT_KEYSET = 1;
final static int SCROLLOPT_DYNAMIC = 2;
final static int SCROLLOPT_FORWARD_ONLY = 4;
final static int SCROLLOPT_STATIC = 8;
final static int SCROLLOPT_FAST_FORWARD = 16;
final static int SCROLLOPT_PARAMETERIZED_STMT = 4096;
final static int SCROLLOPT_AUTO_FETCH = 8192;
final static int SCROLLOPT_AUTO_CLOSE = 16384;
final static int CCOPT_READ_ONLY = 1;
final static int CCOPT_SCROLL_LOCKS = 2;
final static int CCOPT_OPTIMISTIC_CC = 4;
final static int CCOPT_OPTIMISTIC_CCVAL = 8;
final static int CCOPT_ALLOW_DIRECT = 8192;
final static int CCOPT_UPDT_IN_PLACE = 16384;
// Result set rows include an extra, "hidden" ROWSTAT column which indicates
// the overall success or failure of the row fetch operation. With a keyset
// cursor, the value in the ROWSTAT column indicates whether the row has been
// deleted from the database.
static final int ROWSTAT_FETCH_SUCCEEDED = 1;
static final int ROWSTAT_FETCH_MISSING = 2;
// ColumnInfo status
final static int COLINFO_STATUS_EXPRESSION = 0x04;
final static int COLINFO_STATUS_KEY = 0x08;
final static int COLINFO_STATUS_HIDDEN = 0x10;
final static int COLINFO_STATUS_DIFFERENT_NAME = 0x20;
final static int MAX_FRACTIONAL_SECONDS_SCALE = 7;
final static Timestamp MAX_TIMESTAMP = Timestamp.valueOf("2079-06-06 23:59:59");
final static Timestamp MIN_TIMESTAMP = Timestamp.valueOf("1900-01-01 00:00:00");
static int nanosSinceMidnightLength(int scale) {
final int[] scaledLengths = {3, 3, 3, 4, 4, 5, 5, 5};
assert scale >= 0;
assert scale <= MAX_FRACTIONAL_SECONDS_SCALE;
return scaledLengths[scale];
}
final static int DAYS_INTO_CE_LENGTH = 3;
final static int MINUTES_OFFSET_LENGTH = 2;
// Number of days in a "normal" (non-leap) year according to SQL Server.
final static int DAYS_PER_YEAR = 365;
final static int BASE_YEAR_1900 = 1900;
final static int BASE_YEAR_1970 = 1970;
final static String BASE_DATE_1970 = "1970-01-01";
static int timeValueLength(int scale) {
return nanosSinceMidnightLength(scale);
}
static int datetime2ValueLength(int scale) {
return DAYS_INTO_CE_LENGTH + nanosSinceMidnightLength(scale);
}
static int datetimeoffsetValueLength(int scale) {
return DAYS_INTO_CE_LENGTH + MINUTES_OFFSET_LENGTH + nanosSinceMidnightLength(scale);
}
// TDS is just a namespace - it can't be instantiated.
private TDS() {
}
}
class Nanos {
static final int PER_SECOND = 1000000000;
static final int PER_MAX_SCALE_INTERVAL = PER_SECOND / (int) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE);
static final int PER_MILLISECOND = PER_SECOND / 1000;
static final long PER_DAY = 24 * 60 * 60 * (long) PER_SECOND;
private Nanos() {
}
}
// Constants relating to the historically accepted Julian-Gregorian calendar cutover date (October 15, 1582).
// Used in processing SQL Server temporal data types whose date component may precede that date.
// Scoping these constants to a class defers their initialization to first use.
class GregorianChange {
// Cutover date for a pure Gregorian calendar - that is, a proleptic Gregorian calendar with
// Gregorian leap year behavior throughout its entire range. This is the cutover date is used
// with temporal server values, which are represented in terms of number of days relative to a
// base date.
static final java.util.Date PURE_CHANGE_DATE = new java.util.Date(Long.MIN_VALUE);
// The standard Julian to Gregorian cutover date (October 15, 1582) that the JDBC temporal
// classes (Time, Date, Timestamp) assume when converting to and from their UTC milliseconds
// representations.
static final java.util.Date STANDARD_CHANGE_DATE = (new GregorianCalendar(Locale.US)).getGregorianChange();
// A hint as to the number of days since 1/1/0001, past which we do not need to
// not rationalize the difference between SQL Server behavior (pure Gregorian)
// and Java behavior (standard Gregorian).
// Not having to rationalize the difference has a substantial (measured) performance benefit
// for temporal getters.
// The hint does not need to be exact, as long as it's later than the actual change date.
static final int DAYS_SINCE_BASE_DATE_HINT = DDC.daysSinceBaseDate(1583, 1, 1);
// Extra days that need to added to a pure gregorian date, post the gergorian
// cut over date, to match the default julian-gregorain calendar date of java.
static final int EXTRA_DAYS_TO_BE_ADDED;
static {
// This issue refers to the following bugs in java(same issue).
// The issue is fixed in JRE 1.7
// and exists in all the older versions.
// Due to the above bug, in older JVM versions(1.6 and before),
// the date calculation is incorrect at the Gregorian cut over date.
// i.e. the next date after Oct 4th 1582 is Oct 17th 1582, where as
// it should have been Oct 15th 1582.
// We intentionally do not make a check based on JRE version.
// If we do so, our code would break if the bug is fixed in a later update
// to an older JRE. So, we check for the existence of the bug instead.
GregorianCalendar cal = new GregorianCalendar(Locale.US);
cal.clear();
cal.set(1, Calendar.FEBRUARY, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582)
if (cal.get(Calendar.DAY_OF_MONTH) == 15) {
// If the date calculation is correct(the above bug is fixed),
// post the default gregorian cut over date, the pure gregorian date
// falls short by two days for all dates compared to julian-gregorian date.
// so, we add two extra days for functional correctness.
// Note: other ways, in which this issue can be fixed instead of
// trying to detect the JVM bug is
// a) use unoptimized code path in the function convertTemporalToObject
// b) use cal.add api instead of cal.set api in the current optimized code path
// In both the above approaches, the code is about 6-8 times slower,
// resulting in an overall perf regression of about (10-30)% for perf test cases
EXTRA_DAYS_TO_BE_ADDED = 2;
}
else
EXTRA_DAYS_TO_BE_ADDED = 0;
}
private GregorianChange() {
}
}
final class UTC {
// UTC/GMT time zone singleton.
static final TimeZone timeZone = new SimpleTimeZone(0, "UTC");
private UTC() {
}
}
final class TDSChannel {
private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Channel");
final Logger getLogger() {
return logger;
}
private final String traceID;
final public String toString() {
return traceID;
}
private final SQLServerConnection con;
private final TDSWriter tdsWriter;
final TDSWriter getWriter() {
return tdsWriter;
}
final TDSReader getReader(TDSCommand command) {
return new TDSReader(this, con, command);
}
// Socket for raw TCP/IP communications with SQL Server
private Socket tcpSocket;
// Socket for SSL-encrypted communications with SQL Server
private SSLSocket sslSocket;
// Socket providing the communications interface to the driver.
// For SSL-encrypted connections, this is the SSLSocket wrapped
// around the TCP socket. For unencrypted connections, it is
// just the TCP socket itself.
private Socket channelSocket;
// Implementation of a Socket proxy that can switch from TDS-wrapped I/O
// (using the TDSChannel itself) during SSL handshake to raw I/O over
// the TCP/IP socket.
ProxySocket proxySocket = null;
// I/O streams for raw TCP/IP communications with SQL Server
private InputStream tcpInputStream;
private OutputStream tcpOutputStream;
// I/O streams providing the communications interface to the driver.
// For SSL-encrypted connections, these are streams obtained from
// the SSL socket above. They wrap the underlying TCP streams.
// For unencrypted connections, they are just the TCP streams themselves.
private InputStream inputStream;
private OutputStream outputStream;
/** TDS packet payload logger */
private static Logger packetLogger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.DATA");
private final boolean isLoggingPackets = packetLogger.isLoggable(Level.FINEST);
final boolean isLoggingPackets() {
return isLoggingPackets;
}
// Number of TDS messages sent to and received from the server
int numMsgsSent = 0;
int numMsgsRcvd = 0;
// Last SPID received from the server. Used for logging and to tag subsequent outgoing
// packets to facilitate diagnosing problems from the server side.
private int spid = 0;
void setSPID(int spid) {
this.spid = spid;
}
int getSPID() {
return spid;
}
void resetPooledConnection() {
tdsWriter.resetPooledConnection();
}
TDSChannel(SQLServerConnection con) {
this.con = con;
traceID = "TDSChannel (" + con.toString() + ")";
this.tcpSocket = null;
this.sslSocket = null;
this.channelSocket = null;
this.tcpInputStream = null;
this.tcpOutputStream = null;
this.inputStream = null;
this.outputStream = null;
this.tdsWriter = new TDSWriter(this, con);
}
/**
* Opens the physical communications channel (TCP/IP socket and I/O streams) to the SQL Server.
*/
final void open(String host,
int port,
int timeoutMillis,
boolean useParallel,
boolean useTnir,
boolean isTnirFirstAttempt,
int timeoutMillisForFullTimeout) throws SQLServerException {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Opening TCP socket...");
SocketFinder socketFinder = new SocketFinder(traceID, con);
channelSocket = tcpSocket = socketFinder.findSocket(host, port, timeoutMillis, useParallel, useTnir, isTnirFirstAttempt,
timeoutMillisForFullTimeout);
try {
// Set socket options
tcpSocket.setTcpNoDelay(true);
tcpSocket.setKeepAlive(true);
// set SO_TIMEOUT
int socketTimeout = con.getSocketTimeoutMilliseconds();
tcpSocket.setSoTimeout(socketTimeout);
inputStream = tcpInputStream = tcpSocket.getInputStream();
outputStream = tcpOutputStream = tcpSocket.getOutputStream();
}
catch (IOException ex) {
SQLServerException.ConvertConnectExceptionToSQLServerException(host, port, con, ex);
}
}
/**
* Disables SSL on this TDS channel.
*/
void disableSSL() {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Disabling SSL...");
/*
* The mission: To close the SSLSocket and release everything that it is holding onto other than the TCP/IP socket and streams.
*
* The challenge: Simply closing the SSLSocket tries to do additional, unnecessary shutdown I/O over the TCP/IP streams that are bound to the
* socket proxy, resulting in a not responding and confusing SQL Server.
*
* Solution: Rewire the ProxySocket's input and output streams (one more time) to closed streams. SSLSocket sees that the streams are already
* closed and does not attempt to do any further I/O on them before closing itself.
*/
// Create a couple of cheap closed streams
InputStream is = new ByteArrayInputStream(new byte[0]);
try {
is.close();
}
catch (IOException e) {
// No reason to expect a brand new ByteArrayInputStream not to close,
// but just in case...
logger.fine("Ignored error closing InputStream: " + e.getMessage());
}
OutputStream os = new ByteArrayOutputStream();
try {
os.close();
}
catch (IOException e) {
// No reason to expect a brand new ByteArrayOutputStream not to close,
// but just in case...
logger.fine("Ignored error closing OutputStream: " + e.getMessage());
}
// Rewire the proxy socket to the closed streams
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Rewiring proxy streams for SSL socket close");
proxySocket.setStreams(is, os);
// Now close the SSL socket. It will see that the proxy socket's streams
// are closed and not try to do any further I/O over them.
try {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Closing SSL socket");
sslSocket.close();
}
catch (IOException e) {
// Don't care if we can't close the SSL socket. We're done with it anyway.
logger.fine("Ignored error closing SSLSocket: " + e.getMessage());
}
// Do not close the proxy socket. Doing so would close our TCP socket
// to which the proxy socket is bound. Instead, just null out the reference
// to free up the few resources it holds onto.
proxySocket = null;
// Finally, with all of the SSL support out of the way, put the TDSChannel
// back to using the TCP/IP socket and streams directly.
inputStream = tcpInputStream;
outputStream = tcpOutputStream;
channelSocket = tcpSocket;
sslSocket = null;
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL disabled");
}
/**
* Used during SSL handshake, this class implements an InputStream that reads SSL handshake response data (framed in TDS messages) from the TDS
* channel.
*/
private class SSLHandshakeInputStream extends InputStream {
private final TDSReader tdsReader;
private final SSLHandshakeOutputStream sslHandshakeOutputStream;
private final Logger logger;
private final String logContext;
SSLHandshakeInputStream(TDSChannel tdsChannel,
SSLHandshakeOutputStream sslHandshakeOutputStream) {
this.tdsReader = tdsChannel.getReader(null);
this.sslHandshakeOutputStream = sslHandshakeOutputStream;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (SSLHandshakeInputStream):";
}
/**
* If there is no handshake response data available to be read from existing packets then this method ensures that the SSL handshake output
* stream has been flushed to the server, and reads another packet (starting the next TDS response message).
*
* Note that simply using TDSReader.ensurePayload isn't sufficient as it does not automatically start the new response message.
*/
private void ensureSSLPayload() throws IOException {
if (0 == tdsReader.available()) {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " No handshake response bytes available. Flushing SSL handshake output stream.");
try {
sslHandshakeOutputStream.endMessage();
}
catch (SQLServerException e) {
logger.finer(logContext + " Ending TDS message threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Reading first packet of SSL handshake response");
try {
tdsReader.readPacket();
}
catch (SQLServerException e) {
logger.finer(logContext + " Reading response packet threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
}
}
public long skip(long n) throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Skipping " + n + " bytes...");
if (n <= 0)
return 0;
if (n > Integer.MAX_VALUE)
n = Integer.MAX_VALUE;
ensureSSLPayload();
try {
tdsReader.skip((int) n);
}
catch (SQLServerException e) {
logger.finer(logContext + " Skipping bytes threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
return n;
}
private final byte oneByte[] = new byte[1];
public int read() throws IOException {
int bytesRead;
while (0 == (bytesRead = readInternal(oneByte, 0, oneByte.length)))
;
assert 1 == bytesRead || -1 == bytesRead;
return 1 == bytesRead ? oneByte[0] : -1;
}
public int read(byte[] b) throws IOException {
return readInternal(b, 0, b.length);
}
public int read(byte b[],
int offset,
int maxBytes) throws IOException {
return readInternal(b, offset, maxBytes);
}
private int readInternal(byte b[],
int offset,
int maxBytes) throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Reading " + maxBytes + " bytes...");
ensureSSLPayload();
try {
tdsReader.readBytes(b, offset, maxBytes);
}
catch (SQLServerException e) {
logger.finer(logContext + " Reading bytes threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
return maxBytes;
}
}
/**
* Used during SSL handshake, this class implements an OutputStream that writes SSL handshake request data (framed in TDS messages) to the TDS
* channel.
*/
private class SSLHandshakeOutputStream extends OutputStream {
private final TDSWriter tdsWriter;
/** Flag indicating when it is necessary to start a new prelogin TDS message */
private boolean messageStarted;
private final Logger logger;
private final String logContext;
SSLHandshakeOutputStream(TDSChannel tdsChannel) {
this.tdsWriter = tdsChannel.getWriter();
this.messageStarted = false;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (SSLHandshakeOutputStream):";
}
public void flush() throws IOException {
// It seems that the security provider implementation in some JVMs
// (notably SunJSSE in the 6.0 JVM) likes to add spurious calls to
// flush the SSL handshake output stream during SSL handshaking.
// We need to ignore these calls because the SSL handshake payload
// needs to be completely encapsulated in TDS. The SSL handshake
// input stream always ensures that this output stream has been flushed
// before trying to read the response.
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Ignored a request to flush the stream");
}
void endMessage() throws SQLServerException {
// We should only be asked to end the message if we have started one
assert messageStarted;
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Finishing TDS message");
// Flush any remaining bytes through the writer. Since there may be fewer bytes
// ready to send than a full TDS packet, we end the message here and start a new
// one later if additional handshake data needs to be sent.
tdsWriter.endMessage();
messageStarted = false;
}
private final byte singleByte[] = new byte[1];
public void write(int b) throws IOException {
singleByte[0] = (byte) (b & 0xFF);
writeInternal(singleByte, 0, singleByte.length);
}
public void write(byte[] b) throws IOException {
writeInternal(b, 0, b.length);
}
public void write(byte[] b,
int off,
int len) throws IOException {
writeInternal(b, off, len);
}
private void writeInternal(byte[] b,
int off,
int len) throws IOException {
try {
// Start out the handshake request in a new prelogin message. Subsequent
// writes just add handshake data to the request until flushed.
if (!messageStarted) {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Starting new TDS packet...");
tdsWriter.startMessage(null, TDS.PKT_PRELOGIN);
messageStarted = true;
}
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Writing " + len + " bytes...");
tdsWriter.writeBytes(b, off, len);
}
catch (SQLServerException e) {
logger.finer(logContext + " Writing bytes threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
}
}
/**
* This class implements an InputStream that just forwards all of its methods to an underlying InputStream.
*
* It is more predictable than FilteredInputStream which forwards some of its read methods directly to the underlying stream, but not others.
*/
private final class ProxyInputStream extends InputStream {
private InputStream filteredStream;
ProxyInputStream(InputStream is) {
filteredStream = is;
}
final void setFilteredStream(InputStream is) {
filteredStream = is;
}
public long skip(long n) throws IOException {
long bytesSkipped;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Skipping " + n + " bytes");
bytesSkipped = filteredStream.skip(n);
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Skipped " + n + " bytes");
return bytesSkipped;
}
public int available() throws IOException {
int bytesAvailable = filteredStream.available();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " " + bytesAvailable + " bytes available");
return bytesAvailable;
}
private final byte oneByte[] = new byte[1];
public int read() throws IOException {
int bytesRead;
while (0 == (bytesRead = readInternal(oneByte, 0, oneByte.length)))
;
assert 1 == bytesRead || -1 == bytesRead;
return 1 == bytesRead ? oneByte[0] : -1;
}
public int read(byte[] b) throws IOException {
return readInternal(b, 0, b.length);
}
public int read(byte b[],
int offset,
int maxBytes) throws IOException {
return readInternal(b, offset, maxBytes);
}
private int readInternal(byte b[],
int offset,
int maxBytes) throws IOException {
int bytesRead;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Reading " + maxBytes + " bytes");
try {
bytesRead = filteredStream.read(b, offset, maxBytes);
}
catch (IOException e) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " " + e.getMessage());
logger.finer(toString() + " Reading bytes threw exception:" + e.getMessage());
throw e;
}
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Read " + bytesRead + " bytes");
return bytesRead;
}
public boolean markSupported() {
boolean markSupported = filteredStream.markSupported();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Returning markSupported: " + markSupported);
return markSupported;
}
public void mark(int readLimit) {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Marking next " + readLimit + " bytes");
filteredStream.mark(readLimit);
}
public void reset() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Resetting to previous mark");
filteredStream.reset();
}
public void close() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Closing");
filteredStream.close();
}
}
/**
* This class implements an OutputStream that just forwards all of its methods to an underlying OutputStream.
*
* This class essentially does what FilteredOutputStream does, but is more efficient for our usage. FilteredOutputStream transforms block writes
* to sequences of single-byte writes.
*/
final class ProxyOutputStream extends OutputStream {
private OutputStream filteredStream;
ProxyOutputStream(OutputStream os) {
filteredStream = os;
}
final void setFilteredStream(OutputStream os) {
filteredStream = os;
}
public void close() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Closing");
filteredStream.close();
}
public void flush() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Flushing");
filteredStream.flush();
}
private final byte singleByte[] = new byte[1];
public void write(int b) throws IOException {
singleByte[0] = (byte) (b & 0xFF);
writeInternal(singleByte, 0, singleByte.length);
}
public void write(byte[] b) throws IOException {
writeInternal(b, 0, b.length);
}
public void write(byte[] b,
int off,
int len) throws IOException {
writeInternal(b, off, len);
}
private void writeInternal(byte[] b,
int off,
int len) throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Writing " + len + " bytes");
filteredStream.write(b, off, len);
}
}
/**
* This class implements a Socket whose I/O streams can be switched from using a TDSChannel for I/O to using its underlying TCP/IP socket.
*
* The SSL socket binds to a ProxySocket. The initial SSL handshake is done over TDSChannel I/O streams so that the handshake payload is framed in
* TDS packets. The I/O streams are then switched to TCP/IP I/O streams using setStreams, and SSL communications continue directly over the TCP/IP
* I/O streams.
*
* Most methods other than those for getting the I/O streams are simply forwarded to the TDSChannel's underlying TCP/IP socket. Methods that
* change the socket binding or provide direct channel access are disallowed.
*/
private class ProxySocket extends Socket {
private final TDSChannel tdsChannel;
private final Logger logger;
private final String logContext;
private final ProxyInputStream proxyInputStream;
private final ProxyOutputStream proxyOutputStream;
ProxySocket(TDSChannel tdsChannel) {
this.tdsChannel = tdsChannel;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (ProxySocket):";
// Create the I/O streams
SSLHandshakeOutputStream sslHandshakeOutputStream = new SSLHandshakeOutputStream(tdsChannel);
SSLHandshakeInputStream sslHandshakeInputStream = new SSLHandshakeInputStream(tdsChannel, sslHandshakeOutputStream);
this.proxyOutputStream = new ProxyOutputStream(sslHandshakeOutputStream);
this.proxyInputStream = new ProxyInputStream(sslHandshakeInputStream);
}
void setStreams(InputStream is,
OutputStream os) {
proxyInputStream.setFilteredStream(is);
proxyOutputStream.setFilteredStream(os);
}
public InputStream getInputStream() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Getting input stream");
return proxyInputStream;
}
public OutputStream getOutputStream() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Getting output stream");
return proxyOutputStream;
}
// Allow methods that should just forward to the underlying TCP socket or return fixed values
public InetAddress getInetAddress() {
return tdsChannel.tcpSocket.getInetAddress();
}
public boolean getKeepAlive() throws SocketException {
return tdsChannel.tcpSocket.getKeepAlive();
}
public InetAddress getLocalAddress() {
return tdsChannel.tcpSocket.getLocalAddress();
}
public int getLocalPort() {
return tdsChannel.tcpSocket.getLocalPort();
}
public SocketAddress getLocalSocketAddress() {
return tdsChannel.tcpSocket.getLocalSocketAddress();
}
public boolean getOOBInline() throws SocketException {
return tdsChannel.tcpSocket.getOOBInline();
}
public int getPort() {
return tdsChannel.tcpSocket.getPort();
}
public int getReceiveBufferSize() throws SocketException {
return tdsChannel.tcpSocket.getReceiveBufferSize();
}
public SocketAddress getRemoteSocketAddress() {
return tdsChannel.tcpSocket.getRemoteSocketAddress();
}
public boolean getReuseAddress() throws SocketException {
return tdsChannel.tcpSocket.getReuseAddress();
}
public int getSendBufferSize() throws SocketException {
return tdsChannel.tcpSocket.getSendBufferSize();
}
public int getSoLinger() throws SocketException {
return tdsChannel.tcpSocket.getSoLinger();
}
public int getSoTimeout() throws SocketException {
return tdsChannel.tcpSocket.getSoTimeout();
}
public boolean getTcpNoDelay() throws SocketException {
return tdsChannel.tcpSocket.getTcpNoDelay();
}
public int getTrafficClass() throws SocketException {
return tdsChannel.tcpSocket.getTrafficClass();
}
public boolean isBound() {
return true;
}
public boolean isClosed() {
return false;
}
public boolean isConnected() {
return true;
}
public boolean isInputShutdown() {
return false;
}
public boolean isOutputShutdown() {
return false;
}
public String toString() {
return tdsChannel.tcpSocket.toString();
}
public SocketChannel getChannel() {
return null;
}
// Disallow calls to methods that would change the underlying TCP socket
public void bind(SocketAddress bindPoint) throws IOException {
logger.finer(logContext + " Disallowed call to bind. Throwing IOException.");
throw new IOException();
}
public void connect(SocketAddress endpoint) throws IOException {
logger.finer(logContext + " Disallowed call to connect (without timeout). Throwing IOException.");
throw new IOException();
}
public void connect(SocketAddress endpoint,
int timeout) throws IOException {
logger.finer(logContext + " Disallowed call to connect (with timeout). Throwing IOException.");
throw new IOException();
}
// Ignore calls to methods that would otherwise allow the SSL socket
// to directly manipulate the underlying TCP socket
public void close() throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Ignoring close");
}
public void setReceiveBufferSize(int size) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setReceiveBufferSize size:" + size);
}
public void setSendBufferSize(int size) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setSendBufferSize size:" + size);
}
public void setReuseAddress(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setReuseAddress");
}
public void setSoLinger(boolean on,
int linger) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setSoLinger");
}
public void setSoTimeout(int timeout) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setSoTimeout");
}
public void setTcpNoDelay(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setTcpNoDelay");
}
public void setTrafficClass(int tc) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setTrafficClass");
}
public void shutdownInput() throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring shutdownInput");
}
public void shutdownOutput() throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring shutdownOutput");
}
public void sendUrgentData(int data) throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring sendUrgentData");
}
public void setKeepAlive(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setKeepAlive");
}
public void setOOBInline(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setOOBInline");
}
}
/**
* This class implements an X509TrustManager that always accepts the X509Certificate chain offered to it.
*
* A PermissiveX509TrustManager is used to "verify" the authenticity of the server when the trustServerCertificate connection property is set to
* true.
*/
private final class PermissiveX509TrustManager implements X509TrustManager {
private final TDSChannel tdsChannel;
private final Logger logger;
private final String logContext;
PermissiveX509TrustManager(TDSChannel tdsChannel) {
this.tdsChannel = tdsChannel;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (PermissiveX509TrustManager):";
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Trusting client certificate (!)");
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Trusting server certificate");
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
/**
* This class implements an X509TrustManager that hostname for validation.
*
* This validates the subject name in the certificate with the host name
*/
private final class HostNameOverrideX509TrustManager implements X509TrustManager {
private final Logger logger;
private final String logContext;
private final X509TrustManager defaultTrustManager;
private String hostName;
HostNameOverrideX509TrustManager(TDSChannel tdsChannel,
X509TrustManager tm,
String hostName) {
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (HostNameOverrideX509TrustManager):";
defaultTrustManager = tm;
// canonical name is in lower case so convert this to lowercase too.
this.hostName = hostName.toLowerCase(Locale.ENGLISH);
;
}
// Parse name in RFC 2253 format
// Returns the common name if successful, null if failed to find the common name.
// The parser tuned to be safe than sorry so if it sees something it cant parse correctly it returns null
private String parseCommonName(String distinguishedName) {
int index;
// canonical name converts entire name to lowercase
index = distinguishedName.indexOf("cn=");
if (index == -1) {
return null;
}
distinguishedName = distinguishedName.substring(index + 3);
// Parse until a comma or end is reached
// Note the parser will handle gracefully (essentially will return empty string) , inside the quotes (e.g cn="Foo, bar") however
// RFC 952 says that the hostName cant have commas however the parser should not (and will not) crash if it sees a , within quotes.
for (index = 0; index < distinguishedName.length(); index++) {
if (distinguishedName.charAt(index) == ',') {
break;
}
}
String commonName = distinguishedName.substring(0, index);
// strip any quotes
if (commonName.length() > 1 && ('\"' == commonName.charAt(0))) {
if ('\"' == commonName.charAt(commonName.length() - 1))
commonName = commonName.substring(1, commonName.length() - 1);
else {
// Be safe the name is not ended in " return null so the common Name wont match
commonName = null;
}
}
return commonName;
}
private boolean validateServerName(String nameInCert) throws CertificateException {
// Failed to get the common name from DN or empty CN
if (null == nameInCert) {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Failed to parse the name from the certificate or name is empty.");
return false;
}
// Verify that the name in certificate matches exactly with the host name
if (!nameInCert.equals(hostName)) {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " The name in certificate " + nameInCert + " does not match with the server name " + hostName + ".");
return false;
}
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " The name in certificate:" + nameInCert + " validated against server name " + hostName + ".");
return true;
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Forwarding ClientTrusted.");
defaultTrustManager.checkClientTrusted(chain, authType);
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Forwarding Trusting server certificate");
defaultTrustManager.checkServerTrusted(chain, authType);
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " default serverTrusted succeeded proceeding with server name validation");
validateServerNameInCertificate(chain[0]);
}
private void validateServerNameInCertificate(X509Certificate cert) throws CertificateException {
String nameInCertDN = cert.getSubjectX500Principal().getName("canonical");
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " Validating the server name:" + hostName);
logger.finer(logContext + " The DN name in certificate:" + nameInCertDN);
}
boolean isServerNameValidated;
// the name in cert is in RFC2253 format parse it to get the actual subject name
String subjectCN = parseCommonName(nameInCertDN);
isServerNameValidated = validateServerName(subjectCN);
if (!isServerNameValidated) {
Collection<List<?>> sanCollection = cert.getSubjectAlternativeNames();
if (sanCollection != null) {
// find a subjectAlternateName entry corresponding to DNS Name
for (List<?> sanEntry : sanCollection) {
if (sanEntry != null && sanEntry.size() >= 2) {
Object key = sanEntry.get(0);
Object value = sanEntry.get(1);
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + "Key: " + key + "; KeyClass:" + (key != null ? key.getClass() : null) + ";value: " + value
+ "; valueClass:" + (value != null ? value.getClass() : null));
}
// "Note that the Collection returned may contain
// more than one name of the same type."
// So, more than one entry of dnsNameType can be present.
// Java docs guarantee that the first entry in the list will be an integer.
// 2 is the sequence no of a dnsName
if ((key != null) && (key instanceof Integer) && ((Integer) key == 2)) {
// As per RFC2459, the DNSName will be in the
// "preferred name syntax" as specified by RFC
// 1034 and the name can be in upper or lower case.
// And no significance is attached to case.
// Java docs guarantee that the second entry in the list
// will be a string for dnsName
if (value != null && value instanceof String) {
String dnsNameInSANCert = (String) value;
// Use English locale to avoid Turkish i issues.
// Note that, this conversion was not necessary for
// cert.getSubjectX500Principal().getName("canonical");
// as the above API already does this by default as per documentation.
dnsNameInSANCert = dnsNameInSANCert.toLowerCase(Locale.ENGLISH);
isServerNameValidated = validateServerName(dnsNameInSANCert);
if (isServerNameValidated) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " found a valid name in certificate: " + dnsNameInSANCert);
}
break;
}
}
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " the following name in certificate does not match the serverName: " + value);
}
}
}
else {
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " found an invalid san entry: " + sanEntry);
}
}
}
}
}
if (!isServerNameValidated) {
String msg = SQLServerException.getErrString("R_certNameFailed");
throw new CertificateException(msg);
}
}
public X509Certificate[] getAcceptedIssuers() {
return defaultTrustManager.getAcceptedIssuers();
}
}
enum SSLHandhsakeState {
SSL_HANDHSAKE_NOT_STARTED,
SSL_HANDHSAKE_STARTED,
SSL_HANDHSAKE_COMPLETE
};
/**
* Enables SSL Handshake.
*
* @param host
* Server Host Name for SSL Handshake
* @param port
* Server Port for SSL Handshake
* @throws SQLServerException
*/
void enableSSL(String host,
int port) throws SQLServerException {
// If enabling SSL fails, which it can for a number of reasons, the following items
// are used in logging information to the TDS channel logger to help diagnose the problem.
Provider tmfProvider = null; // TrustManagerFactory provider
Provider sslContextProvider = null; // SSLContext provider
Provider ksProvider = null; // KeyStore provider
String tmfDefaultAlgorithm = null; // Default algorithm (typically X.509) used by the TrustManagerFactory
SSLHandhsakeState handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_NOT_STARTED;
boolean isFips = false;
String trustStoreType = null;
String sslProtocol = null;
// If anything in here fails, terminate the connection and throw an exception
try {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Enabling SSL...");
String trustStoreFileName = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE.toString());
String trustStorePassword = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE_PASSWORD.toString());
String hostNameInCertificate = con.activeConnectionProperties
.getProperty(SQLServerDriverStringProperty.HOSTNAME_IN_CERTIFICATE.toString());
trustStoreType = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE_TYPE.toString());
if(StringUtils.isEmpty(trustStoreType)) {
trustStoreType = SQLServerDriverStringProperty.TRUST_STORE_TYPE.getDefaultValue();
}
isFips = Boolean.valueOf(con.activeConnectionProperties.getProperty(SQLServerDriverBooleanProperty.FIPS.toString()));
sslProtocol = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.SSL_PROTOCOL.toString());
if (isFips) {
validateFips(trustStoreType, trustStoreFileName);
}
assert TDS.ENCRYPT_OFF == con.getRequestedEncryptionLevel() || // Login only SSL
TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel(); // Full SSL
assert TDS.ENCRYPT_OFF == con.getNegotiatedEncryptionLevel() || // Login only SSL
TDS.ENCRYPT_ON == con.getNegotiatedEncryptionLevel() || // Full SSL
TDS.ENCRYPT_REQ == con.getNegotiatedEncryptionLevel(); // Full SSL
// If we requested login only SSL or full SSL without server certificate validation,
// then we'll "validate" the server certificate using a naive TrustManager that trusts
// everything it sees.
TrustManager[] tm = null;
if (TDS.ENCRYPT_OFF == con.getRequestedEncryptionLevel()
|| (TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel() && con.trustServerCertificate())) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL handshake will trust any certificate");
tm = new TrustManager[] {new PermissiveX509TrustManager(this)};
}
// Otherwise, we'll check if a specific TrustManager implemenation has been requested and
// if so instantiate it, optionally specifying a constructor argument to customize it.
else if (con.getTrustManagerClass() != null) {
Class<?> tmClass = Class.forName(con.getTrustManagerClass());
if (!TrustManager.class.isAssignableFrom(tmClass)) {
throw new IllegalArgumentException(
"The class specified by the trustManagerClass property must implement javax.net.ssl.TrustManager");
}
String constructorArg = con.getTrustManagerConstructorArg();
if (constructorArg == null) {
tm = new TrustManager[] {(TrustManager) tmClass.getDeclaredConstructor().newInstance()};
}
else {
tm = new TrustManager[] {(TrustManager) tmClass.getDeclaredConstructor(String.class).newInstance(constructorArg)};
}
}
// Otherwise, we'll validate the certificate using a real TrustManager obtained
// from the a security provider that is capable of validating X.509 certificates.
else {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL handshake will validate server certificate");
KeyStore ks = null;
// If we are using the system default trustStore and trustStorePassword
// then we can skip all of the KeyStore loading logic below.
// The security provider's implementation takes care of everything for us.
if (null == trustStoreFileName && null == trustStorePassword) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Using system default trust store and password");
}
// Otherwise either the trustStore, trustStorePassword, or both was specified.
// In that case, we need to load up a KeyStore ourselves.
else {
// First, obtain an interface to a KeyStore that can load trust material
// stored in Java Key Store (JKS) format.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Finding key store interface");
ks = KeyStore.getInstance(trustStoreType);
ksProvider = ks.getProvider();
// Next, load up the trust store file from the specified location.
// Note: This function returns a null InputStream if the trust store cannot
// be loaded. This is by design. See the method comment and documentation
// for KeyStore.load for details.
InputStream is = loadTrustStore(trustStoreFileName);
// Finally, load the KeyStore with the trust material (if any) from the
// InputStream and close the stream.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Loading key store");
try {
ks.load(is, (null == trustStorePassword) ? null : trustStorePassword.toCharArray());
}
finally {
// We are done with the trustStorePassword (if set). Clear it for better security.
con.activeConnectionProperties.remove(SQLServerDriverStringProperty.TRUST_STORE_PASSWORD.toString());
// We are also done with the trust store input stream.
if (null != is) {
try {
is.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Ignoring error closing trust material InputStream...");
}
}
}
}
// Either we now have a KeyStore populated with trust material or we are using the
// default source of trust material (cacerts). Either way, we are now ready to
// use a TrustManagerFactory to create a TrustManager that uses the trust material
// to validate the server certificate.
// Next step is to get a TrustManagerFactory that can produce TrustManagers
// that understands X.509 certificates.
TrustManagerFactory tmf = null;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Locating X.509 trust manager factory");
tmfDefaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
tmf = TrustManagerFactory.getInstance(tmfDefaultAlgorithm);
tmfProvider = tmf.getProvider();
// Tell the TrustManagerFactory to give us TrustManagers that we can use to
// validate the server certificate using the trust material in the KeyStore.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting trust manager");
tmf.init(ks);
tm = tmf.getTrustManagers();
// if the host name in cert provided use it or use the host name Only if it is not FIPS
if (!isFips) {
if (null != hostNameInCertificate) {
tm = new TrustManager[] {new HostNameOverrideX509TrustManager(this, (X509TrustManager) tm[0], hostNameInCertificate)};
}
else {
tm = new TrustManager[] {new HostNameOverrideX509TrustManager(this, (X509TrustManager) tm[0], host)};
}
}
} // end if (!con.trustServerCertificate())
// Now, with a real or fake TrustManager in hand, get a context for creating a
// SSL sockets through a SSL socket factory. We require at least TLS support.
SSLContext sslContext = null;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting TLS or better SSL context");
sslContext = SSLContext.getInstance(sslProtocol);
sslContextProvider = sslContext.getProvider();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Initializing SSL context");
sslContext.init(null, tm, null);
// Got the SSL context. Now create an SSL socket over our own proxy socket
// which we can toggle between TDS-encapsulated and raw communications.
// Initially, the proxy is set to encapsulate the SSL handshake in TDS packets.
proxySocket = new ProxySocket(this);
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Creating SSL socket");
sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(proxySocket, host, port, false); // don't close proxy when SSL socket
// is closed
// At long last, start the SSL handshake ...
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Starting SSL handshake");
// TLS 1.2 intermittent exception happens here.
handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_STARTED;
sslSocket.startHandshake();
handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_COMPLETE;
// After SSL handshake is complete, rewire proxy socket to use raw TCP/IP streams ...
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Rewiring proxy streams after handshake");
proxySocket.setStreams(inputStream, outputStream);
// ... and rewire TDSChannel to use SSL streams.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting SSL InputStream");
inputStream = sslSocket.getInputStream();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting SSL OutputStream");
outputStream = sslSocket.getOutputStream();
// SSL is now enabled; switch over the channel socket
channelSocket = sslSocket;
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL enabled");
}
catch (Exception e) {
// Log the original exception and its source at FINER level
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER, e.getMessage(), e);
// If enabling SSL fails, the following information may help diagnose the problem.
// Do not use Level INFO or above which is sent to standard output/error streams.
// This is because due to an intermittent TLS 1.2 connection issue, we will be retrying the connection and
// do not want to print this message in console.
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER,
"java.security path: " + JAVA_SECURITY + "\n" + "Security providers: " + Arrays.asList(Security.getProviders()) + "\n"
+ ((null != sslContextProvider) ? ("SSLContext provider info: " + sslContextProvider.getInfo() + "\n"
+ "SSLContext provider services:\n" + sslContextProvider.getServices() + "\n") : "")
+ ((null != tmfProvider) ? ("TrustManagerFactory provider info: " + tmfProvider.getInfo() + "\n") : "")
+ ((null != tmfDefaultAlgorithm) ? ("TrustManagerFactory default algorithm: " + tmfDefaultAlgorithm + "\n") : "")
+ ((null != ksProvider) ? ("KeyStore provider info: " + ksProvider.getInfo() + "\n") : "") + "java.ext.dirs: "
+ System.getProperty("java.ext.dirs"));
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_sslFailed"));
Object[] msgArgs = {e.getMessage()};
// It is important to get the localized message here, otherwise error messages won't match for different locales.
String errMsg = e.getLocalizedMessage();
// If the message is null replace it with the non-localized message or a dummy string. This can happen if a custom
// TrustManager implementation is specified that does not provide localized messages.
if (errMsg == null) {
errMsg = e.getMessage();
}
if (errMsg == null) {
errMsg = "";
}
// The error message may have a connection id appended to it. Extract the message only for comparison.
// This client connection id is appended in method checkAndAppendClientConnId().
if (errMsg.contains(SQLServerException.LOG_CLIENT_CONNECTION_ID_PREFIX)) {
errMsg = errMsg.substring(0, errMsg.indexOf(SQLServerException.LOG_CLIENT_CONNECTION_ID_PREFIX));
}
// Isolate the TLS1.2 intermittent connection error.
if (e instanceof IOException && (SSLHandhsakeState.SSL_HANDHSAKE_STARTED == handshakeState)
&& (errMsg.equals(SQLServerException.getErrString("R_truncatedServerResponse")))) {
con.terminate(SQLServerException.DRIVER_ERROR_INTERMITTENT_TLS_FAILED, form.format(msgArgs), e);
}
else {
con.terminate(SQLServerException.DRIVER_ERROR_SSL_FAILED, form.format(msgArgs), e);
}
}
}
/**
* Validate FIPS if fips set as true
*
* Valid FIPS settings:
* <LI>Encrypt should be true
* <LI>trustServerCertificate should be false
* <LI>if certificate is not installed TrustStoreType should be present.
*
* @param trustStoreType
* @param trustStoreFileName
* @throws SQLServerException
* @since 6.1.4
*/
private void validateFips(final String trustStoreType,
final String trustStoreFileName) throws SQLServerException {
boolean isValid = false;
boolean isEncryptOn;
boolean isValidTrustStoreType;
boolean isValidTrustStore;
boolean isTrustServerCertificate;
String strError = SQLServerException.getErrString("R_invalidFipsConfig");
isEncryptOn = (TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel());
isValidTrustStoreType = !StringUtils.isEmpty(trustStoreType);
isValidTrustStore = !StringUtils.isEmpty(trustStoreFileName);
isTrustServerCertificate = con.trustServerCertificate();
if (isEncryptOn && !isTrustServerCertificate) {
isValid = true;
if (isValidTrustStore && !isValidTrustStoreType) {
// In case of valid trust store we need to check TrustStoreType.
isValid = false;
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + "TrustStoreType is required alongside with TrustStore.");
}
}
if (!isValid) {
throw new SQLServerException(strError, null, 0, null);
}
}
private final static String SEPARATOR = System.getProperty("file.separator");
private final static String JAVA_HOME = System.getProperty("java.home");
private final static String JAVA_SECURITY = JAVA_HOME + SEPARATOR + "lib" + SEPARATOR + "security";
private final static String JSSECACERTS = JAVA_SECURITY + SEPARATOR + "jssecacerts";
private final static String CACERTS = JAVA_SECURITY + SEPARATOR + "cacerts";
/**
* Loads the contents of a trust store into an InputStream.
*
* When a location to a trust store is specified, this method attempts to load that store. Otherwise, it looks for and attempts to load the
* default trust store using essentially the same logic (outlined in the JSSE Reference Guide) as the default X.509 TrustManagerFactory.
*
* @return an InputStream containing the contents of the loaded trust store
* @return null if the trust store cannot be loaded.
*
* Note: It is by design that this function returns null when the trust store cannot be loaded rather than throwing an exception. The
* reason is that KeyStore.load, which uses the returned InputStream, interprets a null InputStream to mean that there are no trusted
* certificates, which mirrors the behavior of the default (no trust store, no password specified) path.
*/
final InputStream loadTrustStore(String trustStoreFileName) {
FileInputStream is = null;
// First case: Trust store filename was specified
if (null != trustStoreFileName) {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening specified trust store: " + trustStoreFileName);
is = new FileInputStream(trustStoreFileName);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
// If the trustStoreFileName connection property is set, but the file is not found,
// then treat it as if the file was empty so that the TrustManager reports
// that no certificate is found.
}
}
// Second case: Trust store filename derived from javax.net.ssl.trustStore system property
else if (null != (trustStoreFileName = System.getProperty("javax.net.ssl.trustStore"))) {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening default trust store (from javax.net.ssl.trustStore): " + trustStoreFileName);
is = new FileInputStream(trustStoreFileName);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
// If the javax.net.ssl.trustStore property is set, but the file is not found,
// then treat it as if the file was empty so that the TrustManager reports
// that no certificate is found.
}
}
// Third case: No trust store specified and no system property set. Use jssecerts/cacerts.
else {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening default trust store: " + JSSECACERTS);
is = new FileInputStream(JSSECACERTS);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
}
// No jssecerts. Try again with cacerts...
if (null == is) {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening default trust store: " + CACERTS);
is = new FileInputStream(CACERTS);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
// No jssecerts or cacerts. Treat it as if the trust store is empty so that
// the TrustManager reports that no certificate is found.
}
}
}
return is;
}
final int read(byte[] data,
int offset,
int length) throws SQLServerException {
try {
return inputStream.read(data, offset, length);
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " read failed:" + e.getMessage());
if (e instanceof SocketTimeoutException) {
con.terminate(SQLServerException.ERROR_SOCKET_TIMEOUT, e.getMessage(), e);
}
else {
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage(), e);
}
return 0; // Keep the compiler happy.
}
}
final void write(byte[] data,
int offset,
int length) throws SQLServerException {
try {
outputStream.write(data, offset, length);
}
catch (IOException e) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " write failed:" + e.getMessage());
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage(), e);
}
}
final void flush() throws SQLServerException {
try {
outputStream.flush();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " flush failed:" + e.getMessage());
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage(), e);
}
}
final void close() {
if (null != sslSocket)
disableSSL();
if (null != inputStream) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Closing inputStream...");
try {
inputStream.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored error closing inputStream", e);
}
}
if (null != outputStream) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Closing outputStream...");
try {
outputStream.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored error closing outputStream", e);
}
}
if (null != tcpSocket) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing TCP socket...");
try {
tcpSocket.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored error closing socket", e);
}
}
}
/**
* Logs TDS packet data to the com.microsoft.sqlserver.jdbc.TDS.DATA logger
*
* @param data
* the buffer containing the TDS packet payload data to log
* @param nStartOffset
* offset into the above buffer from where to start logging
* @param nLength
* length (in bytes) of payload
* @param messageDetail
* other loggable details about the payload
*/
void logPacket(byte data[],
int nStartOffset,
int nLength,
String messageDetail) {
assert 0 <= nLength && nLength <= data.length;
assert 0 <= nStartOffset && nStartOffset <= data.length;
final char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
final char printableChars[] = {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', ' ', '!', '\"', '
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'};
// Log message body lines have this form:
// "XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX ................"
// 012345678911111111112222222222333333333344444444445555555555666666
// 01234567890123456789012345678901234567890123456789012345
final char lineTemplate[] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'};
char logLine[] = new char[lineTemplate.length];
System.arraycopy(lineTemplate, 0, logLine, 0, lineTemplate.length);
// Logging builds up a string buffer for the entire log trace
// before writing it out. So use an initial size large enough
// that the buffer doesn't have to resize itself.
StringBuilder logMsg = new StringBuilder(messageDetail.length() + // Message detail
4 * nLength + // 2-digit hex + space + ASCII, per byte
4 * (1 + nLength / 16) + // 2 extra spaces + CR/LF, per line (16 bytes per line)
80); // Extra fluff: IP:Port, Connection #, SPID, ...
// Format the headline like so:
// /157.55.121.182:2983 Connection 1, SPID 53, Message info here ...
// Note: the log formatter itself timestamps what we write so we don't have
// to do it again here.
logMsg.append(tcpSocket.getLocalAddress().toString() + ":" + tcpSocket.getLocalPort() + " SPID:" + spid + " " + messageDetail + "\r\n");
// Fill in the body of the log message, line by line, 16 bytes per line.
int nBytesLogged = 0;
int nBytesThisLine;
while (true) {
// Fill up the line with as many bytes as we can (up to 16 bytes)
for (nBytesThisLine = 0; nBytesThisLine < 16 && nBytesLogged < nLength; nBytesThisLine++, nBytesLogged++) {
int nUnsignedByteVal = (data[nStartOffset + nBytesLogged] + 256) % 256;
logLine[3 * nBytesThisLine] = hexChars[nUnsignedByteVal / 16];
logLine[3 * nBytesThisLine + 1] = hexChars[nUnsignedByteVal % 16];
logLine[50 + nBytesThisLine] = printableChars[nUnsignedByteVal];
}
// Pad out the remainder with whitespace
for (int nBytesJustified = nBytesThisLine; nBytesJustified < 16; nBytesJustified++) {
logLine[3 * nBytesJustified] = ' ';
logLine[3 * nBytesJustified + 1] = ' ';
}
logMsg.append(logLine, 0, 50 + nBytesThisLine);
if (nBytesLogged == nLength)
break;
logMsg.append("\r\n");
}
if (packetLogger.isLoggable(Level.FINEST)) {
packetLogger.finest(logMsg.toString());
}
}
/**
* Get the current socket SO_TIMEOUT value.
*
* @return the current socket timeout value
* @throws IOException thrown if the socket timeout cannot be read
*/
final int getNetworkTimeout() throws IOException {
return tcpSocket.getSoTimeout();
}
/**
* Set the socket SO_TIMEOUT value.
*
* @param timeout the socket timeout in milliseconds
* @throws IOException thrown if the socket timeout cannot be set
*/
final void setNetworkTimeout(int timeout) throws IOException {
tcpSocket.setSoTimeout(timeout);
}
}
/**
* SocketFinder is used to find a server socket to which a connection can be made. This class abstracts the logic of finding a socket from TDSChannel
* class.
*
* In the case when useParallel is set to true, this is achieved by trying to make parallel connections to multiple IP addresses. This class is
* responsible for spawning multiple threads and keeping track of the search result and the connected socket or exception to be thrown.
*
* In the case where multiSubnetFailover is false, we try our old logic of trying to connect to the first ip address
*
* Typical usage of this class is SocketFinder sf = new SocketFinder(traceId, conn); Socket = sf.getSocket(hostName, port, timeout);
*/
final class SocketFinder {
/**
* Indicates the result of a search
*/
enum Result {
UNKNOWN,// search is still in progress
SUCCESS,// found a socket
FAILURE// failed in finding a socket
}
// Thread pool - the values in the constructor are chosen based on the
// explanation given in design_connection_director_multisubnet.doc
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 5, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
// When parallel connections are to be used, use minimum timeout slice of 1500 milliseconds.
private static final int minTimeoutForParallelConnections = 1500;
// lock used for synchronization while updating
// data within a socketFinder object
private final Object socketFinderlock = new Object();
// lock on which the parent thread would wait
// after spawning threads.
private final Object parentThreadLock = new Object();
// indicates whether the socketFinder has succeeded or failed
// in finding a socket or is still trying to find a socket
private volatile Result result = Result.UNKNOWN;
// total no of socket connector threads
// spawned by a socketFinder object
private int noOfSpawnedThreads = 0;
// no of threads that finished their socket connection
// attempts and notified socketFinder about their result
private int noOfThreadsThatNotified = 0;
// If a valid connected socket is found, this value would be non-null,
// else this would be null
private volatile Socket selectedSocket = null;
// This would be one of the exceptions returned by the
// socketConnector threads
private volatile IOException selectedException = null;
// Logging variables
private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SocketFinder");
private final String traceID;
// maximum number of IP Addresses supported
private static final int ipAddressLimit = 64;
// necessary for raising exceptions so that the connection pool can be notified
private final SQLServerConnection conn;
/**
* Constructs a new SocketFinder object with appropriate traceId
*
* @param callerTraceID
* traceID of the caller
* @param sqlServerConnection
* the SQLServer connection
*/
SocketFinder(String callerTraceID,
SQLServerConnection sqlServerConnection) {
traceID = "SocketFinder(" + callerTraceID + ")";
conn = sqlServerConnection;
}
/**
* Used to find a socket to which a connection can be made
*
* @param hostName
* @param portNumber
* @param timeoutInMilliSeconds
* @return connected socket
* @throws IOException
*/
Socket findSocket(String hostName,
int portNumber,
int timeoutInMilliSeconds,
boolean useParallel,
boolean useTnir,
boolean isTnirFirstAttempt,
int timeoutInMilliSecondsForFullTimeout) throws SQLServerException {
assert timeoutInMilliSeconds != 0 : "The driver does not allow a time out of 0";
try {
InetAddress[] inetAddrs = null;
// inetAddrs is only used if useParallel is true or TNIR is true. Skip resolving address if that's not the case.
if (useParallel || useTnir) {
// Ignore TNIR if host resolves to more than 64 IPs. Make sure we are using original timeout for this.
inetAddrs = InetAddress.getAllByName(hostName);
if ((useTnir) && (inetAddrs.length > ipAddressLimit)) {
useTnir = false;
timeoutInMilliSeconds = timeoutInMilliSecondsForFullTimeout;
}
}
if (!useParallel) {
// MSF is false. TNIR could be true or false. DBMirroring could be true or false.
// For TNIR first attempt, we should do existing behavior including how host name is resolved.
if (useTnir && isTnirFirstAttempt) {
return getDefaultSocket(hostName, portNumber, SQLServerConnection.TnirFirstAttemptTimeoutMs);
}
else if (!useTnir) {
return getDefaultSocket(hostName, portNumber, timeoutInMilliSeconds);
}
}
// Code reaches here only if MSF = true or (TNIR = true and not TNIR first attempt)
if (logger.isLoggable(Level.FINER)) {
StringBuilder loggingString = new StringBuilder(this.toString());
loggingString.append(" Total no of InetAddresses: ");
loggingString.append(inetAddrs.length);
loggingString.append(". They are: ");
for (InetAddress inetAddr : inetAddrs) {
loggingString.append(inetAddr.toString() + ";");
}
logger.finer(loggingString.toString());
}
if (inetAddrs.length > ipAddressLimit) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ipAddressLimitWithMultiSubnetFailover"));
Object[] msgArgs = {Integer.toString(ipAddressLimit)};
String errorStr = form.format(msgArgs);
// we do not want any retry to happen here. So, terminate the connection
// as the config is unsupported.
conn.terminate(SQLServerException.DRIVER_ERROR_UNSUPPORTED_CONFIG, errorStr);
}
if (Util.isIBM()) {
timeoutInMilliSeconds = Math.max(timeoutInMilliSeconds, minTimeoutForParallelConnections);
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + "Using Java NIO with timeout:" + timeoutInMilliSeconds);
}
findSocketUsingJavaNIO(inetAddrs, portNumber, timeoutInMilliSeconds);
}
else {
LinkedList<InetAddress> inet4Addrs = new LinkedList<>();
LinkedList<InetAddress> inet6Addrs = new LinkedList<>();
for (InetAddress inetAddr : inetAddrs) {
if (inetAddr instanceof Inet4Address) {
inet4Addrs.add((Inet4Address) inetAddr);
}
else {
assert inetAddr instanceof Inet6Address : "Unexpected IP address " + inetAddr.toString();
inet6Addrs.add((Inet6Address) inetAddr);
}
}
// use half timeout only if both IPv4 and IPv6 addresses are present
int timeoutForEachIPAddressType;
if ((!inet4Addrs.isEmpty()) && (!inet6Addrs.isEmpty())) {
timeoutForEachIPAddressType = Math.max(timeoutInMilliSeconds / 2, minTimeoutForParallelConnections);
}
else
timeoutForEachIPAddressType = Math.max(timeoutInMilliSeconds, minTimeoutForParallelConnections);
if (!inet4Addrs.isEmpty()) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + "Using Java Threading with timeout:" + timeoutForEachIPAddressType);
}
findSocketUsingThreading(inet4Addrs, portNumber, timeoutForEachIPAddressType);
}
if (!result.equals(Result.SUCCESS)) {
// try threading logic
if (!inet6Addrs.isEmpty()) {
// do not start any threads if there is only one ipv6 address
if (inet6Addrs.size() == 1) {
return getConnectedSocket(inet6Addrs.get(0), portNumber, timeoutForEachIPAddressType);
}
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + "Using Threading with timeout:" + timeoutForEachIPAddressType);
}
findSocketUsingThreading(inet6Addrs, portNumber, timeoutForEachIPAddressType);
}
}
}
// If the thread continued execution due to timeout, the result may not be known.
// In that case, update the result to failure. Note that this case is possible
// for both IPv4 and IPv6.
// Using double-checked locking for performance reasons.
if (result.equals(Result.UNKNOWN)) {
synchronized (socketFinderlock) {
if (result.equals(Result.UNKNOWN)) {
result = Result.FAILURE;
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " The parent thread updated the result to failure");
}
}
}
}
// After we reach this point, there is no need for synchronization any more.
// Because, the result would be known(success/failure).
// And no threads would update SocketFinder
// as their function calls would now be no-ops.
if (result.equals(Result.FAILURE)) {
if (selectedException == null) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString()
+ " There is no selectedException. The wait calls timed out before any connect call returned or timed out.");
}
String message = SQLServerException.getErrString("R_connectionTimedOut");
selectedException = new IOException(message);
}
throw selectedException;
}
}
catch (InterruptedException ex) {
// re-interrupt the current thread, in order to restore the thread's interrupt status.
Thread.currentThread().interrupt();
close(selectedSocket);
SQLServerException.ConvertConnectExceptionToSQLServerException(hostName, portNumber, conn, ex);
}
catch (IOException ex) {
close(selectedSocket);
// The code below has been moved from connectHelper.
// If we do not move it, the functions open(caller of findSocket)
// and findSocket will have to
// declare both IOException and SQLServerException in the throws clause
// as we throw custom SQLServerExceptions(eg:IPAddressLimit, wrapping other exceptions
// like interruptedException) in findSocket.
// That would be a bit awkward, because connecthelper(the caller of open)
// just wraps IOException into SQLServerException and throws SQLServerException.
// Instead, it would be good to wrap all exceptions at one place - Right here, their origin.
SQLServerException.ConvertConnectExceptionToSQLServerException(hostName, portNumber, conn, ex);
}
assert result.equals(Result.SUCCESS);
assert selectedSocket != null : "Bug in code. Selected Socket cannot be null here.";
return selectedSocket;
}
/**
* This function uses java NIO to connect to all the addresses in inetAddrs with in a specified timeout. If it succeeds in connecting, it closes
* all the other open sockets and updates the result to success.
*
* @param inetAddrs
* the array of inetAddress to which connection should be made
* @param portNumber
* the port number at which connection should be made
* @param timeoutInMilliSeconds
* @throws IOException
*/
private void findSocketUsingJavaNIO(InetAddress[] inetAddrs,
int portNumber,
int timeoutInMilliSeconds) throws IOException {
// The driver does not allow a time out of zero.
// Also, the unit of time the user can specify in the driver is seconds.
// So, even if the user specifies 1 second(least value), the least possible
// value that can come here as timeoutInMilliSeconds is 500 milliseconds.
assert timeoutInMilliSeconds != 0 : "The timeout cannot be zero";
assert inetAddrs.length != 0 : "Number of inetAddresses should not be zero in this function";
Selector selector = null;
LinkedList<SocketChannel> socketChannels = new LinkedList<>();
SocketChannel selectedChannel = null;
try {
selector = Selector.open();
for (InetAddress inetAddr : inetAddrs) {
SocketChannel sChannel = SocketChannel.open();
socketChannels.add(sChannel);
// make the channel non-blocking
sChannel.configureBlocking(false);
// register the channel for connect event
int ops = SelectionKey.OP_CONNECT;
SelectionKey key = sChannel.register(selector, ops);
sChannel.connect(new InetSocketAddress(inetAddr, portNumber));
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " initiated connection to address: " + inetAddr + ", portNumber: " + portNumber);
}
long timerNow = System.currentTimeMillis();
long timerExpire = timerNow + timeoutInMilliSeconds;
// Denotes the no of channels that still need to processed
int noOfOutstandingChannels = inetAddrs.length;
while (true) {
long timeRemaining = timerExpire - timerNow;
// if the timeout expired or a channel is selected or there are no more channels left to processes
if ((timeRemaining <= 0) || (selectedChannel != null) || (noOfOutstandingChannels <= 0))
break;
// denotes the no of channels that are ready to be processed. i.e. they are either connected
// or encountered an exception while trying to connect
int readyChannels = selector.select(timeRemaining);
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " no of channels ready: " + readyChannels);
// There are no real time guarantees on the time out of the select API used above.
// This check is necessary
// a) to guard against cases where the select returns faster than expected.
// b) for cases where no channels could connect with in the time out
if (readyChannels != 0) {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
SocketChannel ch = (SocketChannel) key.channel();
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " processing the channel :" + ch);// this traces the IP by default
boolean connected = false;
try {
connected = ch.finishConnect();
// ch.finishConnect should either return true or throw an exception
// as we have subscribed for OP_CONNECT.
assert connected == true : "finishConnect on channel:" + ch + " cannot be false";
selectedChannel = ch;
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " selected the channel :" + selectedChannel);
break;
}
catch (IOException ex) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " the exception: " + ex.getClass() + " with message: " + ex.getMessage()
+ " occured while processing the channel: " + ch);
updateSelectedException(ex, this.toString());
// close the channel pro-actively so that we do not
// rely to network resources
ch.close();
}
// unregister the key and remove from the selector's selectedKeys
key.cancel();
keyIterator.remove();
noOfOutstandingChannels
}
}
timerNow = System.currentTimeMillis();
}
}
catch (IOException ex) {
// in case of an exception, close the selected channel.
// All other channels will be closed in the finally block,
// as they need to be closed irrespective of a success/failure
close(selectedChannel);
throw ex;
}
finally {
// close the selector
// As per java docs, on selector.close(), any uncancelled keys still
// associated with this
// selector are invalidated, their channels are deregistered, and any other
// resources associated with this selector are released.
// So, its not necessary to cancel each key again
close(selector);
// Close all channels except the selected one.
// As we close channels pro-actively in the try block,
// its possible that we close a channel twice.
// Closing a channel second time is a no-op.
// This code is should be in the finally block to guard against cases where
// we pre-maturely exit try block due to an exception in selector or other places.
for (SocketChannel s : socketChannels) {
if (s != selectedChannel) {
close(s);
}
}
}
// if a channel was selected, make the necessary updates
if (selectedChannel != null) {
// Note that this must be done after selector is closed. Otherwise,
selectedChannel.configureBlocking(true);
selectedSocket = selectedChannel.socket();
result = Result.SUCCESS;
}
}
// This method contains the old logic of connecting to
// a socket of one of the IPs corresponding to a given host name.
// In the old code below, the logic around 0 timeout has been removed as
// 0 timeout is not allowed. The code has been re-factored so that the logic
// is common for hostName or InetAddress.
private Socket getDefaultSocket(String hostName,
int portNumber,
int timeoutInMilliSeconds) throws IOException {
// Open the socket, with or without a timeout, throwing an UnknownHostException
// if there is a failure to resolve the host name to an InetSocketAddress.
// Note that Socket(host, port) throws an UnknownHostException if the host name
// cannot be resolved, but that InetSocketAddress(host, port) does not - it sets
// the returned InetSocketAddress as unresolved.
InetSocketAddress addr = new InetSocketAddress(hostName, portNumber);
return getConnectedSocket(addr, timeoutInMilliSeconds);
}
private Socket getConnectedSocket(InetAddress inetAddr,
int portNumber,
int timeoutInMilliSeconds) throws IOException {
InetSocketAddress addr = new InetSocketAddress(inetAddr, portNumber);
return getConnectedSocket(addr, timeoutInMilliSeconds);
}
private Socket getConnectedSocket(InetSocketAddress addr,
int timeoutInMilliSeconds) throws IOException {
assert timeoutInMilliSeconds != 0 : "timeout cannot be zero";
if (addr.isUnresolved())
throw new java.net.UnknownHostException();
selectedSocket = new Socket();
selectedSocket.connect(addr, timeoutInMilliSeconds);
return selectedSocket;
}
private void findSocketUsingThreading(LinkedList<InetAddress> inetAddrs,
int portNumber,
int timeoutInMilliSeconds) throws IOException, InterruptedException {
assert timeoutInMilliSeconds != 0 : "The timeout cannot be zero";
assert inetAddrs.isEmpty() == false : "Number of inetAddresses should not be zero in this function";
LinkedList<Socket> sockets = new LinkedList<>();
LinkedList<SocketConnector> socketConnectors = new LinkedList<>();
try {
// create a socket, inetSocketAddress and a corresponding socketConnector per inetAddress
noOfSpawnedThreads = inetAddrs.size();
for (InetAddress inetAddress : inetAddrs) {
Socket s = new Socket();
sockets.add(s);
InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, portNumber);
SocketConnector socketConnector = new SocketConnector(s, inetSocketAddress, timeoutInMilliSeconds, this);
socketConnectors.add(socketConnector);
}
// acquire parent lock and spawn all threads
synchronized (parentThreadLock) {
for (SocketConnector sc : socketConnectors) {
threadPoolExecutor.execute(sc);
}
long timerNow = System.currentTimeMillis();
long timerExpire = timerNow + timeoutInMilliSeconds;
// The below loop is to guard against the spurious wake up problem
while (true) {
long timeRemaining = timerExpire - timerNow;
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " TimeRemaining:" + timeRemaining + "; Result:" + result + "; Max. open thread count: "
+ threadPoolExecutor.getLargestPoolSize() + "; Current open thread count:" + threadPoolExecutor.getActiveCount());
}
// if there is no time left or if the result is determined, break.
// Note that a dirty read of result is totally fine here.
// Since this thread holds the parentThreadLock, even if we do a dirty
// read here, the child thread, after updating the result, would not be
// able to call notify on the parentThreadLock
// (and thus finish execution) as it would be waiting on parentThreadLock
// held by this thread(the parent thread).
// So, this thread will wait again and then be notified by the childThread.
// On the other hand, if we try to take socketFinderLock here to avoid
// dirty read, we would introduce a dead lock due to the
// reverse order of locking in updateResult method.
if (timeRemaining <= 0 || (!result.equals(Result.UNKNOWN)))
break;
parentThreadLock.wait(timeRemaining);
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " The parent thread wokeup.");
}
timerNow = System.currentTimeMillis();
}
}
}
finally {
// Close all sockets except the selected one.
// As we close sockets pro-actively in the child threads,
// its possible that we close a socket twice.
// Closing a socket second time is a no-op.
// If a child thread is waiting on the connect call on a socket s,
// closing the socket s here ensures that an exception is thrown
// in the child thread immediately. This mitigates the problem
// of thread explosion by ensuring that unnecessary threads die
// quickly without waiting for "min(timeOut, 21)" seconds
for (Socket s : sockets) {
if (s != selectedSocket) {
close(s);
}
}
}
if (selectedSocket != null) {
result = Result.SUCCESS;
}
}
/**
* search result
*/
Result getResult() {
return result;
}
void close(Selector selector) {
if (null != selector) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing Selector");
try {
selector.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored the following error while closing Selector", e);
}
}
}
void close(Socket socket) {
if (null != socket) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing TCP socket:" + socket);
try {
socket.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored the following error while closing socket", e);
}
}
}
void close(SocketChannel socketChannel) {
if (null != socketChannel) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing TCP socket channel:" + socketChannel);
try {
socketChannel.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + "Ignored the following error while closing socketChannel", e);
}
}
}
/**
* Used by socketConnector threads to notify the socketFinder of their connection attempt result(a connected socket or exception). It updates the
* result, socket and exception variables of socketFinder object. This method notifies the parent thread if a socket is found or if all the
* spawned threads have notified. It also closes a socket if it is not selected for use by socketFinder.
*
* @param socket
* the SocketConnector's socket
* @param exception
* Exception that occurred in socket connector thread
* @param threadId
* Id of the calling Thread for diagnosis
*/
void updateResult(Socket socket,
IOException exception,
String threadId) {
if (result.equals(Result.UNKNOWN)) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread is waiting for socketFinderLock:" + threadId);
}
synchronized (socketFinderlock) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread acquired socketFinderLock:" + threadId);
}
if (result.equals(Result.UNKNOWN)) {
// if the connection was successful and no socket has been
// selected yet
if (exception == null && selectedSocket == null) {
selectedSocket = socket;
result = Result.SUCCESS;
if (logger.isLoggable(Level.FINER)) {
logger.finer("The socket of the following thread has been chosen:" + threadId);
}
}
// if an exception occurred
if (exception != null) {
updateSelectedException(exception, threadId);
}
}
noOfThreadsThatNotified++;
// if all threads notified, but the result is still unknown,
// update the result to failure
if ((noOfThreadsThatNotified >= noOfSpawnedThreads) && result.equals(Result.UNKNOWN)) {
result = Result.FAILURE;
}
if (!result.equals(Result.UNKNOWN)) {
// 1) Note that at any point of time, there is only one
// thread(parent/child thread) competing for parentThreadLock.
// 2) The only time where a child thread could be waiting on
// parentThreadLock is before the wait call in the parentThread
// 3) After the above happens, the parent thread waits to be
// notified on parentThreadLock. After being notified,
// it would be the ONLY thread competing for the lock.
// for the following reasons
// a) The parentThreadLock is taken while holding the socketFinderLock.
// So, all child threads, except one, block on socketFinderLock
// (not parentThreadLock)
// b) After parentThreadLock is notified by a child thread, the result
// would be known(Refer the double-checked locking done at the
// start of this method). So, all child threads would exit
// as no-ops and would never compete with parent thread
// for acquiring parentThreadLock
// 4) As the parent thread is the only thread that competes for the
// parentThreadLock, it need not wait to acquire the lock once it wakes
// up and gets scheduled.
// This results in better performance as it would close unnecessary
// sockets and thus help child threads die quickly.
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread is waiting for parentThreadLock:" + threadId);
}
synchronized (parentThreadLock) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread acquired parentThreadLock:" + threadId);
}
parentThreadLock.notify();
}
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread released parentThreadLock and notified the parent thread:" + threadId);
}
}
}
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread released socketFinderLock:" + threadId);
}
}
}
/**
* Updates the selectedException if
* <p>
* a) selectedException is null
* <p>
* b) ex is a non-socketTimeoutException and selectedException is a socketTimeoutException
* <p>
* If there are multiple exceptions, that are not related to socketTimeout the first non-socketTimeout exception is picked. If all exceptions are
* related to socketTimeout, the first exception is picked. Note: This method is not thread safe. The caller should ensure thread safety.
*
* @param ex
* the IOException
* @param traceId
* the traceId of the thread
*/
public void updateSelectedException(IOException ex,
String traceId) {
boolean updatedException = false;
if (selectedException == null ||
(!(ex instanceof SocketTimeoutException)) && (selectedException instanceof SocketTimeoutException)) {
selectedException = ex;
updatedException = true;
}
if (updatedException) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The selected exception is updated to the following: ExceptionType:" + ex.getClass() + "; ExceptionMessage:"
+ ex.getMessage() + "; by the following thread:" + traceId);
}
}
}
/**
* Used fof tracing
*
* @return traceID string
*/
public String toString() {
return traceID;
}
}
/**
* This is used to connect a socket in a separate thread
*/
final class SocketConnector implements Runnable {
// socket on which connection attempt would be made
private final Socket socket;
// the socketFinder associated with this connector
private final SocketFinder socketFinder;
// inetSocketAddress to connect to
private final InetSocketAddress inetSocketAddress;
// timeout in milliseconds
private final int timeoutInMilliseconds;
// Logging variables
private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SocketConnector");
private final String traceID;
// Id of the thread. used for diagnosis
private final String threadID;
// a counter used to give unique IDs to each connector thread.
// this will have the id of the thread that was last created.
private static long lastThreadID = 0;
/**
* Constructs a new SocketConnector object with the associated socket and socketFinder
*/
SocketConnector(Socket socket,
InetSocketAddress inetSocketAddress,
int timeOutInMilliSeconds,
SocketFinder socketFinder) {
this.socket = socket;
this.inetSocketAddress = inetSocketAddress;
this.timeoutInMilliseconds = timeOutInMilliSeconds;
this.socketFinder = socketFinder;
this.threadID = Long.toString(nextThreadID());
this.traceID = "SocketConnector:" + this.threadID + "(" + socketFinder.toString() + ")";
}
/**
* If search for socket has not finished, this function tries to connect a socket(with a timeout) synchronously. It further notifies the
* socketFinder the result of the connection attempt
*/
public void run() {
IOException exception = null;
// Note that we do not need socketFinder lock here
// as we update nothing in socketFinder based on the condition.
// So, its perfectly fine to make a dirty read.
SocketFinder.Result result = socketFinder.getResult();
if (result.equals(SocketFinder.Result.UNKNOWN)) {
try {
if (logger.isLoggable(Level.FINER)) {
logger.finer(
this.toString() + " connecting to InetSocketAddress:" + inetSocketAddress + " with timeout:" + timeoutInMilliseconds);
}
socket.connect(inetSocketAddress, timeoutInMilliseconds);
}
catch (IOException ex) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " exception:" + ex.getClass() + " with message:" + ex.getMessage()
+ " occured while connecting to InetSocketAddress:" + inetSocketAddress);
}
exception = ex;
}
socketFinder.updateResult(socket, exception, this.toString());
}
}
/**
* Used for tracing
*
* @return traceID string
*/
public String toString() {
return traceID;
}
/**
* Generates the next unique thread id.
*/
private static synchronized long nextThreadID() {
if (lastThreadID == Long.MAX_VALUE) {
if (logger.isLoggable(Level.FINER))
logger.finer("Resetting the Id count");
lastThreadID = 1;
}
else {
lastThreadID++;
}
return lastThreadID;
}
}
/**
* TDSWriter implements the client to server TDS data pipe.
*/
final class TDSWriter {
private static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Writer");
private final String traceID;
final public String toString() {
return traceID;
}
private final TDSChannel tdsChannel;
private final SQLServerConnection con;
// Flag to indicate whether data written via writeXXX() calls
// is loggable. Data is normally loggable. But sensitive
// data, such as user credentials, should never be logged for
// security reasons.
private boolean dataIsLoggable = true;
void setDataLoggable(boolean value) {
dataIsLoggable = value;
}
private TDSCommand command = null;
// TDS message type (Query, RPC, DTC, etc.) sent at the beginning
// of every TDS message header. Value is set when starting a new
// TDS message of the specified type.
private byte tdsMessageType;
private volatile int sendResetConnection = 0;
// Size (in bytes) of the TDS packets to/from the server.
// This size is normally fixed for the life of the connection,
// but it can change once after the logon packet because packet
// size negotiation happens at logon time.
private int currentPacketSize = 0;
// Size of the TDS packet header, which is:
// byte type
// byte status
// short length
// short SPID
// byte packet
// byte window
private final static int TDS_PACKET_HEADER_SIZE = 8;
private final static byte[] placeholderHeader = new byte[TDS_PACKET_HEADER_SIZE];
// Intermediate array used to convert typically "small" values such as fixed-length types
// (byte, int, long, etc.) and Strings from their native form to bytes for sending to
// the channel buffers.
private byte valueBytes[] = new byte[256];
// Monotonically increasing packet number associated with the current message
private int packetNum = 0;
// Bytes for sending decimal/numeric data
private final static int BYTES4 = 4;
private final static int BYTES8 = 8;
private final static int BYTES12 = 12;
private final static int BYTES16 = 16;
public final static int BIGDECIMAL_MAX_LENGTH = 0x11;
// is set to true when EOM is sent for the current message.
// Note that this variable will never be accessed from multiple threads
// simultaneously and so it need not be volatile
private boolean isEOMSent = false;
boolean isEOMSent() {
return isEOMSent;
}
// Packet data buffers
private ByteBuffer stagingBuffer;
private ByteBuffer socketBuffer;
private ByteBuffer logBuffer;
private CryptoMetadata cryptoMeta = null;
TDSWriter(TDSChannel tdsChannel,
SQLServerConnection con) {
this.tdsChannel = tdsChannel;
this.con = con;
traceID = "TDSWriter@" + Integer.toHexString(hashCode()) + " (" + con.toString() + ")";
}
// TDS message start/end operations
void preparePacket() throws SQLServerException {
if (tdsChannel.isLoggingPackets()) {
Arrays.fill(logBuffer.array(), (byte) 0xFE);
((Buffer)logBuffer).clear();
}
// Write a placeholder packet header. This will be replaced
// with the real packet header when the packet is flushed.
writeBytes(placeholderHeader);
}
/**
* Start a new TDS message.
*/
void writeMessageHeader() throws SQLServerException {
// TDS 7.2 & later:
// Include ALL_Headers/MARS header in message's first packet
// Note: The PKT_BULK message does not nees this ALL_HEADERS
if ((TDS.PKT_QUERY == tdsMessageType || TDS.PKT_DTC == tdsMessageType || TDS.PKT_RPC == tdsMessageType)) {
boolean includeTraceHeader = false;
int totalHeaderLength = TDS.MESSAGE_HEADER_LENGTH;
if (TDS.PKT_QUERY == tdsMessageType || TDS.PKT_RPC == tdsMessageType) {
if (con.isDenaliOrLater() && !ActivityCorrelator.getCurrent().IsSentToServer() && Util.IsActivityTraceOn()) {
includeTraceHeader = true;
totalHeaderLength += TDS.TRACE_HEADER_LENGTH;
}
}
writeInt(totalHeaderLength); // allHeaders.TotalLength (DWORD)
writeInt(TDS.MARS_HEADER_LENGTH); // MARS header length (DWORD)
writeShort((short) 2); // allHeaders.HeaderType(MARS header) (USHORT)
writeBytes(con.getTransactionDescriptor());
writeInt(1); // marsHeader.OutstandingRequestCount
if (includeTraceHeader) {
writeInt(TDS.TRACE_HEADER_LENGTH); // trace header length (DWORD)
writeTraceHeaderData();
ActivityCorrelator.setCurrentActivityIdSentFlag(); // set the flag to indicate this ActivityId is sent
}
}
}
void writeTraceHeaderData() throws SQLServerException {
ActivityId activityId = ActivityCorrelator.getCurrent();
final byte[] actIdByteArray = Util.asGuidByteArray(activityId.getId());
long seqNum = activityId.getSequence();
writeShort(TDS.HEADERTYPE_TRACE); // trace header type
writeBytes(actIdByteArray, 0, actIdByteArray.length); // guid part of ActivityId
writeInt((int) seqNum); // sequence number of ActivityId
if (logger.isLoggable(Level.FINER))
logger.finer("Send Trace Header - ActivityID: " + activityId.toString());
}
/**
* Convenience method to prepare the TDS channel for writing and start a new TDS message.
*
* @param command
* The TDS command
* @param tdsMessageType
* The TDS message type (PKT_QUERY, PKT_RPC, etc.)
*/
void startMessage(TDSCommand command,
byte tdsMessageType) throws SQLServerException {
this.command = command;
this.tdsMessageType = tdsMessageType;
this.packetNum = 0;
this.isEOMSent = false;
this.dataIsLoggable = true;
// If the TDS packet size has changed since the last request
// (which should really only happen after the login packet)
// then allocate new buffers that are the correct size.
int negotiatedPacketSize = con.getTDSPacketSize();
if (currentPacketSize != negotiatedPacketSize) {
socketBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN);
stagingBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN);
logBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN);
currentPacketSize = negotiatedPacketSize;
}
((Buffer) socketBuffer).position(((Buffer) socketBuffer).limit());
((Buffer)stagingBuffer).clear();
preparePacket();
writeMessageHeader();
}
final void endMessage() throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Finishing TDS message");
writePacket(TDS.STATUS_BIT_EOM);
}
// If a complete request has not been sent to the server,
// the client MUST send the next packet with both ignore bit (0x02) and EOM bit (0x01)
// set in the status to cancel the request.
final boolean ignoreMessage() throws SQLServerException {
if (packetNum > 0) {
assert !isEOMSent;
if (logger.isLoggable(Level.FINER))
logger.finest(toString() + " Finishing TDS message by sending ignore bit and end of message");
writePacket(TDS.STATUS_BIT_EOM | TDS.STATUS_BIT_ATTENTION);
return true;
}
return false;
}
final void resetPooledConnection() {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " resetPooledConnection");
sendResetConnection = TDS.STATUS_BIT_RESET_CONN;
}
// Primitive write operations
void writeByte(byte value) throws SQLServerException {
if (stagingBuffer.remaining() >= 1) {
stagingBuffer.put(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value);
else
((Buffer)logBuffer).position(((Buffer)logBuffer).position() + 1);
}
}
else {
valueBytes[0] = value;
writeWrappedBytes(valueBytes, 1);
}
}
/**
* writing sqlCollation information for sqlVariant type when sending character types.
*
* @param variantType
* @throws SQLServerException
*/
void writeCollationForSqlVariant(SqlVariant variantType) throws SQLServerException {
writeInt(variantType.getCollation().getCollationInfo());
writeByte((byte) (variantType.getCollation().getCollationSortID() & 0xFF));
}
void writeChar(char value) throws SQLServerException {
if (stagingBuffer.remaining() >= 2) {
stagingBuffer.putChar(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putChar(value);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + 2);
}
}
else {
Util.writeShort((short) value, valueBytes, 0);
writeWrappedBytes(valueBytes, 2);
}
}
void writeShort(short value) throws SQLServerException {
if (stagingBuffer.remaining() >= 2) {
stagingBuffer.putShort(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putShort(value);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + 2);
}
}
else {
Util.writeShort(value, valueBytes, 0);
writeWrappedBytes(valueBytes, 2);
}
}
void writeInt(int value) throws SQLServerException {
if (stagingBuffer.remaining() >= 4) {
stagingBuffer.putInt(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putInt(value);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + 4);
}
}
else {
Util.writeInt(value, valueBytes, 0);
writeWrappedBytes(valueBytes, 4);
}
}
/**
* Append a real value in the TDS stream.
*
* @param value
* the data value
*/
void writeReal(Float value) throws SQLServerException {
writeInt(Float.floatToRawIntBits(value));
}
/**
* Append a double value in the TDS stream.
*
* @param value
* the data value
*/
void writeDouble(double value) throws SQLServerException {
if (stagingBuffer.remaining() >= 8) {
stagingBuffer.putDouble(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putDouble(value);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + 8);
}
}
else {
long bits = Double.doubleToLongBits(value);
long mask = 0xFF;
int nShift = 0;
for (int i = 0; i < 8; i++) {
writeByte((byte) ((bits & mask) >> nShift));
nShift += 8;
mask = mask << 8;
}
}
}
/**
* Append a big decimal in the TDS stream.
*
* @param bigDecimalVal
* the big decimal data value
* @param srcJdbcType
* the source JDBCType
* @param precision
* the precision of the data value
* @param scale
* the scale of the column
* @throws SQLServerException
*/
void writeBigDecimal(BigDecimal bigDecimalVal,
int srcJdbcType,
int precision,
int scale) throws SQLServerException {
/*
* Length including sign byte One 1-byte unsigned integer that represents the sign of the decimal value (0 => Negative, 1 => positive) One 4-,
* 8-, 12-, or 16-byte signed integer that represents the decimal value multiplied by 10^scale.
*/
/*
* setScale of all BigDecimal value based on metadata as scale is not sent seperately for individual value. Use the rounding used in Server.
* Say, for BigDecimal("0.1"), if scale in metdadata is 0, then ArithmeticException would be thrown if RoundingMode is not set
*/
bigDecimalVal = bigDecimalVal.setScale(scale, RoundingMode.HALF_UP);
// data length + 1 byte for sign
int bLength = BYTES16 + 1;
writeByte((byte) (bLength));
// Byte array to hold all the data and padding bytes.
byte[] bytes = new byte[bLength];
byte[] valueBytes = DDC.convertBigDecimalToBytes(bigDecimalVal, scale);
// removing the precision and scale information from the valueBytes array
System.arraycopy(valueBytes, 2, bytes, 0, valueBytes.length - 2);
writeBytes(bytes);
}
/**
* Append a big decimal inside sql_variant in the TDS stream.
*
* @param bigDecimalVal
* the big decimal data value
* @param srcJdbcType
* the source JDBCType
*/
void writeSqlVariantInternalBigDecimal(BigDecimal bigDecimalVal,
int srcJdbcType) throws SQLServerException {
/*
* Length including sign byte One 1-byte unsigned integer that represents the sign of the decimal value (0 => Negative, 1 => positive) One
* 16-byte signed integer that represents the decimal value multiplied by 10^scale. In sql_variant, we send the bigdecimal with precision 38,
* therefore we use 16 bytes for the maximum size of this integer.
*/
boolean isNegative = (bigDecimalVal.signum() < 0);
BigInteger bi = bigDecimalVal.unscaledValue();
if (isNegative)
{
bi = bi.negate();
}
int bLength;
bLength = BYTES16;
writeByte((byte) (isNegative ? 0 : 1));
// Get the bytes of the BigInteger value. It is in reverse order, with
// most significant byte in 0-th element. We need to reverse it first before sending over TDS.
byte[] unscaledBytes = bi.toByteArray();
if (unscaledBytes.length > bLength) {
// If precession of input is greater than maximum allowed (p><= 38) throw Exception
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {JDBCType.of(srcJdbcType)};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET, null);
}
// Byte array to hold all the reversed and padding bytes.
byte[] bytes = new byte[bLength];
// We need to fill up the rest of the array with zeros, as unscaledBytes may have less bytes
// than the required size for TDS.
int remaining = bLength - unscaledBytes.length;
// Reverse the bytes.
int i, j;
for (i = 0, j = unscaledBytes.length - 1; i < unscaledBytes.length;)
bytes[i++] = unscaledBytes[j
// Fill the rest of the array with zeros.
for (; i < remaining; i++)
{
bytes[i] = (byte) 0x00;
}
writeBytes(bytes);
}
void writeSmalldatetime(String value) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
java.sql.Timestamp timestampValue = java.sql.Timestamp.valueOf(value);
utcMillis = timestampValue.getTime();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
// Number of days since the SQL Server Base Date (January 1, 1900)
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Next, figure out the number of milliseconds since midnight of the current day.
int millisSinceMidnight = 1000 * calendar.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * calendar.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * calendar.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (1000 * 60 * 60 * 24 - 1 <= millisSinceMidnight) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
// Number of days since the SQL Server Base Date (January 1, 1900)
writeShort((short) daysSinceSQLBaseDate);
int secondsSinceMidnight = (millisSinceMidnight / 1000);
int minutesSinceMidnight = (secondsSinceMidnight / 60);
// Values that are 29.998 seconds or less are rounded down to the nearest minute
minutesSinceMidnight = ((secondsSinceMidnight % 60) > 29.998) ? minutesSinceMidnight + 1 : minutesSinceMidnight;
// Minutes since midnight
writeShort((short) minutesSinceMidnight);
}
void writeDatetime(String value) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
int subSecondNanos;
java.sql.Timestamp timestampValue = java.sql.Timestamp.valueOf(value);
utcMillis = timestampValue.getTime();
subSecondNanos = timestampValue.getNanos();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
// Number of days there have been since the SQL Base Date.
// These are based on SQL Server algorithms
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Number of milliseconds since midnight of the current day.
int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second
1000 * calendar.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * calendar.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * calendar.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (1000 * 60 * 60 * 24 - 1 <= millisSinceMidnight) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
// Last-ditch verification that the value is in the valid range for the
// DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then
// throw an exception now so that statement execution is safely canceled.
// Attempting to put an invalid value on the wire would result in a TDS
// exception, which would close the connection.
// These are based on SQL Server algorithms
if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.DATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
// Number of days since the SQL Server Base Date (January 1, 1900)
writeInt(daysSinceSQLBaseDate);
// Milliseconds since midnight (at a resolution of three hundredths of a second)
writeInt((3 * millisSinceMidnight + 5) / 10);
}
void writeDate(String value) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis;
java.sql.Date dateValue = java.sql.Date.valueOf(value);
utcMillis = dateValue.getTime();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
writeScaledTemporal(calendar, 0, // subsecond nanos (none for a date value)
0, // scale (dates are not scaled)
SSType.DATE);
}
void writeTime(java.sql.Timestamp value,
int scale) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
int subSecondNanos;
utcMillis = value.getTime();
subSecondNanos = value.getNanos();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.TIME);
}
void writeDateTimeOffset(Object value,
int scale,
SSType destSSType) throws SQLServerException {
GregorianCalendar calendar;
TimeZone timeZone; // Time zone to associate with the value in the Gregorian calendar
long utcMillis; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
int subSecondNanos;
int minutesOffset;
microsoft.sql.DateTimeOffset dtoValue = (microsoft.sql.DateTimeOffset) value;
utcMillis = dtoValue.getTimestamp().getTime();
subSecondNanos = dtoValue.getTimestamp().getNanos();
minutesOffset = dtoValue.getMinutesOffset();
// If the target data type is DATETIMEOFFSET, then use UTC for the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = (SSType.DATETIMEOFFSET == destSSType) ? UTC.timeZone : new SimpleTimeZone(minutesOffset * 60 * 1000, "");
calendar = new GregorianCalendar(timeZone, Locale.US);
calendar.setLenient(true);
calendar.clear();
calendar.setTimeInMillis(utcMillis);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
void writeOffsetDateTimeWithTimezone(OffsetDateTime offsetDateTimeValue,
int scale) throws SQLServerException {
GregorianCalendar calendar;
TimeZone timeZone;
long utcMillis;
int subSecondNanos;
int minutesOffset = 0;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also supports
// offsets in minutes precision.
minutesOffset = offsetDateTimeValue.getOffset().getTotalSeconds() / 60;
}
catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error is generated in
// the driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetDateTimeValue.getNano();
// writeScaledTemporal() expects subSecondNanos in 9 digits precssion
// but getNano() used in OffsetDateTime returns precession based on nanoseconds read from csv
// padding zeros to match the expectation of writeScaledTemporal()
int padding = 9 - String.valueOf(subSecondNanos).length();
while (padding > 0) {
subSecondNanos = subSecondNanos * 10;
padding
}
// For TIME_WITH_TIMEZONE, use UTC for the calendar that will hold the value
timeZone = UTC.timeZone;
// The behavior is similar to microsoft.sql.DateTimeOffset
// In Timestamp format, only YEAR needs to have 4 digits. The leading zeros for the rest of the fields can be omitted.
String offDateTimeStr = String.format("%04d", offsetDateTimeValue.getYear()) + '-' + offsetDateTimeValue.getMonthValue() + '-'
+ offsetDateTimeValue.getDayOfMonth() + ' ' + offsetDateTimeValue.getHour() + ':' + offsetDateTimeValue.getMinute() + ':'
+ offsetDateTimeValue.getSecond();
utcMillis = Timestamp.valueOf(offDateTimeStr).getTime();
calendar = initializeCalender(timeZone);
calendar.setTimeInMillis(utcMillis);
// Local timezone value in minutes
int minuteAdjustment = ((TimeZone.getDefault().getRawOffset()) / (60 * 1000));
// check if date is in day light savings and add daylight saving minutes
if (TimeZone.getDefault().inDaylightTime(calendar.getTime()))
minuteAdjustment += (TimeZone.getDefault().getDSTSavings()) / (60 * 1000);
// If the local time is negative then positive minutesOffset must be subtracted from calender
minuteAdjustment += (minuteAdjustment < 0) ? (minutesOffset * (-1)) : minutesOffset;
calendar.add(Calendar.MINUTE, minuteAdjustment);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
void writeOffsetTimeWithTimezone(OffsetTime offsetTimeValue,
int scale) throws SQLServerException {
GregorianCalendar calendar;
TimeZone timeZone;
long utcMillis;
int subSecondNanos;
int minutesOffset = 0;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also supports
// offsets in minutes precision.
minutesOffset = offsetTimeValue.getOffset().getTotalSeconds() / 60;
}
catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error is generated in
// the driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetTimeValue.getNano();
// writeScaledTemporal() expects subSecondNanos in 9 digits precssion
// but getNano() used in OffsetDateTime returns precession based on nanoseconds read from csv
// padding zeros to match the expectation of writeScaledTemporal()
int padding = 9 - String.valueOf(subSecondNanos).length();
while (padding > 0) {
subSecondNanos = subSecondNanos * 10;
padding
}
// For TIME_WITH_TIMEZONE, use UTC for the calendar that will hold the value
timeZone = UTC.timeZone;
// Using TDS.BASE_YEAR_1900, based on SQL server behavious
// If date only contains a time part, the return value is 1900, the base year.
// In Timestamp format, leading zeros for the fields can be omitted.
String offsetTimeStr = TDS.BASE_YEAR_1900 + "-01-01" + ' ' + offsetTimeValue.getHour() + ':' + offsetTimeValue.getMinute() + ':'
+ offsetTimeValue.getSecond();
utcMillis = Timestamp.valueOf(offsetTimeStr).getTime();
calendar = initializeCalender(timeZone);
calendar.setTimeInMillis(utcMillis);
int minuteAdjustment = (TimeZone.getDefault().getRawOffset()) / (60 * 1000);
// check if date is in day light savings and add daylight saving minutes to Local timezone(in minutes)
if (TimeZone.getDefault().inDaylightTime(calendar.getTime()))
minuteAdjustment += ((TimeZone.getDefault().getDSTSavings()) / (60 * 1000));
// If the local time is negative then positive minutesOffset must be subtracted from calender
minuteAdjustment += (minuteAdjustment < 0) ? (minutesOffset * (-1)) : minutesOffset;
calendar.add(Calendar.MINUTE, minuteAdjustment);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
void writeLong(long value) throws SQLServerException {
if (stagingBuffer.remaining() >= 8) {
stagingBuffer.putLong(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putLong(value);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + 8);
}
}
else {
valueBytes[0] = (byte) ((value >> 0) & 0xFF);
valueBytes[1] = (byte) ((value >> 8) & 0xFF);
valueBytes[2] = (byte) ((value >> 16) & 0xFF);
valueBytes[3] = (byte) ((value >> 24) & 0xFF);
valueBytes[4] = (byte) ((value >> 32) & 0xFF);
valueBytes[5] = (byte) ((value >> 40) & 0xFF);
valueBytes[6] = (byte) ((value >> 48) & 0xFF);
valueBytes[7] = (byte) ((value >> 56) & 0xFF);
writeWrappedBytes(valueBytes, 8);
}
}
void writeBytes(byte[] value) throws SQLServerException {
writeBytes(value, 0, value.length);
}
void writeBytes(byte[] value,
int offset,
int length) throws SQLServerException {
assert length <= value.length;
int bytesWritten = 0;
int bytesToWrite;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Writing " + length + " bytes");
while ((bytesToWrite = length - bytesWritten) > 0) {
if (0 == stagingBuffer.remaining())
writePacket(TDS.STATUS_NORMAL);
if (bytesToWrite > stagingBuffer.remaining())
bytesToWrite = stagingBuffer.remaining();
stagingBuffer.put(value, offset + bytesWritten, bytesToWrite);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value, offset + bytesWritten, bytesToWrite);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + bytesToWrite);
}
bytesWritten += bytesToWrite;
}
}
void writeWrappedBytes(byte value[],
int valueLength) throws SQLServerException {
// This function should only be used to write a value that is longer than
// what remains in the current staging buffer. However, the value must
// be short enough to fit in an empty buffer.
assert valueLength <= value.length;
int remaining = stagingBuffer.remaining();
assert remaining < valueLength;
assert valueLength <= stagingBuffer.capacity();
// Fill any remaining space in the staging buffer
remaining = stagingBuffer.remaining();
if (remaining > 0) {
stagingBuffer.put(value, 0, remaining);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value, 0, remaining);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + remaining);
}
}
writePacket(TDS.STATUS_NORMAL);
// After swapping, the staging buffer should once again be empty, so the
// remainder of the value can be written to it.
stagingBuffer.put(value, remaining, valueLength - remaining);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value, remaining, valueLength - remaining);
else
((Buffer)logBuffer).position( ((Buffer)logBuffer).position() + remaining);
}
}
void writeString(String value) throws SQLServerException {
int charsCopied = 0;
int length = value.length();
while (charsCopied < length) {
int bytesToCopy = 2 * (length - charsCopied);
if (bytesToCopy > valueBytes.length)
bytesToCopy = valueBytes.length;
int bytesCopied = 0;
while (bytesCopied < bytesToCopy) {
char ch = value.charAt(charsCopied++);
valueBytes[bytesCopied++] = (byte) ((ch >> 0) & 0xFF);
valueBytes[bytesCopied++] = (byte) ((ch >> 8) & 0xFF);
}
writeBytes(valueBytes, 0, bytesCopied);
}
}
void writeStream(InputStream inputStream,
long advertisedLength,
boolean writeChunkSizes) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0;
long actualLength = 0;
final byte[] streamByteBuffer = new byte[4 * currentPacketSize];
int bytesRead = 0;
int bytesToWrite;
do {
// Read in next chunk
for (bytesToWrite = 0; -1 != bytesRead && bytesToWrite < streamByteBuffer.length; bytesToWrite += bytesRead) {
try {
bytesRead = inputStream.read(streamByteBuffer, bytesToWrite, streamByteBuffer.length - bytesToWrite);
}
catch (IOException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {e.toString()};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
if (-1 == bytesRead)
break;
// Check for invalid bytesRead returned from InputStream.read
if (bytesRead < 0 || bytesRead > streamByteBuffer.length - bytesToWrite) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
}
// Write it out
if (writeChunkSizes)
writeInt(bytesToWrite);
writeBytes(streamByteBuffer, 0, bytesToWrite);
actualLength += bytesToWrite;
}
while (-1 != bytesRead || bytesToWrite > 0);
// If we were given an input stream length that we had to match and
// the actual stream length did not match then cancel the request.
if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength"));
Object[] msgArgs = {advertisedLength, actualLength};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET);
}
}
/*
* Adding another function for writing non-unicode reader instead of re-factoring the writeReader() for performance efficiency. As this method
* will only be used in bulk copy, it needs to be efficient. Note: Any changes in algorithm/logic should propagate to both writeReader() and
* writeNonUnicodeReader().
*/
void writeNonUnicodeReader(Reader reader,
long advertisedLength,
boolean isDestBinary,
Charset charSet) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0;
long actualLength = 0;
char[] streamCharBuffer = new char[currentPacketSize];
// The unicode version, writeReader() allocates a byte buffer that is 4 times the currentPacketSize, not sure why.
byte[] streamByteBuffer = new byte[currentPacketSize];
int charsRead = 0;
int charsToWrite;
int bytesToWrite;
String streamString;
do {
// Read in next chunk
for (charsToWrite = 0; -1 != charsRead && charsToWrite < streamCharBuffer.length; charsToWrite += charsRead) {
try {
charsRead = reader.read(streamCharBuffer, charsToWrite, streamCharBuffer.length - charsToWrite);
}
catch (IOException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {e.toString()};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
if (-1 == charsRead)
break;
// Check for invalid bytesRead returned from Reader.read
if (charsRead < 0 || charsRead > streamCharBuffer.length - charsToWrite) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
}
if (!isDestBinary) {
// Write it out
// This also writes the PLP_TERMINATOR token after all the data in the the stream are sent.
// The Do-While loop goes on one more time as charsToWrite is greater than 0 for the last chunk, and
// in this last round the only thing that is written is an int value of 0, which is the PLP Terminator token(0x00000000).
writeInt(charsToWrite);
for (int charsCopied = 0; charsCopied < charsToWrite; ++charsCopied) {
if (null == charSet) {
streamByteBuffer[charsCopied] = (byte) (streamCharBuffer[charsCopied] & 0xFF);
}
else {
// encoding as per collation
streamByteBuffer[charsCopied] = new String(streamCharBuffer[charsCopied] + "").getBytes(charSet)[0];
}
}
writeBytes(streamByteBuffer, 0, charsToWrite);
}
else {
bytesToWrite = charsToWrite;
if (0 != charsToWrite)
bytesToWrite = charsToWrite / 2;
streamString = new String(streamCharBuffer);
byte[] bytes = ParameterUtils.HexToBin(streamString.trim());
writeInt(bytesToWrite);
writeBytes(bytes, 0, bytesToWrite);
}
actualLength += charsToWrite;
}
while (-1 != charsRead || charsToWrite > 0);
// If we were given an input stream length that we had to match and
// the actual stream length did not match then cancel the request.
if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength"));
Object[] msgArgs = {advertisedLength, actualLength};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET);
}
}
/*
* Note: There is another method with same code logic for non unicode reader, writeNonUnicodeReader(), implemented for performance efficiency. Any
* changes in algorithm/logic should propagate to both writeReader() and writeNonUnicodeReader().
*/
void writeReader(Reader reader,
long advertisedLength,
boolean writeChunkSizes) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0;
long actualLength = 0;
char[] streamCharBuffer = new char[2 * currentPacketSize];
byte[] streamByteBuffer = new byte[4 * currentPacketSize];
int charsRead = 0;
int charsToWrite;
do {
// Read in next chunk
for (charsToWrite = 0; -1 != charsRead && charsToWrite < streamCharBuffer.length; charsToWrite += charsRead) {
try {
charsRead = reader.read(streamCharBuffer, charsToWrite, streamCharBuffer.length - charsToWrite);
}
catch (IOException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {e.toString()};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
if (-1 == charsRead)
break;
// Check for invalid bytesRead returned from Reader.read
if (charsRead < 0 || charsRead > streamCharBuffer.length - charsToWrite) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
}
// Write it out
if (writeChunkSizes)
writeInt(2 * charsToWrite);
// Convert from Unicode characters to bytes
// Note: The following inlined code is much faster than the equivalent
// call to (new String(streamCharBuffer)).getBytes("UTF-16LE") because it
// saves a conversion to String and use of Charset in that conversion.
for (int charsCopied = 0; charsCopied < charsToWrite; ++charsCopied) {
streamByteBuffer[2 * charsCopied] = (byte) ((streamCharBuffer[charsCopied] >> 0) & 0xFF);
streamByteBuffer[2 * charsCopied + 1] = (byte) ((streamCharBuffer[charsCopied] >> 8) & 0xFF);
}
writeBytes(streamByteBuffer, 0, 2 * charsToWrite);
actualLength += charsToWrite;
}
while (-1 != charsRead || charsToWrite > 0);
// If we were given an input stream length that we had to match and
// the actual stream length did not match then cancel the request.
if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength"));
Object[] msgArgs = {advertisedLength, actualLength};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET);
}
}
GregorianCalendar initializeCalender(TimeZone timeZone) {
GregorianCalendar calendar;
// Create the calendar that will hold the value. For DateTimeOffset values, the calendar's
// time zone is UTC. For other values, the calendar's time zone is a local time zone.
calendar = new GregorianCalendar(timeZone, Locale.US);
// Set the calendar lenient to allow setting the DAY_OF_YEAR and MILLISECOND fields
// to roll other fields to their correct values.
calendar.setLenient(true);
// Clear the calendar of any existing state. The state of a new Calendar object always
// reflects the current date, time, DST offset, etc.
calendar.clear();
return calendar;
}
final void error(String reason,
SQLState sqlState,
DriverError driverError) throws SQLServerException {
assert null != command;
command.interrupt(reason);
throw new SQLServerException(reason, sqlState, driverError, null);
}
/**
* Sends an attention signal to the server, if necessary, to tell it to stop processing the current command on this connection.
*
* If no packets of the command's request have yet been sent to the server, then no attention signal needs to be sent. The interrupt will be
* handled entirely by the driver.
*
* This method does not need synchronization as it does not manipulate interrupt state and writing is guaranteed to occur only from one thread at
* a time.
*/
final boolean sendAttention() throws SQLServerException {
// If any request packets were already written to the server then send an
// attention signal to the server to tell it to ignore the request or
// cancel its execution.
if (packetNum > 0) {
// Ideally, we would want to add the following assert here.
// But to add that the variable isEOMSent would have to be made
// volatile as this piece of code would be reached from multiple
// threads. So, not doing it to avoid perf hit. Note that
// isEOMSent would be updated in writePacket everytime an EOM is sent
// assert isEOMSent;
if (logger.isLoggable(Level.FINE))
logger.fine(this + ": sending attention...");
++tdsChannel.numMsgsSent;
startMessage(command, TDS.PKT_CANCEL_REQ);
endMessage();
return true;
}
return false;
}
private void writePacket(int tdsMessageStatus) throws SQLServerException {
final boolean atEOM = (TDS.STATUS_BIT_EOM == (TDS.STATUS_BIT_EOM & tdsMessageStatus));
final boolean isCancelled = ((TDS.PKT_CANCEL_REQ == tdsMessageType)
|| ((tdsMessageStatus & TDS.STATUS_BIT_ATTENTION) == TDS.STATUS_BIT_ATTENTION));
// Before writing each packet to the channel, check if an interrupt has occurred.
if (null != command && (!isCancelled))
command.checkForInterrupt();
writePacketHeader(tdsMessageStatus | sendResetConnection);
sendResetConnection = 0;
flush(atEOM);
// If this is the last packet then flush the remainder of the request
// through the socket. The first flush() call ensured that data currently
// waiting in the socket buffer was sent, flipped the buffers, and started
// sending data from the staging buffer (flipped to be the new socket buffer).
// This flush() call ensures that all remaining data in the socket buffer is sent.
if (atEOM) {
flush(atEOM);
isEOMSent = true;
++tdsChannel.numMsgsSent;
}
// If we just sent the first login request packet and SSL encryption was enabled
// for login only, then disable SSL now.
if (TDS.PKT_LOGON70 == tdsMessageType && 1 == packetNum && TDS.ENCRYPT_OFF == con.getNegotiatedEncryptionLevel()) {
tdsChannel.disableSSL();
}
// Notify the currently associated command (if any) that we have written the last
// of the response packets to the channel.
if (null != command && (!isCancelled) && atEOM)
command.onRequestComplete();
}
private void writePacketHeader(int tdsMessageStatus) {
int tdsMessageLength = ((Buffer)stagingBuffer).position();
++packetNum;
// Write the TDS packet header back at the start of the staging buffer
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_TYPE, tdsMessageType);
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_STATUS, (byte) tdsMessageStatus);
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH, (byte) ((tdsMessageLength >> 8) & 0xFF)); // Note: message length is 16 bits,
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH + 1, (byte) ((tdsMessageLength >> 0) & 0xFF)); // written BIG ENDIAN
stagingBuffer.put(TDS.PACKET_HEADER_SPID, (byte) ((tdsChannel.getSPID() >> 8) & 0xFF)); // Note: SPID is 16 bits,
stagingBuffer.put(TDS.PACKET_HEADER_SPID + 1, (byte) ((tdsChannel.getSPID() >> 0) & 0xFF)); // written BIG ENDIAN
stagingBuffer.put(TDS.PACKET_HEADER_SEQUENCE_NUM, (byte) (packetNum % 256));
stagingBuffer.put(TDS.PACKET_HEADER_WINDOW, (byte) 0); // Window (Reserved/Not used)
// Write the header to the log buffer too if logging.
if (tdsChannel.isLoggingPackets()) {
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_TYPE, tdsMessageType);
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_STATUS, (byte) tdsMessageStatus);
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH, (byte) ((tdsMessageLength >> 8) & 0xFF)); // Note: message length is 16 bits,
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH + 1, (byte) ((tdsMessageLength >> 0) & 0xFF)); // written BIG ENDIAN
logBuffer.put(TDS.PACKET_HEADER_SPID, (byte) ((tdsChannel.getSPID() >> 8) & 0xFF)); // Note: SPID is 16 bits,
logBuffer.put(TDS.PACKET_HEADER_SPID + 1, (byte) ((tdsChannel.getSPID() >> 0) & 0xFF)); // written BIG ENDIAN
logBuffer.put(TDS.PACKET_HEADER_SEQUENCE_NUM, (byte) (packetNum % 256));
logBuffer.put(TDS.PACKET_HEADER_WINDOW, (byte) 0); // Window (Reserved/Not used);
}
}
void flush(boolean atEOM) throws SQLServerException {
// First, flush any data left in the socket buffer.
tdsChannel.write(socketBuffer.array(), ((Buffer)socketBuffer).position(), socketBuffer.remaining());
((Buffer)socketBuffer).position(((Buffer)socketBuffer).limit());
// If there is data in the staging buffer that needs to be written
// to the socket, the socket buffer is now empty, so swap buffers
// and start writing data from the staging buffer.
if (((Buffer)stagingBuffer).position() >= TDS_PACKET_HEADER_SIZE) {
// Swap the packet buffers ...
ByteBuffer swapBuffer = stagingBuffer;
stagingBuffer = socketBuffer;
socketBuffer = swapBuffer;
// ... and prepare to send data from the from the new socket
// buffer (the old staging buffer).
// We need to use flip() rather than rewind() here so that
// the socket buffer's limit is properly set for the last
// packet, which may be shorter than the other packets.
((Buffer)socketBuffer).flip();
((Buffer)stagingBuffer).clear();
// If we are logging TDS packets then log the packet we're about
// to send over the wire now.
if (tdsChannel.isLoggingPackets()) {
tdsChannel.logPacket(logBuffer.array(), 0, ((Buffer) socketBuffer).limit(),
this.toString() + " sending packet (" + ((Buffer) socketBuffer).limit() + " bytes)");
}
// Prepare for the next packet
if (!atEOM)
preparePacket();
// Finally, start sending data from the new socket buffer.
tdsChannel.write(socketBuffer.array(), ((Buffer)socketBuffer).position(), socketBuffer.remaining());
((Buffer)socketBuffer).position( ((Buffer)socketBuffer).limit());
}
}
// Composite write operations
/**
* Write out elements common to all RPC values.
*
* @param sName
* the optional parameter name
* @param bOut
* boolean true if the value that follows is being registered as an ouput parameter
* @param tdsType
* TDS type of the value that follows
*/
void writeRPCNameValType(String sName,
boolean bOut,
TDSType tdsType) throws SQLServerException {
int nNameLen = 0;
if (null != sName)
nNameLen = sName.length() + 1; // The @ prefix is required for the param
writeByte((byte) nNameLen); // param name len
if (nNameLen > 0) {
writeChar('@');
writeString(sName);
}
if (null != cryptoMeta)
writeByte((byte) (bOut ? 1 | TDS.AE_METADATA : 0 | TDS.AE_METADATA)); // status
else
writeByte((byte) (bOut ? 1 : 0)); // status
writeByte(tdsType.byteValue()); // type
}
/**
* Append a boolean value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param booleanValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCBit(String sName,
Boolean booleanValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BITN);
writeByte((byte) 1); // max length of datatype
if (null == booleanValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 1); // length of datatype
writeByte((byte) (booleanValue ? 1 : 0));
}
}
/**
* Append a short value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param shortValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCByte(String sName,
Byte byteValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 1); // max length of datatype
if (null == byteValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 1); // length of datatype
writeByte(byteValue);
}
}
/**
* Append a short value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param shortValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCShort(String sName,
Short shortValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 2); // max length of datatype
if (null == shortValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 2); // length of datatype
writeShort(shortValue);
}
}
/**
* Append an int value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param intValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCInt(String sName,
Integer intValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 4); // max length of datatype
if (null == intValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 4); // length of datatype
writeInt(intValue);
}
}
/**
* Append a long value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param longValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCLong(String sName,
Long longValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 8); // max length of datatype
if (null == longValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 8); // length of datatype
writeLong(longValue);
}
}
/**
* Append a real value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param floatValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCReal(String sName,
Float floatValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.FLOATN);
// Data and length
if (null == floatValue) {
writeByte((byte) 4); // max length
writeByte((byte) 0); // actual length (0 == null)
}
else {
writeByte((byte) 4); // max length
writeByte((byte) 4); // actual length
writeInt(Float.floatToRawIntBits(floatValue));
}
}
void writeRPCSqlVariant(String sName,
SqlVariant sqlVariantValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.SQL_VARIANT);
// Data and length
if (null == sqlVariantValue) {
writeInt(0); // max length
writeInt(0); // actual length
}
}
/**
* Append a double value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param doubleValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCDouble(String sName,
Double doubleValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.FLOATN);
int l = 8;
writeByte((byte) l); // max length of datatype
// Data and length
if (null == doubleValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) l); // len of data bytes
long bits = Double.doubleToLongBits(doubleValue);
long mask = 0xFF;
int nShift = 0;
for (int i = 0; i < 8; i++) {
writeByte((byte) ((bits & mask) >> nShift));
nShift += 8;
mask = mask << 8;
}
}
}
/**
* Append a big decimal in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param bdValue
* the data value
* @param nScale
* the desired scale
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCBigDecimal(String sName,
BigDecimal bdValue,
int nScale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DECIMALN);
writeByte((byte) 0x11); // maximum length
writeByte((byte) SQLServerConnection.maxDecimalPrecision); // precision
byte[] valueBytes = DDC.convertBigDecimalToBytes(bdValue, nScale);
writeBytes(valueBytes, 0, valueBytes.length);
}
/**
* Appends a standard v*max header for RPC parameter transmission.
*
* @param headerLength
* the total length of the PLP data block.
* @param isNull
* true if the value is NULL.
* @param collation
* The SQL collation associated with the value that follows the v*max header. Null for non-textual types.
*/
void writeVMaxHeader(long headerLength,
boolean isNull,
SQLCollation collation) throws SQLServerException {
// Send v*max length indicator 0xFFFF.
writeShort((short) 0xFFFF);
// Send collation if requested.
if (null != collation)
collation.writeCollation(this);
// Handle null here and return, we're done here if it's null.
if (isNull) {
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
}
else if (DataTypes.UNKNOWN_STREAM_LENGTH == headerLength) {
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
// NOTE: Don't send the first chunk length, this will be calculated by caller.
}
else {
// For v*max types with known length, length is <totallength8><chunklength4>
// We're sending same total length as chunk length (as we're sending 1 chunk).
writeLong(headerLength);
}
}
/**
* Utility for internal writeRPCString calls
*/
void writeRPCStringUnicode(String sValue) throws SQLServerException {
writeRPCStringUnicode(null, sValue, false, null);
}
/**
* Writes a string value as Unicode for RPC
*
* @param sName
* the optional parameter name
* @param sValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @param collation
* the collation of the data value
*/
void writeRPCStringUnicode(String sName,
String sValue,
boolean bOut,
SQLCollation collation) throws SQLServerException {
boolean bValueNull = (sValue == null);
int nValueLen = bValueNull ? 0 : (2 * sValue.length());
boolean isShortValue = nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
// Textual RPC requires a collation. If none is provided, as is the case when
// the SSType is non-textual, then use the database collation by default.
if (null == collation)
collation = con.getDatabaseCollation();
// Use PLP encoding on Yukon and later with long values and OUT parameters
boolean usePLP = (!isShortValue || bOut);
if (usePLP) {
writeRPCNameValType(sName, bOut, TDSType.NVARCHAR);
// Handle Yukon v*max type header here.
writeVMaxHeader(nValueLen, // Length
bValueNull, // Is null?
collation);
// Send the data.
if (!bValueNull) {
if (nValueLen > 0) {
writeInt(nValueLen);
writeString(sValue);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else // non-PLP type
{
// Write maximum length of data
if (isShortValue) {
writeRPCNameValType(sName, bOut, TDSType.NVARCHAR);
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
}
else {
writeRPCNameValType(sName, bOut, TDSType.NTEXT);
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
}
collation.writeCollation(this);
// Data and length
if (bValueNull) {
writeShort((short) -1); // actual len
}
else {
// Write actual length of data
if (isShortValue)
writeShort((short) nValueLen);
else
writeInt(nValueLen);
// If length is zero, we're done.
if (0 != nValueLen)
writeString(sValue); // data
}
}
}
void writeTVP(TVP value) throws SQLServerException {
if (!value.isNull()) {
writeByte((byte) 0); // status
}
else {
// Default TVP
writeByte((byte) TDS.TVP_STATUS_DEFAULT); // default TVP
}
writeByte((byte) TDS.TDS_TVP);
/*
* TVP_TYPENAME = DbName OwningSchema TypeName
*/
// Database where TVP type resides
if (null != value.getDbNameTVP()) {
writeByte((byte) value.getDbNameTVP().length());
writeString(value.getDbNameTVP());
}
else
writeByte((byte) 0x00); // empty DB name
// Schema where TVP type resides
if (null != value.getOwningSchemaNameTVP()) {
writeByte((byte) value.getOwningSchemaNameTVP().length());
writeString(value.getOwningSchemaNameTVP());
}
else
writeByte((byte) 0x00); // empty Schema name
// TVP type name
if (null != value.getTVPName()) {
writeByte((byte) value.getTVPName().length());
writeString(value.getTVPName());
}
else
writeByte((byte) 0x00); // empty TVP name
if (!value.isNull()) {
writeTVPColumnMetaData(value);
// optional OrderUnique metadata
writeTvpOrderUnique(value);
}
else {
writeShort((short) TDS.TVP_NULL_TOKEN);
}
// TVP_END_TOKEN
writeByte((byte) 0x00);
try {
writeTVPRows(value);
}
catch (NumberFormatException e) {
throw new SQLServerException(SQLServerException.getErrString("R_TVPInvalidColumnValue"), e);
}
catch (ClassCastException e) {
throw new SQLServerException(SQLServerException.getErrString("R_TVPInvalidColumnValue"), e);
}
}
void writeTVPRows(TVP value) throws SQLServerException {
boolean tdsWritterCached = false;
ByteBuffer cachedTVPHeaders = null;
TDSCommand cachedCommand = null;
boolean cachedRequestComplete = false;
boolean cachedInterruptsEnabled = false;
boolean cachedProcessedResponse = false;
if (!value.isNull()) {
// is used, the tdsWriter of the calling preparedStatement is overwritten by the SQLServerResultSet#next() method when fetching new rows.
// Therefore, we need to send TVP data row by row before fetching new row.
if (TVPType.ResultSet == value.tvpType) {
if ((null != value.sourceResultSet) && (value.sourceResultSet instanceof SQLServerResultSet)) {
SQLServerResultSet sourceResultSet = (SQLServerResultSet) value.sourceResultSet;
SQLServerStatement src_stmt = (SQLServerStatement) sourceResultSet.getStatement();
int resultSetServerCursorId = sourceResultSet.getServerCursorId();
if (con.equals(src_stmt.getConnection()) && 0 != resultSetServerCursorId) {
cachedTVPHeaders = ByteBuffer.allocate(stagingBuffer.capacity()).order(stagingBuffer.order());
cachedTVPHeaders.put(stagingBuffer.array(), 0, ((Buffer)stagingBuffer).position());
cachedCommand = this.command;
cachedRequestComplete = command.getRequestComplete();
cachedInterruptsEnabled = command.getInterruptsEnabled();
cachedProcessedResponse = command.getProcessedResponse();
tdsWritterCached = true;
if (sourceResultSet.isForwardOnly()) {
sourceResultSet.setFetchSize(1);
}
}
}
}
Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata();
Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator;
while (value.next()) {
// restore command and TDS header, which have been overwritten by value.next()
if (tdsWritterCached) {
command = cachedCommand;
((Buffer)stagingBuffer).clear();
((Buffer)logBuffer).clear();
writeBytes(cachedTVPHeaders.array(), 0, ((Buffer)cachedTVPHeaders).position());
}
Object[] rowData = value.getRowData();
// ROW
writeByte((byte) TDS.TVP_ROW);
columnsIterator = columnMetadata.entrySet().iterator();
int currentColumn = 0;
while (columnsIterator.hasNext()) {
Map.Entry<Integer, SQLServerMetaData> columnPair = columnsIterator.next();
// If useServerDefault is set, client MUST NOT emit TvpColumnData for the associated column
if (columnPair.getValue().useServerDefault) {
currentColumn++;
continue;
}
JDBCType jdbcType = JDBCType.of(columnPair.getValue().javaSqlType);
String currentColumnStringValue = null;
Object currentObject = null;
if (null != rowData) {
// if rowData has value for the current column, retrieve it. If not, current column will stay null.
if (rowData.length > currentColumn) {
currentObject = rowData[currentColumn];
if (null != currentObject) {
currentColumnStringValue = String.valueOf(currentObject);
}
}
}
writeInternalTVPRowValues(jdbcType, currentColumnStringValue, currentObject, columnPair, false);
currentColumn++;
}
// send this row, read its response (throw exception in case of errors) and reset command status
if (tdsWritterCached) {
// TVP_END_TOKEN
writeByte((byte) 0x00);
writePacket(TDS.STATUS_BIT_EOM);
TDSReader tdsReader = tdsChannel.getReader(command);
int tokenType = tdsReader.peekTokenType();
if (TDS.TDS_ERR == tokenType) {
StreamError databaseError = new StreamError();
databaseError.setFromTDS(tdsReader);
SQLServerException.makeFromDatabaseError(con, null, databaseError.getMessage(), databaseError, false);
}
command.setInterruptsEnabled(true);
command.setRequestComplete(false);
}
}
}
// reset command status which have been overwritten
if (tdsWritterCached) {
command.setRequestComplete(cachedRequestComplete);
command.setInterruptsEnabled(cachedInterruptsEnabled);
command.setProcessedResponse(cachedProcessedResponse);
}
else {
// TVP_END_TOKEN
writeByte((byte) 0x00);
}
}
private void writeInternalTVPRowValues(JDBCType jdbcType,
String currentColumnStringValue,
Object currentObject,
Map.Entry<Integer, SQLServerMetaData> columnPair,
boolean isSqlVariant) throws SQLServerException {
boolean isShortValue, isNull;
int dataLength;
switch (jdbcType) {
case BIGINT:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
if (isSqlVariant) {
writeTVPSqlVariantHeader(10, TDSType.INT8.byteValue(), (byte) 0);
}
else {
writeByte((byte) 8);
}
writeLong(Long.valueOf(currentColumnStringValue).longValue());
}
break;
case BIT:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
if (isSqlVariant)
writeTVPSqlVariantHeader(3, TDSType.BIT1.byteValue(), (byte) 0);
else
writeByte((byte) 1);
writeByte((byte) (Boolean.valueOf(currentColumnStringValue).booleanValue() ? 1 : 0));
}
break;
case INTEGER:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
if (!isSqlVariant)
writeByte((byte) 4);
else
writeTVPSqlVariantHeader(6, TDSType.INT4.byteValue(), (byte) 0);
writeInt(Integer.valueOf(currentColumnStringValue).intValue());
}
break;
case SMALLINT:
case TINYINT:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
if (isSqlVariant) {
writeTVPSqlVariantHeader(6, TDSType.INT4.byteValue(), (byte) 0);
writeInt(Integer.valueOf(currentColumnStringValue));
}
else {
writeByte((byte) 2); // length of datatype
writeShort(Short.valueOf(currentColumnStringValue).shortValue());
}
}
break;
case DECIMAL:
case NUMERIC:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
if (isSqlVariant) {
writeTVPSqlVariantHeader(21, TDSType.DECIMALN.byteValue(), (byte) 2);
writeByte((byte) 38); // scale (byte)variantType.getScale()
writeByte((byte) 4); // scale (byte)variantType.getScale()
}
else {
writeByte((byte) TDSWriter.BIGDECIMAL_MAX_LENGTH); // maximum length
}
BigDecimal bdValue = new BigDecimal(currentColumnStringValue);
/*
* setScale of all BigDecimal value based on metadata as scale is not sent seperately for individual value. Use the rounding used
* in Server. Say, for BigDecimal("0.1"), if scale in metdadata is 0, then ArithmeticException would be thrown if RoundingMode is
* not set
*/
bdValue = bdValue.setScale(columnPair.getValue().scale, RoundingMode.HALF_UP);
byte[] valueBytes = DDC.convertBigDecimalToBytes(bdValue, bdValue.scale());
// 1-byte for sign and 16-byte for integer
byte[] byteValue = new byte[17];
// removing the precision and scale information from the valueBytes array
System.arraycopy(valueBytes, 2, byteValue, 0, valueBytes.length - 2);
writeBytes(byteValue);
}
break;
case DOUBLE:
if (null == currentColumnStringValue)
writeByte((byte) 0); // len of data bytes
else {
if (isSqlVariant) {
writeTVPSqlVariantHeader(10, TDSType.FLOAT8.byteValue(), (byte) 0);
writeDouble(Double.valueOf(currentColumnStringValue));
break;
}
writeByte((byte) 8); // len of data bytes
long bits = Double.doubleToLongBits(Double.valueOf(currentColumnStringValue).doubleValue());
long mask = 0xFF;
int nShift = 0;
for (int i = 0; i < 8; i++) {
writeByte((byte) ((bits & mask) >> nShift));
nShift += 8;
mask = mask << 8;
}
}
break;
case FLOAT:
case REAL:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
if (isSqlVariant) {
writeTVPSqlVariantHeader(6, TDSType.FLOAT4.byteValue(), (byte) 0);
writeInt(Float.floatToRawIntBits(Float.valueOf(currentColumnStringValue).floatValue()));
}
else {
writeByte((byte) 4);
writeInt(Float.floatToRawIntBits(Float.valueOf(currentColumnStringValue).floatValue()));
}
}
break;
case DATE:
case TIME:
case TIMESTAMP:
case DATETIMEOFFSET:
case DATETIME:
case SMALLDATETIME:
case TIMESTAMP_WITH_TIMEZONE:
case TIME_WITH_TIMEZONE:
case CHAR:
case VARCHAR:
case NCHAR:
case NVARCHAR:
case LONGVARCHAR:
case LONGNVARCHAR:
case SQLXML:
isShortValue = (2L * columnPair.getValue().precision) <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
isNull = (null == currentColumnStringValue);
dataLength = isNull ? 0 : currentColumnStringValue.length() * 2;
if (!isShortValue) {
// check null
if (isNull) {
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
}
else if (isSqlVariant) {
// for now we send as bigger type, but is sendStringParameterAsUnicoe is set to false we can't send nvarchar
// since we are writing as nvarchar we need to write as tdstype.bigvarchar value because if we
// want to supprot varchar(8000) it becomes as nvarchar, 8000*2 therefore we should send as longvarchar,
// but we cannot send more than 8000 cause sql_variant datatype in sql server does not support it.
// then throw exception if user is sending more than that
if (dataLength > 2 * DataTypes.SHORT_VARTYPE_MAX_BYTES) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidStringValue"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
}
int length = currentColumnStringValue.length();
writeTVPSqlVariantHeader(9 + length, TDSType.BIGVARCHAR.byteValue(), (byte) 0x07);
SQLCollation col = con.getDatabaseCollation();
// write collation for sql variant
writeInt(col.getCollationInfo());
writeByte((byte) col.getCollationSortID());
writeShort((short) (length));
writeBytes(currentColumnStringValue.getBytes());
break;
}
else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength)
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
else
// For v*max types with known length, length is <totallength8><chunklength4>
writeLong(dataLength);
if (!isNull) {
if (dataLength > 0) {
writeInt(dataLength);
writeString(currentColumnStringValue);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else {
if (isNull)
writeShort((short) -1); // actual len
else {
if (isSqlVariant) {
// for now we send as bigger type, but is sendStringParameterAsUnicoe is set to false we can't send nvarchar
// check for this
int length = currentColumnStringValue.length() * 2;
writeTVPSqlVariantHeader(9 + length, TDSType.NVARCHAR.byteValue(), (byte) 7);
SQLCollation col = con.getDatabaseCollation();
// write collation for sql variant
writeInt(col.getCollationInfo());
writeByte((byte) col.getCollationSortID());
int stringLength = currentColumnStringValue.length();
byte[] typevarlen = new byte[2];
typevarlen[0] = (byte) (2 * stringLength & 0xFF);
typevarlen[1] = (byte) ((2 * stringLength >> 8) & 0xFF);
writeBytes(typevarlen);
writeString(currentColumnStringValue);
break;
}
else {
writeShort((short) dataLength);
writeString(currentColumnStringValue);
}
}
}
break;
case BINARY:
case VARBINARY:
case LONGVARBINARY:
// Handle conversions as done in other types.
isShortValue = columnPair.getValue().precision <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
isNull = (null == currentObject);
if (currentObject instanceof String)
dataLength = isNull ? 0 : (ParameterUtils.HexToBin(currentObject.toString())).length;
else
dataLength = isNull ? 0 : ((byte[]) currentObject).length;
if (!isShortValue) {
// check null
if (isNull)
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength)
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
else
// For v*max types with known length, length is <totallength8><chunklength4>
writeLong(dataLength);
if (!isNull) {
if (dataLength > 0) {
writeInt(dataLength);
if (currentObject instanceof String)
writeBytes(ParameterUtils.HexToBin(currentObject.toString()));
else
writeBytes((byte[]) currentObject);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else {
if (isNull)
writeShort((short) -1); // actual len
else {
writeShort((short) dataLength);
if (currentObject instanceof String)
writeBytes(ParameterUtils.HexToBin(currentObject.toString()));
else
writeBytes((byte[]) currentObject);
}
}
break;
case SQL_VARIANT:
boolean isShiloh = (8 >= con.getServerMajorVersion());
if (isShiloh) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_SQLVariantSupport"));
throw new SQLServerException(null, form.format(new Object[] {}), null, 0, false);
}
JDBCType internalJDBCType;
JavaType javaType = JavaType.of(currentObject);
internalJDBCType = javaType.getJDBCType(SSType.UNKNOWN, jdbcType);
writeInternalTVPRowValues(internalJDBCType, currentColumnStringValue, currentObject, columnPair, true);
break;
default:
assert false : "Unexpected JDBC type " + jdbcType.toString();
}
}
/**
* writes Header for sql_variant for TVP
* @param length
* @param tdsType
* @param probBytes
* @throws SQLServerException
*/
private void writeTVPSqlVariantHeader(int length,
byte tdsType,
byte probBytes) throws SQLServerException {
writeInt(length);
writeByte(tdsType);
writeByte(probBytes);
}
void writeTVPColumnMetaData(TVP value) throws SQLServerException {
boolean isShortValue;
// TVP_COLMETADATA
writeShort((short) value.getTVPColumnCount());
Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata();
/*
* TypeColumnMetaData = UserType Flags TYPE_INFO ColName ;
*/
for (Entry<Integer, SQLServerMetaData> pair : columnMetadata.entrySet()) {
JDBCType jdbcType = JDBCType.of(pair.getValue().javaSqlType);
boolean useServerDefault = pair.getValue().useServerDefault;
// ULONG ; UserType of column
// The value will be 0x0000 with the exceptions of TIMESTAMP (0x0050) and alias types (greater than 0x00FF).
writeInt(0);
/*
* Flags = fNullable ; Column is nullable - %x01 fCaseSen -- Ignored ; usUpdateable -- Ignored ; fIdentity ; Column is identity column -
* %x10 fComputed ; Column is computed - %x20 usReservedODBC -- Ignored ; fFixedLenCLRType-- Ignored ; fDefault ; Column is default value
* - %x200 usReserved -- Ignored ;
*/
short flags = TDS.FLAG_NULLABLE;
if (useServerDefault) {
flags |= TDS.FLAG_TVP_DEFAULT_COLUMN;
}
writeShort(flags);
// Type info
switch (jdbcType) {
case BIGINT:
writeByte(TDSType.INTN.byteValue());
writeByte((byte) 8); // max length of datatype
break;
case BIT:
writeByte(TDSType.BITN.byteValue());
writeByte((byte) 1); // max length of datatype
break;
case INTEGER:
writeByte(TDSType.INTN.byteValue());
writeByte((byte) 4); // max length of datatype
break;
case SMALLINT:
case TINYINT:
writeByte(TDSType.INTN.byteValue());
writeByte((byte) 2); // max length of datatype
break;
case DECIMAL:
case NUMERIC:
writeByte(TDSType.NUMERICN.byteValue());
writeByte((byte) 0x11); // maximum length
writeByte((byte) pair.getValue().precision);
writeByte((byte) pair.getValue().scale);
break;
case DOUBLE:
writeByte(TDSType.FLOATN.byteValue());
writeByte((byte) 8); // max length of datatype
break;
case FLOAT:
case REAL:
writeByte(TDSType.FLOATN.byteValue());
writeByte((byte) 4); // max length of datatype
break;
case DATE:
case TIME:
case TIMESTAMP:
case DATETIMEOFFSET:
case DATETIME:
case SMALLDATETIME:
case TIMESTAMP_WITH_TIMEZONE:
case TIME_WITH_TIMEZONE:
case CHAR:
case VARCHAR:
case NCHAR:
case NVARCHAR:
case LONGVARCHAR:
case LONGNVARCHAR:
case SQLXML:
writeByte(TDSType.NVARCHAR.byteValue());
isShortValue = (2L * pair.getValue().precision) <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
// Use PLP encoding on Yukon and later with long values
if (!isShortValue) // PLP
{
// Handle Yukon v*max type header here.
writeShort((short) 0xFFFF);
con.getDatabaseCollation().writeCollation(this);
} else // non PLP
{
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
con.getDatabaseCollation().writeCollation(this);
}
break;
case BINARY:
case VARBINARY:
case LONGVARBINARY:
writeByte(TDSType.BIGVARBINARY.byteValue());
isShortValue = pair.getValue().precision <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
// Use PLP encoding on Yukon and later with long values
if (!isShortValue) // PLP
// Handle Yukon v*max type header here.
writeShort((short) 0xFFFF);
else // non PLP
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
break;
case SQL_VARIANT:
writeByte(TDSType.SQL_VARIANT.byteValue());
writeInt(TDS.SQL_VARIANT_LENGTH);// write length of sql variant 8009
break;
default:
assert false : "Unexpected JDBC type " + jdbcType.toString();
}
// Column name - must be null (from TDS - TVP_COLMETADATA)
writeByte((byte) 0x00);
// [TVP_ORDER_UNIQUE]
// [TVP_COLUMN_ORDERING]
}
}
void writeTvpOrderUnique(TVP value) throws SQLServerException {
/*
* TVP_ORDER_UNIQUE = TVP_ORDER_UNIQUE_TOKEN (Count <Count>(ColNum OrderUniqueFlags))
*/
Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata();
Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator = columnMetadata.entrySet().iterator();
LinkedList<TdsOrderUnique> columnList = new LinkedList<>();
while (columnsIterator.hasNext()) {
byte flags = 0;
Map.Entry<Integer, SQLServerMetaData> pair = columnsIterator.next();
SQLServerMetaData metaData = pair.getValue();
if (SQLServerSortOrder.Ascending == metaData.sortOrder)
flags = TDS.TVP_ORDERASC_FLAG;
else if (SQLServerSortOrder.Descending == metaData.sortOrder)
flags = TDS.TVP_ORDERDESC_FLAG;
if (metaData.isUniqueKey)
flags |= TDS.TVP_UNIQUE_FLAG;
// Remember this column if any flags were set
if (0 != flags)
columnList.add(new TdsOrderUnique(pair.getKey(), flags));
}
// Write flagged columns
if (!columnList.isEmpty()) {
writeByte((byte) TDS.TVP_ORDER_UNIQUE_TOKEN);
writeShort((short) columnList.size());
for (TdsOrderUnique column : columnList) {
writeShort((short) (column.columnOrdinal + 1));
writeByte(column.flags);
}
}
}
private class TdsOrderUnique {
int columnOrdinal;
byte flags;
TdsOrderUnique(int ordinal,
byte flags) {
this.columnOrdinal = ordinal;
this.flags = flags;
}
}
void setCryptoMetaData(CryptoMetadata cryptoMetaForBulk) {
this.cryptoMeta = cryptoMetaForBulk;
}
CryptoMetadata getCryptoMetaData() {
return cryptoMeta;
}
void writeEncryptedRPCByteArray(byte bValue[]) throws SQLServerException {
boolean bValueNull = (bValue == null);
long nValueLen = bValueNull ? 0 : bValue.length;
boolean isShortValue = (nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES);
boolean isPLP = (!isShortValue) && (nValueLen <= DataTypes.MAX_VARTYPE_MAX_BYTES);
// Handle Shiloh types here.
if (isShortValue) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
}
else if (isPLP) {
writeShort((short) DataTypes.SQL_USHORTVARMAXLEN);
}
else {
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
}
// Data and length
if (bValueNull) {
writeShort((short) -1); // actual len
}
else {
if (isShortValue) {
writeShort((short) nValueLen); // actual len
}
else if (isPLP) {
writeLong(nValueLen); // actual length
}
else {
writeInt((int) nValueLen); // actual len
}
// If length is zero, we're done.
if (0 != nValueLen) {
if (isPLP) {
writeInt((int) nValueLen);
}
writeBytes(bValue);
}
if (isPLP) {
writeInt(0); // PLP_TERMINATOR, 0x00000000
}
}
}
void writeEncryptedRPCPLP() throws SQLServerException {
writeShort((short) DataTypes.SQL_USHORTVARMAXLEN);
writeLong((long) 0); // actual length
writeInt(0); // PLP_TERMINATOR, 0x00000000
}
void writeCryptoMetaData() throws SQLServerException {
writeByte(cryptoMeta.cipherAlgorithmId);
writeByte(cryptoMeta.encryptionType.getValue());
writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).databaseId);
writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekId);
writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekVersion);
writeBytes(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekMdVersion);
writeByte(cryptoMeta.normalizationRuleVersion);
}
void writeRPCByteArray(String sName,
byte bValue[],
boolean bOut,
JDBCType jdbcType,
SQLCollation collation) throws SQLServerException {
boolean bValueNull = (bValue == null);
int nValueLen = bValueNull ? 0 : bValue.length;
boolean isShortValue = (nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES);
// Use PLP encoding on Yukon and later with long values and OUT parameters
boolean usePLP = (!isShortValue || bOut);
TDSType tdsType;
if (null != cryptoMeta) {
// send encrypted data as BIGVARBINARY
tdsType = (isShortValue || usePLP) ? TDSType.BIGVARBINARY : TDSType.IMAGE;
collation = null;
}
else
switch (jdbcType) {
case BINARY:
case VARBINARY:
case LONGVARBINARY:
case BLOB:
default:
tdsType = (isShortValue || usePLP) ? TDSType.BIGVARBINARY : TDSType.IMAGE;
collation = null;
break;
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case CLOB:
tdsType = (isShortValue || usePLP) ? TDSType.BIGVARCHAR : TDSType.TEXT;
if (null == collation)
collation = con.getDatabaseCollation();
break;
case NCHAR:
case NVARCHAR:
case LONGNVARCHAR:
case NCLOB:
tdsType = (isShortValue || usePLP) ? TDSType.NVARCHAR : TDSType.NTEXT;
if (null == collation)
collation = con.getDatabaseCollation();
break;
}
writeRPCNameValType(sName, bOut, tdsType);
if (usePLP) {
// Handle Yukon v*max type header here.
writeVMaxHeader(nValueLen, bValueNull, collation);
// Send the data.
if (!bValueNull) {
if (nValueLen > 0) {
writeInt(nValueLen);
writeBytes(bValue);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else // non-PLP type
{
// Handle Shiloh types here.
if (isShortValue) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
}
else {
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
}
if (null != collation)
collation.writeCollation(this);
// Data and length
if (bValueNull) {
writeShort((short) -1); // actual len
}
else {
if (isShortValue)
writeShort((short) nValueLen); // actual len
else
writeInt(nValueLen); // actual len
// If length is zero, we're done.
if (0 != nValueLen)
writeBytes(bValue);
}
}
}
/**
* Append a timestamp in RPC transmission format as a SQL Server DATETIME data type
*
* @param sName
* the optional parameter name
* @param cal
* Pure Gregorian calendar containing the timestamp, including its associated time zone
* @param subSecondNanos
* the sub-second nanoseconds (0 - 999,999,999)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*
*/
void writeRPCDateTime(String sName,
GregorianCalendar cal,
int subSecondNanos,
boolean bOut) throws SQLServerException {
assert (subSecondNanos >= 0) && (subSecondNanos < Nanos.PER_SECOND) : "Invalid subNanoSeconds value: " + subSecondNanos;
assert (cal != null) || (subSecondNanos == 0) : "Invalid subNanoSeconds value when calendar is null: " + subSecondNanos;
writeRPCNameValType(sName, bOut, TDSType.DATETIMEN);
writeByte((byte) 8); // max length of datatype
if (null == cal) {
writeByte((byte) 0); // len of data bytes
return;
}
writeByte((byte) 8); // len of data bytes
// We need to extract the Calendar's current date & time in terms
// of the number of days since the SQL Base Date (1/1/1900) plus
// the number of milliseconds since midnight in the current day.
// We cannot rely on any pre-calculated value for the number of
// milliseconds in a day or the number of milliseconds since the
// base date to do this because days with DST changes are shorter
// or longer than "normal" days.
// ASSUMPTION: We assume we are dealing with a GregorianCalendar here.
// If not, we have no basis in which to compare dates. E.g. if we
// are dealing with a Chinese Calendar implementation which does not
// use the same value for Calendar.YEAR as the GregorianCalendar,
// we cannot meaningfully compute a value relative to 1/1/1900.
// First, figure out how many days there have been since the SQL Base Date.
// These are based on SQL Server algorithms
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Next, figure out the number of milliseconds since midnight of the current day.
int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second
1000 * cal.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * cal.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * cal.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (millisSinceMidnight >= 1000 * 60 * 60 * 24 - 1) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
// Last-ditch verification that the value is in the valid range for the
// DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then
// throw an exception now so that statement execution is safely canceled.
// Attempting to put an invalid value on the wire would result in a TDS
// exception, which would close the connection.
// These are based on SQL Server algorithms
if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.DATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
// And put it all on the wire...
// Number of days since the SQL Server Base Date (January 1, 1900)
writeInt(daysSinceSQLBaseDate);
// Milliseconds since midnight (at a resolution of three hundredths of a second)
writeInt((3 * millisSinceMidnight + 5) / 10);
}
void writeRPCTime(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.TIMEN);
writeByte((byte) scale);
if (null == localCalendar) {
writeByte((byte) 0);
return;
}
writeByte((byte) TDS.timeValueLength(scale));
writeScaledTemporal(localCalendar, subSecondNanos, scale, SSType.TIME);
}
void writeRPCDate(String sName,
GregorianCalendar localCalendar,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DATEN);
if (null == localCalendar) {
writeByte((byte) 0);
return;
}
writeByte((byte) TDS.DAYS_INTO_CE_LENGTH);
writeScaledTemporal(localCalendar, 0, // subsecond nanos (none for a date value)
0, // scale (dates are not scaled)
SSType.DATE);
}
void writeEncryptedRPCTime(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
if (con.getSendTimeAsDatetime()) {
throw new SQLServerException(SQLServerException.getErrString("R_sendTimeAsDateTimeForAE"), null);
}
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == localCalendar)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, subSecondNanos, scale, SSType.TIME, (short) 0));
writeByte(TDSType.TIMEN.byteValue());
writeByte((byte) scale);
writeCryptoMetaData();
}
void writeEncryptedRPCDate(String sName,
GregorianCalendar localCalendar,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == localCalendar)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, 0, // subsecond nanos (none for a date value)
0, // scale (dates are not scaled)
SSType.DATE, (short) 0));
writeByte(TDSType.DATEN.byteValue());
writeCryptoMetaData();
}
void writeEncryptedRPCDateTime(String sName,
GregorianCalendar cal,
int subSecondNanos,
boolean bOut,
JDBCType jdbcType) throws SQLServerException {
assert (subSecondNanos >= 0) && (subSecondNanos < Nanos.PER_SECOND) : "Invalid subNanoSeconds value: " + subSecondNanos;
assert (cal != null) || (subSecondNanos == 0) : "Invalid subNanoSeconds value when calendar is null: " + subSecondNanos;
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == cal)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(getEncryptedDateTimeAsBytes(cal, subSecondNanos, jdbcType));
if (JDBCType.SMALLDATETIME == jdbcType) {
writeByte(TDSType.DATETIMEN.byteValue());
writeByte((byte) 4);
}
else {
writeByte(TDSType.DATETIMEN.byteValue());
writeByte((byte) 8);
}
writeCryptoMetaData();
}
// getEncryptedDateTimeAsBytes is called if jdbcType/ssType is SMALLDATETIME or DATETIME
byte[] getEncryptedDateTimeAsBytes(GregorianCalendar cal,
int subSecondNanos,
JDBCType jdbcType) throws SQLServerException {
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Next, figure out the number of milliseconds since midnight of the current day.
int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second
1000 * cal.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * cal.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * cal.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (millisSinceMidnight >= 1000 * 60 * 60 * 24 - 1) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
if (JDBCType.SMALLDATETIME == jdbcType) {
int secondsSinceMidnight = (millisSinceMidnight / 1000);
int minutesSinceMidnight = (secondsSinceMidnight / 60);
// Values that are 29.998 seconds or less are rounded down to the nearest minute
minutesSinceMidnight = ((secondsSinceMidnight % 60) > 29.998) ? minutesSinceMidnight + 1 : minutesSinceMidnight;
// minutesSinceMidnight for (23:59:30)
int maxMinutesSinceMidnight_SmallDateTime = 1440;
// Verification for smalldatetime to be within valid range of (1900.01.01) to (2079.06.06)
// smalldatetime for unencrypted does not allow insertion of 2079.06.06 23:59:59 and it is rounded up
// to 2079.06.07 00:00:00, therefore, we are checking minutesSinceMidnight for that condition. If it's not within valid range, then
// throw an exception now so that statement execution is safely canceled.
// 157 is the calculated day of year from 06-06 , 1440 is minutesince midnight for (23:59:30)
if ((daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1900, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate > DDC.daysSinceBaseDate(2079, 157, TDS.BASE_YEAR_1900))
|| (daysSinceSQLBaseDate == DDC.daysSinceBaseDate(2079, 157, TDS.BASE_YEAR_1900)
&& minutesSinceMidnight >= maxMinutesSinceMidnight_SmallDateTime)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.SMALLDATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
ByteBuffer days = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
days.putShort((short) daysSinceSQLBaseDate);
ByteBuffer seconds = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
seconds.putShort((short) minutesSinceMidnight);
byte[] value = new byte[4];
System.arraycopy(days.array(), 0, value, 0, 2);
System.arraycopy(seconds.array(), 0, value, 2, 2);
return SQLServerSecurityUtility.encryptWithKey(value, cryptoMeta, con);
}
else if (JDBCType.DATETIME == jdbcType) {
// Last-ditch verification that the value is in the valid range for the
// DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then
// throw an exception now so that statement execution is safely canceled.
// Attempting to put an invalid value on the wire would result in a TDS
// exception, which would close the connection.
// These are based on SQL Server algorithms
// And put it all on the wire...
if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.DATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
// Number of days since the SQL Server Base Date (January 1, 1900)
ByteBuffer days = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
days.putInt(daysSinceSQLBaseDate);
ByteBuffer seconds = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
seconds.putInt((3 * millisSinceMidnight + 5) / 10);
byte[] value = new byte[8];
System.arraycopy(days.array(), 0, value, 0, 4);
System.arraycopy(seconds.array(), 0, value, 4, 4);
return SQLServerSecurityUtility.encryptWithKey(value, cryptoMeta, con);
}
assert false : "Unexpected JDBCType type " + jdbcType;
return null;
}
void writeEncryptedRPCDateTime2(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == localCalendar)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, subSecondNanos, scale, SSType.DATETIME2, (short) 0));
writeByte(TDSType.DATETIME2N.byteValue());
writeByte((byte) (scale));
writeCryptoMetaData();
}
void writeEncryptedRPCDateTimeOffset(String sName,
GregorianCalendar utcCalendar,
int minutesOffset,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == utcCalendar)
writeEncryptedRPCByteArray(null);
else {
assert 0 == utcCalendar.get(Calendar.ZONE_OFFSET);
writeEncryptedRPCByteArray(
writeEncryptedScaledTemporal(utcCalendar, subSecondNanos, scale, SSType.DATETIMEOFFSET, (short) minutesOffset));
}
writeByte(TDSType.DATETIMEOFFSETN.byteValue());
writeByte((byte) (scale));
writeCryptoMetaData();
}
void writeRPCDateTime2(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DATETIME2N);
writeByte((byte) scale);
if (null == localCalendar) {
writeByte((byte) 0);
return;
}
writeByte((byte) TDS.datetime2ValueLength(scale));
writeScaledTemporal(localCalendar, subSecondNanos, scale, SSType.DATETIME2);
}
void writeRPCDateTimeOffset(String sName,
GregorianCalendar utcCalendar,
int minutesOffset,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DATETIMEOFFSETN);
writeByte((byte) scale);
if (null == utcCalendar) {
writeByte((byte) 0);
return;
}
assert 0 == utcCalendar.get(Calendar.ZONE_OFFSET);
writeByte((byte) TDS.datetimeoffsetValueLength(scale));
writeScaledTemporal(utcCalendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
/**
* Returns subSecondNanos rounded to the maximum precision supported. The maximum fractional scale is MAX_FRACTIONAL_SECONDS_SCALE(7). Eg1: if you
* pass 456,790,123 the function would return 456,790,100 Eg2: if you pass 456,790,150 the function would return 456,790,200 Eg3: if you pass
* 999,999,951 the function would return 1,000,000,000 This is done to ensure that we have consistent rounding behaviour in setters and getters.
* Bug #507919
*/
private int getRoundedSubSecondNanos(int subSecondNanos) {
int roundedNanos = ((subSecondNanos + (Nanos.PER_MAX_SCALE_INTERVAL / 2)) / Nanos.PER_MAX_SCALE_INTERVAL) * Nanos.PER_MAX_SCALE_INTERVAL;
return roundedNanos;
}
/**
* Writes to the TDS channel a temporal value as an instance instance of one of the scaled temporal SQL types: DATE, TIME, DATETIME2, or
* DATETIMEOFFSET.
*
* @param cal
* Calendar representing the value to write, except for any sub-second nanoseconds
* @param subSecondNanos
* the sub-second nanoseconds (0 - 999,999,999)
* @param scale
* the scale (in digits: 0 - 7) to use for the sub-second nanos component
* @param ssType
* the SQL Server data type (DATE, TIME, DATETIME2, or DATETIMEOFFSET)
*
* @throws SQLServerException
* if an I/O error occurs or if the value is not in the valid range
*/
private void writeScaledTemporal(GregorianCalendar cal,
int subSecondNanos,
int scale,
SSType ssType) throws SQLServerException {
assert con.isKatmaiOrLater();
assert SSType.DATE == ssType || SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: "
+ ssType;
// First, for types with a time component, write the scaled nanos since midnight
if (SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
assert subSecondNanos >= 0;
assert subSecondNanos < Nanos.PER_SECOND;
assert scale >= 0;
assert scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
int secondsSinceMidnight = cal.get(Calendar.SECOND) + 60 * cal.get(Calendar.MINUTE) + 60 * 60 * cal.get(Calendar.HOUR_OF_DAY);
// Scale nanos since midnight to the desired scale, rounding the value as necessary
long divisor = Nanos.PER_MAX_SCALE_INTERVAL * (long) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE - scale);
// The scaledNanos variable represents the fractional seconds of the value at the scale
// indicated by the scale variable. So, for example, scaledNanos = 3 means 300 nanoseconds
// at scale TDS.MAX_FRACTIONAL_SECONDS_SCALE, but 3000 nanoseconds at
// TDS.MAX_FRACTIONAL_SECONDS_SCALE - 1
long scaledNanos = ((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos) + divisor / 2) / divisor;
// SQL Server rounding behavior indicates that it always rounds up unless
// we are at the max value of the type(NOT every day), in which case it truncates.
// If rounding nanos to the specified scale rolls the value to the next day ...
if (Nanos.PER_DAY / divisor == scaledNanos) {
// If the type is time, always truncate
if (SSType.TIME == ssType) {
--scaledNanos;
}
// If the type is datetime2 or datetimeoffset, truncate only if its the max value supported
else {
assert SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType;
// ... then bump the date, provided that the resulting date is still within
// the valid date range.
// Extreme edge case (literally, the VERY edge...):
// If nanos overflow rolls the date value out of range (that is, we have a value
// a few nanoseconds later than 9999-12-31 23:59:59) then truncate the nanos
// instead of rolling.
// This case is very likely never hit by "real world" applications, but exists
// here as a security measure to ensure that such values don't result in a
// connection-closing TDS exception.
cal.add(Calendar.SECOND, 1);
if (cal.get(Calendar.YEAR) <= 9999) {
scaledNanos = 0;
}
else {
cal.add(Calendar.SECOND, -1);
--scaledNanos;
}
}
}
// Encode the scaled nanos to TDS
int encodedLength = TDS.nanosSinceMidnightLength(scale);
byte[] encodedBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
writeBytes(encodedBytes);
}
// Second, for types with a date component, write the days into the Common Era
if (SSType.DATE == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
// Computation of the number of days into the Common Era assumes that
// the DAY_OF_YEAR field reflects a pure Gregorian calendar - one that
// uses Gregorian leap year rules across the entire range of dates.
// For the DAY_OF_YEAR field to accurately reflect pure Gregorian behavior,
// we need to use a pure Gregorian calendar for dates that are Julian dates
// under a standard Gregorian calendar and for (Gregorian) dates later than
// the cutover date in the cutover year.
if (cal.getTimeInMillis() < GregorianChange.STANDARD_CHANGE_DATE.getTime()
|| cal.getActualMaximum(Calendar.DAY_OF_YEAR) < TDS.DAYS_PER_YEAR) {
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
// Set the cutover as early as possible (pure Gregorian behavior)
cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE);
// Initialize the date field by field (preserving the "wall calendar" value)
cal.set(year, month, date);
}
int daysIntoCE = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), 1);
// Last-ditch verification that the value is in the valid range for the
// DATE/DATETIME2/DATETIMEOFFSET TDS data type (1/1/0001 to 12/31/9999).
// If it's not, then throw an exception now so that statement execution
// is safely canceled. Attempting to put an invalid value on the wire
// would result in a TDS exception, which would close the connection.
if (daysIntoCE < 0 || daysIntoCE >= DDC.daysSinceBaseDate(10000, 1, 1)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {ssType};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
byte encodedBytes[] = new byte[3];
encodedBytes[0] = (byte) ((daysIntoCE >> 0) & 0xFF);
encodedBytes[1] = (byte) ((daysIntoCE >> 8) & 0xFF);
encodedBytes[2] = (byte) ((daysIntoCE >> 16) & 0xFF);
writeBytes(encodedBytes);
}
}
/**
* Writes to the TDS channel a temporal value as an instance instance of one of the scaled temporal SQL types: DATE, TIME, DATETIME2, or
* DATETIMEOFFSET.
*
* @param cal
* Calendar representing the value to write, except for any sub-second nanoseconds
* @param subSecondNanos
* the sub-second nanoseconds (0 - 999,999,999)
* @param scale
* the scale (in digits: 0 - 7) to use for the sub-second nanos component
* @param ssType
* the SQL Server data type (DATE, TIME, DATETIME2, or DATETIMEOFFSET)
* @param minutesOffset
* the offset value for DATETIMEOFFSET
* @throws SQLServerException
* if an I/O error occurs or if the value is not in the valid range
*/
byte[] writeEncryptedScaledTemporal(GregorianCalendar cal,
int subSecondNanos,
int scale,
SSType ssType,
short minutesOffset) throws SQLServerException {
assert con.isKatmaiOrLater();
assert SSType.DATE == ssType || SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: "
+ ssType;
// store the time and minutesOffset portion of DATETIME2 and DATETIMEOFFSET to be used with date portion
byte encodedBytesForEncryption[] = null;
int secondsSinceMidnight = 0;
long divisor = 0;
long scaledNanos = 0;
// First, for types with a time component, write the scaled nanos since midnight
if (SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
assert subSecondNanos >= 0;
assert subSecondNanos < Nanos.PER_SECOND;
assert scale >= 0;
assert scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
secondsSinceMidnight = cal.get(Calendar.SECOND) + 60 * cal.get(Calendar.MINUTE) + 60 * 60 * cal.get(Calendar.HOUR_OF_DAY);
// Scale nanos since midnight to the desired scale, rounding the value as necessary
divisor = Nanos.PER_MAX_SCALE_INTERVAL * (long) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE - scale);
// The scaledNanos variable represents the fractional seconds of the value at the scale
// indicated by the scale variable. So, for example, scaledNanos = 3 means 300 nanoseconds
// at scale TDS.MAX_FRACTIONAL_SECONDS_SCALE, but 3000 nanoseconds at
// TDS.MAX_FRACTIONAL_SECONDS_SCALE - 1
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos) + divisor / 2) / divisor)
* divisor / 100;
// for encrypted time value, SQL server cannot do rounding or casting,
// So, driver needs to cast it before encryption.
if (SSType.TIME == ssType && 864000000000L <= scaledNanos) {
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor) * divisor / 100;
}
// SQL Server rounding behavior indicates that it always rounds up unless
// we are at the max value of the type(NOT every day), in which case it truncates.
// If rounding nanos to the specified scale rolls the value to the next day ...
if (Nanos.PER_DAY / divisor == scaledNanos) {
// If the type is time, always truncate
if (SSType.TIME == ssType) {
--scaledNanos;
}
// If the type is datetime2 or datetimeoffset, truncate only if its the max value supported
else {
assert SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType;
// ... then bump the date, provided that the resulting date is still within
// the valid date range.
// Extreme edge case (literally, the VERY edge...):
// If nanos overflow rolls the date value out of range (that is, we have a value
// a few nanoseconds later than 9999-12-31 23:59:59) then truncate the nanos
// instead of rolling.
// This case is very likely never hit by "real world" applications, but exists
// here as a security measure to ensure that such values don't result in a
// connection-closing TDS exception.
cal.add(Calendar.SECOND, 1);
if (cal.get(Calendar.YEAR) <= 9999) {
scaledNanos = 0;
}
else {
cal.add(Calendar.SECOND, -1);
--scaledNanos;
}
}
}
// Encode the scaled nanos to TDS
int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE);
byte[] encodedBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
if (SSType.TIME == ssType) {
byte[] cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytes, cryptoMeta, con);
return cipherText;
}
else if (SSType.DATETIME2 == ssType) {
// for DATETIME2 sends both date and time part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 3];
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, 0, encodedBytes.length);
}
else if (SSType.DATETIMEOFFSET == ssType) {
// for DATETIMEOFFSET sends date, time and offset part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 5];
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, 0, encodedBytes.length);
}
}
// Second, for types with a date component, write the days into the Common Era
if (SSType.DATE == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
// Computation of the number of days into the Common Era assumes that
// the DAY_OF_YEAR field reflects a pure Gregorian calendar - one that
// uses Gregorian leap year rules across the entire range of dates.
// For the DAY_OF_YEAR field to accurately reflect pure Gregorian behavior,
// we need to use a pure Gregorian calendar for dates that are Julian dates
// under a standard Gregorian calendar and for (Gregorian) dates later than
// the cutover date in the cutover year.
if (cal.getTimeInMillis() < GregorianChange.STANDARD_CHANGE_DATE.getTime()
|| cal.getActualMaximum(Calendar.DAY_OF_YEAR) < TDS.DAYS_PER_YEAR) {
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
// Set the cutover as early as possible (pure Gregorian behavior)
cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE);
// Initialize the date field by field (preserving the "wall calendar" value)
cal.set(year, month, date);
}
int daysIntoCE = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), 1);
// Last-ditch verification that the value is in the valid range for the
// DATE/DATETIME2/DATETIMEOFFSET TDS data type (1/1/0001 to 12/31/9999).
// If it's not, then throw an exception now so that statement execution
// is safely canceled. Attempting to put an invalid value on the wire
// would result in a TDS exception, which would close the connection.
if (daysIntoCE < 0 || daysIntoCE >= DDC.daysSinceBaseDate(10000, 1, 1)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {ssType};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
byte encodedBytes[] = new byte[3];
encodedBytes[0] = (byte) ((daysIntoCE >> 0) & 0xFF);
encodedBytes[1] = (byte) ((daysIntoCE >> 8) & 0xFF);
encodedBytes[2] = (byte) ((daysIntoCE >> 16) & 0xFF);
byte[] cipherText;
if (SSType.DATE == ssType) {
cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytes, cryptoMeta, con);
}
else if (SSType.DATETIME2 == ssType) {
// for Max value, does not round up, do casting instead.
if (3652058 == daysIntoCE) { // 9999-12-31
if (864000000000L == scaledNanos) { // 24:00:00 in nanoseconds
// does not round up
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor)
* divisor / 100;
int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE);
byte[] encodedNanoBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
// for DATETIME2 sends both date and time part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 3];
System.arraycopy(encodedNanoBytes, 0, encodedBytesForEncryption, 0, encodedNanoBytes.length);
}
}
// Copy the 3 byte date value
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, (encodedBytesForEncryption.length - 3), 3);
cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytesForEncryption, cryptoMeta, con);
}
else {
// for Max value, does not round up, do casting instead.
if (3652058 == daysIntoCE) { // 9999-12-31
if (864000000000L == scaledNanos) { // 24:00:00 in nanoseconds
// does not round up
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor)
* divisor / 100;
int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE);
byte[] encodedNanoBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
// for DATETIMEOFFSET sends date, time and offset part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 5];
System.arraycopy(encodedNanoBytes, 0, encodedBytesForEncryption, 0, encodedNanoBytes.length);
}
}
// Copy the 3 byte date value
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, (encodedBytesForEncryption.length - 5), 3);
// Copy the 2 byte minutesOffset value
System.arraycopy(ByteBuffer.allocate(Short.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putShort(minutesOffset).array(), 0,
encodedBytesForEncryption, (encodedBytesForEncryption.length - 2), 2);
cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytesForEncryption, cryptoMeta, con);
}
return cipherText;
}
// Invalid type ssType. This condition should never happen.
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unknownSSType"));
Object[] msgArgs = {ssType};
SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), null, true);
return null;
}
private byte[] scaledNanosToEncodedBytes(long scaledNanos,
int encodedLength) {
byte encodedBytes[] = new byte[encodedLength];
for (int i = 0; i < encodedLength; i++)
encodedBytes[i] = (byte) ((scaledNanos >> (8 * i)) & 0xFF);
return encodedBytes;
}
/**
* Append the data in a stream in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param stream
* is the stream
* @param streamLength
* length of the stream (may be unknown)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @param jdbcType
* The JDBC type used to determine whether the value is textual or non-textual.
* @param collation
* The SQL collation associated with the value. Null for non-textual SQL Server types.
* @throws SQLServerException
*/
void writeRPCInputStream(String sName,
InputStream stream,
long streamLength,
boolean bOut,
JDBCType jdbcType,
SQLCollation collation) throws SQLServerException {
assert null != stream;
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength >= 0;
// Send long values and values with unknown length
// using PLP chunking on Yukon and later.
boolean usePLP = (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength > DataTypes.SHORT_VARTYPE_MAX_BYTES);
if (usePLP) {
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength <= DataTypes.MAX_VARTYPE_MAX_BYTES;
writeRPCNameValType(sName, bOut, jdbcType.isTextual() ? TDSType.BIGVARCHAR : TDSType.BIGVARBINARY);
// Handle Yukon v*max type header here.
writeVMaxHeader(streamLength, false, jdbcType.isTextual() ? collation : null);
}
// Send non-PLP in all other cases
else {
// If the length of the InputStream is unknown then we need to buffer the entire stream
// in memory so that we can determine its length and send that length to the server
// before the stream data itself.
if (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength) {
// Create ByteArrayOutputStream with initial buffer size of 8K to handle typical
// binary field sizes more efficiently. Note we can grow beyond 8000 bytes.
ByteArrayOutputStream baos = new ByteArrayOutputStream(8000);
streamLength = 0L;
// Since Shiloh is limited to 64K TDS packets, that's a good upper bound on the maximum
// length of InputStream we should try to handle before throwing an exception.
long maxStreamLength = 65535L * con.getTDSPacketSize();
try {
byte buff[] = new byte[8000];
int bytesRead;
while (streamLength < maxStreamLength && -1 != (bytesRead = stream.read(buff, 0, buff.length))) {
baos.write(buff);
streamLength += bytesRead;
}
}
catch (IOException e) {
throw new SQLServerException(e.getMessage(), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET, e);
}
if (streamLength >= maxStreamLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidLength"));
Object[] msgArgs = {streamLength};
SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), "", true);
}
assert streamLength <= Integer.MAX_VALUE;
stream = new ByteArrayInputStream(baos.toByteArray(), 0, (int) streamLength);
}
assert 0 <= streamLength && streamLength <= DataTypes.IMAGE_TEXT_MAX_BYTES;
boolean useVarType = streamLength <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
writeRPCNameValType(sName, bOut,
jdbcType.isTextual() ? (useVarType ? TDSType.BIGVARCHAR : TDSType.TEXT) : (useVarType ? TDSType.BIGVARBINARY : TDSType.IMAGE));
// Write maximum length, optional collation, and actual length
if (useVarType) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
if (jdbcType.isTextual())
collation.writeCollation(this);
writeShort((short) streamLength);
}
else {
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
if (jdbcType.isTextual())
collation.writeCollation(this);
writeInt((int) streamLength);
}
}
// Write the data
writeStream(stream, streamLength, usePLP);
}
/**
* Append the XML data in a stream in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param stream
* is the stream
* @param streamLength
* length of the stream (may be unknown)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @throws SQLServerException
*/
void writeRPCXML(String sName,
InputStream stream,
long streamLength,
boolean bOut) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength >= 0;
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength <= DataTypes.MAX_VARTYPE_MAX_BYTES;
writeRPCNameValType(sName, bOut, TDSType.XML);
writeByte((byte) 0); // No schema
// Handle null here and return, we're done here if it's null.
if (null == stream) {
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
}
else if (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength) {
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
// NOTE: Don't send the first chunk length, this will be calculated by caller.
}
else {
// For v*max types with known length, length is <totallength8><chunklength4>
// We're sending same total length as chunk length (as we're sending 1 chunk).
writeLong(streamLength);
}
if (null != stream)
// Write the data
writeStream(stream, streamLength, true);
}
/**
* Append the data in a character reader in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param re
* the reader
* @param reLength
* the reader data length (in characters)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @param collation
* The SQL collation associated with the value. Null for non-textual SQL Server types.
* @throws SQLServerException
*/
void writeRPCReaderUnicode(String sName,
Reader re,
long reLength,
boolean bOut,
SQLCollation collation) throws SQLServerException {
assert null != re;
assert DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength >= 0;
// Textual RPC requires a collation. If none is provided, as is the case when
// the SSType is non-textual, then use the database collation by default.
if (null == collation)
collation = con.getDatabaseCollation();
// Send long values and values with unknown length
// using PLP chunking on Yukon and later.
boolean usePLP = (DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength > DataTypes.SHORT_VARTYPE_MAX_CHARS);
if (usePLP) {
assert DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength <= DataTypes.MAX_VARTYPE_MAX_CHARS;
writeRPCNameValType(sName, bOut, TDSType.NVARCHAR);
// Handle Yukon v*max type header here.
writeVMaxHeader((DataTypes.UNKNOWN_STREAM_LENGTH == reLength) ? DataTypes.UNKNOWN_STREAM_LENGTH : 2 * reLength, // Length (in bytes)
false, collation);
}
// Send non-PLP in all other cases
else {
// Length must be known if we're not sending PLP-chunked data. Yukon is handled above.
// For Shiloh, this is enforced in DTV by converting the Reader to some other length-
// prefixed value in the setter.
assert 0 <= reLength && reLength <= DataTypes.NTEXT_MAX_CHARS;
// For non-PLP types, use the long TEXT type rather than the short VARCHAR
// type if the stream is too long to fit in the latter or if we don't know the length up
// front so we have to assume that it might be too long.
boolean useVarType = reLength <= DataTypes.SHORT_VARTYPE_MAX_CHARS;
writeRPCNameValType(sName, bOut, useVarType ? TDSType.NVARCHAR : TDSType.NTEXT);
// Write maximum length, collation, and actual length of the data
if (useVarType) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
collation.writeCollation(this);
writeShort((short) (2 * reLength));
}
else {
writeInt(DataTypes.NTEXT_MAX_CHARS);
collation.writeCollation(this);
writeInt((int) (2 * reLength));
}
}
// Write the data
writeReader(re, reLength, usePLP);
}
}
/**
* TDSPacket provides a mechanism for chaining TDS response packets together in a singly-linked list.
*
* Having both the link and the data in the same class allows TDSReader marks (see below) to automatically hold onto exactly as much response data as
* they need, and no more. Java reference semantics ensure that a mark holds onto its referenced packet and subsequent packets (through next
* references). When all marked references to a packet go away, the packet, and any linked unmarked packets, can be reclaimed by GC.
*/
final class TDSPacket {
final byte[] header = new byte[TDS.PACKET_HEADER_SIZE];
final byte[] payload;
int payloadLength;
volatile TDSPacket next;
final public String toString() {
return "TDSPacket(SPID:" + Util.readUnsignedShortBigEndian(header, TDS.PACKET_HEADER_SPID) + " Seq:" + header[TDS.PACKET_HEADER_SEQUENCE_NUM]
+ ")";
}
TDSPacket(int size) {
payload = new byte[size];
payloadLength = 0;
next = null;
}
final boolean isEOM() {
return TDS.STATUS_BIT_EOM == (header[TDS.PACKET_HEADER_MESSAGE_STATUS] & TDS.STATUS_BIT_EOM);
}
};
/**
* TDSReaderMark encapsulates a fixed position in the response data stream.
*
* Response data is quantized into a linked chain of packets. A mark refers to a specific location in a specific packet and relies on Java's reference
* semantics to automatically keep all subsequent packets accessible until the mark is destroyed.
*/
final class TDSReaderMark {
final TDSPacket packet;
final int payloadOffset;
TDSReaderMark(TDSPacket packet,
int payloadOffset) {
this.packet = packet;
this.payloadOffset = payloadOffset;
}
}
/**
* TDSReader encapsulates the TDS response data stream.
*
* Bytes are read from SQL Server into a FIFO of packets. Reader methods traverse the packets to access the data.
*/
final class TDSReader {
private final static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Reader");
final private String traceID;
private TimeoutTimer tcpKeepAliveTimeoutTimer;
final public String toString() {
return traceID;
}
private final TDSChannel tdsChannel;
private final SQLServerConnection con;
private final TDSCommand command;
final TDSCommand getCommand() {
assert null != command;
return command;
}
final SQLServerConnection getConnection() {
return con;
}
private TDSPacket currentPacket = new TDSPacket(0);
private TDSPacket lastPacket = currentPacket;
private int payloadOffset = 0;
private int packetNum = 0;
private boolean isStreaming = true;
private boolean useColumnEncryption = false;
private boolean serverSupportsColumnEncryption = false;
private final byte valueBytes[] = new byte[256];
private static final AtomicInteger lastReaderID = new AtomicInteger(0);
private static int nextReaderID() {
return lastReaderID.incrementAndGet();
}
TDSReader(TDSChannel tdsChannel,
SQLServerConnection con,
TDSCommand command) {
this.tdsChannel = tdsChannel;
this.con = con;
this.command = command; // may be null
if(null != command) {
//if cancelQueryTimeout is set, we should wait for the total amount of queryTimeout + cancelQueryTimeout to terminate the connection.
this.tcpKeepAliveTimeoutTimer = (command.getCancelQueryTimeoutSeconds() > 0 && command.getQueryTimeoutSeconds() > 0 ) ?
(new TimeoutTimer(command.getCancelQueryTimeoutSeconds() + command.getQueryTimeoutSeconds(), null, con)) : null;
}
// if the logging level is not detailed than fine or more we will not have proper readerids.
if (logger.isLoggable(Level.FINE))
traceID = "TDSReader@" + nextReaderID() + " (" + con.toString() + ")";
else
traceID = con.toString();
if (con.isColumnEncryptionSettingEnabled()) {
useColumnEncryption = true;
}
serverSupportsColumnEncryption = con.getServerSupportsColumnEncryption();
}
final boolean isColumnEncryptionSettingEnabled() {
return useColumnEncryption;
}
final boolean getServerSupportsColumnEncryption() {
return serverSupportsColumnEncryption;
}
final void throwInvalidTDS() throws SQLServerException {
if (logger.isLoggable(Level.SEVERE))
logger.severe(toString() + " got unexpected value in TDS response at offset:" + payloadOffset);
con.throwInvalidTDS();
}
final void throwInvalidTDSToken(String tokenName) throws SQLServerException {
if (logger.isLoggable(Level.SEVERE))
logger.severe(toString() + " got unexpected value in TDS response at offset:" + payloadOffset);
con.throwInvalidTDSToken(tokenName);
}
/**
* Ensures that payload data is available to be read, automatically advancing to (and possibly reading) the next packet.
*
* @return true if additional data is available to be read false if no more data is available
*/
private boolean ensurePayload() throws SQLServerException {
if (payloadOffset == currentPacket.payloadLength)
if (!nextPacket())
return false;
assert payloadOffset < currentPacket.payloadLength;
return true;
}
/**
* Advance (and possibly read) the next packet.
*
* @return true if additional data is available to be read false if no more data is available
*/
private boolean nextPacket() throws SQLServerException {
assert null != currentPacket;
// Shouldn't call this function unless we're at the end of the current packet...
TDSPacket consumedPacket = currentPacket;
assert payloadOffset == consumedPacket.payloadLength;
// If no buffered packets are left then maybe we can read one...
// This action must be synchronized against against another thread calling
// readAllPackets() to read in ALL of the remaining packets of the current response.
if (null == consumedPacket.next) {
readPacket();
if (null == consumedPacket.next)
return false;
}
// Advance to that packet. If we are streaming through the
// response, then unlink the current packet from the next
// before moving to allow the packet to be reclaimed.
TDSPacket nextPacket = consumedPacket.next;
if (isStreaming) {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Moving to next packet -- unlinking consumed packet");
consumedPacket.next = null;
}
currentPacket = nextPacket;
payloadOffset = 0;
return true;
}
/**
* Reads the next packet of the TDS channel.
*
* This method is synchronized to guard against simultaneously reading packets from one thread that is processing the response and another thread
* that is trying to buffer it with TDSCommand.detach().
*/
synchronized final boolean readPacket() throws SQLServerException {
if (null != command && !command.readingResponse())
return false;
// Number of packets in should always be less than number of packets out.
// If the server has been notified for an interrupt, it may be less by
// more than one packet.
assert tdsChannel.numMsgsRcvd < tdsChannel.numMsgsSent : "numMsgsRcvd:" + tdsChannel.numMsgsRcvd + " should be less than numMsgsSent:"
+ tdsChannel.numMsgsSent;
TDSPacket newPacket = new TDSPacket(con.getTDSPacketSize());
if (null != tcpKeepAliveTimeoutTimer) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest(this.toString() + ": starting timer...");
}
tcpKeepAliveTimeoutTimer.start();
}
// First, read the packet header.
for (int headerBytesRead = 0; headerBytesRead < TDS.PACKET_HEADER_SIZE;) {
int bytesRead = tdsChannel.read(newPacket.header, headerBytesRead, TDS.PACKET_HEADER_SIZE - headerBytesRead);
if (bytesRead < 0) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Premature EOS in response. packetNum:" + packetNum + " headerBytesRead:" + headerBytesRead);
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, ((0 == packetNum && 0 == headerBytesRead)
? SQLServerException.getErrString("R_noServerResponse") : SQLServerException.getErrString("R_truncatedServerResponse")));
}
headerBytesRead += bytesRead;
}
// if execution was subject to timeout then stop timing
if (null != tcpKeepAliveTimeoutTimer) {
if (logger.isLoggable(Level.FINEST)) {
logger.finest(this.toString() + ":stopping timer...");
}
tcpKeepAliveTimeoutTimer.stop();
}
// Header size is a 2 byte unsigned short integer in big-endian order.
int packetLength = Util.readUnsignedShortBigEndian(newPacket.header, TDS.PACKET_HEADER_MESSAGE_LENGTH);
// Make header size is properly bounded and compute length of the packet payload.
if (packetLength < TDS.PACKET_HEADER_SIZE || packetLength > con.getTDSPacketSize()) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning(
toString() + " TDS header contained invalid packet length:" + packetLength + "; packet size:" + con.getTDSPacketSize());
}
throwInvalidTDS();
}
newPacket.payloadLength = packetLength - TDS.PACKET_HEADER_SIZE;
// Just grab the SPID for logging (another big-endian unsigned short).
tdsChannel.setSPID(Util.readUnsignedShortBigEndian(newPacket.header, TDS.PACKET_HEADER_SPID));
// Packet header looks good enough.
// When logging, copy the packet header to the log buffer.
byte[] logBuffer = null;
if (tdsChannel.isLoggingPackets()) {
logBuffer = new byte[packetLength];
System.arraycopy(newPacket.header, 0, logBuffer, 0, TDS.PACKET_HEADER_SIZE);
}
// Now for the payload...
for (int payloadBytesRead = 0; payloadBytesRead < newPacket.payloadLength;) {
int bytesRead = tdsChannel.read(newPacket.payload, payloadBytesRead, newPacket.payloadLength - payloadBytesRead);
if (bytesRead < 0)
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, SQLServerException.getErrString("R_truncatedServerResponse"));
payloadBytesRead += bytesRead;
}
++packetNum;
lastPacket.next = newPacket;
lastPacket = newPacket;
// When logging, append the payload to the log buffer and write out the whole thing.
if (tdsChannel.isLoggingPackets()) {
System.arraycopy(newPacket.payload, 0, logBuffer, TDS.PACKET_HEADER_SIZE, newPacket.payloadLength);
tdsChannel.logPacket(logBuffer, 0, packetLength,
this.toString() + " received Packet:" + packetNum + " (" + newPacket.payloadLength + " bytes)");
}
// If end of message, then bump the count of messages received and disable
// interrupts. If an interrupt happened prior to disabling, then expect
// to read the attention ack packet as well.
if (newPacket.isEOM()) {
++tdsChannel.numMsgsRcvd;
// Notify the command (if any) that we've reached the end of the response.
if (null != command)
command.onResponseEOM();
}
return true;
}
final TDSReaderMark mark() {
TDSReaderMark mark = new TDSReaderMark(currentPacket, payloadOffset);
isStreaming = false;
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Buffering from: " + mark.toString());
return mark;
}
final void reset(TDSReaderMark mark) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Resetting to: " + mark.toString());
currentPacket = mark.packet;
payloadOffset = mark.payloadOffset;
}
final void stream() {
isStreaming = true;
}
/**
* Returns the number of bytes that can be read (or skipped over) from this TDSReader without blocking by the next caller of a method for this
* TDSReader.
*
* @return the actual number of bytes available.
*/
final int available() {
// The number of bytes that can be read without blocking is just the number
// of bytes that are currently buffered. That is the number of bytes left
// in the current packet plus the number of bytes in the remaining packets.
int available = currentPacket.payloadLength - payloadOffset;
for (TDSPacket packet = currentPacket.next; null != packet; packet = packet.next)
available += packet.payloadLength;
return available;
}
/**
*
* @return number of bytes available in the current packet
*/
final int availableCurrentPacket() {
/*
* The number of bytes that can be read from the current chunk, without including the next chunk that is buffered. This is so the driver can
* confirm if the next chunk sent is new packet or just continuation
*/
int available = currentPacket.payloadLength - payloadOffset;
return available;
}
final int peekTokenType() throws SQLServerException {
// Check whether we're at EOF
if (!ensurePayload())
return -1;
// Peek at the current byte (don't increment payloadOffset!)
return currentPacket.payload[payloadOffset] & 0xFF;
}
final short peekStatusFlag() throws SQLServerException {
// skip the current packet(i.e, TDS packet type) and peek into the status flag (USHORT)
if (payloadOffset + 3 <= currentPacket.payloadLength) {
short value = Util.readShort(currentPacket.payload, payloadOffset + 1);
return value;
}
return 0;
}
final int readUnsignedByte() throws SQLServerException {
// Ensure that we have a packet to read from.
if (!ensurePayload())
throwInvalidTDS();
return currentPacket.payload[payloadOffset++] & 0xFF;
}
final short readShort() throws SQLServerException {
if (payloadOffset + 2 <= currentPacket.payloadLength) {
short value = Util.readShort(currentPacket.payload, payloadOffset);
payloadOffset += 2;
return value;
}
return Util.readShort(readWrappedBytes(2), 0);
}
final int readUnsignedShort() throws SQLServerException {
if (payloadOffset + 2 <= currentPacket.payloadLength) {
int value = Util.readUnsignedShort(currentPacket.payload, payloadOffset);
payloadOffset += 2;
return value;
}
return Util.readUnsignedShort(readWrappedBytes(2), 0);
}
final String readUnicodeString(int length) throws SQLServerException {
int byteLength = 2 * length;
byte bytes[] = new byte[byteLength];
readBytes(bytes, 0, byteLength);
return Util.readUnicodeString(bytes, 0, byteLength, con);
}
final char readChar() throws SQLServerException {
return (char) readShort();
}
final int readInt() throws SQLServerException {
if (payloadOffset + 4 <= currentPacket.payloadLength) {
int value = Util.readInt(currentPacket.payload, payloadOffset);
payloadOffset += 4;
return value;
}
return Util.readInt(readWrappedBytes(4), 0);
}
final int readIntBigEndian() throws SQLServerException {
if (payloadOffset + 4 <= currentPacket.payloadLength) {
int value = Util.readIntBigEndian(currentPacket.payload, payloadOffset);
payloadOffset += 4;
return value;
}
return Util.readIntBigEndian(readWrappedBytes(4), 0);
}
final long readUnsignedInt() throws SQLServerException {
return readInt() & 0xFFFFFFFFL;
}
final long readLong() throws SQLServerException {
if (payloadOffset + 8 <= currentPacket.payloadLength) {
long value = Util.readLong(currentPacket.payload, payloadOffset);
payloadOffset += 8;
return value;
}
return Util.readLong(readWrappedBytes(8), 0);
}
final void readBytes(byte[] value,
int valueOffset,
int valueLength) throws SQLServerException {
for (int bytesRead = 0; bytesRead < valueLength;) {
// Ensure that we have a packet to read from.
if (!ensurePayload())
throwInvalidTDS();
// Figure out how many bytes to copy from the current packet
// (the lesser of the remaining value bytes and the bytes left in the packet).
int bytesToCopy = valueLength - bytesRead;
if (bytesToCopy > currentPacket.payloadLength - payloadOffset)
bytesToCopy = currentPacket.payloadLength - payloadOffset;
// Copy some bytes from the current packet to the destination value.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Reading " + bytesToCopy + " bytes from offset " + payloadOffset);
System.arraycopy(currentPacket.payload, payloadOffset, value, valueOffset + bytesRead, bytesToCopy);
bytesRead += bytesToCopy;
payloadOffset += bytesToCopy;
}
}
final byte[] readWrappedBytes(int valueLength) throws SQLServerException {
assert valueLength <= valueBytes.length;
readBytes(valueBytes, 0, valueLength);
return valueBytes;
}
final Object readDecimal(int valueLength,
TypeInfo typeInfo,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
if (valueLength > valueBytes.length) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning(toString() + " Invalid value length:" + valueLength);
}
throwInvalidTDS();
}
readBytes(valueBytes, 0, valueLength);
return DDC.convertBigDecimalToObject(Util.readBigDecimal(valueBytes, valueLength, typeInfo.getScale()), jdbcType, streamType);
}
final Object readMoney(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
BigInteger bi;
switch (valueLength) {
case 8: // money
{
int intBitsHi = readInt();
int intBitsLo = readInt();
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[8];
Util.writeIntBigEndian(intBitsHi, value, 0);
Util.writeIntBigEndian(intBitsLo, value, 4);
return value;
}
bi = BigInteger.valueOf(((long) intBitsHi << 32) | (intBitsLo & 0xFFFFFFFFL));
break;
}
case 4: // smallmoney
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[4];
Util.writeIntBigEndian(readInt(), value, 0);
return value;
}
bi = BigInteger.valueOf(readInt());
break;
default:
throwInvalidTDS();
return null;
}
return DDC.convertBigDecimalToObject(new BigDecimal(bi, 4), jdbcType, streamType);
}
final Object readReal(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
if (4 != valueLength)
throwInvalidTDS();
return DDC.convertFloatToObject(Float.intBitsToFloat(readInt()), jdbcType, streamType);
}
final Object readFloat(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
if (8 != valueLength)
throwInvalidTDS();
return DDC.convertDoubleToObject(Double.longBitsToDouble(readLong()), jdbcType, streamType);
}
final Object readDateTime(int valueLength,
Calendar appTimeZoneCalendar,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
// Build and return the right kind of temporal object.
int daysSinceSQLBaseDate;
int ticksSinceMidnight;
int msecSinceMidnight;
switch (valueLength) {
case 8:
// SQL datetime is 4 bytes for days since SQL Base Date
// (January 1, 1900 00:00:00 GMT) and 4 bytes for
// the number of three hundredths (1/300) of a second
// since midnight.
daysSinceSQLBaseDate = readInt();
ticksSinceMidnight = readInt();
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[8];
Util.writeIntBigEndian(daysSinceSQLBaseDate, value, 0);
Util.writeIntBigEndian(ticksSinceMidnight, value, 4);
return value;
}
msecSinceMidnight = (ticksSinceMidnight * 10 + 1) / 3; // Convert to msec (1 tick = 1 300th of a sec = 3 msec)
break;
case 4:
// SQL smalldatetime has less precision. It stores 2 bytes
// for the days since SQL Base Date and 2 bytes for minutes
// after midnight.
daysSinceSQLBaseDate = readUnsignedShort();
ticksSinceMidnight = readUnsignedShort();
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[4];
Util.writeShortBigEndian((short) daysSinceSQLBaseDate, value, 0);
Util.writeShortBigEndian((short) ticksSinceMidnight, value, 2);
return value;
}
msecSinceMidnight = ticksSinceMidnight * 60 * 1000; // Convert to msec (1 tick = 1 min = 60,000 msec)
break;
default:
throwInvalidTDS();
return null;
}
// Convert the DATETIME/SMALLDATETIME value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME, appTimeZoneCalendar, daysSinceSQLBaseDate, msecSinceMidnight, 0); // scale
// (ignored
// for
// fixed-scale
// DATETIME/SMALLDATETIME
// types)
}
final Object readDate(int valueLength,
Calendar appTimeZoneCalendar,
JDBCType jdbcType) throws SQLServerException {
if (TDS.DAYS_INTO_CE_LENGTH != valueLength)
throwInvalidTDS();
// Initialize the date fields to their appropriate values.
int localDaysIntoCE = readDaysIntoCE();
// Convert the DATE value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATE, appTimeZoneCalendar, localDaysIntoCE, 0, // midnight local to app time zone
0); // scale (ignored for DATE)
}
final Object readTime(int valueLength,
TypeInfo typeInfo,
Calendar appTimeZoneCalendar,
JDBCType jdbcType) throws SQLServerException {
if (TDS.timeValueLength(typeInfo.getScale()) != valueLength)
throwInvalidTDS();
// Read the value from the server
long localNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale());
// Convert the TIME value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.TIME, appTimeZoneCalendar, 0, localNanosSinceMidnight, typeInfo.getScale());
}
final Object readDateTime2(int valueLength,
TypeInfo typeInfo,
Calendar appTimeZoneCalendar,
JDBCType jdbcType) throws SQLServerException {
if (TDS.datetime2ValueLength(typeInfo.getScale()) != valueLength)
throwInvalidTDS();
// Read the value's constituent components
long localNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale());
int localDaysIntoCE = readDaysIntoCE();
// Convert the DATETIME2 value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME2, appTimeZoneCalendar, localDaysIntoCE, localNanosSinceMidnight,
typeInfo.getScale());
}
final Object readDateTimeOffset(int valueLength,
TypeInfo typeInfo,
JDBCType jdbcType) throws SQLServerException {
if (TDS.datetimeoffsetValueLength(typeInfo.getScale()) != valueLength)
throwInvalidTDS();
// The nanos since midnight and days into Common Era parts of DATETIMEOFFSET values
// are in UTC. Use the minutes offset part to convert to local.
long utcNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale());
int utcDaysIntoCE = readDaysIntoCE();
int localMinutesOffset = readShort();
// Convert the DATETIMEOFFSET value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIMEOFFSET,
new GregorianCalendar(new SimpleTimeZone(localMinutesOffset * 60 * 1000, ""), Locale.US), utcDaysIntoCE, utcNanosSinceMidnight,
typeInfo.getScale());
}
private int readDaysIntoCE() throws SQLServerException {
byte value[] = new byte[TDS.DAYS_INTO_CE_LENGTH];
readBytes(value, 0, value.length);
int daysIntoCE = 0;
for (int i = 0; i < value.length; i++)
daysIntoCE |= ((value[i] & 0xFF) << (8 * i));
// Theoretically should never encounter a value that is outside of the valid date range
if (daysIntoCE < 0)
throwInvalidTDS();
return daysIntoCE;
}
// Scale multipliers used to convert variable-scaled temporal values to a fixed 100ns scale.
// Using this array is measurably faster than using Math.pow(10, ...)
private final static int[] SCALED_MULTIPLIERS = {10000000, 1000000, 100000, 10000, 1000, 100, 10, 1};
private long readNanosSinceMidnight(int scale) throws SQLServerException {
assert 0 <= scale && scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
byte value[] = new byte[TDS.nanosSinceMidnightLength(scale)];
readBytes(value, 0, value.length);
long hundredNanosSinceMidnight = 0;
for (int i = 0; i < value.length; i++)
hundredNanosSinceMidnight |= (value[i] & 0xFFL) << (8 * i);
hundredNanosSinceMidnight *= SCALED_MULTIPLIERS[scale];
if (!(0 <= hundredNanosSinceMidnight && hundredNanosSinceMidnight < Nanos.PER_DAY / 100))
throwInvalidTDS();
return 100 * hundredNanosSinceMidnight;
}
final static String guidTemplate = "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN";
final Object readGUID(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
// GUIDs must be exactly 16 bytes
if (16 != valueLength)
throwInvalidTDS();
// Read in the GUID's binary value
byte guid[] = new byte[16];
readBytes(guid, 0, 16);
switch (jdbcType) {
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case GUID: {
StringBuilder sb = new StringBuilder(guidTemplate.length());
for (int i = 0; i < 4; i++) {
sb.append(Util.hexChars[(guid[3 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[3 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[5 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[5 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[7 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[7 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[8 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[8 + i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 6; i++) {
sb.append(Util.hexChars[(guid[10 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[10 + i] & 0x0F]);
}
try {
return DDC.convertStringToObject(sb.toString(), Encoding.UNICODE.charset(), jdbcType, streamType);
}
catch (UnsupportedEncodingException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
throw new SQLServerException(form.format(new Object[] {"UNIQUEIDENTIFIER", jdbcType}), null, 0, e);
}
}
default: {
if (StreamType.BINARY == streamType || StreamType.ASCII == streamType)
return new ByteArrayInputStream(guid);
return guid;
}
}
}
/**
* Reads a multi-part table name from TDS and returns it as an array of Strings.
*/
final SQLIdentifier readSQLIdentifier() throws SQLServerException {
// Multi-part names should have between 1 and 4 parts
int numParts = readUnsignedByte();
if (!(1 <= numParts && numParts <= 4))
throwInvalidTDS();
// Each part is a length-prefixed Unicode string
String[] nameParts = new String[numParts];
for (int i = 0; i < numParts; i++)
nameParts[i] = readUnicodeString(readUnsignedShort());
// Build the identifier from the name parts
SQLIdentifier identifier = new SQLIdentifier();
identifier.setObjectName(nameParts[numParts - 1]);
if (numParts >= 2)
identifier.setSchemaName(nameParts[numParts - 2]);
if (numParts >= 3)
identifier.setDatabaseName(nameParts[numParts - 3]);
if (4 == numParts)
identifier.setServerName(nameParts[numParts - 4]);
return identifier;
}
final SQLCollation readCollation() throws SQLServerException {
SQLCollation collation = null;
try {
collation = new SQLCollation(this);
}
catch (UnsupportedEncodingException e) {
con.terminate(SQLServerException.DRIVER_ERROR_INVALID_TDS, e.getMessage(), e);
// not reached
}
return collation;
}
final void skip(int bytesToSkip) throws SQLServerException {
assert bytesToSkip >= 0;
while (bytesToSkip > 0) {
// Ensure that we have a packet to read from.
if (!ensurePayload())
throwInvalidTDS();
int bytesSkipped = bytesToSkip;
if (bytesSkipped > currentPacket.payloadLength - payloadOffset)
bytesSkipped = currentPacket.payloadLength - payloadOffset;
bytesToSkip -= bytesSkipped;
payloadOffset += bytesSkipped;
}
}
final void TryProcessFeatureExtAck(boolean featureExtAckReceived) throws SQLServerException {
// in case of redirection, do not check if TDS_FEATURE_EXTENSION_ACK is received or not.
if (null != this.con.getRoutingInfo()) {
return;
}
if (isColumnEncryptionSettingEnabled() && !featureExtAckReceived)
throw new SQLServerException(this, SQLServerException.getErrString("R_AE_NotSupportedByServer"), null, 0, false);
}
}
/**
* Timer for use with Commands that support a timeout.
*
* Once started, the timer runs for the prescribed number of seconds unless stopped. If the timer runs out, it interrupts its associated Command with
* a reason like "timed out".
*/
final class TimeoutTimer implements Runnable {
private static final String threadGroupName = "mssql-jdbc-TimeoutTimer";
private final int timeoutSeconds;
private final TDSCommand command;
private volatile Future<?> task;
private final SQLServerConnection con;
private static final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
private final AtomicReference<ThreadGroup> tgr = new AtomicReference<>();
private final AtomicInteger threadNumber = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r)
{
ThreadGroup tg = tgr.get();
if (tg == null || tg.isDestroyed())
{
tg = new ThreadGroup(threadGroupName);
tgr.set(tg);
}
Thread t = new Thread(tg, r, tg.getName() + "-" + threadNumber.incrementAndGet());
t.setDaemon(true);
return t;
}
});
private volatile boolean canceled = false;
TimeoutTimer(int timeoutSeconds,
TDSCommand command,
SQLServerConnection con) {
assert timeoutSeconds > 0;
assert null != command;
this.timeoutSeconds = timeoutSeconds;
this.command = command;
this.con = con;
}
final void start() {
task = executor.submit(this);
}
final void stop() {
task.cancel(true);
canceled = true;
}
public void run() {
int secondsRemaining = timeoutSeconds;
try {
// Poll every second while time is left on the timer.
// Return if/when the timer is canceled.
do {
if (canceled)
return;
Thread.sleep(1000);
}
while (--secondsRemaining > 0);
}
catch (InterruptedException e) {
// re-interrupt the current thread, in order to restore the thread's interrupt status.
Thread.currentThread().interrupt();
return;
}
// If the timer wasn't canceled before it ran out of
// time then interrupt the registered command.
try {
// If TCP Connection to server is silently dropped, exceeding the query timeout on the same connection does not throw SQLTimeoutException
// The application hangs instead until SocketTimeoutException is thrown. In this case, we must manually terminate the connection.
if (null == command && null != con) {
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, SQLServerException.getErrString("R_connectionIsClosed"));
}
else {
// If the timer wasn't canceled before it ran out of
// time then interrupt the registered command.
command.interrupt(SQLServerException.getErrString("R_queryTimedOut"));
}
}
catch (SQLServerException e) {
// Unfortunately, there's nothing we can do if we
// fail to time out the request. There is no way
// to report back what happened.
assert null != command;
command.log(Level.FINE, "Command could not be timed out. Reason: " + e.getMessage());
}
}
}
/**
* TDSCommand encapsulates an interruptable TDS conversation.
*
* A conversation may consist of one or more TDS request and response messages. A command may be interrupted at any point, from any thread, and for
* any reason. Acknowledgement and handling of an interrupt is fully encapsulated by this class.
*
* Commands may be created with an optional timeout (in seconds). Timeouts are implemented as a form of interrupt, where the interrupt event occurs
* when the timeout period expires. Currently, only the time to receive the response from the channel counts against the timeout period.
*/
abstract class TDSCommand {
abstract boolean doExecute() throws SQLServerException;
final static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Command");
private final String logContext;
final String getLogContext() {
return logContext;
}
private String traceID;
final public String toString() {
if (traceID == null)
traceID = "TDSCommand@" + Integer.toHexString(hashCode()) + " (" + logContext + ")";
return traceID;
}
final void log(Level level,
String message) {
logger.log(level, toString() + ": " + message);
}
// Optional timer that is set if the command was created with a non-zero timeout period.
// When the timer expires, the command is interrupted.
private final TimeoutTimer timeoutTimer;
// TDS channel accessors
// These are set/reset at command execution time.
// Volatile ensures visibility to execution thread and interrupt thread
private volatile TDSWriter tdsWriter;
private volatile TDSReader tdsReader;
protected TDSWriter getTDSWriter(){
return tdsWriter;
}
// Lock to ensure atomicity when manipulating more than one of the following
// shared interrupt state variables below.
private final Object interruptLock = new Object();
// Flag set when this command starts execution, indicating that it is
// ready to respond to interrupts; and cleared when its last response packet is
// received, indicating that it is no longer able to respond to interrupts.
// If the command is interrupted after interrupts have been disabled, then the
// interrupt is ignored.
private volatile boolean interruptsEnabled = false;
protected boolean getInterruptsEnabled() {
return interruptsEnabled;
}
protected void setInterruptsEnabled(boolean interruptsEnabled) {
synchronized (interruptLock) {
this.interruptsEnabled = interruptsEnabled;
}
}
// Flag set to indicate that an interrupt has happened.
private volatile boolean wasInterrupted = false;
private boolean wasInterrupted() {
return wasInterrupted;
}
// The reason for the interrupt.
private volatile String interruptReason = null;
// Flag set when this command's request to the server is complete.
// If a command is interrupted before its request is complete, it is the executing
// thread's responsibility to send the attention signal to the server if necessary.
// After the request is complete, the interrupting thread must send the attention signal.
private volatile boolean requestComplete;
protected boolean getRequestComplete() {
return requestComplete;
}
protected void setRequestComplete(boolean requestComplete) {
synchronized (interruptLock) {
this.requestComplete = requestComplete;
}
}
// Flag set when an attention signal has been sent to the server, indicating that a
// TDS packet containing the attention ack message is to be expected in the response.
// This flag is cleared after the attention ack message has been received and processed.
private volatile boolean attentionPending = false;
boolean attentionPending() {
return attentionPending;
}
// Flag set when this command's response has been processed. Until this flag is set,
// there may be unprocessed information left in the response, such as transaction
// ENVCHANGE notifications.
private volatile boolean processedResponse;
protected boolean getProcessedResponse() {
return processedResponse;
}
protected void setProcessedResponse(boolean processedResponse) {
synchronized (interruptLock) {
this.processedResponse = processedResponse;
}
}
// Flag set when this command's response is ready to be read from the server and cleared
// after its response has been received, but not necessarily processed, up to and including
// any attention ack. The command's response is read either on demand as it is processed,
// or by detaching.
private volatile boolean readingResponse;
private int queryTimeoutSeconds;
private int cancelQueryTimeoutSeconds;
protected int getQueryTimeoutSeconds() {
return this.queryTimeoutSeconds;
}
protected int getCancelQueryTimeoutSeconds() {
return this.cancelQueryTimeoutSeconds;
}
final boolean readingResponse() {
return readingResponse;
}
/**
* Creates this command with an optional timeout.
*
* @param logContext
* the string describing the context for this command.
* @param timeoutSeconds
* (optional) the time before which the command must complete before it is interrupted. A value of 0 means no timeout.
*/
TDSCommand(String logContext,
int queryTimeoutSeconds, int cancelQueryTimeoutSeconds) {
this.logContext = logContext;
this.queryTimeoutSeconds = queryTimeoutSeconds;
this.cancelQueryTimeoutSeconds = cancelQueryTimeoutSeconds;
this.timeoutTimer = (queryTimeoutSeconds > 0) ? (new TimeoutTimer(queryTimeoutSeconds, this, null)) : null;
}
/**
* Executes this command.
*
* @param tdsWriter
* @param tdsReader
* @throws SQLServerException
* on any error executing the command, including cancel or timeout.
*/
boolean execute(TDSWriter tdsWriter,
TDSReader tdsReader) throws SQLServerException {
this.tdsWriter = tdsWriter;
this.tdsReader = tdsReader;
assert null != tdsReader;
try {
return doExecute(); // Derived classes implement the execution details
}
catch (SQLServerException e) {
try {
// If command execution threw an exception for any reason before the request
// was complete then interrupt the command (it may already be interrupted)
// and close it out to ensure that any response to the error/interrupt
// is processed.
// no point in trying to cancel on a closed connection.
if (!requestComplete && !tdsReader.getConnection().isClosed()) {
interrupt(e.getMessage());
onRequestComplete();
close();
}
}
catch (SQLServerException interruptException) {
if (logger.isLoggable(Level.FINE))
logger.fine(this.toString() + ": Ignoring error in sending attention: " + interruptException.getMessage());
}
// throw the original exception even if trying to interrupt fails even in the case
// of trying to send a cancel to the server.
throw e;
}
}
/**
* Provides sane default response handling.
*
* This default implementation just consumes everything in the response message.
*/
void processResponse(TDSReader tdsReader) throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Processing response");
try {
TDSParser.parse(tdsReader, getLogContext());
}
catch (SQLServerException e) {
if (SQLServerException.DRIVER_ERROR_FROM_DATABASE != e.getDriverErrorCode())
throw e;
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Ignoring error from database: " + e.getMessage());
}
}
/**
* Clears this command from the TDS channel so that another command can execute.
*
* This method does not process the response. It just buffers it in memory, including any attention ack that may be present.
*/
final void detach() throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": detaching...");
// Read any remaining response packets from the server.
// This operation may be timed out or cancelled from another thread.
while (tdsReader.readPacket())
;
// Postcondition: the entire response has been read
assert !readingResponse;
}
final void close() {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": closing...");
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": processing response...");
while (!processedResponse) {
try {
processResponse(tdsReader);
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": close ignoring error processing response: " + e.getMessage());
if (tdsReader.getConnection().isSessionUnAvailable()) {
processedResponse = true;
attentionPending = false;
}
}
}
if (attentionPending) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": processing attention ack...");
try {
TDSParser.parse(tdsReader, "attention ack");
}
catch (SQLServerException e) {
if (tdsReader.getConnection().isSessionUnAvailable()) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": giving up on attention ack after connection closed by exception: " + e);
attentionPending = false;
}
else {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": ignored exception: " + e);
}
}
// If the parser returns to us without processing the expected attention ack,
// then assume that no attention ack is forthcoming from the server and
// terminate the connection to prevent any other command from executing.
if (attentionPending) {
if (logger.isLoggable(Level.SEVERE)) {
logger.severe(this.toString() + ": expected attn ack missing or not processed; terminating connection...");
}
try {
tdsReader.throwInvalidTDS();
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": ignored expected invalid TDS exception: " + e);
assert tdsReader.getConnection().isSessionUnAvailable();
attentionPending = false;
}
}
}
// Postcondition:
// Response has been processed and there is no attention pending -- the command is closed.
// Of course the connection may be closed too, but the command is done regardless...
assert processedResponse && !attentionPending;
}
/**
* Interrupts execution of this command, typically from another thread.
*
* Only the first interrupt has any effect. Subsequent interrupts are ignored. Interrupts are also ignored until enabled. If interrupting the
* command requires an attention signal to be sent to the server, then this method sends that signal if the command's request is already complete.
*
* Signalling mechanism is "fire and forget". It is up to either the execution thread or, possibly, a detaching thread, to ensure that any pending
* attention ack later will be received and processed.
*
* @param reason
* the reason for the interrupt, typically cancel or timeout.
* @throws SQLServerException
* if interrupting fails for some reason. This call does not throw the reason for the interrupt.
*/
void interrupt(String reason) throws SQLServerException {
// Multiple, possibly simultaneous, interrupts may occur.
// Only the first one should be recognized and acted upon.
synchronized (interruptLock) {
if (interruptsEnabled && !wasInterrupted()) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": Raising interrupt for reason:" + reason);
wasInterrupted = true;
interruptReason = reason;
if (requestComplete)
attentionPending = tdsWriter.sendAttention();
}
}
}
private boolean interruptChecked = false;
/**
* Checks once whether an interrupt has occurred, and, if it has, throws an exception indicating that fact.
*
* Any calls after the first to check for interrupts are no-ops. This method is called periodically from this command's execution thread to notify
* the app when an interrupt has happened.
*
* It should only be called from places where consistent behavior can be ensured after the exception is thrown. For example, it should not be
* called at arbitrary times while processing the response, as doing so could leave the response token stream in an inconsistent state. Currently,
* response processing only checks for interrupts after every result or OUT parameter.
*
* Request processing checks for interrupts before writing each packet.
*
* @throws SQLServerException
* if this command was interrupted, throws the reason for the interrupt.
*/
final void checkForInterrupt() throws SQLServerException {
// Throw an exception with the interrupt reason if this command was interrupted.
// Note that the interrupt reason may be null. Checking whether the
// command was interrupted does not require the interrupt lock since only one
// of the shared state variables is being manipulated; interruptChecked is not
// shared with the interrupt thread.
if (wasInterrupted() && !interruptChecked) {
interruptChecked = true;
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": throwing interrupt exception, reason: " + interruptReason);
throw new SQLServerException(interruptReason, SQLState.STATEMENT_CANCELED, DriverError.NOT_SET, null);
}
}
/**
* Notifies this command when no more request packets are to be sent to the server.
*
* After the last packet has been sent, the only way to interrupt the request is to send an attention signal from the interrupt() method.
*
* Note that this method is called when the request completes normally (last packet sent with EOM bit) or when it completes after being
* interrupted (0 or more packets sent with no EOM bit).
*/
final void onRequestComplete() throws SQLServerException {
synchronized (interruptLock) {
assert !requestComplete;
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": request complete");
requestComplete = true;
// If this command was interrupted before its request was complete then
// we need to send the attention signal if necessary. Note that if no
// attention signal is sent (i.e. no packets were sent to the server before
// the interrupt happened), then don't expect an attention ack or any
// other response.
if (!interruptsEnabled) {
assert !attentionPending;
assert !processedResponse;
assert !readingResponse;
processedResponse = true;
}
else if (wasInterrupted()) {
if (tdsWriter.isEOMSent()) {
attentionPending = tdsWriter.sendAttention();
readingResponse = attentionPending;
}
else {
assert !attentionPending;
readingResponse = tdsWriter.ignoreMessage();
}
processedResponse = !readingResponse;
}
else {
assert !attentionPending;
assert !processedResponse;
readingResponse = true;
}
}
}
/**
* Notifies this command when the last packet of the response has been read.
*
* When the last packet is read, interrupts are disabled. If an interrupt occurred prior to disabling that caused an attention signal to be sent
* to the server, then an extra packet containing the attention ack is read.
*
* This ensures that on return from this method, the TDS channel is clear of all response packets for this command.
*
* Note that this method is called for the attention ack message itself as well, so we need to be sure not to expect more than one attention
* ack...
*/
final void onResponseEOM() throws SQLServerException {
boolean readAttentionAck = false;
// Atomically disable interrupts and check for a previous interrupt requiring
// an attention ack to be read.
synchronized (interruptLock) {
if (interruptsEnabled) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": disabling interrupts");
// Determine whether we still need to read the attention ack packet.
// When a command is interrupted, Yukon (and later) always sends a response
// containing at least a DONE(ERROR) token before it sends the attention ack,
// even if the command's request was not complete.
readAttentionAck = attentionPending;
interruptsEnabled = false;
}
}
// If an attention packet needs to be read then read it. This should
// be done outside of the interrupt lock to avoid unnecessarily blocking
// interrupting threads. Note that it is remotely possible that the call
// to readPacket won't actually read anything if the attention ack was
// already read by TDSCommand.detach(), in which case this method could
// be called from multiple threads, leading to a benign followup process
// to clear the readingResponse flag.
if (readAttentionAck)
tdsReader.readPacket();
readingResponse = false;
}
/**
* Notifies this command when the end of its response token stream has been reached.
*
* After this call, we are guaranteed that tokens in the response have been processed.
*/
final void onTokenEOF() {
processedResponse = true;
}
/**
* Notifies this command when the attention ack (a DONE token with a special flag) has been processed.
*
* After this call, the attention ack should no longer be expected.
*/
final void onAttentionAck() {
assert attentionPending;
attentionPending = false;
}
/**
* Starts sending this command's TDS request to the server.
*
* @param tdsMessageType
* the type of the TDS message (RPC, QUERY, etc.)
* @return the TDS writer used to write the request.
* @throws SQLServerException
* on any error, including acknowledgement of an interrupt.
*/
final TDSWriter startRequest(byte tdsMessageType) throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": starting request...");
// Start this command's request message
try {
tdsWriter.startMessage(this, tdsMessageType);
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": starting request: exception: " + e.getMessage());
throw e;
}
// (Re)initialize this command's interrupt state for its current execution.
// To ensure atomically consistent behavior, do not leave the interrupt lock
// until interrupts have been (re)enabled.
synchronized (interruptLock) {
requestComplete = false;
readingResponse = false;
processedResponse = false;
attentionPending = false;
wasInterrupted = false;
interruptReason = null;
interruptsEnabled = true;
}
return tdsWriter;
}
/**
* Finishes the TDS request and then starts reading the TDS response from the server.
*
* @return the TDS reader used to read the response.
* @throws SQLServerException
* if there is any kind of error.
*/
final TDSReader startResponse() throws SQLServerException {
return startResponse(false);
}
final TDSReader startResponse(boolean isAdaptive) throws SQLServerException {
// Finish sending the request message. If this command was interrupted
// at any point before endMessage() returns, then endMessage() throws an
// exception with the reason for the interrupt. Request interrupts
// are disabled by the time endMessage() returns.
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": finishing request");
try {
tdsWriter.endMessage();
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": finishing request: endMessage threw exception: " + e.getMessage());
throw e;
}
// If command execution is subject to timeout then start timing until
// the server returns the first response packet.
if (null != timeoutTimer) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Starting timer...");
timeoutTimer.start();
}
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Reading response...");
try {
// Wait for the server to execute the request and read the first packet
// (responseBuffering=adaptive) or all packets (responseBuffering=full)
// of the response.
if (isAdaptive) {
tdsReader.readPacket();
}
else {
while (tdsReader.readPacket())
;
}
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Exception reading response: " + e.getMessage());
throw e;
}
finally {
// If command execution was subject to timeout then stop timing as soon
// as the server returns the first response packet or errors out.
if (null != timeoutTimer) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Stopping timer...");
timeoutTimer.stop();
}
}
return tdsReader;
}
}
/**
* UninterruptableTDSCommand encapsulates an uninterruptable TDS conversation.
*
* TDSCommands have interruptability built in. However, some TDSCommands such as DTC commands, connection commands, cursor close and prepared
* statement handle close shouldn't be interruptable. This class provides a base implementation for such commands.
*/
abstract class UninterruptableTDSCommand extends TDSCommand {
UninterruptableTDSCommand(String logContext) {
super(logContext, 0, 0);
}
final void interrupt(String reason) throws SQLServerException {
// Interrupting an uninterruptable command is a no-op. That is,
// it can happen, but it should have no effect.
if (logger.isLoggable(Level.FINEST)) {
logger.finest(toString() + " Ignoring interrupt of uninterruptable TDS command; Reason:" + reason);
}
}
}
|
package com.opera.core.systems.util;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* A thread safe stack hash map for use in window manager
* The backing map is a {@link LinkedHashMap} that provides
* predictable iteration order. All the operations that require
* thread safety are protected by the lock of synchronized map.
*
* @author Deniz Turkoglu
*
* @param <K>
* @param <V>
*/
public class StackHashMap<K,V> implements Map<K,V> {
private final Map<K, V> map;
private final LinkedList<K> list;
public StackHashMap() {
map = Collections.synchronizedMap(new LinkedHashMap<K,V>());
list = new LinkedList<K>();
}
public boolean containsKey(Object key) {
return map.containsKey(key);
}
public boolean containsValue(Object value) {
return map.containsValue(value);
}
public V get(Object key) {
return map.get(key);
}
public V put(K key, V value) {
synchronized(map) {
//check if we already have the key
if(!map.containsKey(key))
list.addLast(key); //if not add last
//if we already have the key, just update the value
return map.put(key, value);
}
}
public void putAll(Map<? extends K, ? extends V> t) {
synchronized (map) {
Iterator<? extends Entry<? extends K, ? extends V>> itr = t.entrySet().iterator();
while (itr.hasNext()) {
Entry<? extends K, ? extends V> entry = itr.next();
put(entry.getKey(), entry.getValue());
}
}
}
public Set<K> keySet() {
throw new NotImplementedException();
}
public Collection<V> values() {
return map.values();
}
public Set<Map.Entry<K, V>> entrySet() {
throw new NotImplementedException();
}
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public V remove(Object key) {
synchronized (map) {
list.remove(key);
return map.remove(key);
}
}
public void clear() {
synchronized (map) {
list.clear();
map.clear();
}
}
/**
* Removes the first value from the map
* @return the value that was removed
*/
public V pop() {
synchronized (map) {
return map.remove(list.removeFirst());
}
}
public V push(K k,V v) {
synchronized (map) {
list.addFirst(k);
return map.put(k, v);
}
}
/**
* @return the first value in the backing map
*/
public V peek() {
synchronized (map) {
K k = peekKey();
return (k == null) ? null : map.get(k);
}
}
/**
* @return the first key in the backing linked list
*/
public K peekKey() {
return (list.isEmpty()) ? null : list.getFirst();
}
/**
* @return an unmodifiable copy of the backing linkedlist(used as a stack)
*/
public List<K> asStack() {
return Collections.unmodifiableList(list);
}
/**
* @return an unmodifiable copy of the backing map
*/
public Map<K,V> asMap() {
return Collections.unmodifiableMap(map);
}
/**
* Puts a key to top of the map if absent
* if the key is present in stack it is removed
* @param k
* @param v
* @return the value if it is not contained, null otherwise
*/
public V pushIfAbsent(K k, V v) {
synchronized (map) {
if(!list.contains(k)) {
return map.put(k, v);
} else {
list.remove(k);
}
list.addFirst(k);
return null;
}
}
}
|
package com.kierdavis.kmail;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class WebClient {
private KMail plugin;
private XMLMessageSerializer serializer;
public WebClient(KMail plugin_) {
plugin = plugin_;
serializer = new XMLMessageSerializer();
}
public void send(Message msg) {
String addr;
if (msg.hasSendVia()) {
addr = msg.getSendVia();
}
else {
addr = msg.getDestAddress().getHostname();
}
if (addr.indexOf(":") < 0) {
addr += ":4880";
}
send(addr, msg);
}
public void send(String addr, Message msg) {
plugin.getLogger().info("Sending message via HTTP to " + addr + ": " + msg.getSrcAddress().toString() + " -> " + msg.getDestAddress().toString());
boolean success = false;
HttpURLConnection conn = null;
try {
Collection<Message> msgs = new ArrayList<Message>();
msgs.add(msg);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
serializer.serialize(bos, msgs);
byte[] requestBytes = bos.toByteArray();
URL url = new URL("http://" + addr + "/");
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(plugin.getClientTimeout() * 1000);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Content-Length", Integer.toString(requestBytes.length));
conn.setUseCaches(false);
conn.setDoOutput(true);
conn.setDoInput(true);
OutputStream os = conn.getOutputStream();
os.write(requestBytes);
os.flush();
os.close();
if (conn.getResponseCode() >= 300) {
throw new IOException("Bad HTTP response from server: " + conn.getResponseMessage());
}
//InputStream is = conn.getInputStream();
//InputStreamReader isr = new InputStreamReader(is);
//BufferedReader br = new BufferedReader(isr);
//String line = br.readLine();
//while (line != null) {
// line = br.readLine();
//br.close();
success = true;
}
catch (XMLMessageSerializationException e) {
plugin.getLogger().severe("Could not serialize messages: " + e.toString());
}
catch (IOException e) {
plugin.getLogger().severe("Could not send messages: " + e.toString());
}
finally {
if (conn != null) {
conn.disconnect();
}
}
if (!success) {
retry(msg);
}
}
public void retry(Message msg) {
msg.incRetries();
if (msg.getRetries() >= plugin.getNumRetries()) {
plugin.getLogger().severe("Sending failed permanently");
msg = plugin.errorResponse(msg, "Sending failed after " + Integer.toString(plugin.getNumRetries()) + " attempts");
}
plugin.sendMessage(msg);
}
public List<Message> pollQueue(String addr) {
plugin.getLogger().info("Polling queue at " + addr + " for new messages");
HttpURLConnection conn = null;
List<Message> messages = null;
try {
String hostname = URLEncoder.encode(plugin.getLocalHostname(), "UTF-8");
URL url = new URL("http://" + addr + "/fetch?hostname=" + hostname);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(plugin.getClientTimeout() * 1000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoOutput(false);
conn.setDoInput(true);
if (conn.getResponseCode() == 404) {
if (!registerQueue(addr)) {
return null;
}
//return pollQueue(addr;
return null;
}
if (conn.getResponseCode() >= 300) {
throw new IOException("Bad HTTP response from server: " + conn.getResponseMessage());
}
XMLMessageParser parser = new XMLMessageParser();
InputStream is = conn.getInputStream();
messages = parser.parse(is);
is.close();
}
catch (XMLMessageParseException e) {
plugin.getLogger().severe("Could not parse response: " + e.toString());
}
catch (IOException e) {
plugin.getLogger().severe("Could not fetch messages: " + e.toString());
}
finally {
if (conn != null) {
conn.disconnect();
}
}
return messages;
}
public boolean registerQueue(String addr) {
plugin.getLogger().info("Registering a new queue at " + addr);
HttpURLConnection conn = null;
List<Message> messages = null;
try {
String hostname = URLEncoder.encode(plugin.getLocalHostname(), "UTF-8");
URL url = new URL("http://" + addr + "/register?hostname=" + hostname);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(plugin.getClientTimeout() * 1000);
conn.setRequestMethod("POST");
conn.setUseCaches(false);
conn.setDoOutput(false);
conn.setDoInput(true);
if (conn.getResponseCode() >= 300) {
throw new IOException("Bad HTTP response from server: " + conn.getResponseMessage());
}
}
catch (XMLMessageParseException e) {
plugin.getLogger().severe("Could not parse response: " + e.toString());
}
catch (IOException e) {
plugin.getLogger().severe("Could not fetch messages: " + e.toString());
}
finally {
if (conn != null) {
conn.disconnect();
}
}
return messages;
}
}
|
package com.mysema.codegen.model;
import java.util.HashSet;
import java.util.Set;
import javax.annotation.Nullable;
/**
* TypeCategory defines the expression type used for a Field
*
* @author tiwe
*
*/
public enum TypeCategory {
SIMPLE(null),
MAP(null),
COLLECTION(null),
LIST(COLLECTION),
SET(COLLECTION),
ARRAY(null),
COMPARABLE(SIMPLE),
BOOLEAN(COMPARABLE, Boolean.class.getName()),
DATE(COMPARABLE, java.sql.Date.class.getName(), "org.joda.time.LocalDate"),
DATETIME(COMPARABLE,
java.util.Calendar.class.getName(),
java.util.Date.class.getName(),
java.sql.Timestamp.class.getName(),
"org.joda.time.LocalDateTime",
"org.joda.time.Instant",
"org.joda.time.DateTime",
"org.joda.time.DateMidnight"),
ENUM(COMPARABLE),
CUSTOM(null),
ENTITY(null),
NUMERIC(COMPARABLE),
STRING(COMPARABLE, String.class.getName()),
TIME(COMPARABLE, java.sql.Time.class.getName(), "org.joda.time.LocalTime");
@Nullable
private final TypeCategory superType;
private final Set<String> types;
TypeCategory(@Nullable TypeCategory superType, String... types){
this.superType = superType;
this.types = new HashSet<String>(types.length);
for (String type : types){
this.types.add(type);
}
}
public TypeCategory getSuperType() {
return superType;
}
public boolean supports(Class<?> cl){
return supports(cl.getName());
}
public boolean supports(String className){
return types.contains(className);
}
/**
* transitive and reflexive subCategoryOf check
*
* @param ancestor
* @return
*/
public boolean isSubCategoryOf(TypeCategory ancestor){
if (this == ancestor){
return true;
}else if (superType == null){
return false;
}else{
return superType == ancestor || superType.isSubCategoryOf(ancestor);
}
}
public static TypeCategory get(String className){
for (TypeCategory category : values()){
if (category.supports(className)){
return category;
}
}
return SIMPLE;
}
}
|
package com.reason.ide.folding;
import com.intellij.lang.ASTNode;
import com.intellij.lang.folding.FoldingBuilderEx;
import com.intellij.lang.folding.FoldingDescriptor;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.util.PsiTreeUtil;
import com.reason.psi.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import static com.reason.lang.RmlTypes.*;
public class RmlFoldingBuilder extends FoldingBuilderEx {
@NotNull
@Override
public FoldingDescriptor[] buildFoldRegions(@NotNull PsiElement root, @NotNull Document document, boolean quick) {
List<FoldingDescriptor> descriptors = new ArrayList<>();
PsiTreeUtil.processElements(root, element -> {
IElementType elementType = element.getNode().getElementType();
if (COMMENT.equals(elementType)) {
descriptors.add(fold(element));
} else if (TYPE_EXPRESSION.equals(elementType)) {
foldType(descriptors, (ReasonMLType) element);
} else if (LET_EXPRESSION.equals(elementType)) {
foldLet(descriptors, (ReasonMLLet) element);
} else if (MODULE_EXPRESSION.equals(elementType)) {
foldModule(descriptors, (ReasonMLModule) element);
}
return true;
});
return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
}
private void foldType(List<FoldingDescriptor> descriptors, ReasonMLType typeExpression) {
FoldingDescriptor fold = fold(typeExpression.getScopedExpression());
if (fold != null) {
descriptors.add(fold);
}
}
private void foldLet(List<FoldingDescriptor> descriptors, ReasonMLLet letExpression) {
ReasonMLFunBody functionBody = letExpression.getFunctionBody();
if (functionBody != null) {
FoldingDescriptor fold = fold(functionBody);
if (fold != null) {
descriptors.add(fold);
}
} else {
ReasonMLLetBinding letBinding = letExpression.getLetBinding();
FoldingDescriptor fold = fold(letBinding);
if (fold != null) {
descriptors.add(fold);
}
}
}
private void foldModule(List<FoldingDescriptor> descriptors, ReasonMLModule module) {
FoldingDescriptor fold = fold(module.getModuleBody());
if (fold != null) {
descriptors.add(fold);
}
// PsiElement lBrace = RmlPsiTreeUtil.getNextSiblingOfType(element, LBRACE);
// PsiElement rBrace = RmlPsiTreeUtil.getNextSiblingOfType(lBrace, RBRACE);
// if (lBrace != null && rBrace != null) {
// FoldingDescriptor fold = foldBetween(element, lBrace, rBrace, 5);
// if (fold != null)
// descriptors.add(fold);
}
@Nullable
@Override
public String getPlaceholderText(@NotNull ASTNode node) {
if (node.getElementType().equals(COMMENT)) {
return "";
}
return "{...}";
}
@Override
public boolean isCollapsedByDefault(@NotNull ASTNode node) {
return false;
}
// @Nullable
// private FoldingDescriptor foldBetween(PsiElement element, PsiElement left, PsiElement right, int minWidth) {
// if (right.getTextOffset() - left.getTextOffset() < minWidth) {
// return null;
// TextRange range = new TextRange(left.getTextOffset() + 1, right.getTextOffset());
// return new FoldingDescriptor(element, range);
@Nullable
private FoldingDescriptor fold(@Nullable PsiElement element) {
if (element == null) {
return null;
}
TextRange textRange = element.getTextRange();
return textRange.getLength() > 5 ? new FoldingDescriptor(element, textRange) : null;
}
}
|
import java.io.File;
import java.nio.file.Files;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import raytracer.*;
public class WebServer {
public static final String INPUT_FILES_DIR = "input";
public static final String OUTPUT_FILES_DIR = "output";
public static final String RENDER_PATH = "/r.html";
public static final String HEALTHCHECK_PATH = "/healthcheck";
public static final String MODEL_FILENAME_PARAM = "f";
public static final String SCENE_COLUMNS_PARAM = "sc";
public static final String SCENE_ROWS_PARAM = "sr";
public static final String WINDOW_COLUMNS_PARAM = "wc";
public static final String WINDOW_ROWS_PARAM = "wr";
public static final String COLUMNS_OFFSET_PARAM = "coff";
public static final String ROWS_OFFSET_PARAM = "roff";
public static final Integer PORT = 8000;
public static void main(String[] args) throws Exception {
// Let's bind to all the supported ipv4 interfaces
HttpServer server = HttpServer.create(new InetSocketAddress("0.0.0.0", PORT), 0);
// Set routes
server.createContext(RENDER_PATH, new RenderHandler());
server.createContext(HEALTHCHECK_PATH, new HealthcheckHandler());
// Multi thread support
server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
server.start();
System.out.println("Server running on port: " + PORT);
}
public static Map<String, String> getQueryParameters(HttpExchange req) {
Map<String, String> result = new HashMap<String, String>();
String query = req.getRequestURI().getQuery();
if (query == null) return result;
for (String param : query.split("&")) {
String pair[] = param.split("=");
if (pair.length>1) {
result.put(pair[0], pair[1]);
}else{
result.put(pair[0], "");
}
}
return result;
}
static class HealthcheckHandler implements HttpHandler {
@Override
public void handle(HttpExchange req) throws IOException {
String outResponse = "OK";
OutputStream os = req.getResponseBody();
Integer responseCode = 200;
req.sendResponseHeaders(responseCode, outResponse.length());
os.write(outResponse.getBytes());
os.close();
}
}
static class RenderHandler implements HttpHandler {
@Override
public void handle(HttpExchange req) throws IOException {
String outError = "Invalid Request";
OutputStream os = req.getResponseBody();
Map<String,String> queryParams = WebServer.getQueryParameters(req);
Integer response = 400;
try {
int scols = Integer.parseInt(queryParams.get(SCENE_COLUMNS_PARAM));
int srows = Integer.parseInt(queryParams.get(SCENE_ROWS_PARAM));
int wcols = Integer.parseInt(queryParams.get(WINDOW_COLUMNS_PARAM));
int wrows = Integer.parseInt(queryParams.get(WINDOW_ROWS_PARAM));
int coff = Integer.parseInt(queryParams.get(COLUMNS_OFFSET_PARAM));
int roff = - Integer.parseInt(queryParams.get(ROWS_OFFSET_PARAM));
String fileName = queryParams.get(MODEL_FILENAME_PARAM);
File inFile = new File(INPUT_FILES_DIR + "/" + fileName);
File outFile = new File(OUTPUT_FILES_DIR + "/" + fileName + ".bmp");
RayTracer rayTracer = new RayTracer(scols, srows, wcols, wrows, coff, roff);
rayTracer.readScene(inFile);
rayTracer.draw(outFile);
response = 200;
req.getResponseHeaders().set("Content-Type", "image/bmp");
req.sendResponseHeaders(response, outFile.length());
Files.copy(outFile.toPath(), os);
} catch (NumberFormatException e) {
outError += e.getMessage();
response = 400;
req.sendResponseHeaders(response, outError.length());
os.write(outError.getBytes());
} catch (Exception e) {
outError = "Internal Server Error: " + e.getMessage();
response = 500;
req.sendResponseHeaders(response, outError.length());
os.write(outError.getBytes());
} finally {
os.close();
}
}
}
}
|
package com.nearsoft.incubator.model;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import java.util.List;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Schedule {
private List<Flight> departureFlights;
private List<Flight> arrivalFlights;
public List<Flight> getDepartureFlights() {
return departureFlights;
}
public void setDepartureFlights(List<Flight> departureFlights) {
this.departureFlights = departureFlights;
}
public List<Flight> getArrivalFlights() {
return arrivalFlights;
}
public void setArrivalFlights(List<Flight> returnFlights) {
this.arrivalFlights = returnFlights;
}
}
|
package com.sebnarware.avalanche;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
@SuppressLint("SetJavaScriptEnabled")
public class WebViewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
// get access to the activity indicator
// NOTE must happen before content is added
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
// show our icon
requestWindowFeature(Window.FEATURE_LEFT_ICON);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.logo);
WebView webView = (WebView) findViewById(R.id.webview);
// show full page width by default
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
// enable zooming
webView.getSettings().setBuiltInZoomControls(true);
// make link navigation stay within this webview, vs. launching the browser
webView.setWebViewClient(new WebViewClient());
// enable javascript
webView.getSettings().setJavaScriptEnabled(true);
// enable activity indicator during loading
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress == 100) {
// all done
setProgressBarIndeterminateVisibility(false);
} else {
// in progress
setProgressBarIndeterminateVisibility(true);
}
}
});
// NOTE set our user agent string to something benign and non-mobile looking, to work around website
// popups from nwac.us asking if you would like to be redirected to the mobile version of the site
webView.getSettings().setUserAgentString("Mozilla/5.0");
// get the desired url from the intent
Intent intent = getIntent();
String url = intent.getStringExtra(MainActivity.INTENT_EXTRA_WEB_VIEW_URL);
// set cache mode, depending on current network availability
if (NetworkEngine.isNetworkAvailable(this)){
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
} else {
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
webView.loadUrl(url);
}
}
|
package com.networknt.schema;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* A Single Context for holding the output returned by the {@link Collector} implementations.
*
*/
public enum CollectorContext {
INSTANCE;
/**
* Map for holding the collector type and {@link Collector}
*/
private Map<String, Collector<?>> collectorMap = new HashMap<String, Collector<?>>();
/**
* Map for holding the collector type and {@link Collector} class collect method output.
*/
private Map<String, Object> collectorLoadMap = new HashMap<String, Object>();
public <E> void add(String collectorType, Collector<E> collector) {
collectorMap.put(collectorType, collector);
}
public Object get(String collectorType) {
if (collectorLoadMap.get(collectorType) == null && collectorMap.get(collectorType) != null) {
collectorLoadMap.put(collectorType, collectorMap.get(collectorType).collect());
}
return collectorLoadMap.get(collectorType);
}
/**
* Load all the collectors associated with the context.
*/
void load() {
for (Entry<String, Collector<?>> collectorEntrySet : collectorMap.entrySet()) {
collectorLoadMap.put(collectorEntrySet.getKey(), collectorEntrySet.getValue().collect());
}
}
/**
* Reset the context
*/
void reset() {
this.collectorMap = new HashMap<String, Collector<?>>();
this.collectorLoadMap = new HashMap<String, Object>();
}
}
|
package com.robohorse.pagerbullet;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class PagerBullet extends FrameLayout {
private static final String DIGIT_PATTERN = "[^0-9.]";
private static final int DEFAULT_INDICATOR_OFFSET_VALUE = 20;
private int offset = DEFAULT_INDICATOR_OFFSET_VALUE;
private ViewPager viewPager;
private TextView textIndicator;
private LinearLayout layoutIndicator;
private View indicatorContainer;
private int activeColorTint;
private int inactiveColorTint;
public PagerBullet(Context context) {
super(context);
init(context);
}
public PagerBullet(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
setAttributes(context, attrs);
}
public PagerBullet(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
setAttributes(context, attrs);
}
private void setAttributes(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PagerBullet);
String heightValue = typedArray.getString(R.styleable.PagerBullet_panelHeightInDp);
if (null != heightValue) {
heightValue = heightValue.replaceAll(DIGIT_PATTERN, "");
float height = Float.parseFloat(heightValue);
FrameLayout.LayoutParams params = (LayoutParams) indicatorContainer.getLayoutParams();
params.height = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, height,
getResources().getDisplayMetrics()));
indicatorContainer.requestLayout();
}
typedArray.recycle();
}
public void setIndicatorTintColorScheme(int activeColorTint, int inactiveColorTint) {
this.activeColorTint = activeColorTint;
this.inactiveColorTint = inactiveColorTint;
invalidateBullets();
}
public void setTextSeparatorOffset(int offset) {
this.offset = offset;
}
public void setAdapter(final PagerAdapter adapter) {
viewPager.setAdapter(adapter);
invalidateBullets(adapter);
}
public void setCurrentItem(int position) {
viewPager.setCurrentItem(position);
setIndicatorItem(position);
}
public ViewPager getViewPager() {
return viewPager;
}
public void addOnPageChangeListener(ViewPager.OnPageChangeListener onPageChangeListener) {
viewPager.addOnPageChangeListener(onPageChangeListener);
}
public void invalidateBullets() {
PagerAdapter adapter = viewPager.getAdapter();
if (null != adapter) {
invalidateBullets(adapter);
}
}
public void invalidateBullets(PagerAdapter adapter) {
final boolean hasSeparator = hasSeparator();
textIndicator.setVisibility(hasSeparator ? VISIBLE : INVISIBLE);
layoutIndicator.setVisibility(hasSeparator ? INVISIBLE : VISIBLE);
if (!hasSeparator) {
initIndicator(adapter.getCount());
}
setIndicatorItem(viewPager.getCurrentItem());
}
private void init(Context context) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View rootView = layoutInflater.inflate(R.layout.item_view_pager, this);
indicatorContainer = rootView.findViewById(R.id.pagerBulletIndicatorContainer);
textIndicator = (TextView) indicatorContainer.findViewById(R.id.pagerBulletIndicatorText);
layoutIndicator = (LinearLayout) indicatorContainer.findViewById(R.id.pagerBulletIndicator);
viewPager = (ViewPager) rootView.findViewById(R.id.viewPagerBullet);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
setIndicatorItem(position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void initIndicator(int count) {
layoutIndicator.removeAllViews();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
int margin = Math.round(getContext().getResources()
.getDimension(R.dimen.pager_bullet_indicator_dot_margin));
params.setMargins(margin, 0, margin, 0);
Drawable drawableInactive = ContextCompat.getDrawable(getContext(),
R.drawable.inactive_dot);
for (int i = 0; i < count; i++) {
ImageView imageView = new ImageView(getContext());
imageView.setImageDrawable(drawableInactive);
layoutIndicator.addView(imageView, params);
}
}
private void setIndicatorItem(int index) {
if (!hasSeparator()) {
setItemBullet(index);
} else {
setItemText(index);
}
}
private boolean hasSeparator() {
PagerAdapter pagerAdapter = viewPager.getAdapter();
return null != pagerAdapter && pagerAdapter.getCount() > offset;
}
private void setItemText(int index) {
PagerAdapter adapter = viewPager.getAdapter();
if (null != adapter) {
final int count = adapter.getCount();
textIndicator.setText(String.format(getContext()
.getString(R.string.pager_bullet_separator), index + 1, count));
}
}
private void setItemBullet(int selectedPosition) {
Drawable drawableInactive = ContextCompat.getDrawable(getContext(), R.drawable.inactive_dot);
drawableInactive = wrapTintDrawable(drawableInactive, inactiveColorTint);
Drawable drawableActive = ContextCompat.getDrawable(getContext(), R.drawable.active_dot);
drawableActive = wrapTintDrawable(drawableActive, activeColorTint);
final int indicatorItemsCount = layoutIndicator.getChildCount();
for (int position = 0; position < indicatorItemsCount; position++) {
ImageView imageView = (ImageView) layoutIndicator.getChildAt(position);
if (position != selectedPosition) {
imageView.setImageDrawable(drawableInactive);
} else {
imageView.setImageDrawable(drawableActive);
}
}
}
public static Drawable wrapTintDrawable(Drawable sourceDrawable, int color) {
if (color != 0) {
Drawable wrapDrawable = DrawableCompat.wrap(sourceDrawable);
DrawableCompat.setTint(wrapDrawable, color);
wrapDrawable.setBounds(0, 0, wrapDrawable.getIntrinsicWidth(),
wrapDrawable.getIntrinsicHeight());
return wrapDrawable;
} else {
return sourceDrawable;
}
}
}
|
package com.testclient.controller;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.testclient.enums.Suffix4Deleted;
import com.testclient.httpmodel.Json;
import com.testclient.service.TreeNodeService;
import com.testclient.utils.MyFileUtils;
@Controller
public class TreeController {
private static final Logger logger = Logger.getLogger(TreeController.class);
private String _action,_path,_json;
@Autowired
TreeNodeService treeNodeService;
@RequestMapping(value="/getUserRootName")
@ResponseBody
public String getUserRootName() {
return SecurityContextHolder.getContext().getAuthentication().getName();
}
@RequestMapping(value="/isAdminUser")
@ResponseBody
public boolean isAdminUser() {
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities();
String role=authorities.toArray()[0].toString();
return role.toUpperCase().equals("ROLE_ADMIN");
}
@RequestMapping(value="/copyNodeWithoutHistory", method=RequestMethod.POST )
@ResponseBody
public Json copyNodeWithoutHistory(@RequestParam("srcPath")String srcPath, @RequestParam("targetPath")String targetPath) {
Json j=new Json();
try{
MyFileUtils.copyTestWithoutHistory(srcPath, targetPath);
j.setSuccess(true);
}
catch(IOException ioe){
j.setSuccess(false);
j.setMsg(ioe.getClass().toString()+": "+ioe.getMessage());
}
return j;
}
@RequestMapping(value="/copyNode", method=RequestMethod.POST )
@ResponseBody
public Json copyNode(@RequestParam("srcPath")String srcPath, @RequestParam("targetPath")String targetPath) {
Json j=new Json();
try{
MyFileUtils.copyArtifact(srcPath, targetPath);
j.setSuccess(true);
}
catch(IOException ioe){
j.setSuccess(false);
logger.error(ioe.getClass().toString()+": "+ioe.getMessage());
}
return j;
}
@RequestMapping(value="/batchCopyTest", method=RequestMethod.POST )
@ResponseBody
public Json batchCopyTest(@RequestParam String testPath, @RequestParam int number) {
Json j=new Json();
try{
MyFileUtils.copyMultipleTestsAtSameDir(testPath, number);
j.setSuccess(true);
}
catch(IOException ioe){
j.setSuccess(false);
logger.error(ioe.getClass().toString()+": "+ioe.getMessage());
}
return j;
}
@RequestMapping(value="/addNode", method=RequestMethod.POST )
@ResponseBody
public Json addNode(@RequestParam("folderName")String foldername) {
Json j=new Json();
File parent=new File(StringUtils.substringBeforeLast(foldername, "/"));
String filename=StringUtils.substringAfterLast(foldername, "/");
if(parent.exists()){
for(String child : parent.list()){
if(child.equalsIgnoreCase(filename)){
j.setSuccess(false);
j.setMsg("Duplicated node "+filename);
return j;
}
}
}
File f=new File(foldername);
MyFileUtils.makeDir(foldername);
j.setSuccess(true);
return j;
}
@RequestMapping(value="/delNode", method=RequestMethod.POST )
@ResponseBody
public Json delNode(@RequestParam("folderName")String foldername) {
Json j=new Json();
try {
FileUtils.forceDelete(new File(foldername));
j.setSuccess(true);
} catch (IOException e) {
// TODO Auto-generated catch block
logger.error("delNode ", e);
j.setSuccess(false);
j.setMsg("");
}
return j;
}
@RequestMapping(value="/logicalDelNode", method=RequestMethod.POST )
@ResponseBody
public Json logicalDelNode(@RequestParam("nodePath")String nodePath) {
Json j=new Json();
try {
String renamedPath=nodePath+Suffix4Deleted.deleted;
boolean isSuccess = treeNodeService.renameDirectory(nodePath, renamedPath);
j.setSuccess(isSuccess);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("", e);
j.setSuccess(false);
j.setMsg("");
}
return j;
}
@RequestMapping(value="/modifyNode", method=RequestMethod.POST )
@ResponseBody
public Json modifyNode(@RequestParam("folderName")String foldername,@RequestParam("oldFolderName")String oldFoldername) {
Json j=new Json();
File path=new File(oldFoldername);
path.renameTo(new File(foldername));
j.setSuccess(true);
return j;
}
@RequestMapping(value="/gettree")
@ResponseBody
public List getTree(@RequestParam String rootName) {
List list = treeNodeService.getTree(rootName,false);
return list;
}
@RequestMapping(value="/getTreeChildNodes")
@ResponseBody
public List getTreeChildNodes(@RequestParam String topPath,@RequestParam String node) {
topPath = (node==null || node.isEmpty()) ? topPath : node;
List list = treeNodeService.getChildNodes(topPath,false);
return list;
}
@RequestMapping(value="/getSelectingTree")
@ResponseBody
public List getSelectingTree(@RequestParam String rootName) {
return treeNodeService.getTree(rootName,true);
}
@RequestMapping(value="/getSelectedTree")
@ResponseBody
public List getSelectedTree(@RequestParam String rootName,@RequestParam String[] testset) {
return treeNodeService.getCheckedTree(rootName,testset);
}
@RequestMapping(value="/getSelectedTreeChildNodes")
@ResponseBody
public List getSelectedTreeChildNodes(@RequestParam String topPath,@RequestParam String[] testset,@RequestParam String node) {
topPath = (node==null || node.isEmpty()) ? topPath : node;
return treeNodeService.getCheckedChildNodes(topPath,testset);
}
@RequestMapping(value="/getFolderTree", method=RequestMethod.GET )
@ResponseBody
public List getFolderTree(@RequestParam String rootName){
return treeNodeService.getFolderTree(rootName);
}
@RequestMapping(value="/getNodeIdByText", method=RequestMethod.POST )
@ResponseBody
public String getNodeIdByText(@RequestParam String rootName,@RequestParam String text,@RequestParam boolean isTest){
List<String> nodes=treeNodeService.getNodes(rootName,">");
for(String node : nodes){
String[] arr=node.split(">");
String name=arr[arr.length-1].toLowerCase();
if(name.contains(text.toLowerCase())){
if(isTest){
return (name.endsWith("-leaf") || name.endsWith("-t")) ? node : "";
}else
return name.endsWith("-dir") ? node : "";
}
}
return "";
}
@RequestMapping(value="/isDuplicatedNode")
@ResponseBody
public boolean isDuplicatedNode(@RequestParam String folderName,@RequestParam String name){
boolean isduplicated=true;
if(folderName.endsWith("-dir")){
File f=new File(folderName);
for(String fname : f.list()){
if(fname.equalsIgnoreCase(name)){
return true;
}
}
isduplicated=false;
}
return isduplicated;
}
// @RequestMapping(value="/subscribleQueue")
// @ResponseBody
// public void subscribleQueue(@RequestParam String action,@RequestParam String path){
// _action=action;
// _path=path;
// ApplicationContext context = new ClassPathXmlApplicationContext("spring-jms.xml");
// // JMS
// JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
// Destination destination = (Destination) context.getBean("topicDestination");
// jmsTemplate.send(destination, new MessageCreator() {
// public Message createMessage(Session session) throws JMSException {
// Node4Queue node=new Node4Queue();
// node.setAction(_action);
// if(_path.endsWith("/")){
// _path=_path.substring(0, _path.length()-1);
// String name=StringUtils.substringAfterLast(_path, "/");
// boolean istest=_path.endsWith("-dir") ? false : true;
// name=StringUtils.substringBeforeLast(name, "-");
// node.setPath(_path);
// node.setIsTest(istest);
// node.setName(name);
// String json=JSONObject.fromObject(node).toString();
// return session.createObjectMessage(json);
// @RequestMapping(value="/pushAllNodesIntoQueue")
// @ResponseBody
// public void pushAllNodesIntoQueue(){
// List<Node4Queue> nodes=treeNodeService.getTreeNodes("root");
// ApplicationContext context = new ClassPathXmlApplicationContext("spring-jms.xml");
// // JMS
// JmsTemplate jmsTemplate = (JmsTemplate) context.getBean("jmsTemplate");
// Destination destination = (Destination) context.getBean("topicDestination");
// for(Node4Queue node : nodes){
// _json=JSONObject.fromObject(node).toString();
// jmsTemplate.send(destination, new MessageCreator() {
// public Message createMessage(Session session) throws JMSException {
// return session.createObjectMessage(_json);
}
|
package com.rox.emu.processor.mos6502;
import com.rox.emu.env.RoxByte;
import com.rox.emu.env.RoxWord;
import com.rox.emu.mem.Memory;
import com.rox.emu.processor.mos6502.op.OpCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.rox.emu.processor.mos6502.Registers.*;
/**
* A emulated representation of MOS 6502, 8 bit
* microprocessor functionality.
*
* XXX: At this point, we are only emulating the NES custom version of the 6502
*
* @author Ross Drew
*/
public class Mos6502 {
private final Logger LOG = LoggerFactory.getLogger(this.getClass());
private final Memory memory;
private final Registers registers = new Registers();
private final Mos6502Alu alu = new Mos6502Alu(registers);
/** The bit set on a byte when a it is negative */
private static final int NEGATIVE_INDICATOR_BIT = 0x80;
public Mos6502(Memory memory) {
this.memory = memory;
}
/**
* Reset the CPU; akin to firing the Reset pin on a 6502.<br/>
* <br/>
* This will
* <ul>
* <li>Set Accumulator → <code>0</code></li>
* <li>Set Indexes → <code>0</code></li>
* <li>Status register → <code>0x34</code></li>
* <li>Set PC to the values at <code>0xFFFC</code> and <code>0xFFFD</code></li>
* <li>Reset Stack Pointer → 0xFF</li>
* </ul>
* <br/>
* Note: IRL this takes 6 CPU cycles but we'll cross that bridge IF we come to it-
*/
public void reset(){
LOG.debug("RESETTING...");
setRegisterValue(REG_ACCUMULATOR, 0x0);
setRegisterValue(REG_X_INDEX, 0x0);
setRegisterValue(REG_Y_INDEX, 0x0);
setRegisterValue(REG_STATUS, 0x34);
setRegisterValue(REG_PC_HIGH, getByteOfMemoryAt(0xFFFC));
setRegisterValue(REG_PC_LOW, getByteOfMemoryAt(0xFFFD));
setRegisterValue(REG_SP, 0xFF);
LOG.debug("...READY!");
}
/**
* Fire an <b>I</b>nterrupt <b>R</b>e<b>Q</b>uest; akin to setting the IRQ pin on a 6502.<br/>
* <br>
* This will stash the PC and Status registers and set the Program Counter to the values at
* <code>0xFFFE</code> and <code>0xFFFF</code> where the <b>I</b>nterrupt <b>S</b>ervice
* <b>R</b>outine is expected to be
*/
public void irq() {
LOG.debug("IRQ!");
registers.setFlag(I);
pushRegister(REG_PC_HIGH);
pushRegister(REG_PC_LOW);
pushRegister(REG_STATUS);
setRegisterValue(REG_PC_HIGH, getByteOfMemoryAt(0xFFFe));
setRegisterValue(REG_PC_LOW, getByteOfMemoryAt(0xFFFF));
}
/**
* Fire a <b>N</b>on <b>M</b>askable <b>I</b>nterrupt; akin to setting the NMI pin on a 6502.<br/>
* <br>
* This will stash the PC and Status registers and set the Program Counter to the values at <code>0xFFFA</code>
* and <code>0xFFFB</code> where the <b>I</b>nterrupt <b>S</b>ervice <b>R</b>outine is expected to be
*/
public void nmi() {
LOG.debug("NMI!");
registers.setFlag(I);
pushRegister(REG_PC_HIGH);
pushRegister(REG_PC_LOW);
pushRegister(REG_STATUS);
setRegisterValue(REG_PC_HIGH, getByteOfMemoryAt(0xFFFA));
setRegisterValue(REG_PC_LOW, getByteOfMemoryAt(0xFFFB));
}
/**
* @return the {@link Registers} being used
*/
public Registers getRegisters(){
return registers;
}
/**
* Execute the next program instruction as per {@link Registers#getNextProgramCounter()}
*
* @param steps number of instructions to execute
*/
public void step(int steps){
for (int i=0; i<steps; i++)
step();
}
/**
* Execute the next program instruction as per {@link Registers#getNextProgramCounter()}
*/
public void step() {
LOG.debug("STEP >>>");
final int opCodeByte = nextProgramByte();
final OpCode opCode = OpCode.from(opCodeByte);
//Execute the opcode
LOG.debug("Instruction: " + opCode.getOpCodeName() + "...");
switch (opCode){
default:
case BRK:
//XXX Why do we do this at all? A program of [BRK] will push 0x03 as the PC...why is that right?
registers.setPC(performSilently(this::performADC, registers.getPC(), 2, false));
push(registers.getRegister(REG_PC_HIGH));
push(registers.getRegister(REG_PC_LOW));
push(registers.getRegister(REG_STATUS) | STATUS_FLAG_BREAK);
registers.setRegister(REG_PC_HIGH, getByteOfMemoryAt(0xFFFE));
registers.setRegister(REG_PC_LOW, getByteOfMemoryAt(0xFFFF));
break;
case ASL_A:
withRegister(REG_ACCUMULATOR, this::performASL);
break;
case ASL_Z:
withByteAt(nextProgramByte(), this::performASL);
break;
case ASL_Z_IX:
withByteXIndexedAt(nextProgramByte(), this::performASL);
break;
case ASL_ABS_IX:
withByteXIndexedAt(nextProgramWord(), this::performASL);
break;
case ASL_ABS:
withByteAt(nextProgramWord(), this::performASL);
break;
case LSR_A:
withRegister(REG_ACCUMULATOR, this::performLSR);
break;
case LSR_Z:
withByteAt(nextProgramByte(), this::performLSR);
break;
case LSR_Z_IX:
withByteXIndexedAt(nextProgramByte(), this::performLSR);
break;
case LSR_ABS:
withByteAt(nextProgramWord(), this::performLSR);
break;
case LSR_ABS_IX:
withByteXIndexedAt(nextProgramWord(), this::performLSR);
break;
case ROL_A:
withRegister(REG_ACCUMULATOR, this::performROL);
break;
case ROL_Z:
withByteAt(nextProgramByte(), this::performROL);
break;
case ROL_Z_IX:
withByteXIndexedAt(nextProgramByte(), this::performROL);
break;
case ROL_ABS:
withByteAt(nextProgramWord(), this::performROL);
break;
case ROL_ABS_IX:
withByteXIndexedAt(nextProgramWord(), this::performROL);
break;
/* Not implemented and/or not published on older 6502s */
case ROR_A:
withRegister(REG_ACCUMULATOR, this::performROR);
break;
case SEC:
registers.setFlag(C);
break;
case CLC:
registers.clearFlag(C);
break;
case CLV:
registers.clearFlag(V);
break;
case INC_Z:
withByteAt(nextProgramByte(), this::performINC);
break;
case INC_Z_IX:
withByteXIndexedAt(nextProgramByte(), this::performINC);
break;
case INC_ABS:
withByteAt(nextProgramWord(), this::performINC);break;
case INC_ABS_IX:
withByteXIndexedAt(nextProgramWord(), this::performINC);
break;
case DEC_Z:
withByteAt(nextProgramByte(), this::performDEC);
break;
case DEC_Z_IX:
withByteXIndexedAt(nextProgramByte(), this::performDEC);
break;
case DEC_ABS:
withByteAt(nextProgramWord(), this::performDEC);
break;
case DEC_ABS_IX:
withByteXIndexedAt(nextProgramWord(), this::performDEC);
break;
case INX:
withRegister(REG_X_INDEX, this::performINC);
break;
case DEX:
withRegister(REG_X_INDEX, this::performDEC);
break;
case INY:
withRegister(REG_Y_INDEX, this::performINC);
break;
case DEY:
withRegister(REG_Y_INDEX, this::performDEC);
break;
case LDX_I:
registers.setRegisterAndFlags(REG_X_INDEX, nextProgramByte());
break;
case LDX_Z:
registers.setRegisterAndFlags(REG_X_INDEX, getByteOfMemoryAt(nextProgramByte()));
break;
case LDX_Z_IY:
registers.setRegisterAndFlags(REG_X_INDEX, getByteOfMemoryYIndexedAt(nextProgramByte()));
break;
case LDX_ABS:
registers.setRegisterAndFlags(REG_X_INDEX, getByteOfMemoryAt(nextProgramWord()));
break;
case LDX_ABS_IY:
registers.setRegisterAndFlags(REG_X_INDEX, getByteOfMemoryYIndexedAt(nextProgramWord()));
break;
case LDY_I:
registers.setRegisterAndFlags(REG_Y_INDEX, nextProgramByte());
break;
case LDY_Z:
registers.setRegisterAndFlags(REG_Y_INDEX, getByteOfMemoryAt(nextProgramByte()));
break;
case LDY_Z_IX:
registers.setRegisterAndFlags(REG_Y_INDEX, getByteOfMemoryXIndexedAt(nextProgramByte()));
break;
case LDY_ABS:
registers.setRegisterAndFlags(REG_Y_INDEX, getByteOfMemoryAt(nextProgramWord()));
break;
case LDY_ABS_IX:
registers.setRegisterAndFlags(REG_Y_INDEX, getByteOfMemoryXIndexedAt(nextProgramWord()));
break;
case LDA_I:
registers.setRegisterAndFlags(REG_ACCUMULATOR, nextProgramByte());
break;
case LDA_Z:
registers.setRegisterAndFlags(REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramByte()));
break;
case LDA_Z_IX:
registers.setRegisterAndFlags(REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramByte()));
break;
case LDA_ABS:
registers.setRegisterAndFlags(REG_ACCUMULATOR, getByteOfMemoryAt(nextProgramWord()));
break;
case LDA_ABS_IY:
registers.setRegisterAndFlags(REG_ACCUMULATOR, getByteOfMemoryYIndexedAt(nextProgramWord()));
break;
case LDA_ABS_IX:
registers.setRegisterAndFlags(REG_ACCUMULATOR, getByteOfMemoryXIndexedAt(nextProgramWord()));
break;
case LDA_IND_IX: {
//TODO this needs to be wrappable for zero page addressing
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
registers.setRegisterAndFlags(REG_ACCUMULATOR, getByteOfMemoryAt(pointerLocation));
}break;
case LDA_IND_IY: {
final int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
registers.setRegisterAndFlags(REG_ACCUMULATOR, getByteOfMemoryAt(pointerLocation));
}break;
case AND_Z:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramByte(), this::performAND);
break;
case AND_ABS:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramWord(), this::performAND);
break;
case AND_I:
withRegisterAndByte(REG_ACCUMULATOR, nextProgramByte(), this::performAND);
break;
case AND_Z_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramByte(), this::performAND);
break;
case AND_ABS_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performAND);
break;
case AND_ABS_IY:
withRegisterAndByteYIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performAND);
break;
case AND_IND_IX: {
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performAND);
}break;
case AND_IND_IY: {
int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performAND);
}break;
case BIT_Z:
performBIT(getByteOfMemoryAt(nextProgramByte()));
break;
case BIT_ABS:
performBIT(getByteOfMemoryAt(nextProgramWord()));
break;
case ORA_I:
withRegisterAndByte(REG_ACCUMULATOR, nextProgramByte(), this::performORA);
break;
case ORA_Z:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramByte(), this::performORA);
break;
case ORA_Z_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramByte(), this::performORA);
break;
case ORA_ABS:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramWord(), this::performORA);
break;
case ORA_ABS_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performORA);
break;
case ORA_ABS_IY:
withRegisterAndByteYIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performORA);
break;
case ORA_IND_IX: {
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performORA);
}break;
case ORA_IND_IY: {
int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performORA);
}break;
case EOR_I:
withRegisterAndByte(REG_ACCUMULATOR, nextProgramByte(), this::performEOR);
break;
case EOR_Z:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramByte(), this::performEOR);
break;
case EOR_Z_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramByte(), this::performEOR);
break;
case EOR_ABS:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramWord(), this::performEOR);
break;
case EOR_ABS_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performEOR);
break;
case EOR_ABS_IY:
withRegisterAndByteYIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performEOR);
break;
case EOR_IND_IX: {
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performEOR);
}break;
case EOR_IND_IY: {
int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performEOR);
}break;
case ADC_Z:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramByte(), this::performADC);
break;
case ADC_I:
withRegisterAndByte(REG_ACCUMULATOR, nextProgramByte(), this::performADC);
break;
case ADC_ABS:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramWord(), this::performADC);
break;
case ADC_ABS_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performADC);
break;
case ADC_ABS_IY:
withRegisterAndByteYIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performADC);
break;
case ADC_Z_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramByte(), this::performADC);
break;
case ADC_IND_IX: {
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performADC);
}break;
case ADC_IND_IY: {
int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performADC);
}break;
case CMP_I:
performCMP(nextProgramByte(), REG_ACCUMULATOR);
break;
case CMP_Z:
performCMP(getByteOfMemoryAt(nextProgramByte()), REG_ACCUMULATOR);
break;
case CMP_Z_IX:
performCMP(getByteOfMemoryXIndexedAt(nextProgramByte()), REG_ACCUMULATOR);
break;
case CMP_ABS:
performCMP(getByteOfMemoryAt(nextProgramWord()), REG_ACCUMULATOR);
break;
case CMP_ABS_IX:
performCMP(getByteOfMemoryXIndexedAt(nextProgramWord()), REG_ACCUMULATOR);
break;
case CMP_ABS_IY:
performCMP(getByteOfMemoryYIndexedAt(nextProgramWord()), REG_ACCUMULATOR);
break;
case CMP_IND_IX: {
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
performCMP(getByteOfMemoryAt(pointerLocation), REG_ACCUMULATOR);
}break;
case CMP_IND_IY: {
int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
performCMP(getByteOfMemoryAt(pointerLocation), REG_ACCUMULATOR);
}break;
case CPX_I:
performCMP(nextProgramByte(), REG_X_INDEX);
break;
case CPX_Z:
performCMP(getByteOfMemoryAt(nextProgramByte()), REG_X_INDEX);
break;
case CPX_ABS:
performCMP(getByteOfMemoryAt(nextProgramWord()), REG_X_INDEX);
break;
case CPY_I:
performCMP(nextProgramByte(), REG_Y_INDEX);
break;
case CPY_Z:
performCMP(getByteOfMemoryAt(nextProgramByte()), REG_Y_INDEX);
break;
case CPY_ABS:
performCMP(getByteOfMemoryAt(nextProgramWord()), REG_Y_INDEX);
break;
case SBC_I:
withRegisterAndByte(REG_ACCUMULATOR, nextProgramByte(), this::performSBC);
break;
case SBC_Z:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramByte(), this::performSBC);
break;
case SBC_Z_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramByte(), this::performSBC);
break;
case SBC_ABS:
withRegisterAndByteAt(REG_ACCUMULATOR, nextProgramWord(), this::performSBC);
break;
case SBC_ABS_IX:
withRegisterAndByteXIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performSBC);
break;
case SBC_ABS_IY:
withRegisterAndByteYIndexedAt(REG_ACCUMULATOR, nextProgramWord(), this::performSBC);
break;
case SBC_IND_IX: {
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performSBC);
}break;
case SBC_IND_IY: {
int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
withRegisterAndByteAt(REG_ACCUMULATOR, pointerLocation, this::performSBC);
}break;
case STY_Z:
setByteOfMemoryAt(nextProgramByte(), getRegisterValue(REG_Y_INDEX));
break;
case STY_ABS:
setByteOfMemoryAt(nextProgramWord(), getRegisterValue(REG_Y_INDEX));
break;
case STY_Z_IX:
setByteOfMemoryXIndexedAt(nextProgramByte(), getRegisterValue(REG_Y_INDEX));
break;
case STA_Z:
setByteOfMemoryAt(nextProgramByte(), getRegisterValue(REG_ACCUMULATOR));
break;
case STA_ABS:
setByteOfMemoryAt(nextProgramWord(), getRegisterValue(REG_ACCUMULATOR));
break;
case STA_Z_IX:
setByteOfMemoryXIndexedAt(nextProgramByte(), getRegisterValue(REG_ACCUMULATOR));
break;
case STA_ABS_IX:
setByteOfMemoryXIndexedAt(nextProgramWord(), getRegisterValue(REG_ACCUMULATOR));
break;
case STA_ABS_IY:
setByteOfMemoryYIndexedAt(nextProgramWord(), getRegisterValue(REG_ACCUMULATOR));
break;
case STA_IND_IX: {
int pointerLocation = getWordOfMemoryXIndexedAt(nextProgramByte());
setByteOfMemoryAt(pointerLocation, getRegisterValue(REG_ACCUMULATOR));
}break;
case STA_IND_IY: {
int pointerLocation = getWordOfMemoryAt(nextProgramByte()) + getRegisterValue(REG_Y_INDEX);
setByteOfMemoryAt(pointerLocation, getRegisterValue(REG_ACCUMULATOR));
}break;
case STX_Z:
setByteOfMemoryAt(nextProgramByte(), getRegisterValue(REG_X_INDEX));
break;
case STX_Z_IY:
setByteOfMemoryYIndexedAt(nextProgramByte(), getRegisterValue(REG_X_INDEX));
break;
case STX_ABS:
setByteOfMemoryAt(nextProgramWord(), getRegisterValue(REG_X_INDEX));
break;
case PHA:
pushRegister(REG_ACCUMULATOR);
break;
case PLA:
registers.setRegisterAndFlags(REG_ACCUMULATOR, pop());
break;
case PHP:
pushRegister(REG_STATUS);
break;
case PLP:
registers.setRegister(REG_STATUS, pop());
break;
case JMP_ABS: {
int h = nextProgramByte();
int l = nextProgramByte();
registers.setRegister(REG_PC_HIGH, h);
setRegisterValue(REG_PC_LOW, l);
}break;
case JMP_IND: {
final RoxByte h = RoxByte.fromLiteral(nextProgramByte());
final RoxByte l = RoxByte.fromLiteral(nextProgramByte());
int pointer = RoxWord.from(h,l).getAsInt();
registers.setPC(getWordOfMemoryAt(pointer));
}break;
case BCS:
branchIf(registers.getFlag(C));
break;
case BCC:
branchIf(!registers.getFlag(C));
break;
case BEQ:
branchIf(registers.getFlag(Z));
break;
case BNE:
branchIf(!registers.getFlag(Z));
break;
case BMI:
branchIf(registers.getFlag(N));
break;
case JSR:
int hi = nextProgramByte();
int lo = nextProgramByte();
pushRegister(REG_PC_HIGH);
pushRegister(REG_PC_LOW);
setRegisterValue(REG_PC_HIGH, hi);
setRegisterValue(REG_PC_LOW, lo);
break;
case BPL:
branchIf(!registers.getFlag(N));
break;
case BVS:
branchIf(registers.getFlag(V));
break;
case BVC:
branchIf(!registers.getFlag(V));
break;
case TAX:
setRegisterValue(REG_X_INDEX, getRegisterValue(REG_ACCUMULATOR));
break;
case TAY:
setRegisterValue(REG_Y_INDEX, getRegisterValue(REG_ACCUMULATOR));
break;
case TYA:
setRegisterValue(REG_ACCUMULATOR, getRegisterValue(REG_Y_INDEX));
break;
case TXA:
setRegisterValue(REG_ACCUMULATOR, getRegisterValue(REG_X_INDEX));
break;
case TXS:
setRegisterValue(REG_SP, getRegisterValue(REG_X_INDEX));
break;
case TSX:
setRegisterValue(REG_X_INDEX, getRegisterValue(REG_SP));
registers.setFlagsBasedOn(getRegisterValue(REG_X_INDEX));
break;
case NOP:
//Do nothing
break;
case SEI:
registers.setFlag(I);
break;
case CLI:
registers.clearFlag(I);
break;
case SED:
registers.setFlag(D);
break;
case CLD:
registers.clearFlag(D);
break;
case RTS:
setRegisterValue(REG_PC_LOW, pop());
setRegisterValue(REG_PC_HIGH, pop());
break;
case RTI:
setRegisterValue(REG_STATUS, pop());
setRegisterValue(REG_PC_LOW, pop());
setRegisterValue(REG_PC_HIGH, pop());
break;
}
}
private int getRegisterValue(int registerID){
return registers.getRegister(registerID);
}
private void setRegisterValue(int registerID, int value){
registers.setRegister(registerID, value);
}
/**
* Get the value of the 16 bit Program Counter (PC) and increment
*/
private int getAndStepPC(){
final int originalPC = registers.getPC();
registers.setPC(originalPC + 1);
return originalPC;
}
/**
* Return the next byte from program memory, as defined
* by the Program Counter.<br/>
* <br/>
* <em>Increments the Program Counter by 1</em>
*
* @return byte {@code from mem[ PC[0] ]}
*/
private int nextProgramByte(){
int memoryLocation = getAndStepPC();
return getByteOfMemoryAt(memoryLocation);
}
/**
* Combine the next two bytes in program memory, as defined by
* the Program Counter into a word so that:-
*
* PC[0] = high order byte
* PC[1] = low order byte
*<br/><br/>
* <em>Increments the Program Counter by 1</em>
*
* @return word made up of both bytes
*/
private int nextProgramWord(){
int byte1 = nextProgramByte();
return RoxWord.from(RoxByte.fromLiteral(byte1),
RoxByte.fromLiteral(nextProgramByte())).getAsInt();
}
/**
* Pop value from stack
*
* @return popped value
*/
private int pop(){
setRegisterValue(REG_SP, getRegisterValue(REG_SP) + 1);
int address = 0x0100 | getRegisterValue(REG_SP);
int value = getByteOfMemoryAt(address);
LOG.debug("POP " + value + "(0b" + Integer.toBinaryString(value) + ") from mem[0x" + Integer.toHexString(address).toUpperCase() + "]");
return value;
}
private void pushRegister(int registerID){
push(getRegisterValue(registerID));
}
/**
* Push to stack
*
* @param value value to push
*/
private void push(int value){
LOG.debug("PUSH " + value + "(0b" + Integer.toBinaryString(value) + ") to mem[0x" + Integer.toHexString(getRegisterValue(REG_SP)).toUpperCase() + "]");
setByteOfMemoryAt(0x0100 | getRegisterValue(REG_SP), value);
setRegisterValue(REG_SP, getRegisterValue(REG_SP) - 1);
}
private int getByteOfMemoryXIndexedAt(int location){
return getByteOfMemoryAt(location, getRegisterValue(REG_X_INDEX));
}
private int getByteOfMemoryYIndexedAt(int location){
return getByteOfMemoryAt(location, getRegisterValue(REG_Y_INDEX));
}
private void setByteOfMemoryYIndexedAt(int location, int newByte){
setByteOfMemoryAt(location, getRegisterValue(REG_Y_INDEX), newByte);
}
private int getByteOfMemoryAt(int location){
return getByteOfMemoryAt(location, 0);
}
private int getByteOfMemoryAt(int location, int index){
final int memoryByte = memory.getByte(location + index);
LOG.debug("Got 0x" + Integer.toHexString(memoryByte) + " from mem[" + location + (index != 0 ? "[" + index + "]" : "") +"]");
return memoryByte;
}
private void setByteOfMemoryXIndexedAt(int location, int newByte){
setByteOfMemoryAt(location, getRegisterValue(REG_X_INDEX), newByte);
}
private void setByteOfMemoryAt(int location, int newByte){
setByteOfMemoryAt(location, 0, newByte);
}
private void setByteOfMemoryAt(int location, int index, int newByte){
memory.setByteAt(location + index, newByte);
LOG.debug("Stored 0x" + Integer.toHexString(newByte) + " at mem[" + location + (index != 0 ? "[" + index + "]" : "") +"]");
}
private int getWordOfMemoryXIndexedAt(int location){
int indexedLocation = location + getRegisterValue(REG_X_INDEX);
return getWordOfMemoryAt(indexedLocation);
}
private int getWordOfMemoryAt(int location) {
int memoryWord = memory.getWord(location);
LOG.debug("Got 0x" + Integer.toHexString(memoryWord) + " from mem[" + location +"]");
return memoryWord;
}
/**
* Call {@link Mos6502#branchTo(int)} with next program byte
*
* @param condition if {@code true} then branch is followed
*/
private void branchIf(boolean condition){
int location = nextProgramByte();
LOG.debug("{Branch:0x" + Integer.toHexString(registers.getPC()) + " by " + Integer.toBinaryString(location) + "} " + (condition ? "YES->" : "NO..."));
if (condition) branchTo(location);
}
/**
* Branch to a relative location as defined by a signed byte
*
* @param displacement relative (-127 → 128) location from end of branch instruction
*/
private void branchTo(int displacement) {
//possible improvement?
// int v = performSilently(this::performADC, getRegisterValue(REG_PC_LOW), displacement, registers.getFlag(STATUS_FLAG_CARRY));
// setRegisterValue(REG_PC_LOW, v);
final RoxByte displacementByte = RoxByte.fromLiteral(displacement);
if (displacementByte.isNegative())
setRegisterValue(REG_PC_LOW, getRegisterValue(REG_PC_LOW) - displacementByte.asOnesCompliment().getRawValue());
else
setRegisterValue(REG_PC_LOW, getRegisterValue(REG_PC_LOW) + displacementByte.getRawValue());
}
private int fromOnesComplimented(int byteValue){
return ((~byteValue)) & 0xFF;
}
private int fromTwosComplimented(int byteValue){
return fromOnesComplimented(byteValue) - 1;
}
private void performCMP(int value, int toRegister){
int result = performSilently(this::performSBC, getRegisterValue(toRegister), value, true);
registers.setFlagsBasedOn(result & 0xFF);
registers.setFlagTo(C, (fromTwosComplimented(result) >=0));
}
@FunctionalInterface
private interface SingleByteOperation {
int perform(int byteValue);
}
private void withByteAt(int location, SingleByteOperation singleByteOperation){
int b = getByteOfMemoryAt(location);
setByteOfMemoryAt(location, singleByteOperation.perform(b));
}
private void withByteXIndexedAt(int location, SingleByteOperation singleByteOperation){
int b = getByteOfMemoryXIndexedAt(location);
setByteOfMemoryXIndexedAt(location, singleByteOperation.perform(b));
}
private void withRegister(int registerId, SingleByteOperation singleByteOperation){
int b = getRegisterValue(registerId);
setRegisterValue(registerId, singleByteOperation.perform(b));
}
private int performASL(int byteValue){
int newValue = alu.asl(RoxByte.fromLiteral(byteValue)).getRawValue();
registers.setFlagsBasedOn(newValue);
return newValue;
}
private int performROL(int initialValue){
int rotatedValue = alu.rol(RoxByte.fromLiteral(initialValue)).getRawValue();
registers.setFlagsBasedOn(rotatedValue);
return rotatedValue;
}
private int performROR(int initialValue){
int rotatedValue = alu.ror(RoxByte.fromLiteral(initialValue)).getRawValue();
registers.setFlagsBasedOn(rotatedValue);
return rotatedValue;
}
private int performLSR(int initialValue){
int rotatedValue = alu.lsr(RoxByte.fromLiteral(initialValue)).getRawValue();
registers.setFlagsBasedOn(rotatedValue);
return rotatedValue;
}
private int performINC(int initialValue){
int incrementedValue = performSilently(this::performADC, initialValue, 1,false);
registers.setFlagsBasedOn(incrementedValue);
return incrementedValue;
}
private int performDEC(int initialValue){
int incrementedValue = performSilently(this::performSBC, initialValue, 1,true);
registers.setFlagsBasedOn(incrementedValue);
return incrementedValue;
}
private void performBIT(int memData) {
registers.setFlagTo(Z, ((memData & getRegisterValue(REG_ACCUMULATOR)) == memData));
//Set N, V to bits 7 and 6 of memory data
setRegisterValue(REG_STATUS, (memData & 0b11000000) | (getRegisterValue(REG_STATUS) & 0b00111111));
}
@FunctionalInterface
private interface TwoByteOperation {
int perform(int byteValueOne, int byteValueTwo);
}
/**
* Perform byteA given operation and have the state of the registers be the same as before the operation was performed
*
* @param operation operation to perform
* @param byteA byte A to pass into the operation
* @param byteB byte B to pass into the operation
* @param carryInState the state in which to assume the carry flag is in at the start of the operation
* @return the result of the operation.
*/
private int performSilently(TwoByteOperation operation, int byteA, int byteB, boolean carryInState){
int statusState = registers.getRegister(REG_STATUS);
registers.setFlagTo(C, carryInState); //To allow ignore of the carry: ignore = 0 for ADC, 1 for SBC
int result = operation.perform(byteA, byteB);
registers.setRegister(REG_STATUS, statusState);
return result;
}
private void withRegisterAndByteAt(int registerId, int memoryLocation, TwoByteOperation twoByteOperation){
withRegisterAndByte(registerId, getByteOfMemoryAt(memoryLocation), twoByteOperation);
}
private void withRegisterAndByteXIndexedAt(int registerId, int memoryLocation, TwoByteOperation twoByteOperation){
withRegisterAndByte(registerId, getByteOfMemoryXIndexedAt(memoryLocation), twoByteOperation);
}
private void withRegisterAndByteYIndexedAt(int registerId, int memoryLocation, TwoByteOperation twoByteOperation){
withRegisterAndByte(registerId, getByteOfMemoryYIndexedAt(memoryLocation), twoByteOperation);
}
private void withRegisterAndByte(int registerId, int byteValue, TwoByteOperation twoByteOperation){
int registerByte = getRegisterValue(registerId);
registers.setRegisterAndFlags(registerId, twoByteOperation.perform(registerByte, byteValue));
}
private int performAND(int byteValueA, int byteValueB){
return alu.and(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue();
}
private int performEOR(int byteValueA, int byteValueB){
return alu.xor(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue();
}
private int performORA(int byteValueA, int byteValueB){
return alu.or(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue();
}
private int performADC(int byteValueA, int byteValueB){
return alu.adc(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue();
}
private int performSBC(int byteValueA, int byteValueB){
return alu.sbc(RoxByte.fromLiteral(byteValueA), RoxByte.fromLiteral(byteValueB)).getRawValue();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.