diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/apps/BOB/src/net/i2p/BOB/BOB.java b/apps/BOB/src/net/i2p/BOB/BOB.java
index 2c42a9834..0229932a1 100644
--- a/apps/BOB/src/net/i2p/BOB/BOB.java
+++ b/apps/BOB/src/net/i2p/BOB/BOB.java
@@ -1,238 +1,239 @@
/**
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* Version 2, December 2004
*
* Copyright (C) sponge
* Planet Earth
* Everyone is permitted to copy and distribute verbatim or modified
* copies of this license document, and changing it is allowed as long
* as the name is changed.
*
* DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
* TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
*
* 0. You just DO WHAT THE FUCK YOU WANT TO.
*
* See...
*
* http://sam.zoy.org/wtfpl/
* and
* http://en.wikipedia.org/wiki/WTFPL
*
* ...for any additional details and liscense questions.
*/
package net.i2p.BOB;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Properties;
import net.i2p.client.I2PClient;
import net.i2p.client.streaming.RetransmissionTimer;
import net.i2p.util.Log;
import net.i2p.util.SimpleTimer;
/**
* <span style="font-size:8px;font-family:courier;color:#EEEEEE;background-color:#000000">
* ################################################################################<br>
* ############################.#..........#..#..........##########################<br>
* #######################......................................###################<br>
* ####################...........................#.......#........################<br>
* #################..................##...................#.........##############<br>
* ###############................###...####.....#..###.....#.........#############<br>
* #############...........###..#..###...#####...###.##........#.......############<br>
* ###########................#......##...#####...##..##.......#..#........########<br>
* ##########.........................#....##.##..#...##.....................######<br>
* #########...................................#....#.........................#####<br>
* ########.........................................#...............#..........####<br>
* ########.........................................#..........#######..........###<br>
* #######.................................................############..........##<br>
* #######..........................................####################.........##<br>
* #######............####################......########################.........##<br>
* ######.............###############################################.##.........##<br>
* ######............################################################..##........##<br>
* ######............################################################..##........##<br>
* ######.............##############################################..##.........##<br>
* ######............##############################################...##..........#<br>
* ######............#..###########################################...##..........#<br>
* ######.............#############################################....#..........#<br>
* #######...........###############################################..##.........##<br>
* #######...........#####.#.#.#.########################.....#.####...##........##<br>
* ######............#..............##################.................##.........#<br>
* ######................####.........###############........#####......##........#<br>
* ######..............####..#.........############.......##.#.######...##.......##<br>
* ######.................#.####.........########...........##....###...##.......##<br>
* #######....#....###...................#######...............#...###..##.......##<br>
* #######.........###..###.....###.......######.##.#####.........####..##.......##<br>
* #######.....#...##############.........############......###########.###......##<br>
* #######....##...##########.......##...##############......#.############.....###<br>
* ########....#..########......######...##################################....####<br>
* ########....##.####################...##################################....####<br>
* ########..#.##..###################..##################################..#..####<br>
* ##########..###..#################...##################################...#.####<br>
* #########....##...##############....########..#####.################.##..#.#####<br>
* ############.##....##########.......#########.###.......###########..#.#########<br>
* ###############.....#######...#.......########.....##.....######.....###########<br>
* ###############......###....##..........##.......######....#.........#.#########<br>
* ##############............##..................##########..............##########<br>
* ##############..............................##########..#.............##########<br>
* ###############.......##..................#####..............####....###########<br>
* ###############.......#####.......#.............####.....#######.....###########<br>
* ################...#...####......##################.....########....############<br>
* ################...##..#####.........####.##.....#....##########....############<br>
* ##################..##..####...........#####.#....############.....#############<br>
* ##################......#####.................################....##############<br>
* ###################.....####..........##########..###########....###############<br>
* ####################..#..#..........................########.....###############<br>
* #####################.##.......###.................########....#################<br>
* ######################.........#.......#.##.###############....#################<br>
* #############.#######...............#####################....###################<br>
* ###..#.....##...####..........#.....####################....####################<br>
* ####......##........................##################....######################<br>
* #.##...###..............###.........###############......#######################<br>
* #...###..##............######...........................########################<br>
* ##.......###..........##########....#...#...........############################<br>
* ##.........##.......############################################################<br>
* ###........##.....##############################################################<br>
* ####.............###############################################################<br>
* ######.........#################################################################<br>
* #########....###################################################################<br>
* ################################################################################<br>
* </span>
* BOB, main command socket listener, launches the command parser engine.
*
* @author sponge
*/
public class BOB {
private final static Log _log = new Log(BOB.class);
public final static String PROP_CONFIG_LOCATION = "BOB.config";
public final static String PROP_BOB_PORT = "BOB.port";
public final static String PROP_BOB_HOST = "BOB.host";
private static int maxConnections = 0;
private static NamedDB database;
private static Properties props = new Properties();
/**
* Log a warning
*
* @param arg
*/
public static void info(String arg) {
System.out.println("INFO:" + arg);
_log.info(arg);
}
/**
* Log a warning
*
* @param arg
*/
public static void warn(String arg) {
System.out.println("WARNING:" + arg);
_log.warn(arg);
}
/**
* Log an error
*
* @param arg
*/
public static void error(String arg) {
System.out.println("ERROR: " + arg);
_log.error(arg);
}
/**
* Listen for incoming connections and handle them
*
* @param args
*/
public static void main(String[] args) {
database = new NamedDB();
int i = 0;
boolean save = false;
// Set up all defaults to be passed forward to other threads.
// Re-reading the config file in each thread is pretty damn stupid.
// I2PClient client = I2PClientFactory.createClient();
String configLocation = System.getProperty(PROP_CONFIG_LOCATION, "bob.config");
// This is here just to ensure there is no interference with our threadgroups.
SimpleTimer Y = RetransmissionTimer.getInstance();
i = Y.hashCode();
{
try {
FileInputStream fi = new FileInputStream(configLocation);
props.load(fi);
fi.close();
} catch(FileNotFoundException fnfe) {
warn("Unable to load up the BOB config file " + configLocation + ", Using defaults.");
warn(fnfe.toString());
save = true;
} catch(IOException ioe) {
warn("IOException on BOB config file " + configLocation + ", using defaults.");
warn(ioe.toString());
}
}
// Global router and client API configurations that are missing are set to defaults here.
if(!props.containsKey(I2PClient.PROP_TCP_HOST)) {
props.setProperty(I2PClient.PROP_TCP_HOST, "localhost");
}
if(!props.containsKey(I2PClient.PROP_TCP_PORT)) {
props.setProperty(I2PClient.PROP_TCP_PORT, "7654");
}
if(!props.containsKey(I2PClient.PROP_RELIABILITY)) {
props.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_BEST_EFFORT);
}
if(!props.containsKey(PROP_BOB_PORT)) {
props.setProperty(PROP_BOB_PORT, "2827"); // 0xB0B
}
if(!props.containsKey("inbound.length")) {
props.setProperty("inbound.length", "1");
}
if(!props.containsKey("outbound.length")) {
props.setProperty("outbound.length", "1");
}
if(!props.containsKey("inbound.lengthVariance")) {
props.setProperty("inbound.lengthVariance", "0");
}
if(!props.containsKey("outbound.lengthVariance")) {
props.setProperty("outbound.lengthVariance", "0");
}
if(!props.containsKey(PROP_BOB_HOST)) {
props.setProperty(PROP_BOB_HOST, "localhost");
}
if(save) {
try {
warn("Writing new defaults file " + configLocation);
FileOutputStream fo = new FileOutputStream(configLocation);
props.store(fo, configLocation);
fo.close();
} catch(IOException ioe) {
error("IOException on BOB config file " + configLocation + ", " + ioe);
}
}
+ i = 0;
try {
info("BOB is now running.");
ServerSocket listener = new ServerSocket(Integer.parseInt(props.getProperty(PROP_BOB_PORT)), 10, InetAddress.getByName(props.getProperty(PROP_BOB_HOST)));
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)) {
//DoCMDS connection;
server = listener.accept();
DoCMDS conn_c = new DoCMDS(server, props, database, _log);
Thread t = new Thread(conn_c);
t.start();
}
} catch(IOException ioe) {
error("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
| true | true | public static void main(String[] args) {
database = new NamedDB();
int i = 0;
boolean save = false;
// Set up all defaults to be passed forward to other threads.
// Re-reading the config file in each thread is pretty damn stupid.
// I2PClient client = I2PClientFactory.createClient();
String configLocation = System.getProperty(PROP_CONFIG_LOCATION, "bob.config");
// This is here just to ensure there is no interference with our threadgroups.
SimpleTimer Y = RetransmissionTimer.getInstance();
i = Y.hashCode();
{
try {
FileInputStream fi = new FileInputStream(configLocation);
props.load(fi);
fi.close();
} catch(FileNotFoundException fnfe) {
warn("Unable to load up the BOB config file " + configLocation + ", Using defaults.");
warn(fnfe.toString());
save = true;
} catch(IOException ioe) {
warn("IOException on BOB config file " + configLocation + ", using defaults.");
warn(ioe.toString());
}
}
// Global router and client API configurations that are missing are set to defaults here.
if(!props.containsKey(I2PClient.PROP_TCP_HOST)) {
props.setProperty(I2PClient.PROP_TCP_HOST, "localhost");
}
if(!props.containsKey(I2PClient.PROP_TCP_PORT)) {
props.setProperty(I2PClient.PROP_TCP_PORT, "7654");
}
if(!props.containsKey(I2PClient.PROP_RELIABILITY)) {
props.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_BEST_EFFORT);
}
if(!props.containsKey(PROP_BOB_PORT)) {
props.setProperty(PROP_BOB_PORT, "2827"); // 0xB0B
}
if(!props.containsKey("inbound.length")) {
props.setProperty("inbound.length", "1");
}
if(!props.containsKey("outbound.length")) {
props.setProperty("outbound.length", "1");
}
if(!props.containsKey("inbound.lengthVariance")) {
props.setProperty("inbound.lengthVariance", "0");
}
if(!props.containsKey("outbound.lengthVariance")) {
props.setProperty("outbound.lengthVariance", "0");
}
if(!props.containsKey(PROP_BOB_HOST)) {
props.setProperty(PROP_BOB_HOST, "localhost");
}
if(save) {
try {
warn("Writing new defaults file " + configLocation);
FileOutputStream fo = new FileOutputStream(configLocation);
props.store(fo, configLocation);
fo.close();
} catch(IOException ioe) {
error("IOException on BOB config file " + configLocation + ", " + ioe);
}
}
try {
info("BOB is now running.");
ServerSocket listener = new ServerSocket(Integer.parseInt(props.getProperty(PROP_BOB_PORT)), 10, InetAddress.getByName(props.getProperty(PROP_BOB_HOST)));
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)) {
//DoCMDS connection;
server = listener.accept();
DoCMDS conn_c = new DoCMDS(server, props, database, _log);
Thread t = new Thread(conn_c);
t.start();
}
} catch(IOException ioe) {
error("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
| public static void main(String[] args) {
database = new NamedDB();
int i = 0;
boolean save = false;
// Set up all defaults to be passed forward to other threads.
// Re-reading the config file in each thread is pretty damn stupid.
// I2PClient client = I2PClientFactory.createClient();
String configLocation = System.getProperty(PROP_CONFIG_LOCATION, "bob.config");
// This is here just to ensure there is no interference with our threadgroups.
SimpleTimer Y = RetransmissionTimer.getInstance();
i = Y.hashCode();
{
try {
FileInputStream fi = new FileInputStream(configLocation);
props.load(fi);
fi.close();
} catch(FileNotFoundException fnfe) {
warn("Unable to load up the BOB config file " + configLocation + ", Using defaults.");
warn(fnfe.toString());
save = true;
} catch(IOException ioe) {
warn("IOException on BOB config file " + configLocation + ", using defaults.");
warn(ioe.toString());
}
}
// Global router and client API configurations that are missing are set to defaults here.
if(!props.containsKey(I2PClient.PROP_TCP_HOST)) {
props.setProperty(I2PClient.PROP_TCP_HOST, "localhost");
}
if(!props.containsKey(I2PClient.PROP_TCP_PORT)) {
props.setProperty(I2PClient.PROP_TCP_PORT, "7654");
}
if(!props.containsKey(I2PClient.PROP_RELIABILITY)) {
props.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_BEST_EFFORT);
}
if(!props.containsKey(PROP_BOB_PORT)) {
props.setProperty(PROP_BOB_PORT, "2827"); // 0xB0B
}
if(!props.containsKey("inbound.length")) {
props.setProperty("inbound.length", "1");
}
if(!props.containsKey("outbound.length")) {
props.setProperty("outbound.length", "1");
}
if(!props.containsKey("inbound.lengthVariance")) {
props.setProperty("inbound.lengthVariance", "0");
}
if(!props.containsKey("outbound.lengthVariance")) {
props.setProperty("outbound.lengthVariance", "0");
}
if(!props.containsKey(PROP_BOB_HOST)) {
props.setProperty(PROP_BOB_HOST, "localhost");
}
if(save) {
try {
warn("Writing new defaults file " + configLocation);
FileOutputStream fo = new FileOutputStream(configLocation);
props.store(fo, configLocation);
fo.close();
} catch(IOException ioe) {
error("IOException on BOB config file " + configLocation + ", " + ioe);
}
}
i = 0;
try {
info("BOB is now running.");
ServerSocket listener = new ServerSocket(Integer.parseInt(props.getProperty(PROP_BOB_PORT)), 10, InetAddress.getByName(props.getProperty(PROP_BOB_HOST)));
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)) {
//DoCMDS connection;
server = listener.accept();
DoCMDS conn_c = new DoCMDS(server, props, database, _log);
Thread t = new Thread(conn_c);
t.start();
}
} catch(IOException ioe) {
error("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
|
diff --git a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java
index 153b31f..9602664 100644
--- a/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java
+++ b/org.eclipse.mylyn.tests/src/org/eclipse/mylyn/tests/integration/ChangeDataDirTest.java
@@ -1,309 +1,309 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.tests.integration;
import java.io.File;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.mylar.context.core.InteractionEvent;
import org.eclipse.mylar.internal.bugzilla.core.BugzillaTask;
import org.eclipse.mylar.internal.context.core.MylarContextManager;
import org.eclipse.mylar.monitor.usage.MylarUsageMonitorPlugin;
import org.eclipse.mylar.tasks.core.AbstractRepositoryTask;
import org.eclipse.mylar.tasks.core.ITask;
import org.eclipse.mylar.tasks.core.Task;
import org.eclipse.mylar.tasks.ui.TaskListManager;
import org.eclipse.mylar.tasks.ui.TasksUiPlugin;
/**
* Tests changes to the main mylar data directory location.
*
* @author Wesley Coelho
* @author Mik Kersten (rewrites)
*/
public class ChangeDataDirTest extends TestCase {
private String newDataDir = null;
private final String defaultDir = TasksUiPlugin.getDefault().getDefaultDataDirectory();
private TaskListManager manager = TasksUiPlugin.getTaskListManager();
protected void setUp() throws Exception {
super.setUp();
newDataDir = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ ChangeDataDirTest.class.getSimpleName();
File dir = new File(newDataDir);
dir.mkdir();
dir.deleteOnExit();
manager.resetTaskList();
assertTrue(manager.getTaskList().isEmpty());
TasksUiPlugin.getDefault().getTaskListSaveManager().saveTaskList(true);
}
protected void tearDown() throws Exception {
super.tearDown();
manager.resetTaskList();
TasksUiPlugin.getDefault().setDataDirectory(defaultDir);
}
public void testMonitorFileMove() {
MylarUsageMonitorPlugin.getDefault().startMonitoring();
MylarUsageMonitorPlugin.getDefault().getInteractionLogger().interactionObserved(
InteractionEvent.makeCommand("id", "delta"));
String oldPath = MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(oldPath).exists());
TasksUiPlugin.getDefault().setDataDirectory(newDataDir);
assertFalse(new File(oldPath).exists());
String newPath = MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(newPath).exists());
assertTrue(MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().exists());
- String monitorFileName = MylarUsageMonitorPlugin.MONITOR_LOG_NAME + MylarContextManager.OLD_CONTEXT_FILE_EXTENSION;
+ String monitorFileName = MylarUsageMonitorPlugin.MONITOR_LOG_NAME + MylarContextManager.CONTEXT_FILE_EXTENSION_OLD;
List<String> newFiles = Arrays.asList(new File(newDataDir).list());
assertTrue(newFiles.toString(), newFiles.contains(monitorFileName));
List<String> filesLeft = Arrays.asList(new File(defaultDir).list());
assertFalse(filesLeft.toString(), filesLeft.contains(monitorFileName));
MylarUsageMonitorPlugin.getDefault().stopMonitoring();
}
public void testDefaultDataDirectoryMove() {
String workspaceRelativeDir = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ ".mylar";
assertEquals(defaultDir, workspaceRelativeDir);
TasksUiPlugin.getDefault().setDataDirectory(newDataDir);
assertEquals(TasksUiPlugin.getDefault().getDataDirectory(), newDataDir);
}
public void testTaskMove() {
String handle = "task-1";
ITask task = new Task(handle, "label", true);
manager.getTaskList().moveToRoot(task);
ITask readTaskBeforeMove = manager.getTaskList().getTask(handle);
TasksUiPlugin.getDefault().getTaskListSaveManager().copyDataDirContentsTo(newDataDir);
TasksUiPlugin.getDefault().setDataDirectory(newDataDir);
ITask readTaskAfterMove = manager.getTaskList().getTask(handle);
assertNotNull(readTaskAfterMove);
assertEquals(readTaskBeforeMove.getCreationDate(), readTaskAfterMove.getCreationDate());
}
// TODO: delete? using lastOpened date wrong
public void testBugzillaTaskMove() {
String handle = AbstractRepositoryTask.getHandle("server", 1);
BugzillaTask bugzillaTask = new BugzillaTask(handle, "bug1", true);
String refreshDate = (new Date()).toString();
bugzillaTask.setLastSyncDateStamp(refreshDate);
addBugzillaTask(bugzillaTask);
BugzillaTask readTaskBeforeMove = (BugzillaTask) manager.getTaskList().getTask(handle);
assertNotNull(readTaskBeforeMove);
assertEquals(refreshDate, readTaskBeforeMove.getLastSyncDateStamp());
TasksUiPlugin.getDefault().getTaskListSaveManager().copyDataDirContentsTo(newDataDir);
TasksUiPlugin.getDefault().setDataDirectory(newDataDir);
BugzillaTask readTaskAfterMove = (BugzillaTask) manager.getTaskList().getTask(handle);
assertNotNull(readTaskAfterMove);
assertEquals(refreshDate, readTaskAfterMove.getLastSyncDateStamp());
}
private void addBugzillaTask(BugzillaTask newTask) {
// AbstractRepositoryClient client =
// MylarTaskListPlugin.getRepositoryManager().getRepositoryClient(BugzillaPlugin.REPOSITORY_KIND);
// client.addTaskToArchive(newTask);
// TODO: put back?
// MylarTaskListPlugin.getTaskListManager().getTaskList().internalAddTask(newTask);
// BugzillaTaskHandler handler = new BugzillaTaskHandler();
// handler.addTaskToArchive(newTask);
TasksUiPlugin.getTaskListManager().getTaskList().moveToRoot(newTask);
}
// /**
// * Tests moving the main mylar data directory to another location (Without
// * copying existing data to the new directory)
// */
// public void testChangeMainDataDir() {
//
// ITask mainDataDirTask = createAndSaveTask("Main Task", false);
//
// // ContextCorePlugin.getDefault().setDataDirectory(newDataDir);
// assertEquals(0, manager.getTaskList().getRootTasks().size());
//
// // Check that the main data dir task isn't in the list or the folder
// File taskFile = new File(ContextCorePlugin.getDefault().getDataDirectory() +
// File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertFalse(taskFile.exists());
// assertNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(),
// false));
//
// // Check that a newly created task appears in the right place (method
// // will check)
// ITask newDataDirTask = createAndSaveTask("New Data Dir", false);
// taskFile = new File(ContextCorePlugin.getDefault().getDataDirectory() +
// File.separator
// + newDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check for other the tasklist file in the new dir
// File destTaskListFile = new
// File(ContextCorePlugin.getDefault().getDataDirectory() + File.separator
// + MylarTaskListPlugin.DEFAULT_TASK_LIST_FILE);
// assertTrue(destTaskListFile.exists());
//
// // Switch back to the main task directory
// ContextCorePlugin.getDefault().setDataDirectory(ContextCorePlugin.getDefault().getDefaultDataDirectory());
//
// // Check that the previously created main dir task is in the task list
// and its file exists
// assertNotNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(),
// false));
// taskFile = new File(ContextCorePlugin.getDefault().getDataDirectory() +
// File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check that the task created in the "New Data Dir" isn't there now
// // that we're back to the main dir
// assertNull(manager.getTaskForHandle(newDataDirTask.getHandleIdentifier(),
// false));
//
// }
//
// /**
// * Creates a task with an interaction event and checks that it has been
// * properly saved in the currently active data directory
// */
// protected ITask createAndSaveTask(String taskName, boolean
// createBugzillaTask) {
//
// // Create the task and add it to the root of the task list
// BugzillaTask newTask = null;
// if (!createBugzillaTask) {
// String handle =
// MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle();
// newTask = new BugzillaTask(handle, "bug1", true, true);//new
// Task(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(),
// taskName, true);
// manager.moveToRoot(newTask);
// } else {
// newTask = new
// BugzillaTask(MylarTaskListPlugin.getTaskListManager().genUniqueTaskHandle(),
// taskName, true,
// true);
// addBugzillaTask(newTask);
// }
//
// MylarContext mockContext =
// ContextCorePlugin.getContextManager().loadContext(newTask.getHandleIdentifier(),
// newTask.getContextPath());
// InteractionEvent event = new InteractionEvent(InteractionEvent.Kind.EDIT,
// "structureKind", "handle", "originId");
// mockContext.parseEvent(event);
// ContextCorePlugin.getContextManager().contextActivated(mockContext);
//
// // Save the context file and check that it exists
// ContextCorePlugin.getContextManager().saveContext(mockContext.getId(),
// newTask.getContextPath());
// File taskFile = new File(ContextCorePlugin.getDefault().getDataDirectory() +
// File.separator
// + newTask.getContextPath() + MylarContextManager.CONTEXT_FILE_EXTENSION);
// assertTrue(ContextCorePlugin.getContextManager().hasContext(newTask.getContextPath()));
// assertTrue(taskFile.exists());
//
// return newTask;
// }
//
// /**
// * Same as above but using bugzilla tasks Tests moving the main mylar data
// * directory to another location (Without copying existing data to the new
// * directory)
// */
// public void testChangeMainDataDirBugzilla() {
//
// // Create a task in the main dir and context with an interaction event
// // to be saved
// ITask mainDataDirTask = createAndSaveTask("Main Task", true);
//
// // Set time to see if the right task data is returned by the registry
// // mechanism
// mainDataDirTask.setElapsedTime(ELAPSED_TIME1);
//
// // Save tasklist
// MylarTaskListPlugin.getDefault().getTaskListSaveManager().saveTaskListAndContexts();
//
// // Temp check that the task is there
// assertNotNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(),
// false));
//
// // Switch task directory
// ContextCorePlugin.getDefault().setDataDirectory(newDataDir);
//
// // Check that there are no tasks in the tasklist after switching to the
// // empty dir
// assertTrue(manager.getTaskList().getRootTasks().size() == 0);
//
// // Check that the main data dir task isn't in the list or the folder
// File taskFile = new File(ContextCorePlugin.getDefault().getDataDirectory() +
// File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertFalse(taskFile.exists());
// assertNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(),
// false));
//
// // Check that a newly created task appears in the right place (method
// // will check)
// ITask newDataDirTask = createAndSaveTask("New Data Dir", true);
// taskFile = new File(ContextCorePlugin.getDefault().getDataDirectory() +
// File.separator
// + newDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check for tasklist file in the new dir
// File destTaskListFile = new
// File(ContextCorePlugin.getDefault().getDataDirectory() + File.separator
// + MylarTaskListPlugin.DEFAULT_TASK_LIST_FILE);
// assertTrue(destTaskListFile.exists());
//
// ContextCorePlugin.getDefault().setDataDirectory(ContextCorePlugin.getDefault().getDefaultDataDirectory());
//
// // Check that the previously created main dir task is in the task list
// // and its file exists
// assertNotNull(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(),
// false));
// taskFile = new File(ContextCorePlugin.getDefault().getDataDirectory() +
// File.separator
// + mainDataDirTask.getContextPath() + MylarTaskListPlugin.FILE_EXTENSION);
// assertTrue(taskFile.exists());
//
// // Check that the elapsed time is still right
// assertTrue(manager.getTaskForHandle(mainDataDirTask.getHandleIdentifier(),
// false).getElapsedTime() == ELAPSED_TIME1);
//
// // Check that the task created in the "New Data Dir" isn't there now
// // that we're back to the main dir
// assertNull(manager.getTaskForHandle(newDataDirTask.getHandleIdentifier(),
// false));
// }
}
| true | true | public void testMonitorFileMove() {
MylarUsageMonitorPlugin.getDefault().startMonitoring();
MylarUsageMonitorPlugin.getDefault().getInteractionLogger().interactionObserved(
InteractionEvent.makeCommand("id", "delta"));
String oldPath = MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(oldPath).exists());
TasksUiPlugin.getDefault().setDataDirectory(newDataDir);
assertFalse(new File(oldPath).exists());
String newPath = MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(newPath).exists());
assertTrue(MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().exists());
String monitorFileName = MylarUsageMonitorPlugin.MONITOR_LOG_NAME + MylarContextManager.OLD_CONTEXT_FILE_EXTENSION;
List<String> newFiles = Arrays.asList(new File(newDataDir).list());
assertTrue(newFiles.toString(), newFiles.contains(monitorFileName));
List<String> filesLeft = Arrays.asList(new File(defaultDir).list());
assertFalse(filesLeft.toString(), filesLeft.contains(monitorFileName));
MylarUsageMonitorPlugin.getDefault().stopMonitoring();
}
| public void testMonitorFileMove() {
MylarUsageMonitorPlugin.getDefault().startMonitoring();
MylarUsageMonitorPlugin.getDefault().getInteractionLogger().interactionObserved(
InteractionEvent.makeCommand("id", "delta"));
String oldPath = MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(oldPath).exists());
TasksUiPlugin.getDefault().setDataDirectory(newDataDir);
assertFalse(new File(oldPath).exists());
String newPath = MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().getAbsolutePath();
assertTrue(new File(newPath).exists());
assertTrue(MylarUsageMonitorPlugin.getDefault().getInteractionLogger().getOutputFile().exists());
String monitorFileName = MylarUsageMonitorPlugin.MONITOR_LOG_NAME + MylarContextManager.CONTEXT_FILE_EXTENSION_OLD;
List<String> newFiles = Arrays.asList(new File(newDataDir).list());
assertTrue(newFiles.toString(), newFiles.contains(monitorFileName));
List<String> filesLeft = Arrays.asList(new File(defaultDir).list());
assertFalse(filesLeft.toString(), filesLeft.contains(monitorFileName));
MylarUsageMonitorPlugin.getDefault().stopMonitoring();
}
|
diff --git a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/support/RestUtils.java b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/support/RestUtils.java
index 028465eaa43..375c702900e 100644
--- a/modules/elasticsearch/src/main/java/org/elasticsearch/rest/support/RestUtils.java
+++ b/modules/elasticsearch/src/main/java/org/elasticsearch/rest/support/RestUtils.java
@@ -1,72 +1,71 @@
/*
* Licensed to Elastic Search and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Elastic Search licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.support;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Map;
/**
* @author kimchy (shay.banon)
*/
public class RestUtils {
public static void decodeQueryString(String queryString, int fromIndex, Map<String, String> params) {
if (fromIndex < 0) {
return;
}
if (fromIndex >= queryString.length()) {
return;
}
int toIndex;
while ((toIndex = queryString.indexOf('&', fromIndex)) >= 0) {
int idx = queryString.indexOf('=', fromIndex);
- if (idx < 0) {
- continue;
+ if (fromIndex < idx && idx < toIndex) {
+ params.put(decodeComponent(queryString.substring(fromIndex, idx)), decodeComponent(queryString.substring(idx + 1, toIndex)));
}
- params.put(decodeComponent(queryString.substring(fromIndex, idx)), decodeComponent(queryString.substring(idx + 1, toIndex)));
fromIndex = toIndex + 1;
}
int idx = queryString.indexOf('=', fromIndex);
if (idx < 0) {
return;
}
params.put(decodeComponent(queryString.substring(fromIndex, idx)), decodeComponent(queryString.substring(idx + 1)));
}
public static String decodeComponent(String s) {
if (s == null) {
return "";
}
int numChars = s.length();
for (int i = 0; i < numChars; i++) {
// do an initial check if it requires decoding do it and return
if (s.charAt(i) == '+' || s.charAt(i) == '%') {
try {
return URLDecoder.decode(s, "UTF8");
} catch (UnsupportedEncodingException e) {
throw new UnsupportedCharsetException("UTF8");
}
}
}
return s;
}
}
| false | true | public static void decodeQueryString(String queryString, int fromIndex, Map<String, String> params) {
if (fromIndex < 0) {
return;
}
if (fromIndex >= queryString.length()) {
return;
}
int toIndex;
while ((toIndex = queryString.indexOf('&', fromIndex)) >= 0) {
int idx = queryString.indexOf('=', fromIndex);
if (idx < 0) {
continue;
}
params.put(decodeComponent(queryString.substring(fromIndex, idx)), decodeComponent(queryString.substring(idx + 1, toIndex)));
fromIndex = toIndex + 1;
}
int idx = queryString.indexOf('=', fromIndex);
if (idx < 0) {
return;
}
params.put(decodeComponent(queryString.substring(fromIndex, idx)), decodeComponent(queryString.substring(idx + 1)));
}
| public static void decodeQueryString(String queryString, int fromIndex, Map<String, String> params) {
if (fromIndex < 0) {
return;
}
if (fromIndex >= queryString.length()) {
return;
}
int toIndex;
while ((toIndex = queryString.indexOf('&', fromIndex)) >= 0) {
int idx = queryString.indexOf('=', fromIndex);
if (fromIndex < idx && idx < toIndex) {
params.put(decodeComponent(queryString.substring(fromIndex, idx)), decodeComponent(queryString.substring(idx + 1, toIndex)));
}
fromIndex = toIndex + 1;
}
int idx = queryString.indexOf('=', fromIndex);
if (idx < 0) {
return;
}
params.put(decodeComponent(queryString.substring(fromIndex, idx)), decodeComponent(queryString.substring(idx + 1)));
}
|
diff --git a/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/editor/DefaultEditorManager.java b/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/editor/DefaultEditorManager.java
index 2a50599c2..1d7262077 100644
--- a/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/editor/DefaultEditorManager.java
+++ b/orbisgis-core/src/main/java/org/orbisgis/core/ui/plugins/views/editor/DefaultEditorManager.java
@@ -1,147 +1,144 @@
/*
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information. OrbisGIS is
* distributed under GPL 3 license. It is produced by the "Atelier SIG" team of
* the IRSTV Institute <http://www.irstv.cnrs.fr/> CNRS FR 2488.
*
*
* Team leader Erwan BOCHER, scientific researcher,
*
* User support leader : Gwendall Petit, geomatic engineer.
*
*
* Copyright (C) 2007 Erwan BOCHER, Fernando GONZALEZ CORTES, Thomas LEDUC
*
* Copyright (C) 2010 Erwan BOCHER, Pierre-Yves FADET, Alexis GUEGANNO, Maxence LAURENT
*
* This file is part of OrbisGIS.
*
* OrbisGIS is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* OrbisGIS is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
*
* or contact directly:
* erwan.bocher _at_ ec-nantes.fr
* gwendall.petit _at_ ec-nantes.fr
*/
package org.orbisgis.core.ui.plugins.views.editor;
import org.apache.log4j.Logger;
import org.orbisgis.core.edition.EditableElement;
import org.orbisgis.core.edition.EditableElementException;
import org.orbisgis.core.ui.editor.EditorDecorator;
import org.orbisgis.core.ui.editor.EditorListener;
import org.orbisgis.core.ui.editor.IEditor;
import org.orbisgis.progress.IProgressMonitor;
public class DefaultEditorManager implements EditorManager {
private static final Logger logger = Logger
.getLogger(DefaultEditorManager.class);
private EditorPanel editorPanel;
public EditorPanel getEditorPanel() {
return editorPanel;
}
public DefaultEditorManager(EditorPanel editor) {
this.editorPanel = editor;
}
public EditableElement getActiveElement() {
return editorPanel.getCurrentDocument();
}
public IEditor getActiveEditor() {
if (editorPanel.getCurrentEditor() == null) {
return null;
} else {
return editorPanel.getCurrentEditor().getEditor();
}
}
public boolean closeEditor(IEditor editor) {
return this.editorPanel.closeEditor(editor);
}
public IEditor[] getEditors() {
return editorPanel.getEditors();
}
@Override
public boolean hasEditor(EditableElement element) {
return EditorPanel.hasEditor(element);
}
@Override
public void open(EditableElement element, IProgressMonitor pm)
throws UnsupportedOperationException {
EditorDecorator editor = EditorPanel.getFirstEditor(element);
if (editor == null) {
throw new UnsupportedOperationException(
"There is no suitable editor for this element");
} else {
if (!this.editorPanel.isBeingEdited(element, editor.getEditor()
.getClass())) {
try {
element.open(pm);
editor.setElement(element);
} catch (EditableElementException e) {
- logger.debug(
- "Cannot open the document: " + element.getId(), e);
- editor = new EditorDecorator(new ErrorEditor(element
- .getId(), e.getMessage()), null, "");
+ throw new UnsupportedOperationException("There was an error opening the element.",e);
}
this.editorPanel.addEditor(editor);
} else {
this.editorPanel.showEditor(element, editor.getEditor()
.getClass());
}
}
}
@Override
public IEditor[] getEditor(EditableElement element) {
return this.editorPanel.getEditor(element);
}
@Override
public String getEditorId(IEditor editor) {
return editorPanel.getEditorId(editor);
}
@Override
public void addEditorListener(EditorListener listener) {
editorPanel.addEditorListener(listener);
}
@Override
public void removeEditorListener(EditorListener listener) {
editorPanel.removeEditorListener(listener);
}
@Override
public IEditor[] getEditors(String editorId, Object object) {
return editorPanel.getEditors(editorId, object);
}
@Override
public IEditor[] getEditors(String editorId) {
return editorPanel.getEditors(editorId);
}
}
| true | true | public void open(EditableElement element, IProgressMonitor pm)
throws UnsupportedOperationException {
EditorDecorator editor = EditorPanel.getFirstEditor(element);
if (editor == null) {
throw new UnsupportedOperationException(
"There is no suitable editor for this element");
} else {
if (!this.editorPanel.isBeingEdited(element, editor.getEditor()
.getClass())) {
try {
element.open(pm);
editor.setElement(element);
} catch (EditableElementException e) {
logger.debug(
"Cannot open the document: " + element.getId(), e);
editor = new EditorDecorator(new ErrorEditor(element
.getId(), e.getMessage()), null, "");
}
this.editorPanel.addEditor(editor);
} else {
this.editorPanel.showEditor(element, editor.getEditor()
.getClass());
}
}
}
| public void open(EditableElement element, IProgressMonitor pm)
throws UnsupportedOperationException {
EditorDecorator editor = EditorPanel.getFirstEditor(element);
if (editor == null) {
throw new UnsupportedOperationException(
"There is no suitable editor for this element");
} else {
if (!this.editorPanel.isBeingEdited(element, editor.getEditor()
.getClass())) {
try {
element.open(pm);
editor.setElement(element);
} catch (EditableElementException e) {
throw new UnsupportedOperationException("There was an error opening the element.",e);
}
this.editorPanel.addEditor(editor);
} else {
this.editorPanel.showEditor(element, editor.getEditor()
.getClass());
}
}
}
|
diff --git a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java
index 5d0d5f7f..422936a2 100644
--- a/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java
+++ b/src/main/java/org/cloudifysource/quality/iTests/test/cli/cloudify/cloud/ec2/dynamicstorage/AbstractDynamicStorageTest.java
@@ -1,149 +1,149 @@
package org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.ec2.dynamicstorage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;
import org.apache.commons.io.FileUtils;
import org.cloudifysource.quality.iTests.framework.utils.AssertUtils;
import org.cloudifysource.quality.iTests.framework.utils.Ec2StorageApiForRegionHelper;
import org.cloudifysource.quality.iTests.framework.utils.IOUtils;
import org.cloudifysource.quality.iTests.framework.utils.LogUtils;
import org.cloudifysource.quality.iTests.framework.utils.ScriptUtils;
import org.cloudifysource.quality.iTests.test.cli.cloudify.CommandTestUtils;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.NewAbstractCloudTest;
import org.cloudifysource.quality.iTests.test.cli.cloudify.cloud.services.ec2.Ec2CloudService;
import org.jclouds.ec2.domain.Volume;
import org.jclouds.ec2.domain.Volume.Status;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
public abstract class AbstractDynamicStorageTest extends NewAbstractCloudTest {
private static final long VOLUME_WAIT_TIMEOUT = 3 * 60 * 1000;
private static final String PATH_TO_SERVICE = CommandTestUtils.getPath("/src/main/resources/apps/USM/usm/dynamicstorage/");;
protected static final String SERVICE_NAME = "groovy";
protected Ec2StorageApiForRegionHelper storageHelper;
public abstract void doTest() throws Exception ;
public abstract String getServiceFolder();
@Override
protected void bootstrap() throws Exception {
super.bootstrap();
Ec2CloudService ec2CloudService = (Ec2CloudService)getService();
this.storageHelper = new Ec2StorageApiForRegionHelper(ec2CloudService.getRegion(), ec2CloudService.getComputeServiceContext());
}
@BeforeMethod
public void prepareService() throws IOException {
String buildRecipesServicesPath = ScriptUtils.getBuildRecipesServicesPath();
File serviceFolder = new File(buildRecipesServicesPath, getServiceFolder());
if (serviceFolder.exists()) {
FileUtils.deleteDirectory(serviceFolder);
}
FileUtils.copyDirectoryToDirectory( new File(PATH_TO_SERVICE + "/" + getServiceFolder()), new File(buildRecipesServicesPath));
}
public void testUbuntu() throws Exception {
setTemplate("SMALL_UBUNTU", false);
doTest();
}
public void testLinux(final boolean useManagement) throws Exception {
setTemplate("SMALL_LINUX", useManagement);
doTest();
}
public void testLinux() throws Exception {
testLinux(true);
}
@Override
protected void customizeCloud() throws Exception {
super.customizeCloud();
((Ec2CloudService)getService()).getAdditionalPropsToReplace().put("cloudify-storage-volume", System.getProperty("user.name") + "-" + this.getClass().getSimpleName().toLowerCase());
}
public void scanForLeakedVolumes(final String name) throws TimeoutException {
Set<Volume> volumesByName = storageHelper.getVolumesByName(name);
Set<Volume> nonDeletingVolumes = new HashSet<Volume>();
for (Volume volumeByName : volumesByName) {
if (volumeByName != null && !volumeByName.getStatus().equals(Status.DELETING)) {
LogUtils.log("Found a leaking volume " + volumeByName + ". status is " + volumeByName.getStatus());
LogUtils.log("Volume attachments are : " + volumeByName.getAttachments());
if (volumeByName.getAttachments() != null && !volumeByName.getAttachments().isEmpty()) {
LogUtils.log("Detaching attachment before deletion");
storageHelper.detachVolume(volumeByName.getId());
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
}
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
LogUtils.log("Deleting volume " + volumeByName.getId());
storageHelper.deleteVolume(volumeByName.getId());
} else {
nonDeletingVolumes.add(volumeByName);
}
}
if (!nonDeletingVolumes.isEmpty()) {
- AssertUtils.assertFail("Found leaking volumes after test ended :" + volumesByName);
+ AssertUtils.assertFail("Found leaking volumes after test ended :" + nonDeletingVolumes);
}
}
public void scanForLeakedVolumesCreatedViaTemplate(final String templateName) throws TimeoutException {
final String name = getService().getCloud().getCloudStorage().getTemplates().get(templateName).getNamePrefix();
scanForLeakedVolumes(name);
}
private void waitForVolumeStatus(final Volume vol, final Status status) throws TimeoutException {
final long end = System.currentTimeMillis() + VOLUME_WAIT_TIMEOUT;
while (System.currentTimeMillis() < end) {
Volume volume = storageHelper.getVolumeById(vol.getId());
if (volume.getStatus().equals(status)) {
return;
} else {
try {
LogUtils.log("Waiting for volume " + vol.getId()
+ " to reach status " + status + " . current status is : " + volume.getStatus());
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
}
throw new TimeoutException("Timed out waiting for volume " + vol + " to reach status " + status);
}
@AfterMethod
public void deleteService() throws IOException {
FileUtils.deleteDirectory(new File(ScriptUtils.getBuildRecipesServicesPath() + "/" + getServiceFolder()));
}
protected void setTemplate(final String computeTemplateName, boolean useManagement) throws Exception {
File serviceFile = new File(ScriptUtils.getBuildRecipesServicesPath() + "/" + getServiceFolder(), SERVICE_NAME + "-service.groovy");
Map<String, String> props = new HashMap<String,String>();
props.put("ENTER_TEMPLATE", computeTemplateName);
if (!useManagement) {
props.put("useManagement true", "useManagement false");
}
IOUtils.replaceTextInFile(serviceFile.getAbsolutePath(), props);
}
}
| true | true | public void scanForLeakedVolumes(final String name) throws TimeoutException {
Set<Volume> volumesByName = storageHelper.getVolumesByName(name);
Set<Volume> nonDeletingVolumes = new HashSet<Volume>();
for (Volume volumeByName : volumesByName) {
if (volumeByName != null && !volumeByName.getStatus().equals(Status.DELETING)) {
LogUtils.log("Found a leaking volume " + volumeByName + ". status is " + volumeByName.getStatus());
LogUtils.log("Volume attachments are : " + volumeByName.getAttachments());
if (volumeByName.getAttachments() != null && !volumeByName.getAttachments().isEmpty()) {
LogUtils.log("Detaching attachment before deletion");
storageHelper.detachVolume(volumeByName.getId());
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
}
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
LogUtils.log("Deleting volume " + volumeByName.getId());
storageHelper.deleteVolume(volumeByName.getId());
} else {
nonDeletingVolumes.add(volumeByName);
}
}
if (!nonDeletingVolumes.isEmpty()) {
AssertUtils.assertFail("Found leaking volumes after test ended :" + volumesByName);
}
}
| public void scanForLeakedVolumes(final String name) throws TimeoutException {
Set<Volume> volumesByName = storageHelper.getVolumesByName(name);
Set<Volume> nonDeletingVolumes = new HashSet<Volume>();
for (Volume volumeByName : volumesByName) {
if (volumeByName != null && !volumeByName.getStatus().equals(Status.DELETING)) {
LogUtils.log("Found a leaking volume " + volumeByName + ". status is " + volumeByName.getStatus());
LogUtils.log("Volume attachments are : " + volumeByName.getAttachments());
if (volumeByName.getAttachments() != null && !volumeByName.getAttachments().isEmpty()) {
LogUtils.log("Detaching attachment before deletion");
storageHelper.detachVolume(volumeByName.getId());
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
}
waitForVolumeStatus(volumeByName, Status.AVAILABLE);
LogUtils.log("Deleting volume " + volumeByName.getId());
storageHelper.deleteVolume(volumeByName.getId());
} else {
nonDeletingVolumes.add(volumeByName);
}
}
if (!nonDeletingVolumes.isEmpty()) {
AssertUtils.assertFail("Found leaking volumes after test ended :" + nonDeletingVolumes);
}
}
|
diff --git a/moria2/modules/moria-log/src/java/no/feide/moria/log/AccessLogger.java b/moria2/modules/moria-log/src/java/no/feide/moria/log/AccessLogger.java
index 348bb0a7..c9803c24 100644
--- a/moria2/modules/moria-log/src/java/no/feide/moria/log/AccessLogger.java
+++ b/moria2/modules/moria-log/src/java/no/feide/moria/log/AccessLogger.java
@@ -1,149 +1,149 @@
/*
* Copyright (c) 2004 UNINETT FAS
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place - Suite 330, Boston, MA 02111-1307, USA.
*
* $Id$
*
*/
package no.feide.moria.log;
import java.io.Serializable;
import org.apache.log4j.Logger;
/**
* Logs system events in a strict format that may later
* be used for usage statistics generation.
*
* Logging is done at log4j level WARN. If the loglevel of
* log4j is set above this, no log-entries will be written.
*
* The format of the log-lines is the following:
* <pre>
* [2004-04-30 17:10:19,046] "BAD USER CREDENTIALS" "no.feide.test" "[email protected]" "235892791" "350215527"
*
* [Timestamp] "STATUS" "service principal" "userid" "incoming ticket" "outgoing ticket"
* </pre>
*
* @author Bj�rn Ola Smievoll <[email protected]>
* @version $Revision$
*/
public final class AccessLogger implements Serializable {
/**
* The name of this logger.
* Same for all classes, so we can be redirect output to a common file.
*/
private static final Class ACCESS_LOGGER_CLASS = AccessLogger.class;
/**
* Log to this logger.
* Transient so the class can be serialized.
*/
private transient Logger logger = null;
/**
* Default constructor.
*/
public AccessLogger() {
this.logger = Logger.getLogger(ACCESS_LOGGER_CLASS);
}
/**
* Used for logging user-inititated access (user interaction through the
* web interface).
*
* @param status
* indicates the type of event
* @param servicePrincipal
* the id of the service that is responsible for this operation
* @param userId
* the id of the user, may be null if unknow at time of event
* @param incomingTicketId
* the id of the ticket given with the request
* @param outgoingTicketId
* the id of the potentially returned ticket, may be null
*/
public void logUser(final AccessStatusType status, final String servicePrincipal, final String userId,
final String incomingTicketId, final String outgoingTicketId) {
/* Generate the log message and log it. */
getLogger().warn(generateLogMessage(status, servicePrincipal, userId, incomingTicketId, outgoingTicketId));
}
/**
* Used for logging service-inititated access.
*
* @param status
* indicates the type of event
* @param servicePrincipal
* the id of the service that is peforming the operation
* @param incomingTicketId
* the id of the ticket given with the request
* @param outgoingTicketId
* the id of the potentially returned ticket, may be null
*/
public void logService(final AccessStatusType status, final String servicePrincipal, final String incomingTicketId,
final String outgoingTicketId) {
/* Generate the log message and log it. */
getLogger().warn(generateLogMessage(status, servicePrincipal, null, incomingTicketId, outgoingTicketId));
}
/**
* Generates log messages in the correct format.
*
* @param status
* indicates the type of event
* @param servicePrincipal
* the id of the service that is peforming the operation
* @param userId
* the id of the user
* @param incomingTicketId
* the id of the ticket given with the request
* @param outgoingTicketId
* the id of the potentially returned ticket, may be null
* @return the string to be logged
*/
private String generateLogMessage(final AccessStatusType status, final String servicePrincipal, final String userId,
final String incomingTicketId, final String outgoingTicketId) {
StringBuffer buffer = new StringBuffer();
/* Add default value "-" if variabel is null */
buffer.append(status != null ? "\"" + status + "\" " : "\"-\" ");
buffer.append(servicePrincipal != null ? "\"" + servicePrincipal + "\" " : "\"-\" ");
buffer.append(userId != null ? "\"" + userId + "\"" : "\"-\"");
buffer.append(incomingTicketId != null ? "\"" + incomingTicketId + "\" " : "\"-\" ");
- buffer.append(outgoingTicketId != null ? "\"" + outgoingTicketId + "\"" : "\"-\"");
+ buffer.append(outgoingTicketId != null ? "\"" + outgoingTicketId + "\" " : "\"-\" ");
return buffer.toString();
}
/**
* Returns the logger, instanciates it if not already so.
* Private so that nobody overrides the formatting that is done by
* generateLogMessage.
*
* @return the logger instance of this class
*/
private Logger getLogger() {
if (logger == null)
logger = Logger.getLogger(ACCESS_LOGGER_CLASS);
return logger;
}
}
| true | true | private String generateLogMessage(final AccessStatusType status, final String servicePrincipal, final String userId,
final String incomingTicketId, final String outgoingTicketId) {
StringBuffer buffer = new StringBuffer();
/* Add default value "-" if variabel is null */
buffer.append(status != null ? "\"" + status + "\" " : "\"-\" ");
buffer.append(servicePrincipal != null ? "\"" + servicePrincipal + "\" " : "\"-\" ");
buffer.append(userId != null ? "\"" + userId + "\"" : "\"-\"");
buffer.append(incomingTicketId != null ? "\"" + incomingTicketId + "\" " : "\"-\" ");
buffer.append(outgoingTicketId != null ? "\"" + outgoingTicketId + "\"" : "\"-\"");
return buffer.toString();
}
| private String generateLogMessage(final AccessStatusType status, final String servicePrincipal, final String userId,
final String incomingTicketId, final String outgoingTicketId) {
StringBuffer buffer = new StringBuffer();
/* Add default value "-" if variabel is null */
buffer.append(status != null ? "\"" + status + "\" " : "\"-\" ");
buffer.append(servicePrincipal != null ? "\"" + servicePrincipal + "\" " : "\"-\" ");
buffer.append(userId != null ? "\"" + userId + "\"" : "\"-\"");
buffer.append(incomingTicketId != null ? "\"" + incomingTicketId + "\" " : "\"-\" ");
buffer.append(outgoingTicketId != null ? "\"" + outgoingTicketId + "\" " : "\"-\" ");
return buffer.toString();
}
|
diff --git a/app/controllers/BlogController.java b/app/controllers/BlogController.java
index b2c2305..24687d9 100644
--- a/app/controllers/BlogController.java
+++ b/app/controllers/BlogController.java
@@ -1,223 +1,223 @@
package controllers;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Set;
import java.util.TreeSet;
import models.Tag;
import models.blog.Post;
import models.blog.PostRef;
import models.user.GAppUser;
import models.user.User;
import play.data.validation.Validation;
import play.mvc.Controller;
import play.mvc.With;
import play.vfs.VirtualFile;
/**
*
* @author clementnivolle
* @author keruspe
*/
@With(Secure.class)
public class BlogController extends Controller {
/**
* Ask confirmation for deleting a Post
* @param urlId The urlId of the Post
* @param language The lang of the Post
*/
public static void deletePost_confirm(String urlId, String language) {
Post post = Post.getPostByLocale(urlId, new Locale(language));
render(post);
}
/**
* Delete a Post
* @param urlId The urlId of the Post
* @param language The lang of the Post
*/
public static void deletePost(String urlId, String language) {
Post post = Post.getPostByLocale(urlId, new Locale(language));
if (post == null) {
return;
}
PostRef postRef = post.reference;
post.delete();
if (Post.getFirstPostByPostRef(postRef) == null) {
postRef.delete();
}
BlogViewer.index();
}
/**
* Create a new Post
*/
public static void newPost() {
renderArgs.put("action", "create");
render();
}
/**
* Edit a Post
* @param urlId The urlId of the Post
* @param language The lang of the Post
*/
public static void edit(String urlId, String language) {
Post otherPost = Post.getPostByLocale(urlId, new Locale(language));
renderArgs.put("otherPost", otherPost);
renderArgs.put("action", "edit");
String overrider = null;
for (Post p : Post.getPostsByPostRef(otherPost.reference)) {
overrider = "/view/PageEvent/edit/" + p.urlId + ".html";
if (VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists()) {
break;
}
}
if (!VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists()) {
overrider = "BlogController/newPost.html";
}
renderTemplate(overrider);
}
/**
* Translate a Post
* @param otherUrlId The urlId of the Post to translate
* @param language The lang of the Post
*/
public static void translate(String otherUrlId, String language) {
Post otherPost = Post.getPostByLocale(otherUrlId, new Locale(language));
renderArgs.put("otherPost", otherPost);
renderArgs.put("action", "translate");
String overrider = null;
for (Post p : Post.getPostsByPostRef(otherPost.reference)) {
overrider = "/view/PageEvent/translate/" + p.urlId + ".html";
if (VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists()) {
break;
}
}
if (!VirtualFile.fromRelativePath("app/views" + overrider).getRealFile().exists()) {
overrider = "BlogController/newPost.html";
}
renderTemplate(overrider);
}
/**
* Create/Edit/Translate a Post
* @param actionz The action we're performing ("edit", "create", "translate")
* @param otherUrlId The urlId of the Post we're translating or editing (may be null)
* @param otherLanguage The lang of the Post we're translating or editing (may be null)
*/
public static void doNewPost(String actionz, String otherUrlId, String otherLanguage) {
String urlId = params.get("post.urlId");
String title = params.get("post.title");
String content = params.get("post.content");
Locale language = params.get("post.language", Locale.class);
Date postedAt = new Date();
String openId = session.get("username");
GAppUser author = GAppUser.getByOpenId(openId);
if (author == null) {
author = new GAppUser();
author.openId = openId;
author.firstName = session.get("firstName");
author.lastName = session.get("lastName");
author.userName = author.firstName + " " + author.lastName;
author.email = session.get("email");
- author.language = new Locale(session.get("language"));
+ author.language = language;
validation.valid(author);
if (Validation.hasErrors()) {
unauthorized("Could not authenticate you");
}
if (actionz.equals("edit")) {
author.refresh().save();
} else {
author.save();
}
}
Post post = Post.getPostByUrlId(otherUrlId);
PostRef postRef = null;
if (post != null) {
postRef = post.reference;
} else {
postRef = BlogController.doNewPostRef(params.get("postReference.tags"), postedAt, author, actionz, otherUrlId, otherLanguage);
}
if (!actionz.equals("edit")) {
post = new Post();
}
post.reference = postRef;
post.author = author;
post.content = content;
post.urlId = urlId;
post.title = title;
post.postedAt = postedAt;
post.language = language;
validation.valid(post);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (actionz.equals("edit")) {
BlogController.edit(urlId, otherLanguage);
} else if (actionz.equals("translate")) {
BlogController.translate(urlId, otherLanguage);
} else {
BlogController.newPost();
}
}
if (actionz.equals("edit")) {
post.reference.refresh().save();
post.refresh().save();
} else {
post.reference.save();
post.save();
}
BlogViewer.index();
}
/**
* Create a PostRef for a new Post
* @param actionz The action we're performing ("edit", "create", "translate")
* @param otherUrlId The urlId of the Post we're translating or editing (may be null)
* @param otherLanguage The lang of the Post we're translating or editing (may be null)
* @return The PostRef
*/
private static PostRef doNewPostRef(String tagsString, Date postedAt, User author, String action, String otherUrlId, String otherLanguage) {
PostRef postRef = new PostRef();
Set<Tag> tags = new TreeSet<Tag>();
Tag t = null;
if (!tagsString.isEmpty()) {
for (String tag : Arrays.asList(tagsString.split(","))) {
t = Tag.findOrCreateByName(tag);
if (!tags.contains(t)) {
tags.add(t);
}
}
}
postRef.tags = tags;
postRef.author = author;
postRef.postedAt = postedAt;
validation.valid(postRef);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (action.equals("edit")) {
BlogController.edit(otherUrlId, otherLanguage);
} else if (action.equals("translate")) {
BlogController.translate(otherUrlId, otherLanguage);
} else {
BlogController.newPost();
}
}
return postRef;
}
}
| true | true | public static void doNewPost(String actionz, String otherUrlId, String otherLanguage) {
String urlId = params.get("post.urlId");
String title = params.get("post.title");
String content = params.get("post.content");
Locale language = params.get("post.language", Locale.class);
Date postedAt = new Date();
String openId = session.get("username");
GAppUser author = GAppUser.getByOpenId(openId);
if (author == null) {
author = new GAppUser();
author.openId = openId;
author.firstName = session.get("firstName");
author.lastName = session.get("lastName");
author.userName = author.firstName + " " + author.lastName;
author.email = session.get("email");
author.language = new Locale(session.get("language"));
validation.valid(author);
if (Validation.hasErrors()) {
unauthorized("Could not authenticate you");
}
if (actionz.equals("edit")) {
author.refresh().save();
} else {
author.save();
}
}
Post post = Post.getPostByUrlId(otherUrlId);
PostRef postRef = null;
if (post != null) {
postRef = post.reference;
} else {
postRef = BlogController.doNewPostRef(params.get("postReference.tags"), postedAt, author, actionz, otherUrlId, otherLanguage);
}
if (!actionz.equals("edit")) {
post = new Post();
}
post.reference = postRef;
post.author = author;
post.content = content;
post.urlId = urlId;
post.title = title;
post.postedAt = postedAt;
post.language = language;
validation.valid(post);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (actionz.equals("edit")) {
BlogController.edit(urlId, otherLanguage);
} else if (actionz.equals("translate")) {
BlogController.translate(urlId, otherLanguage);
} else {
BlogController.newPost();
}
}
if (actionz.equals("edit")) {
post.reference.refresh().save();
post.refresh().save();
} else {
post.reference.save();
post.save();
}
BlogViewer.index();
}
| public static void doNewPost(String actionz, String otherUrlId, String otherLanguage) {
String urlId = params.get("post.urlId");
String title = params.get("post.title");
String content = params.get("post.content");
Locale language = params.get("post.language", Locale.class);
Date postedAt = new Date();
String openId = session.get("username");
GAppUser author = GAppUser.getByOpenId(openId);
if (author == null) {
author = new GAppUser();
author.openId = openId;
author.firstName = session.get("firstName");
author.lastName = session.get("lastName");
author.userName = author.firstName + " " + author.lastName;
author.email = session.get("email");
author.language = language;
validation.valid(author);
if (Validation.hasErrors()) {
unauthorized("Could not authenticate you");
}
if (actionz.equals("edit")) {
author.refresh().save();
} else {
author.save();
}
}
Post post = Post.getPostByUrlId(otherUrlId);
PostRef postRef = null;
if (post != null) {
postRef = post.reference;
} else {
postRef = BlogController.doNewPostRef(params.get("postReference.tags"), postedAt, author, actionz, otherUrlId, otherLanguage);
}
if (!actionz.equals("edit")) {
post = new Post();
}
post.reference = postRef;
post.author = author;
post.content = content;
post.urlId = urlId;
post.title = title;
post.postedAt = postedAt;
post.language = language;
validation.valid(post);
if (Validation.hasErrors()) {
params.flash(); // add http parameters to the flash scope
Validation.keep(); // keep the errors for the next request
if (actionz.equals("edit")) {
BlogController.edit(urlId, otherLanguage);
} else if (actionz.equals("translate")) {
BlogController.translate(urlId, otherLanguage);
} else {
BlogController.newPost();
}
}
if (actionz.equals("edit")) {
post.reference.refresh().save();
post.refresh().save();
} else {
post.reference.save();
post.save();
}
BlogViewer.index();
}
|
diff --git a/app/src/iic3686/rocketscience/GameThread.java b/app/src/iic3686/rocketscience/GameThread.java
index d51c530..1e44690 100644
--- a/app/src/iic3686/rocketscience/GameThread.java
+++ b/app/src/iic3686/rocketscience/GameThread.java
@@ -1,140 +1,141 @@
package iic3686.rocketscience;
import org.andengine.entity.IEntity;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
public class GameThread extends Thread{
private Scene currentScene;
private GameManager gm;
//Game Logic Variables
boolean gameIsRunning;
int levelCounter;
Rectangle orderRectangle;
Rectangle timeRectangle;
//Time counter
int timeCounter;
int errorCounter;
float colorValue;
Sprite loseSplash;
Sprite victorySplash;
//
public GameThread(Scene startScene, GameManager gm, Rectangle orderRectangle, Sprite loseSplash, Sprite victorySplash)
{
this.currentScene = startScene;
this.gm = gm;
this.gameIsRunning = true;
this.levelCounter = 1;
this.orderRectangle = orderRectangle;
this.timeCounter = 0;
this.errorCounter = 0;
this.loseSplash = loseSplash;
this.victorySplash = victorySplash;
this.timeRectangle = (Rectangle)currentScene.getChildByTag(500);
}
public void run() {
while(gameIsRunning)
{
timeCounter = 0;
errorCounter = 0;
while(!this.gm.isRoundOver())
{
//GAME LOOP EL LUP LUP
if(this.gm.currentOrder == null)
this.gm.getNewOrder();
//Create new round
/*if(this.gm.isRoundOver())
{
//Start new round
this.gm.newRound();
}*/
//ERROR CHECK
if(errorCounter > 10)
{
loseSplash.setPosition(0,200);
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loseSplash.setPosition(2000,2000);
this.gm.resetGame();
+ errorCounter = 0;
levelCounter = 1;
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Check to see if the order has changed recently
if(this.gm.hasBeenChangedRecently())
timeCounter = 0;
//Change the text of the buttons if needed
//currentScene
//Change the text of the instruction and check the status
//Background progressive change
if(timeCounter < 5000)
{
//colorValue = (float)0.8+(timeCounter/5000);
//this.orderRectangle.setColor((float)colorValue, 0, 0);
timeRectangle.setWidth((float) (480.0 / 5000)*(5000 - timeCounter));
timeCounter++;
}
else
{
//5 seconds have passed, change mission, increase errorCounter
this.gm.getNewOrder();
errorCounter++;
this.orderRectangle.setColor(1, 1, 1);
timeCounter = 0;
}
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
orderTextLabel.setText(this.gm.getCurrentOrderText());
//IEntity boton1 = currentScene.getChildByTag(10);
//boton1.setVisible(!boton1.isVisible());
//IEntity boton2 = currentScene.getChildByTag(11);
//boton2.setVisible(!boton2.isVisible());
try {
//this.orderRectangle.setColor(1, 1, 1);
this.sleep(1);
//this.orderRectangle.setColor(1, 0, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//END OF ROUND
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
//orderTextLabel.setText("Level Complete!");
victorySplash.setPosition(0,200);
try {
this.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
levelCounter++;
victorySplash.setPosition(2000,2000);
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.gm.newRound();
}
}
}
| true | true | public void run() {
while(gameIsRunning)
{
timeCounter = 0;
errorCounter = 0;
while(!this.gm.isRoundOver())
{
//GAME LOOP EL LUP LUP
if(this.gm.currentOrder == null)
this.gm.getNewOrder();
//Create new round
/*if(this.gm.isRoundOver())
{
//Start new round
this.gm.newRound();
}*/
//ERROR CHECK
if(errorCounter > 10)
{
loseSplash.setPosition(0,200);
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loseSplash.setPosition(2000,2000);
this.gm.resetGame();
levelCounter = 1;
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Check to see if the order has changed recently
if(this.gm.hasBeenChangedRecently())
timeCounter = 0;
//Change the text of the buttons if needed
//currentScene
//Change the text of the instruction and check the status
//Background progressive change
if(timeCounter < 5000)
{
//colorValue = (float)0.8+(timeCounter/5000);
//this.orderRectangle.setColor((float)colorValue, 0, 0);
timeRectangle.setWidth((float) (480.0 / 5000)*(5000 - timeCounter));
timeCounter++;
}
else
{
//5 seconds have passed, change mission, increase errorCounter
this.gm.getNewOrder();
errorCounter++;
this.orderRectangle.setColor(1, 1, 1);
timeCounter = 0;
}
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
orderTextLabel.setText(this.gm.getCurrentOrderText());
//IEntity boton1 = currentScene.getChildByTag(10);
//boton1.setVisible(!boton1.isVisible());
//IEntity boton2 = currentScene.getChildByTag(11);
//boton2.setVisible(!boton2.isVisible());
try {
//this.orderRectangle.setColor(1, 1, 1);
this.sleep(1);
//this.orderRectangle.setColor(1, 0, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//END OF ROUND
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
//orderTextLabel.setText("Level Complete!");
victorySplash.setPosition(0,200);
try {
this.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
levelCounter++;
victorySplash.setPosition(2000,2000);
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.gm.newRound();
}
}
| public void run() {
while(gameIsRunning)
{
timeCounter = 0;
errorCounter = 0;
while(!this.gm.isRoundOver())
{
//GAME LOOP EL LUP LUP
if(this.gm.currentOrder == null)
this.gm.getNewOrder();
//Create new round
/*if(this.gm.isRoundOver())
{
//Start new round
this.gm.newRound();
}*/
//ERROR CHECK
if(errorCounter > 10)
{
loseSplash.setPosition(0,200);
try {
this.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
loseSplash.setPosition(2000,2000);
this.gm.resetGame();
errorCounter = 0;
levelCounter = 1;
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Check to see if the order has changed recently
if(this.gm.hasBeenChangedRecently())
timeCounter = 0;
//Change the text of the buttons if needed
//currentScene
//Change the text of the instruction and check the status
//Background progressive change
if(timeCounter < 5000)
{
//colorValue = (float)0.8+(timeCounter/5000);
//this.orderRectangle.setColor((float)colorValue, 0, 0);
timeRectangle.setWidth((float) (480.0 / 5000)*(5000 - timeCounter));
timeCounter++;
}
else
{
//5 seconds have passed, change mission, increase errorCounter
this.gm.getNewOrder();
errorCounter++;
this.orderRectangle.setColor(1, 1, 1);
timeCounter = 0;
}
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
orderTextLabel.setText(this.gm.getCurrentOrderText());
//IEntity boton1 = currentScene.getChildByTag(10);
//boton1.setVisible(!boton1.isVisible());
//IEntity boton2 = currentScene.getChildByTag(11);
//boton2.setVisible(!boton2.isVisible());
try {
//this.orderRectangle.setColor(1, 1, 1);
this.sleep(1);
//this.orderRectangle.setColor(1, 0, 0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//END OF ROUND
Text orderTextLabel= (Text)currentScene.getChildByTag(1);
//orderTextLabel.setText("Level Complete!");
victorySplash.setPosition(0,200);
try {
this.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
levelCounter++;
victorySplash.setPosition(2000,2000);
orderTextLabel.setText("Get ready for Level "+levelCounter+"!");
try {
this.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
this.gm.newRound();
}
}
|
diff --git a/test/net/fortuna/mstor/connector/ProtocolConnectorFactoryTest.java b/test/net/fortuna/mstor/connector/ProtocolConnectorFactoryTest.java
index 2f452ca..f39e2ed 100644
--- a/test/net/fortuna/mstor/connector/ProtocolConnectorFactoryTest.java
+++ b/test/net/fortuna/mstor/connector/ProtocolConnectorFactoryTest.java
@@ -1,68 +1,70 @@
/*
* $Id$
*
* Created on 08/10/2007
*
* Copyright (c) 2007, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.mstor.connector;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.URLName;
import net.fortuna.mstor.connector.ProtocolConnectorFactory;
import net.fortuna.mstor.connector.jcr.RepositoryConnector;
import net.fortuna.mstor.connector.mbox.MboxConnector;
import junit.framework.TestCase;
/**
* @author Ben
*
*/
public class ProtocolConnectorFactoryTest extends TestCase {
/**
* Test method for {@link net.fortuna.mstor.connector.ProtocolConnectorFactory#create(javax.mail.URLName, net.fortuna.mstor.MStorStore, javax.mail.Session)}.
*/
public void testCreate() {
+ Properties p = new Properties();
assertTrue(ProtocolConnectorFactory.getInstance().create(
new URLName("mstor", null, -1, "/tmp/mbox", null, null),
- null, Session.getDefaultInstance(new Properties())) instanceof MboxConnector);
+ null, Session.getDefaultInstance(p)) instanceof MboxConnector);
+ p.setProperty("mstor.repository.name", "test");
assertTrue(ProtocolConnectorFactory.getInstance().create(
new URLName("mstor", "localhost", -1, "/tmp/mbox", "test", null),
- null, null) instanceof RepositoryConnector);
+ null, Session.getDefaultInstance(p)) instanceof RepositoryConnector);
}
}
| false | true | public void testCreate() {
assertTrue(ProtocolConnectorFactory.getInstance().create(
new URLName("mstor", null, -1, "/tmp/mbox", null, null),
null, Session.getDefaultInstance(new Properties())) instanceof MboxConnector);
assertTrue(ProtocolConnectorFactory.getInstance().create(
new URLName("mstor", "localhost", -1, "/tmp/mbox", "test", null),
null, null) instanceof RepositoryConnector);
}
| public void testCreate() {
Properties p = new Properties();
assertTrue(ProtocolConnectorFactory.getInstance().create(
new URLName("mstor", null, -1, "/tmp/mbox", null, null),
null, Session.getDefaultInstance(p)) instanceof MboxConnector);
p.setProperty("mstor.repository.name", "test");
assertTrue(ProtocolConnectorFactory.getInstance().create(
new URLName("mstor", "localhost", -1, "/tmp/mbox", "test", null),
null, Session.getDefaultInstance(p)) instanceof RepositoryConnector);
}
|
diff --git a/src/com/olympuspvp/tp/olyTP.java b/src/com/olympuspvp/tp/olyTP.java
index ffea579..07b6f1b 100644
--- a/src/com/olympuspvp/tp/olyTP.java
+++ b/src/com/olympuspvp/tp/olyTP.java
@@ -1,67 +1,68 @@
package com.olympuspvp.tp;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.plugin.java.JavaPlugin;
public class olyTP extends JavaPlugin{
final String tag = ChatColor.GOLD + "[" + ChatColor.YELLOW + "olyTP" + ChatColor.GOLD+"] " + ChatColor.YELLOW;
@Override
public void onEnable(){
System.out.println("[olyTP] olyTP by willno123 (badass coderleetzors) has been enabled!");
}
public boolean onCommand(CommandSender s, Command cmd, String c, String[] args){
if(s instanceof Player == false){
System.out.println("[olyTP] Go home console, you're drunk.");
return true;
}Player p = (Player)s;
if((p.isOp()==false)&&(p.hasPermission("olyTP.use")==false)){
p.sendMessage(tag+"You do not have permission to use this command.");
}
if(args.length==1){
String to = args[0];
List<Player> matches = Bukkit.matchPlayer(to);
if(matches.size() !=1){
p.sendMessage(tag+"The player could not be found.");
return true;
}Player pto=matches.get(0);
if(p==pto){
p.sendMessage(tag+"You cannot teleport to yourself.");
return true;
}p.teleport(pto, TeleportCause.PLUGIN);
p.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName());
if(p.isOp() || p.hasPermission("olyTP.use")) pto.sendMessage(tag+ ChatColor.GOLD + p.getName() + ChatColor.YELLOW + " teleported to you.");
}else if(args.length == 2){
String to = args[1];
String from = args[0];
List<Player> matches = Bukkit.matchPlayer(to);
if(matches.size() !=1){
p.sendMessage(tag + to + " could not be found.");
return true;
}
Player pto = matches.get(0);
matches = Bukkit.matchPlayer(from);
if(matches.size() !=1){
p.sendMessage(tag + from + " could not be found.");
+ return true;
}
Player pfrom = matches.get(0);
pfrom.teleport(pto, TeleportCause.PLUGIN);
pfrom.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName());
if(!p.equals(pfrom) && !(p.equals(pto))) p.sendMessage(tag + "Teleporting " + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " to " + ChatColor.GOLD + pto.getName());
pto.sendMessage(tag + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " has been teleported to you.");
return true;
}else{
p.sendMessage(tag + "Incorrect usage. /tp {player} {player}");
return true;
}return true;
}
}
| true | true | public boolean onCommand(CommandSender s, Command cmd, String c, String[] args){
if(s instanceof Player == false){
System.out.println("[olyTP] Go home console, you're drunk.");
return true;
}Player p = (Player)s;
if((p.isOp()==false)&&(p.hasPermission("olyTP.use")==false)){
p.sendMessage(tag+"You do not have permission to use this command.");
}
if(args.length==1){
String to = args[0];
List<Player> matches = Bukkit.matchPlayer(to);
if(matches.size() !=1){
p.sendMessage(tag+"The player could not be found.");
return true;
}Player pto=matches.get(0);
if(p==pto){
p.sendMessage(tag+"You cannot teleport to yourself.");
return true;
}p.teleport(pto, TeleportCause.PLUGIN);
p.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName());
if(p.isOp() || p.hasPermission("olyTP.use")) pto.sendMessage(tag+ ChatColor.GOLD + p.getName() + ChatColor.YELLOW + " teleported to you.");
}else if(args.length == 2){
String to = args[1];
String from = args[0];
List<Player> matches = Bukkit.matchPlayer(to);
if(matches.size() !=1){
p.sendMessage(tag + to + " could not be found.");
return true;
}
Player pto = matches.get(0);
matches = Bukkit.matchPlayer(from);
if(matches.size() !=1){
p.sendMessage(tag + from + " could not be found.");
}
Player pfrom = matches.get(0);
pfrom.teleport(pto, TeleportCause.PLUGIN);
pfrom.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName());
if(!p.equals(pfrom) && !(p.equals(pto))) p.sendMessage(tag + "Teleporting " + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " to " + ChatColor.GOLD + pto.getName());
pto.sendMessage(tag + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " has been teleported to you.");
return true;
}else{
p.sendMessage(tag + "Incorrect usage. /tp {player} {player}");
return true;
}return true;
}
| public boolean onCommand(CommandSender s, Command cmd, String c, String[] args){
if(s instanceof Player == false){
System.out.println("[olyTP] Go home console, you're drunk.");
return true;
}Player p = (Player)s;
if((p.isOp()==false)&&(p.hasPermission("olyTP.use")==false)){
p.sendMessage(tag+"You do not have permission to use this command.");
}
if(args.length==1){
String to = args[0];
List<Player> matches = Bukkit.matchPlayer(to);
if(matches.size() !=1){
p.sendMessage(tag+"The player could not be found.");
return true;
}Player pto=matches.get(0);
if(p==pto){
p.sendMessage(tag+"You cannot teleport to yourself.");
return true;
}p.teleport(pto, TeleportCause.PLUGIN);
p.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName());
if(p.isOp() || p.hasPermission("olyTP.use")) pto.sendMessage(tag+ ChatColor.GOLD + p.getName() + ChatColor.YELLOW + " teleported to you.");
}else if(args.length == 2){
String to = args[1];
String from = args[0];
List<Player> matches = Bukkit.matchPlayer(to);
if(matches.size() !=1){
p.sendMessage(tag + to + " could not be found.");
return true;
}
Player pto = matches.get(0);
matches = Bukkit.matchPlayer(from);
if(matches.size() !=1){
p.sendMessage(tag + from + " could not be found.");
return true;
}
Player pfrom = matches.get(0);
pfrom.teleport(pto, TeleportCause.PLUGIN);
pfrom.sendMessage(tag + "Teleporting you to " + ChatColor.GOLD + pto.getName());
if(!p.equals(pfrom) && !(p.equals(pto))) p.sendMessage(tag + "Teleporting " + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " to " + ChatColor.GOLD + pto.getName());
pto.sendMessage(tag + ChatColor.GOLD + pfrom.getName() + ChatColor.YELLOW + " has been teleported to you.");
return true;
}else{
p.sendMessage(tag + "Incorrect usage. /tp {player} {player}");
return true;
}return true;
}
|
diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java
index 5e8b60c9..bc75f1c1 100644
--- a/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java
+++ b/52n-wps-server/src/main/java/org/n52/wps/server/RepositoryManager.java
@@ -1,219 +1,222 @@
/***************************************************************
This implementation provides a framework to publish processes to the
web through the OGC Web Processing Service interface. The framework
is extensible in terms of processes and data handlers. It is compliant
to the WPS version 0.4.0 (OGC 05-007r4).
Copyright (C) 2009 by con terra GmbH
Authors:
Bastian Sch�ffer, University of Muenster
Contact: Albert Remke, con terra GmbH, Martin-Luther-King-Weg 24,
48155 Muenster, Germany, [email protected]
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program (see gnu-gpl v2.txt); if not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA or visit the web page of the Free
Software Foundation, http://www.fsf.org.
***************************************************************/
package org.n52.wps.server;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.n52.wps.RepositoryDocument.Repository;
import org.n52.wps.commons.WPSConfig;
import org.n52.wps.server.request.ExecuteRequest;
public class RepositoryManager {
private static RepositoryManager instance;
private static Logger LOGGER = Logger.getLogger(RepositoryManager.class);
private List<IAlgorithmRepository> repositories;
private ProcessIDRegistry globalProcessIDs = ProcessIDRegistry.getInstance();
private RepositoryManager(){
// clear registry
globalProcessIDs.clearRegistry();
// initialize all Repositories
loadAllRepositories();
// FvK: added Property Change Listener support
// creates listener and register it to the wpsConfig instance.
WPSConfig.getInstance().addPropertyChangeListener(WPSConfig.WPSCONFIG_PROPERTY_EVENT_NAME, new PropertyChangeListener() {
public void propertyChange(
final PropertyChangeEvent propertyChangeEvent) {
LOGGER.info(this.getClass().getName() + ": Received Property Change Event: " + propertyChangeEvent.getPropertyName());
loadAllRepositories();
}
});
}
private void loadAllRepositories(){
repositories = new ArrayList<IAlgorithmRepository>();
Repository[] repositoryList = WPSConfig.getInstance().getRegisterdAlgorithmRepositories();
for(Repository repository : repositoryList){
+ if(repository.getActive()==false){
+ continue;
+ }
String repositoryClassName = repository.getClassName();
try {
IAlgorithmRepository algorithmRepository = (IAlgorithmRepository)RepositoryManager.class.getClassLoader().loadClass(repositoryClassName).newInstance();
repositories.add(algorithmRepository);
LOGGER.info("Algorithm Repositories initialized");
} catch (InstantiationException e) {
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
} catch (IllegalAccessException e) {
//in case of an singleton
// try {
//
// IAlgorithmRepository algorithmRepository = (IAlgorithmRepository)RepositoryManager.class.getClassLoader().loadClass(repositoryClassName).getMethod("getInstance", new Class[0]).invoke(null, new Object[0]);
// repositories.add(algorithmRepository);
// } catch (IllegalArgumentException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (SecurityException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (IllegalAccessException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (InvocationTargetException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (NoSuchMethodException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (ClassNotFoundException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// }
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
} catch (ClassNotFoundException e) {
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName + ". Class not found");
}
}
}
public static RepositoryManager getInstance(){
if(instance==null){
instance = new RepositoryManager();
}
return instance;
}
/**
* Allows to reInitialize the RepositoryManager... This should not be called to often.
*
*/
public static void reInitialize() {
instance = new RepositoryManager();
}
/**
* Methods looks for Algorithhm in all Repositories.
* The first match is returned.
* If no match could be found, null is returned
*
* @param className
* @return IAlgorithm or null
* @throws Exception
*/
public IAlgorithm getAlgorithm(String className, ExecuteRequest executeRequest){
for(IAlgorithmRepository repository : repositories){
if(repository.containsAlgorithm(className)){
return repository.getAlgorithm(className, executeRequest);
}
}
return null;
}
/**
*
* @return allAlgorithms
*/
public List<String> getAlgorithms(){
List<String> allAlgorithmNamesCollection = new ArrayList<String>();
for(IAlgorithmRepository repository : repositories){
allAlgorithmNamesCollection.addAll(repository.getAlgorithmNames());
}
return allAlgorithmNamesCollection;
}
public boolean containsAlgorithm(String algorithmName) {
for(IAlgorithmRepository repository : repositories){
if(repository.containsAlgorithm(algorithmName)){
return true;
}
}
return false;
}
public IAlgorithmRepository getRepositoryForAlgorithm(String algorithmName){
for(IAlgorithmRepository repository : repositories){
if(repository.containsAlgorithm(algorithmName)){
return repository;
}
}
return null;
}
public Class getInputDataTypeForAlgorithm(String algorithmIdentifier, String inputIdentifier){
IAlgorithm algorithm = getAlgorithm(algorithmIdentifier, null);
return algorithm.getInputDataType(inputIdentifier);
}
public Class getOutputDataTypeForAlgorithm(String algorithmIdentifier, String inputIdentifier){
IAlgorithm algorithm = getAlgorithm(algorithmIdentifier, null);
return algorithm.getOutputDataType(inputIdentifier);
}
public boolean registerAlgorithm(String id, IAlgorithmRepository repository){
if (globalProcessIDs.addID(id)){
return true;
}
else return false;
}
public boolean unregisterAlgorithm(String id){
if (globalProcessIDs.removeID(id)){
return true;
}
else return false;
}
public IAlgorithmRepository getAlgorithmRepository(String name){
for (IAlgorithmRepository repo : repositories ){
if(repo.getClass().getName().equals(name)){
return repo;
}
}
return null;
}
}
| true | true | private void loadAllRepositories(){
repositories = new ArrayList<IAlgorithmRepository>();
Repository[] repositoryList = WPSConfig.getInstance().getRegisterdAlgorithmRepositories();
for(Repository repository : repositoryList){
String repositoryClassName = repository.getClassName();
try {
IAlgorithmRepository algorithmRepository = (IAlgorithmRepository)RepositoryManager.class.getClassLoader().loadClass(repositoryClassName).newInstance();
repositories.add(algorithmRepository);
LOGGER.info("Algorithm Repositories initialized");
} catch (InstantiationException e) {
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
} catch (IllegalAccessException e) {
//in case of an singleton
// try {
//
// IAlgorithmRepository algorithmRepository = (IAlgorithmRepository)RepositoryManager.class.getClassLoader().loadClass(repositoryClassName).getMethod("getInstance", new Class[0]).invoke(null, new Object[0]);
// repositories.add(algorithmRepository);
// } catch (IllegalArgumentException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (SecurityException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (IllegalAccessException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (InvocationTargetException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (NoSuchMethodException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (ClassNotFoundException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// }
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
} catch (ClassNotFoundException e) {
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName + ". Class not found");
}
}
}
| private void loadAllRepositories(){
repositories = new ArrayList<IAlgorithmRepository>();
Repository[] repositoryList = WPSConfig.getInstance().getRegisterdAlgorithmRepositories();
for(Repository repository : repositoryList){
if(repository.getActive()==false){
continue;
}
String repositoryClassName = repository.getClassName();
try {
IAlgorithmRepository algorithmRepository = (IAlgorithmRepository)RepositoryManager.class.getClassLoader().loadClass(repositoryClassName).newInstance();
repositories.add(algorithmRepository);
LOGGER.info("Algorithm Repositories initialized");
} catch (InstantiationException e) {
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
} catch (IllegalAccessException e) {
//in case of an singleton
// try {
//
// IAlgorithmRepository algorithmRepository = (IAlgorithmRepository)RepositoryManager.class.getClassLoader().loadClass(repositoryClassName).getMethod("getInstance", new Class[0]).invoke(null, new Object[0]);
// repositories.add(algorithmRepository);
// } catch (IllegalArgumentException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (SecurityException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (IllegalAccessException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (InvocationTargetException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (NoSuchMethodException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// } catch (ClassNotFoundException e1) {
// LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
// }
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName);
} catch (ClassNotFoundException e) {
LOGGER.warn("An error occured while registering AlgorithmRepository: " + repositoryClassName + ". Class not found");
}
}
}
|
diff --git a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java
index cda7d5afe..c8dd34119 100644
--- a/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java
+++ b/org.eclipse.mylyn.java.ui/src/org/eclipse/mylyn/java/MylarChangeSetManager.java
@@ -1,154 +1,154 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.java;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.mylar.core.IMylarContext;
import org.eclipse.mylar.core.IMylarContextListener;
import org.eclipse.mylar.core.IMylarElement;
import org.eclipse.mylar.core.IMylarStructureBridge;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.ide.MylarIdePlugin;
import org.eclipse.mylar.tasklist.ITask;
import org.eclipse.mylar.tasklist.MylarTasklistPlugin;
import org.eclipse.team.internal.ccvs.ui.CVSUIPlugin;
import org.eclipse.team.internal.core.subscribers.SubscriberChangeSetCollector;
/**
* @author Mik Kersten
*/
public class MylarChangeSetManager implements IMylarContextListener {
private SubscriberChangeSetCollector collector;
private Map<String, MylarContextChangeSet> changeSets = new HashMap<String, MylarContextChangeSet>();
public MylarChangeSetManager() {
collector = CVSUIPlugin.getPlugin().getChangeSetManager();
// collector.addListener(new InterestInducingChangeSetListener());
}
public IResource[] getResources(ITask task) {
MylarContextChangeSet changeSet = changeSets.get(task);
if (changeSet != null) {
return changeSet.getResources();
} else {
return null;
}
}
public void contextActivated(IMylarContext context) {
try {
ITask task = getTask(context);
if (task == null) {
MylarPlugin.log("could not resolve task for context", this);
} else if (!changeSets.containsKey(task.getHandleIdentifier())) {
MylarContextChangeSet changeSet = new MylarContextChangeSet(task, collector);
changeSet.add(changeSet.getResources());
changeSets.put(task.getHandleIdentifier(), changeSet);
if (!collector.contains(changeSet)) collector.add(changeSet);
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not update change set", false);
}
}
public void contextDeactivated(IMylarContext context) {
// TODO: support multiple tasks
for (String taskHandle : changeSets.keySet()) {
collector.remove(changeSets.get(taskHandle));
}
changeSets.clear();
}
public List<MylarContextChangeSet> getChangeSets() {
return new ArrayList<MylarContextChangeSet>(changeSets.values());
}
private ITask getTask(IMylarContext context) {
List<ITask> activeTasks = MylarTasklistPlugin.getTaskListManager().getTaskList().getActiveTasks();
// TODO: support multiple tasks
if (activeTasks.size() > 0) {
return activeTasks.get(0);
} else {
return null;
}
}
public void interestChanged(IMylarElement element) {
IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element);
if (resource != null) {
for (MylarContextChangeSet changeSet: getChangeSets()) {
try {
if (!changeSet.contains(resource)) {
if (element.getInterest().isInteresting()) {
changeSet.add(new IResource[] { resource });
}
} else if (!element.getInterest().isInteresting()){
changeSet.remove(resource);
// HACK: touching ensures file is added outside of set
- if (resource instanceof IFile) {
+ if (resource instanceof IFile && resource.exists()) {
((IFile)resource).touch(new NullProgressMonitor());
}
if (!collector.contains(changeSet)) {
collector.add(changeSet);
}
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not add resource to change set", false);
}
}
}
}
}
public void interestChanged(List<IMylarElement> elements) {
for (IMylarElement element : elements) {
interestChanged(element);
}
}
public void nodeDeleted(IMylarElement node) {
// ignore
}
public void landmarkAdded(IMylarElement node) {
// ignore
}
public void landmarkRemoved(IMylarElement node) {
// ignore
}
public void edgesChanged(IMylarElement node) {
// ignore
}
public void presentationSettingsChanging(UpdateKind kind) {
// ignore
}
public void presentationSettingsChanged(UpdateKind kind) {
// ignore
}
}
| true | true | public void interestChanged(IMylarElement element) {
IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element);
if (resource != null) {
for (MylarContextChangeSet changeSet: getChangeSets()) {
try {
if (!changeSet.contains(resource)) {
if (element.getInterest().isInteresting()) {
changeSet.add(new IResource[] { resource });
}
} else if (!element.getInterest().isInteresting()){
changeSet.remove(resource);
// HACK: touching ensures file is added outside of set
if (resource instanceof IFile) {
((IFile)resource).touch(new NullProgressMonitor());
}
if (!collector.contains(changeSet)) {
collector.add(changeSet);
}
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not add resource to change set", false);
}
}
}
}
}
| public void interestChanged(IMylarElement element) {
IMylarStructureBridge bridge = MylarPlugin.getDefault().getStructureBridge(element.getContentType());
if (bridge.isDocument(element.getHandleIdentifier())) {
IResource resource = MylarIdePlugin.getDefault().getResourceForElement(element);
if (resource != null) {
for (MylarContextChangeSet changeSet: getChangeSets()) {
try {
if (!changeSet.contains(resource)) {
if (element.getInterest().isInteresting()) {
changeSet.add(new IResource[] { resource });
}
} else if (!element.getInterest().isInteresting()){
changeSet.remove(resource);
// HACK: touching ensures file is added outside of set
if (resource instanceof IFile && resource.exists()) {
((IFile)resource).touch(new NullProgressMonitor());
}
if (!collector.contains(changeSet)) {
collector.add(changeSet);
}
}
} catch (Exception e) {
MylarPlugin.fail(e, "could not add resource to change set", false);
}
}
}
}
}
|
diff --git a/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java b/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java
index 94c0ff8..1fa370a 100644
--- a/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java
+++ b/src/com/martinbrook/tesseractuhc/notification/DamageNotification.java
@@ -1,106 +1,106 @@
package com.martinbrook.tesseractuhc.notification;
import org.bukkit.ChatColor;
import org.bukkit.entity.AnimalTamer;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Wolf;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import com.martinbrook.tesseractuhc.UhcPlayer;
public class DamageNotification extends UhcNotification {
private UhcPlayer damaged;
private int damageAmount;
private DamageCause cause;
private Entity damager;
public DamageNotification(UhcPlayer damaged, int damageAmount, DamageCause cause, Entity damager) {
super();
this.damaged = damaged;
this.damageAmount = damageAmount;
this.cause = cause;
this.damager = damager;
}
public DamageNotification(UhcPlayer damaged, int damageAmount, DamageCause cause) {
super();
this.damaged = damaged;
this.damageAmount = damageAmount;
this.cause = cause;
this.damager = null;
}
@Override
public String formatForPlayers() {
String formattedDamage;
formattedDamage = String.format("%d", damageAmount / 2);
if (damageAmount / 2.0 != Math.floor(damageAmount / 2.0))
formattedDamage += ".5";
formattedDamage += " heart";
if (damageAmount != 2) formattedDamage += "s";
if (damager != null) {
if (damager instanceof Player) {
// PVP damage
if (cause == DamageCause.ENTITY_ATTACK)
return damaged.getName() + " was hurt by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!";
if (cause == DamageCause.PROJECTILE)
return damaged.getName() + " was shot at by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!";
} else {
// Mob damage
String type = "an unknown entity";
if (damager.getType() == EntityType.BLAZE) type = "a blaze";
else if (damager.getType() == EntityType.CAVE_SPIDER) type = "a cave spider";
else if (damager.getType() == EntityType.CREEPER) type = "a creeper";
else if (damager.getType() == EntityType.ENDER_DRAGON) type = "the dragon";
else if (damager.getType() == EntityType.ENDERMAN) type = "an enderman";
else if (damager.getType() == EntityType.GHAST) type = "a ghast";
else if (damager.getType() == EntityType.IRON_GOLEM) type = "an iron golem";
else if (damager.getType() == EntityType.MAGMA_CUBE) type = "a magma cube";
else if (damager.getType() == EntityType.PIG_ZOMBIE) type = "a zombie pigman";
else if (damager.getType() == EntityType.SILVERFISH) type = "a silverfish";
else if (damager.getType() == EntityType.SKELETON) type = "a skeleton";
else if (damager.getType() == EntityType.SLIME) type = "a slime";
else if (damager.getType() == EntityType.WITCH) type = "a witch";
else if (damager.getType() == EntityType.WITHER) type = "a wither";
else if (damager.getType() == EntityType.WITHER_SKULL) type = "a wither skull";
else if (damager.getType() == EntityType.ZOMBIE) type = "a zombie";
else if (damager.getType() == EntityType.WOLF) {
AnimalTamer owner = ((Wolf) damager).getOwner();
if (owner != null) type = owner.getName() + "'s wolf";
else type = "a wolf";
}
else if (damager.getType() == EntityType.PRIMED_TNT) return null;
return ChatColor.RED + damaged.getName() + " took " + formattedDamage + " of damage from " + type;
}
}
// Environmental damage
String type = "unknown";
if (cause == DamageCause.BLOCK_EXPLOSION) type = "TNT";
else if (cause == DamageCause.CONTACT) type = "cactus";
else if (cause == DamageCause.DROWNING) type = "drowning";
else if (cause == DamageCause.FALL) type = "fall";
- else if (cause == DamageCause.FIRE) return null;
+ else if (cause == DamageCause.FIRE) type = "burning";
else if (cause == DamageCause.FIRE_TICK) type = "burning";
else if (cause == DamageCause.LAVA) type = "lava";
else if (cause == DamageCause.LIGHTNING) type = "lightning";
else if (cause == DamageCause.MAGIC) type = "magic";
else if (cause == DamageCause.POISON) type = "poison";
else if (cause == DamageCause.STARVATION) type = "starvation";
else if (cause == DamageCause.SUFFOCATION) type = "suffocation";
else if (cause == DamageCause.VOID) type = "void";
else if (cause == DamageCause.WITHER) type = "wither";
return ChatColor.RED + damaged.getName() + " took " + formattedDamage + " of " + type + " damage!";
}
}
| true | true | public String formatForPlayers() {
String formattedDamage;
formattedDamage = String.format("%d", damageAmount / 2);
if (damageAmount / 2.0 != Math.floor(damageAmount / 2.0))
formattedDamage += ".5";
formattedDamage += " heart";
if (damageAmount != 2) formattedDamage += "s";
if (damager != null) {
if (damager instanceof Player) {
// PVP damage
if (cause == DamageCause.ENTITY_ATTACK)
return damaged.getName() + " was hurt by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!";
if (cause == DamageCause.PROJECTILE)
return damaged.getName() + " was shot at by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!";
} else {
// Mob damage
String type = "an unknown entity";
if (damager.getType() == EntityType.BLAZE) type = "a blaze";
else if (damager.getType() == EntityType.CAVE_SPIDER) type = "a cave spider";
else if (damager.getType() == EntityType.CREEPER) type = "a creeper";
else if (damager.getType() == EntityType.ENDER_DRAGON) type = "the dragon";
else if (damager.getType() == EntityType.ENDERMAN) type = "an enderman";
else if (damager.getType() == EntityType.GHAST) type = "a ghast";
else if (damager.getType() == EntityType.IRON_GOLEM) type = "an iron golem";
else if (damager.getType() == EntityType.MAGMA_CUBE) type = "a magma cube";
else if (damager.getType() == EntityType.PIG_ZOMBIE) type = "a zombie pigman";
else if (damager.getType() == EntityType.SILVERFISH) type = "a silverfish";
else if (damager.getType() == EntityType.SKELETON) type = "a skeleton";
else if (damager.getType() == EntityType.SLIME) type = "a slime";
else if (damager.getType() == EntityType.WITCH) type = "a witch";
else if (damager.getType() == EntityType.WITHER) type = "a wither";
else if (damager.getType() == EntityType.WITHER_SKULL) type = "a wither skull";
else if (damager.getType() == EntityType.ZOMBIE) type = "a zombie";
else if (damager.getType() == EntityType.WOLF) {
AnimalTamer owner = ((Wolf) damager).getOwner();
if (owner != null) type = owner.getName() + "'s wolf";
else type = "a wolf";
}
else if (damager.getType() == EntityType.PRIMED_TNT) return null;
return ChatColor.RED + damaged.getName() + " took " + formattedDamage + " of damage from " + type;
}
}
// Environmental damage
String type = "unknown";
if (cause == DamageCause.BLOCK_EXPLOSION) type = "TNT";
else if (cause == DamageCause.CONTACT) type = "cactus";
else if (cause == DamageCause.DROWNING) type = "drowning";
else if (cause == DamageCause.FALL) type = "fall";
else if (cause == DamageCause.FIRE) return null;
else if (cause == DamageCause.FIRE_TICK) type = "burning";
else if (cause == DamageCause.LAVA) type = "lava";
else if (cause == DamageCause.LIGHTNING) type = "lightning";
else if (cause == DamageCause.MAGIC) type = "magic";
else if (cause == DamageCause.POISON) type = "poison";
else if (cause == DamageCause.STARVATION) type = "starvation";
else if (cause == DamageCause.SUFFOCATION) type = "suffocation";
else if (cause == DamageCause.VOID) type = "void";
else if (cause == DamageCause.WITHER) type = "wither";
return ChatColor.RED + damaged.getName() + " took " + formattedDamage + " of " + type + " damage!";
}
| public String formatForPlayers() {
String formattedDamage;
formattedDamage = String.format("%d", damageAmount / 2);
if (damageAmount / 2.0 != Math.floor(damageAmount / 2.0))
formattedDamage += ".5";
formattedDamage += " heart";
if (damageAmount != 2) formattedDamage += "s";
if (damager != null) {
if (damager instanceof Player) {
// PVP damage
if (cause == DamageCause.ENTITY_ATTACK)
return damaged.getName() + " was hurt by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!";
if (cause == DamageCause.PROJECTILE)
return damaged.getName() + " was shot at by " + ((Player) damager).getDisplayName() + " (" + (damageAmount / 2.0) + " hearts)!";
} else {
// Mob damage
String type = "an unknown entity";
if (damager.getType() == EntityType.BLAZE) type = "a blaze";
else if (damager.getType() == EntityType.CAVE_SPIDER) type = "a cave spider";
else if (damager.getType() == EntityType.CREEPER) type = "a creeper";
else if (damager.getType() == EntityType.ENDER_DRAGON) type = "the dragon";
else if (damager.getType() == EntityType.ENDERMAN) type = "an enderman";
else if (damager.getType() == EntityType.GHAST) type = "a ghast";
else if (damager.getType() == EntityType.IRON_GOLEM) type = "an iron golem";
else if (damager.getType() == EntityType.MAGMA_CUBE) type = "a magma cube";
else if (damager.getType() == EntityType.PIG_ZOMBIE) type = "a zombie pigman";
else if (damager.getType() == EntityType.SILVERFISH) type = "a silverfish";
else if (damager.getType() == EntityType.SKELETON) type = "a skeleton";
else if (damager.getType() == EntityType.SLIME) type = "a slime";
else if (damager.getType() == EntityType.WITCH) type = "a witch";
else if (damager.getType() == EntityType.WITHER) type = "a wither";
else if (damager.getType() == EntityType.WITHER_SKULL) type = "a wither skull";
else if (damager.getType() == EntityType.ZOMBIE) type = "a zombie";
else if (damager.getType() == EntityType.WOLF) {
AnimalTamer owner = ((Wolf) damager).getOwner();
if (owner != null) type = owner.getName() + "'s wolf";
else type = "a wolf";
}
else if (damager.getType() == EntityType.PRIMED_TNT) return null;
return ChatColor.RED + damaged.getName() + " took " + formattedDamage + " of damage from " + type;
}
}
// Environmental damage
String type = "unknown";
if (cause == DamageCause.BLOCK_EXPLOSION) type = "TNT";
else if (cause == DamageCause.CONTACT) type = "cactus";
else if (cause == DamageCause.DROWNING) type = "drowning";
else if (cause == DamageCause.FALL) type = "fall";
else if (cause == DamageCause.FIRE) type = "burning";
else if (cause == DamageCause.FIRE_TICK) type = "burning";
else if (cause == DamageCause.LAVA) type = "lava";
else if (cause == DamageCause.LIGHTNING) type = "lightning";
else if (cause == DamageCause.MAGIC) type = "magic";
else if (cause == DamageCause.POISON) type = "poison";
else if (cause == DamageCause.STARVATION) type = "starvation";
else if (cause == DamageCause.SUFFOCATION) type = "suffocation";
else if (cause == DamageCause.VOID) type = "void";
else if (cause == DamageCause.WITHER) type = "wither";
return ChatColor.RED + damaged.getName() + " took " + formattedDamage + " of " + type + " damage!";
}
|
diff --git a/src/main/java/org/apache/camel/splunk/demo/SplunkTwitterSearchRoute.java b/src/main/java/org/apache/camel/splunk/demo/SplunkTwitterSearchRoute.java
index 42fe1ff..a57cee8 100644
--- a/src/main/java/org/apache/camel/splunk/demo/SplunkTwitterSearchRoute.java
+++ b/src/main/java/org/apache/camel/splunk/demo/SplunkTwitterSearchRoute.java
@@ -1,19 +1,19 @@
package org.apache.camel.splunk.demo;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.properties.PropertiesComponent;
public class SplunkTwitterSearchRoute extends RouteBuilder {
@Override
public void configure() throws Exception {
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:splunk-demo.properties");
getContext().addComponent("properties", pc);
from(
- "splunk://normal?delay=5s&username={{splunk-username}}&password={{splunk-password}}&initEarliestTime=-2s&"
- + "search=search index=camel-tweets sourcetype=twitter-feed").log("${body}");
+ "splunk://normal?delay=5s&username={{splunk-username}}&password={{splunk-password}}&initEarliestTime=-2m&"
+ + "search=search index=camel-tweets sourcetype=twitter-feed&count=40").log("${body}");
}
}
| true | true | public void configure() throws Exception {
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:splunk-demo.properties");
getContext().addComponent("properties", pc);
from(
"splunk://normal?delay=5s&username={{splunk-username}}&password={{splunk-password}}&initEarliestTime=-2s&"
+ "search=search index=camel-tweets sourcetype=twitter-feed").log("${body}");
}
| public void configure() throws Exception {
PropertiesComponent pc = new PropertiesComponent();
pc.setLocation("classpath:splunk-demo.properties");
getContext().addComponent("properties", pc);
from(
"splunk://normal?delay=5s&username={{splunk-username}}&password={{splunk-password}}&initEarliestTime=-2m&"
+ "search=search index=camel-tweets sourcetype=twitter-feed&count=40").log("${body}");
}
|
diff --git a/src/org/mvnsearch/snippet/plugin/actions/CreateSnippetFileAction.java b/src/org/mvnsearch/snippet/plugin/actions/CreateSnippetFileAction.java
index e3aa257..e6c9dc0 100644
--- a/src/org/mvnsearch/snippet/plugin/actions/CreateSnippetFileAction.java
+++ b/src/org/mvnsearch/snippet/plugin/actions/CreateSnippetFileAction.java
@@ -1,102 +1,104 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mvnsearch.snippet.plugin.actions;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogBuilder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.util.FileContentUtil;
import org.mvnsearch.snippet.plugin.SnippetAppComponent;
import org.mvnsearch.snippet.impl.mvnsearch.SnippetService;
import org.mvnsearch.snippet.plugin.ui.SnippetFileCreationForm;
/**
* action to create a new file from snippet file
*
* @author [email protected]
*/
public class CreateSnippetFileAction extends AnAction {
public void actionPerformed(AnActionEvent event) {
final Project project = event.getData(PlatformDataKeys.PROJECT);
final PsiElement psiElement = event.getData(LangDataKeys.PSI_ELEMENT);
if (psiElement instanceof PsiDirectory) {
final SnippetFileCreationForm form = new SnippetFileCreationForm();
final DialogBuilder builder = new DialogBuilder(project);
builder.setTitle("Create file from snippet");
builder.setCenterPanel(form.getRootPanel());
builder.setOkOperation(new Runnable() {
public void run() {
String result = generateFile((PsiDirectory) psiElement, form.getMnemonic(), form.getFileName(), project);
if (StringUtil.isEmpty(result)) { //create successfully
builder.getDialogWrapper().close(1);
} else { //failed
builder.setTitle(result);
}
}
});
builder.showModal(true);
}
}
/**
* generate file from snippet
*
* @param psiDirectory directory
* @param mnemonic mnemonic
* @param fileName file name
* @param project project
* @return error information
*/
public String generateFile(final PsiDirectory psiDirectory, final String mnemonic, final String fileName, final Project project) {
final StringBuffer buffer = new StringBuffer();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
SnippetService service = SnippetAppComponent.getInstance().getSnippetService();
if (service != null) {
PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
String packageName = psiPackage == null ? null : psiPackage.getName();
String content = service.renderTemplate(mnemonic, packageName, fileName, SnippetAppComponent.getInstance().userName);
if (content == null) {
buffer.append("Mnemonic not found!");
return;
}
+ //\r is forbidden for Intellij document
+ content = content.replaceAll("\r","");
PsiFile destinationFile = psiDirectory.findFile(fileName);
if (destinationFile == null) {
destinationFile = psiDirectory.createFile(fileName);
FileContentUtil.setFileText(project, destinationFile.getVirtualFile(), content);
}
destinationFile.navigate(true);
} else {
buffer.append("Cannot create connection to snippet repository!");
}
} catch (Exception e) {
buffer.append("Failed to create file");
}
}
});
return buffer.toString();
}
}
| true | true | public String generateFile(final PsiDirectory psiDirectory, final String mnemonic, final String fileName, final Project project) {
final StringBuffer buffer = new StringBuffer();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
SnippetService service = SnippetAppComponent.getInstance().getSnippetService();
if (service != null) {
PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
String packageName = psiPackage == null ? null : psiPackage.getName();
String content = service.renderTemplate(mnemonic, packageName, fileName, SnippetAppComponent.getInstance().userName);
if (content == null) {
buffer.append("Mnemonic not found!");
return;
}
PsiFile destinationFile = psiDirectory.findFile(fileName);
if (destinationFile == null) {
destinationFile = psiDirectory.createFile(fileName);
FileContentUtil.setFileText(project, destinationFile.getVirtualFile(), content);
}
destinationFile.navigate(true);
} else {
buffer.append("Cannot create connection to snippet repository!");
}
} catch (Exception e) {
buffer.append("Failed to create file");
}
}
});
return buffer.toString();
}
| public String generateFile(final PsiDirectory psiDirectory, final String mnemonic, final String fileName, final Project project) {
final StringBuffer buffer = new StringBuffer();
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
SnippetService service = SnippetAppComponent.getInstance().getSnippetService();
if (service != null) {
PsiPackage psiPackage = JavaDirectoryService.getInstance().getPackage(psiDirectory);
String packageName = psiPackage == null ? null : psiPackage.getName();
String content = service.renderTemplate(mnemonic, packageName, fileName, SnippetAppComponent.getInstance().userName);
if (content == null) {
buffer.append("Mnemonic not found!");
return;
}
//\r is forbidden for Intellij document
content = content.replaceAll("\r","");
PsiFile destinationFile = psiDirectory.findFile(fileName);
if (destinationFile == null) {
destinationFile = psiDirectory.createFile(fileName);
FileContentUtil.setFileText(project, destinationFile.getVirtualFile(), content);
}
destinationFile.navigate(true);
} else {
buffer.append("Cannot create connection to snippet repository!");
}
} catch (Exception e) {
buffer.append("Failed to create file");
}
}
});
return buffer.toString();
}
|
diff --git a/freeplane/src/org/freeplane/features/url/mindmapmode/SaveAll.java b/freeplane/src/org/freeplane/features/url/mindmapmode/SaveAll.java
index 38b101dd2..a966f198d 100644
--- a/freeplane/src/org/freeplane/features/url/mindmapmode/SaveAll.java
+++ b/freeplane/src/org/freeplane/features/url/mindmapmode/SaveAll.java
@@ -1,76 +1,77 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.features.url.mindmapmode;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import javax.swing.JOptionPane;
import org.freeplane.core.ui.AFreeplaneAction;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.map.MapModel;
import org.freeplane.features.mode.Controller;
import org.freeplane.features.mode.ModeController;
import org.freeplane.features.mode.mindmapmode.MModeController;
/**
* @author foltin
*/
public class SaveAll extends AFreeplaneAction {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
public SaveAll() {
super("SaveAll");
}
public void actionPerformed(final ActionEvent e) {
final Controller controller = Controller.getCurrentController();
final Component initialMapView = controller.getViewController().getMapView();
final Map<String, MapModel> mapViews = getMapViews();
final Iterator<Entry<String, MapModel>> iterator = mapViews.entrySet().iterator();
while (iterator.hasNext()) {
final Entry<String, MapModel> entry = iterator.next();
controller.getMapViewManager().changeToMapView(entry.getKey());
final ModeController modeController = controller.getModeController();
if (modeController instanceof MModeController && !((MModeController) modeController).save()) {
- JOptionPane.showMessageDialog(controller.getViewController().getContentPane(), "Freeplane", TextUtils
- .getText("accessories/plugins/SaveAll.properties_save_all_cancelled"), JOptionPane.ERROR_MESSAGE);
+ //DOCEAR: remove meaningless (static text "Freeplane") dialog
+// JOptionPane.showMessageDialog(controller.getViewController().getContentPane(), "Freeplane", TextUtils
+// .getText("accessories/plugins/SaveAll.properties_save_all_cancelled"), JOptionPane.ERROR_MESSAGE);
return;
}
}
if (initialMapView != null) {
controller.getMapViewManager().changeToMapView(initialMapView);
}
}
/**
*/
private Map<String, MapModel> getMapViews() {
return Controller.getCurrentController().getMapViewManager().getMaps();
}
}
| true | true | public void actionPerformed(final ActionEvent e) {
final Controller controller = Controller.getCurrentController();
final Component initialMapView = controller.getViewController().getMapView();
final Map<String, MapModel> mapViews = getMapViews();
final Iterator<Entry<String, MapModel>> iterator = mapViews.entrySet().iterator();
while (iterator.hasNext()) {
final Entry<String, MapModel> entry = iterator.next();
controller.getMapViewManager().changeToMapView(entry.getKey());
final ModeController modeController = controller.getModeController();
if (modeController instanceof MModeController && !((MModeController) modeController).save()) {
JOptionPane.showMessageDialog(controller.getViewController().getContentPane(), "Freeplane", TextUtils
.getText("accessories/plugins/SaveAll.properties_save_all_cancelled"), JOptionPane.ERROR_MESSAGE);
return;
}
}
if (initialMapView != null) {
controller.getMapViewManager().changeToMapView(initialMapView);
}
}
| public void actionPerformed(final ActionEvent e) {
final Controller controller = Controller.getCurrentController();
final Component initialMapView = controller.getViewController().getMapView();
final Map<String, MapModel> mapViews = getMapViews();
final Iterator<Entry<String, MapModel>> iterator = mapViews.entrySet().iterator();
while (iterator.hasNext()) {
final Entry<String, MapModel> entry = iterator.next();
controller.getMapViewManager().changeToMapView(entry.getKey());
final ModeController modeController = controller.getModeController();
if (modeController instanceof MModeController && !((MModeController) modeController).save()) {
//DOCEAR: remove meaningless (static text "Freeplane") dialog
// JOptionPane.showMessageDialog(controller.getViewController().getContentPane(), "Freeplane", TextUtils
// .getText("accessories/plugins/SaveAll.properties_save_all_cancelled"), JOptionPane.ERROR_MESSAGE);
return;
}
}
if (initialMapView != null) {
controller.getMapViewManager().changeToMapView(initialMapView);
}
}
|
diff --git a/src/com/arm/nevada/client/parser/InstructionFormats.java b/src/com/arm/nevada/client/parser/InstructionFormats.java
index 11fe0b9..4ac3dbf 100644
--- a/src/com/arm/nevada/client/parser/InstructionFormats.java
+++ b/src/com/arm/nevada/client/parser/InstructionFormats.java
@@ -1,1436 +1,1436 @@
/*
* Copyright (C) 2011, 2012 University of Szeged
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY UNIVERSITY OF SZEGED ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL UNIVERSITY OF SZEGED OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.arm.nevada.client.parser;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.arm.nevada.client.interpreter.AbsoluteAndNegateInstruction;
import com.arm.nevada.client.interpreter.ArithmeticInstructions;
import com.arm.nevada.client.interpreter.ComparisonInstruction;
import com.arm.nevada.client.interpreter.ConversationInstruction;
import com.arm.nevada.client.interpreter.CountInstruction;
import com.arm.nevada.client.interpreter.EnumDataType;
import com.arm.nevada.client.interpreter.Instruction;
import com.arm.nevada.client.interpreter.LogicalInstruction;
import com.arm.nevada.client.interpreter.MemoryInstruction;
import com.arm.nevada.client.interpreter.MinimumAndMaximumInstruction;
import com.arm.nevada.client.interpreter.MoveFPSCAndRAPSR;
import com.arm.nevada.client.interpreter.MoveInstruction;
import com.arm.nevada.client.interpreter.MultiplyInstruction;
import com.arm.nevada.client.interpreter.ReciprocalSqrtReciprocalEstimate;
import com.arm.nevada.client.interpreter.ReciprocalSqrtReciprocalStep;
import com.arm.nevada.client.interpreter.ReverseInstruction;
import com.arm.nevada.client.interpreter.ShiftInstruction;
import com.arm.nevada.client.interpreter.TableInstruction;
import com.arm.nevada.client.interpreter.VdupInstruction;
import com.arm.nevada.client.interpreter.VextInstruction;
import com.arm.nevada.client.interpreter.VmovInstruction;
import com.arm.nevada.client.interpreter.VswpInstruction;
import com.arm.nevada.client.interpreter.VtrnInstruction;
import com.arm.nevada.client.interpreter.ZipInstruction;
/**
* This helper class for defining the list of valid instructions also the required parameters.
*
*/
public class InstructionFormats {
private static final HashMap<EnumInstruction, List<InstructionForm>> instructionList;
static {
instructionList = new HashMap<EnumInstruction, List<InstructionForm>>();
fillInstructions00();
fillInstructions01();
}
private static void fillInstructions00(){
//ARITHMETIC2
//vadd int
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vadd float
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vsub int
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vsub float
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vaddhn
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vsubhn
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vaddl
append(new ArithmeticInstructions(EnumInstruction.vaddl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vaddw
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
//vsubl
append(new ArithmeticInstructions(EnumInstruction.vsubl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vsubw
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
//vhadd
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vhsub
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpadal
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vpadd integer
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpadd float
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpaddl
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vraddhn
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vrsubn
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vrhadd
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vqadd
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vqsub
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//LOGICAL2
//vand register
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vand immediate
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVbic.p());
//vbic immediate
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVbic.p());
//vbic register
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//veor register
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbif register
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbit register
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbsl register
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vorr register
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vorr immediate
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVorr.p());
//vorn register
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//MOVE
// special vmov
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_D), Space.p(), D.p(), Comma.p(), RNotPCNotSP.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.D_TO_ARM), Space.p(), RNotPCNotSP.p(), Comma.p(), RNotPCNotSP.p(), Comma.p(), D.p());
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_DSUB), AllSingleWide.p(), Space.p(), DSubReg.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_DSUB), DefType.p(EnumDataType._32), Space.p(), DSubReg.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), AllSignedSingle.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), AllUnsignedSingle.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), All32.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), DefType.p(EnumDataType._32), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
//ordinary move
//vmov neon imm
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.QUAD, true), All.p(), Space.p(), Q.p(), Comma.p(), ImmVmov.p());
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.DOUBLE, true), All.p(), Space.p(), D.p(), Comma.p(), ImmVmov.p());
//vmov neon neon
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p());
//vmvn neon imm
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.QUAD, true), All.p(), Space.p(), Q.p(), Comma.p(), ImmVmvn.p());
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.DOUBLE, true), All.p(), Space.p(), D.p(), Comma.p(), ImmVmvn.p());
//vmvn neon neon
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p());
//vmovn neon neon
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I64.p(), Space.p(), D.p(), Comma.p(), Q.p());
//vmovl neon neon
append(new MoveInstruction(EnumInstruction.vmovl, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p());
append(new MoveInstruction(EnumInstruction.vmovl, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p());
//vqmov{u}n neon neon
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S64.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U64.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S64.p(), Space.p(), D.p(), Comma.p(), Q.p());
//DUPLICATE
// #vdup
append(new VdupInstruction(false, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), DSubReg.p());
append(new VdupInstruction(false, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), DSubReg.p());
append(new VdupInstruction(true, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), R.p());
append(new VdupInstruction(true, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), R.p());
// VLD: #vld1 #vld2 #vld3 #vld4
// #vld1: all
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, true), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, true), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, true), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, true), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// #vld1: One
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// #vld1: Repeat one
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld2: all
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vld2: one
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld2: repeat one
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld3: all
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld3: one
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, true), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, true), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld3: one repeat
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld4: all
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vld4: one
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
// vld4: one repeat
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
// VST: #vst1 #vst2 #vst3 #vst4
// #vst1: ALL
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, true), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, true), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, true), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, true), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst1: ONE
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
// vst2: ALL
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst2: ONE
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vst3: ALL
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vst3: ONE
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, true), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, true), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vst4: ALL
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst4: ONE
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
//SHIFT instructions
//vqrshl
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vshl
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vshr
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vsra
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vrshl
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vrshr
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vrsra
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vshll //only VSHLL<c><q>.<type><size> <Qd>, <Dm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), ImmIsSize.p());
//vshrn //only VSHRN<c><q>.I<size> <Dd>, <Qm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vrshrn //VRSHRN<c><q>.I<size> <Dd>, <Qm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vsli
- append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
- append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
- append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
- append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
+ append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
+ append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
+ append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
+ append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
//vsri
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//VQSHL{u}
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
//vqrshr{U}n
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vqshr{u}n
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//Comparison instructions
//VACGE, VACGT, VACLE,VACLT
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vceq reg
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vceq imm
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcge reg
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vcge imm
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcgt reg
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vcgt imm
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcle imm
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vclt imm
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vtst reg
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
}
private static void fillInstructions01(){
// Multiply instructions
//VMLA
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), AllISingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, false), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, false), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), U16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), U32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), U16.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), U32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), I16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), I32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), I16.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), I32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmla, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
//VMLAL
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlal, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
// VMLS
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), AllISingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, false), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, false), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), U16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), U32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), U16.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), U32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), I16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), I32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), I16.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), I32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmls, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
//VMLSL
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmlsl, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
// VMUL
//quad
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllP.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllP.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
//double
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, false), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmul, EnumRegisterType.QUAD, true), F32.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
// VMULL
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, false), AllISingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, false), AllP.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, true), I16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, true), I32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, true), U16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, true), U32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vmull, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
// VQDMLAL
append(new MultiplyInstruction(EnumInstruction.vqdmlal, EnumRegisterType.QUAD, false), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmlal, EnumRegisterType.QUAD, false), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmlal, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmlal, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
// VQDMLSL
append(new MultiplyInstruction(EnumInstruction.vqdmlsl, EnumRegisterType.QUAD, false), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmlsl, EnumRegisterType.QUAD, false), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmlsl, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmlsl, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
// VQDMULH
//quad type
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, false), S16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, false), S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, false), S16.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, false), S32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
//double
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmulh, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
// vqrdmulh
//quad type
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, false), S16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, false), S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, false), S16.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, false), S32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q2in1.p(), Comma.p(), DsubRegForScalar.p());
//double
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, true), S16.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqrdmulh, EnumRegisterType.DOUBLE, true), S32.p(), Space.p(), D2in1.p(), Comma.p(), DsubRegForScalar.p());
// VQDMULL
append(new MultiplyInstruction(EnumInstruction.vqdmull, EnumRegisterType.QUAD, false), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmull, EnumRegisterType.QUAD, false), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MultiplyInstruction(EnumInstruction.vqdmull, EnumRegisterType.QUAD, true), S16.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
append(new MultiplyInstruction(EnumInstruction.vqdmull, EnumRegisterType.QUAD, true), S32.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), DsubRegForScalar.p());
// ABSOLUTE AND NEGATE instructions
//vaba
append(new AbsoluteAndNegateInstruction(EnumInstruction.vaba, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vaba, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vaba, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vaba, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vabal
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabal, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabal, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vabd
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabd, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vabdl
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabdl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabdl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vabs
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabs, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabs, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabs, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vabs, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
//append(new AbsoluteAndNegateInstruction(EnumInstruction.vabs, EnumRegisterType.DOUBLE), F64.p(), Space.p(), D.p(), Comma.p(), D.p());
//append(new AbsoluteAndNegateInstruction(EnumInstruction.vabs, EnumRegisterType.QUAD), F64.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vqabs
append(new AbsoluteAndNegateInstruction(EnumInstruction.vqabs, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vqabs, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vneg
append(new AbsoluteAndNegateInstruction(EnumInstruction.vneg, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vneg, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vneg, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vneg, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
//vqneg
append(new AbsoluteAndNegateInstruction(EnumInstruction.vqneg, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new AbsoluteAndNegateInstruction(EnumInstruction.vqneg, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//CONVERSION INSTRUCTIONS
//vcvt : fixed < - > single
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, true), S32F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, true), S32F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, true), F32S32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, true), F32S32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, true), U32F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, true), U32F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, true), F32U32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, true), F32U32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
// vcvt: single < - > integer
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, false), S32F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, false), S32F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, false), F32S32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, false), F32S32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, false), U32F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, false), U32F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, false), F32U32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, false), F32U32.p(), Space.p(), D.p(), Comma.p(), D.p());
//vcvt: half < - > single precision
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.QUAD, false), F32F16.p(), Space.p(), Q.p(), Comma.p(), D.p());
append(new ConversationInstruction(EnumInstruction.vcvt, EnumRegisterType.DOUBLE, false), F16F32.p(), Space.p(), D.p(), Comma.p(), Q.p());
//COUNT INSTRUCTIONS
//vcls
append(new CountInstruction(EnumInstruction.vcls, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new CountInstruction(EnumInstruction.vcls, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vclz
append(new CountInstruction(EnumInstruction.vclz, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new CountInstruction(EnumInstruction.vclz, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vcnt
append(new CountInstruction(EnumInstruction.vcnt, EnumRegisterType.QUAD), _8.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new CountInstruction(EnumInstruction.vcnt, EnumRegisterType.DOUBLE), _8.p(), Space.p(), D.p(), Comma.p(), D.p());
//ZIP INSTRUCTIONS
//vzip
append(new ZipInstruction(EnumInstruction.vzip, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ZipInstruction(EnumInstruction.vzip, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), D.p());
//vuzip
append(new ZipInstruction(EnumInstruction.vuzp, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ZipInstruction(EnumInstruction.vuzp, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), D.p());
//VECTOR TRANSPOSE
//vtrn
append(new VtrnInstruction(EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new VtrnInstruction(EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), D.p());
//TABLE INSTRUCTION
//vtbl
append(new TableInstruction(EnumInstruction.vtbl, EnumRegisterType.DOUBLE, 1), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), D.p());
append(new TableInstruction(EnumInstruction.vtbl, EnumRegisterType.DOUBLE, 2), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), D.p());
append(new TableInstruction(EnumInstruction.vtbl, EnumRegisterType.DOUBLE, 3), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), D.p());
append(new TableInstruction(EnumInstruction.vtbl, EnumRegisterType.DOUBLE, 4), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), D.p());
//vtbx
append(new TableInstruction(EnumInstruction.vtbx, EnumRegisterType.DOUBLE, 1), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), D.p());
append(new TableInstruction(EnumInstruction.vtbx, EnumRegisterType.DOUBLE, 2), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), D.p());
append(new TableInstruction(EnumInstruction.vtbx, EnumRegisterType.DOUBLE, 3), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), D.p());
append(new TableInstruction(EnumInstruction.vtbx, EnumRegisterType.DOUBLE, 4), _8.p(), Space.p(), D.p(), Comma.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), D.p());
//SWAP INSTRUCTION
//vswp
append(new VswpInstruction(EnumRegisterType.QUAD), All.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new VswpInstruction(EnumRegisterType.DOUBLE), All.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new VswpInstruction(EnumRegisterType.QUAD), Space.p(), Q.p(), Comma.p(), Q.p());
append(new VswpInstruction(EnumRegisterType.DOUBLE), Space.p(), D.p(), Comma.p(), D.p());
//REVERSE INSTRUCTION
//vrev32
append(new ReverseInstruction(EnumInstruction.vrev16, EnumRegisterType.QUAD), _8.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReverseInstruction(EnumInstruction.vrev16, EnumRegisterType.DOUBLE), _8.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ReverseInstruction(EnumInstruction.vrev32, EnumRegisterType.QUAD), _8.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReverseInstruction(EnumInstruction.vrev32, EnumRegisterType.DOUBLE), _8.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ReverseInstruction(EnumInstruction.vrev32, EnumRegisterType.QUAD), _16.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReverseInstruction(EnumInstruction.vrev32, EnumRegisterType.DOUBLE), _16.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ReverseInstruction(EnumInstruction.vrev64, EnumRegisterType.QUAD), _8.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReverseInstruction(EnumInstruction.vrev64, EnumRegisterType.DOUBLE), _8.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ReverseInstruction(EnumInstruction.vrev64, EnumRegisterType.QUAD), _16.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReverseInstruction(EnumInstruction.vrev64, EnumRegisterType.DOUBLE), _16.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ReverseInstruction(EnumInstruction.vrev64, EnumRegisterType.QUAD), _32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReverseInstruction(EnumInstruction.vrev64, EnumRegisterType.DOUBLE), _32.p(), Space.p(), D.p(), Comma.p(), D.p());
//MINIMUM AND MAXIMUM INSTRUCTION
//vmin
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmin, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vmax
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vmax, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpmin
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmin, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpmax
// there is NO QUAD version!
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmax, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmax, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmax, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmax, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmax, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new MinimumAndMaximumInstruction(EnumInstruction.vpmax, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//RECIPROCAL ESTIMATE
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrecpe, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrecpe, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrecpe, EnumRegisterType.QUAD), U32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrecpe, EnumRegisterType.DOUBLE), U32.p(), Space.p(), D.p(), Comma.p(), D.p());
//vrsqrte
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrsqrte, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrsqrte, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrsqrte, EnumRegisterType.QUAD), U32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalEstimate(EnumInstruction.vrsqrte, EnumRegisterType.DOUBLE), U32.p(), Space.p(), D.p(), Comma.p(), D.p());
//FIXME: add testcases
//RECIPROCAL (SQUARE ROOT) STEP
//vrsqrts
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrsqrts, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrsqrts, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrsqrts, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrsqrts, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vrecps
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrecps, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrecps, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrecps, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ReciprocalSqrtReciprocalStep(EnumInstruction.vrecps, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//EXTRACT
//vext
append(new VextInstruction(EnumInstruction.vext, EnumRegisterType.QUAD), All.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p() , Comma.p(), ImmTimesDtDividedBy8IsMax15.p());
append(new VextInstruction(EnumInstruction.vext, EnumRegisterType.DOUBLE), All.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p() , Comma.p(), ImmTimesDtDividedBy8IsMax7.p());
append(new VextInstruction(EnumInstruction.vext, EnumRegisterType.QUAD), All.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p(), Comma.p(), ImmTimesDtDividedBy8IsMax15.p());
append(new VextInstruction(EnumInstruction.vext, EnumRegisterType.DOUBLE), All.p(), Space.p(), D2in1.p(), Comma.p(), D.p(), Comma.p(), ImmTimesDtDividedBy8IsMax7.p());
//VMRS and VMSR
append(new MoveFPSCAndRAPSR(EnumInstruction.vmrs), Space.p(), R.p(), Comma.p(), FPSCR.p());
append(new MoveFPSCAndRAPSR(EnumInstruction.vmsr), Space.p(), FPSCR.p(), Comma.p(), R.p());
}
private static void append(Instruction create, Token... tokens) {
EnumInstruction instruction = create.getInstructionName();
List<InstructionForm> list = instructionList.get(instruction);
if (list == null) {
list = new ArrayList<InstructionForm>();
instructionList.put(instruction, list);
}
Token[] formatsWithEnd = new Token[tokens.length + 1];
for (int i = 0; i < tokens.length; i++) {
formatsWithEnd[i] = tokens[i];
}
formatsWithEnd[tokens.length] = End.p();
list.add(new InstructionForm(create, formatsWithEnd));
}
/***
* Returns a list of InstuctionForms for the given insturction name.
*
* @param instruction
* @return List of instruction formats for the given instruction.
*/
public static List<InstructionForm> get(EnumInstruction instruction) {
return instructionList.get(instruction);
}
}
| true | true | private static void fillInstructions00(){
//ARITHMETIC2
//vadd int
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vadd float
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vsub int
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vsub float
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vaddhn
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vsubhn
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vaddl
append(new ArithmeticInstructions(EnumInstruction.vaddl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vaddw
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
//vsubl
append(new ArithmeticInstructions(EnumInstruction.vsubl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vsubw
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
//vhadd
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vhsub
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpadal
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vpadd integer
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpadd float
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpaddl
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vraddhn
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vrsubn
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vrhadd
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vqadd
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vqsub
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//LOGICAL2
//vand register
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vand immediate
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVbic.p());
//vbic immediate
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVbic.p());
//vbic register
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//veor register
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbif register
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbit register
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbsl register
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vorr register
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vorr immediate
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVorr.p());
//vorn register
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//MOVE
// special vmov
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_D), Space.p(), D.p(), Comma.p(), RNotPCNotSP.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.D_TO_ARM), Space.p(), RNotPCNotSP.p(), Comma.p(), RNotPCNotSP.p(), Comma.p(), D.p());
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_DSUB), AllSingleWide.p(), Space.p(), DSubReg.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_DSUB), DefType.p(EnumDataType._32), Space.p(), DSubReg.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), AllSignedSingle.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), AllUnsignedSingle.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), All32.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), DefType.p(EnumDataType._32), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
//ordinary move
//vmov neon imm
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.QUAD, true), All.p(), Space.p(), Q.p(), Comma.p(), ImmVmov.p());
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.DOUBLE, true), All.p(), Space.p(), D.p(), Comma.p(), ImmVmov.p());
//vmov neon neon
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p());
//vmvn neon imm
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.QUAD, true), All.p(), Space.p(), Q.p(), Comma.p(), ImmVmvn.p());
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.DOUBLE, true), All.p(), Space.p(), D.p(), Comma.p(), ImmVmvn.p());
//vmvn neon neon
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p());
//vmovn neon neon
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I64.p(), Space.p(), D.p(), Comma.p(), Q.p());
//vmovl neon neon
append(new MoveInstruction(EnumInstruction.vmovl, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p());
append(new MoveInstruction(EnumInstruction.vmovl, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p());
//vqmov{u}n neon neon
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S64.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U64.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S64.p(), Space.p(), D.p(), Comma.p(), Q.p());
//DUPLICATE
// #vdup
append(new VdupInstruction(false, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), DSubReg.p());
append(new VdupInstruction(false, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), DSubReg.p());
append(new VdupInstruction(true, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), R.p());
append(new VdupInstruction(true, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), R.p());
// VLD: #vld1 #vld2 #vld3 #vld4
// #vld1: all
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, true), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, true), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, true), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, true), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// #vld1: One
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// #vld1: Repeat one
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld2: all
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vld2: one
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld2: repeat one
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld3: all
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld3: one
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, true), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, true), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld3: one repeat
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld4: all
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vld4: one
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
// vld4: one repeat
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
// VST: #vst1 #vst2 #vst3 #vst4
// #vst1: ALL
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, true), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, true), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, true), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, true), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst1: ONE
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
// vst2: ALL
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst2: ONE
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vst3: ALL
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vst3: ONE
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, true), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, true), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vst4: ALL
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst4: ONE
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
//SHIFT instructions
//vqrshl
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vshl
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vshr
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vsra
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vrshl
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vrshr
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vrsra
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vshll //only VSHLL<c><q>.<type><size> <Qd>, <Dm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), ImmIsSize.p());
//vshrn //only VSHRN<c><q>.I<size> <Dd>, <Qm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vrshrn //VRSHRN<c><q>.I<size> <Dd>, <Qm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vsli
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vsri
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//VQSHL{u}
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
//vqrshr{U}n
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vqshr{u}n
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//Comparison instructions
//VACGE, VACGT, VACLE,VACLT
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vceq reg
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vceq imm
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcge reg
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vcge imm
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcgt reg
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vcgt imm
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcle imm
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vclt imm
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vtst reg
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
}
| private static void fillInstructions00(){
//ARITHMETIC2
//vadd int
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vadd float
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vsub int
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), AllI.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), AllI.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vsub float
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.QUAD), F32.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsub, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vaddhn
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vaddhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vsubhn
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vsubhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vaddl
append(new ArithmeticInstructions(EnumInstruction.vaddl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vaddw
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vaddw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
//vsubl
append(new ArithmeticInstructions(EnumInstruction.vsubl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), D.p());
//vsubw
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vsubw, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), D.p());
//vhadd
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vhsub
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vhsub, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpadal
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadal, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vpadd integer
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpadd float
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpadd, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vpaddl
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vpaddl, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
//vraddhn
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vraddhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vrsubn
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrsubhn, EnumRegisterType.DOUBLE), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
//vrhadd
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vrhadd, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vqadd
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqadd, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vqsub
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.QUAD), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ArithmeticInstructions(EnumInstruction.vqsub, EnumRegisterType.DOUBLE), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//LOGICAL2
//vand register
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vand immediate
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vand, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVbic.p());
//vbic immediate
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVbic.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVbic.p());
//vbic register
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbic, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//veor register
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.veor, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbif register
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbif, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbit register
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbit, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vbsl register
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vbsl, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vorr register
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vorr immediate
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.QUAD, true), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmVorr.p());
append(new LogicalInstruction(EnumInstruction.vorr, EnumRegisterType.DOUBLE, true), OptType.p(), Space.p(), D2in1.p(), Comma.p(), ImmVorr.p());
//vorn register
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new LogicalInstruction(EnumInstruction.vorn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//MOVE
// special vmov
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_D), Space.p(), D.p(), Comma.p(), RNotPCNotSP.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.D_TO_ARM), Space.p(), RNotPCNotSP.p(), Comma.p(), RNotPCNotSP.p(), Comma.p(), D.p());
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_DSUB), AllSingleWide.p(), Space.p(), DSubReg.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.ARM_TO_DSUB), DefType.p(EnumDataType._32), Space.p(), DSubReg.p(), Comma.p(), RNotPCNotSP.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), AllSignedSingle.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), AllUnsignedSingle.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), All32.p(), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
append(new VmovInstruction(VmovInstruction.Mode.DSUB_TO_ARM), DefType.p(EnumDataType._32), Space.p(), RNotPCNotSP.p(), Comma.p(), DSubReg.p());
//ordinary move
//vmov neon imm
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.QUAD, true), All.p(), Space.p(), Q.p(), Comma.p(), ImmVmov.p());
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.DOUBLE, true), All.p(), Space.p(), D.p(), Comma.p(), ImmVmov.p());
//vmov neon neon
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmov, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p());
//vmvn neon imm
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.QUAD, true), All.p(), Space.p(), Q.p(), Comma.p(), ImmVmvn.p());
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.DOUBLE, true), All.p(), Space.p(), D.p(), Comma.p(), ImmVmvn.p());
//vmvn neon neon
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.QUAD, false), OptType.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmvn, EnumRegisterType.DOUBLE, false), OptType.p(), Space.p(), D.p(), Comma.p(), D.p());
//vmovn neon neon
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vmovn, EnumRegisterType.DOUBLE, false), I64.p(), Space.p(), D.p(), Comma.p(), Q.p());
//vmovl neon neon
append(new MoveInstruction(EnumInstruction.vmovl, EnumRegisterType.QUAD, false), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p());
append(new MoveInstruction(EnumInstruction.vmovl, EnumRegisterType.QUAD, false), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p());
//vqmov{u}n neon neon
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovun, EnumRegisterType.DOUBLE, false), S64.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), U64.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S16.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S32.p(), Space.p(), D.p(), Comma.p(), Q.p());
append(new MoveInstruction(EnumInstruction.vqmovn, EnumRegisterType.DOUBLE, false), S64.p(), Space.p(), D.p(), Comma.p(), Q.p());
//DUPLICATE
// #vdup
append(new VdupInstruction(false, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), DSubReg.p());
append(new VdupInstruction(false, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), DSubReg.p());
append(new VdupInstruction(true, EnumRegisterType.QUAD), AllSingleWide.p(), Space.p(), Q.p(), Comma.p(), R.p());
append(new VdupInstruction(true, EnumRegisterType.DOUBLE), AllSingleWide.p(), Space.p(), D.p(), Comma.p(), R.p());
// VLD: #vld1 #vld2 #vld3 #vld4
// #vld1: all
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 1, 1, true), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 2, 1, true), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 3, 1, true), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ALL, 4, 1, true), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// #vld1: One
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE, 1, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// #vld1: Repeat one
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 1, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(1, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld1, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld2: all
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 2, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vld2: one
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld2: repeat one
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All8.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld2, MemoryInstruction.Mode.ONE_REPEAT, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld3: all
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ALL, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vld3: one
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, true), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE, 3, 2, true), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld3: one repeat
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld3, MemoryInstruction.Mode.ONE_REPEAT, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vld4: all
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ALL, 4, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vld4: one
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
// vld4: one repeat
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vld4, MemoryInstruction.Mode.ONE_REPEAT, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
// VST: #vst1 #vst2 #vst3 #vst4
// #vst1: ALL
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, false), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 1, 1, true), All.p(), Space.p(), ListSubIndex.p(1, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, false), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 2, 1, true), All.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, false), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 3, 1, true), All.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, false), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ALL, 4, 1, true), All.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst1: ONE
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All8.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All16.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, false), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst1, MemoryInstruction.Mode.ONE, 1, 1, true), All32.p(), Space.p(), ListSubIndex.p(1, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
// vst2: ALL
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 2, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(2, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst2: ONE
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All8.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 16 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All16.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, false), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 1, true), All32.p(), Space.p(), ListSubIndex.p(2, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, true), All16.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, false), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst2, MemoryInstruction.Mode.ONE, 2, 2, true), All32.p(), Space.p(), ListSubIndex.p(2, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vst3: ALL
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ALL, 3, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
// vst3: ONE
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(3, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, true), All16.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }));
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, false), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst3, MemoryInstruction.Mode.ONE, 3, 2, true), All32.p(), Space.p(), ListSubIndex.p(3, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8 }), WriteBack.p());
// vst4: ALL
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 1, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 1, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, false), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ALL, 4, 2, true), AllSingleWide.p(), Space.p(), ListSubIndex.p(4, 2, false, false), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128, 256 }), WriteBack.p());
// vst4: ONE
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All8.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All16.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, false), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 1, true), All32.p(), Space.p(), ListSubIndex.p(4, 1, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All8.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 32 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All16.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64 }), WriteBack.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }));
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, false), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), Comma.p(), ROffset.p());
append(new MemoryInstruction(EnumInstruction.vst4, MemoryInstruction.Mode.ONE, 4, 2, true), All32.p(), Space.p(), ListSubIndex.p(4, 2, true, true), Comma.p(), BaseAddress.p(new int[] { 8, 64, 128 }), WriteBack.p());
//SHIFT instructions
//vqrshl
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
//vshl
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vshr
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vsra
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vrshl
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vrshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vrshr
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrshr, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vrsra
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vrsra, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//vshll //only VSHLL<c><q>.<type><size> <Qd>, <Dm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vshll, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), D.p(), Comma.p(), ImmIsSize.p());
//vshrn //only VSHRN<c><q>.I<size> <Dd>, <Qm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vshrn, EnumRegisterType.QUAD, true), _64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vrshrn //VRSHRN<c><q>.I<size> <Dd>, <Qm>, #<imm>
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), I64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vrshrn, EnumRegisterType.QUAD, true), _64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vsli
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vsli, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
//vsri
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.DOUBLE, true), AllI.p(), Space.p(), D.p(), Comma.p(), Imm1toSize.p());
append(new ShiftInstruction(EnumInstruction.vsri, EnumRegisterType.QUAD, true), AllI.p(), Space.p(), Q.p(), Comma.p(), Imm1toSize.p());
//VQSHL{u}
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllS.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, false), AllU.p(), Space.p(), Q2in1.p(), Comma.p(), Q.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllS.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, false), AllU.p(), Space.p(), D2in1.p(), Comma.p(), D.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.DOUBLE, true), AllU.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshl, EnumRegisterType.QUAD, true), AllU.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.DOUBLE, true), AllS.p(), Space.p(), D.p(), Comma.p(), Imm0toSizeMinus1.p());
append(new ShiftInstruction(EnumInstruction.vqshlu, EnumRegisterType.QUAD, true), AllS.p(), Space.p(), Q.p(), Comma.p(), Imm0toSizeMinus1.p());
//vqrshr{U}n
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrn, EnumRegisterType.QUAD, true), U64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqrshrun, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//vqshr{u}n
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrn, EnumRegisterType.QUAD, true), U64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S16.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S32.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
append(new ShiftInstruction(EnumInstruction.vqshrun, EnumRegisterType.QUAD, true), S64.p(), Space.p(), D.p(), Comma.p(), Q.p(), Comma.p(), Imm1toHalfSize.p());
//Comparison instructions
//VACGE, VACGT, VACLE,VACLT
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vacle, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vaclt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vceq reg
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vceq imm
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), AllISingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), AllISingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vceq, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcge reg
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vcge imm
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcge, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcgt reg
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), AllUnsignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), AllUnsignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE), F32.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p());
//vcgt imm
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcgt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vcle imm
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vcle, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vclt imm
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), AllSignedSingle.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), AllSignedSingle.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.DOUBLE, true), F32.p(), Space.p(), D.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), ImmIsZero.p());
append(new ComparisonInstruction(EnumInstruction.vclt, EnumRegisterType.QUAD, true), F32.p(), Space.p(), Q.p(), Comma.p(), ImmIsZero.p());
//vtst reg
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.DOUBLE), AllISingle.p(), Space.p(), D.p(), Comma.p(), D.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p(), Comma.p(), Q.p());
append(new ComparisonInstruction(EnumInstruction.vtst, EnumRegisterType.QUAD), AllISingle.p(), Space.p(), Q.p(), Comma.p(), Q.p());
}
|
diff --git a/main/src/com/google/refine/browsing/facets/RangeFacet.java b/main/src/com/google/refine/browsing/facets/RangeFacet.java
index 6b63cf11..d2c696a4 100644
--- a/main/src/com/google/refine/browsing/facets/RangeFacet.java
+++ b/main/src/com/google/refine/browsing/facets/RangeFacet.java
@@ -1,259 +1,261 @@
package com.google.refine.browsing.facets;
import java.util.Properties;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.google.refine.browsing.FilteredRecords;
import com.google.refine.browsing.FilteredRows;
import com.google.refine.browsing.RecordFilter;
import com.google.refine.browsing.RowFilter;
import com.google.refine.browsing.filters.AnyRowRecordFilter;
import com.google.refine.browsing.filters.ExpressionNumberComparisonRowFilter;
import com.google.refine.browsing.util.ExpressionBasedRowEvaluable;
import com.google.refine.browsing.util.ExpressionNumericValueBinner;
import com.google.refine.browsing.util.NumericBinIndex;
import com.google.refine.browsing.util.NumericBinRecordIndex;
import com.google.refine.browsing.util.NumericBinRowIndex;
import com.google.refine.browsing.util.RowEvaluable;
import com.google.refine.expr.Evaluable;
import com.google.refine.expr.MetaParser;
import com.google.refine.expr.ParsingException;
import com.google.refine.model.Column;
import com.google.refine.model.Project;
import com.google.refine.util.JSONUtilities;
public class RangeFacet implements Facet {
/*
* Configuration, from the client side
*/
protected String _name; // name of facet
protected String _expression; // expression to compute numeric value(s) per row
protected String _columnName; // column to base expression on, if any
protected double _from; // the numeric selection
protected double _to;
protected boolean _selectNumeric; // whether the numeric selection applies, default true
protected boolean _selectNonNumeric;
protected boolean _selectBlank;
protected boolean _selectError;
/*
* Derived configuration data
*/
protected int _cellIndex;
protected Evaluable _eval;
protected String _errorMessage;
protected boolean _selected; // false if we're certain that all rows will match
// and there isn't any filtering to do
/*
* Computed data, to return to the client side
*/
protected double _min;
protected double _max;
protected double _step;
protected int[] _baseBins;
protected int[] _bins;
protected int _baseNumericCount;
protected int _baseNonNumericCount;
protected int _baseBlankCount;
protected int _baseErrorCount;
protected int _numericCount;
protected int _nonNumericCount;
protected int _blankCount;
protected int _errorCount;
public RangeFacet() {
}
protected static final String MIN = "min";
protected static final String MAX = "max";
protected static final String TO = "to";
protected static final String FROM = "from";
public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("name"); writer.value(_name);
writer.key("expression"); writer.value(_expression);
writer.key("columnName"); writer.value(_columnName);
if (_errorMessage != null) {
writer.key("error"); writer.value(_errorMessage);
} else {
if (!Double.isInfinite(_min) && !Double.isInfinite(_max)) {
writer.key(MIN); writer.value(_min);
writer.key(MAX); writer.value(_max);
writer.key("step"); writer.value(_step);
writer.key("bins"); writer.array();
for (int b : _bins) {
writer.value(b);
}
writer.endArray();
writer.key("baseBins"); writer.array();
for (int b : _baseBins) {
writer.value(b);
}
writer.endArray();
writer.key(FROM); writer.value(_from);
writer.key(TO); writer.value(_to);
+ } else {
+ writer.key("error"); writer.value("No numeric value present.");
}
writer.key("baseNumericCount"); writer.value(_baseNumericCount);
writer.key("baseNonNumericCount"); writer.value(_baseNonNumericCount);
writer.key("baseBlankCount"); writer.value(_baseBlankCount);
writer.key("baseErrorCount"); writer.value(_baseErrorCount);
writer.key("numericCount"); writer.value(_numericCount);
writer.key("nonNumericCount"); writer.value(_nonNumericCount);
writer.key("blankCount"); writer.value(_blankCount);
writer.key("errorCount"); writer.value(_errorCount);
}
writer.endObject();
}
public void initializeFromJSON(Project project, JSONObject o) throws Exception {
_name = o.getString("name");
_expression = o.getString("expression");
_columnName = o.getString("columnName");
if (_columnName.length() > 0) {
Column column = project.columnModel.getColumnByName(_columnName);
if (column != null) {
_cellIndex = column.getCellIndex();
} else {
_errorMessage = "No column named " + _columnName;
}
} else {
_cellIndex = -1;
}
try {
_eval = MetaParser.parse(_expression);
} catch (ParsingException e) {
_errorMessage = e.getMessage();
}
if (o.has(FROM) || o.has(TO)) {
_from = o.has(FROM) ? o.getDouble(FROM) : _min;
_to = o.has(TO) ? o.getDouble(TO) : _max;
_selected = true;
}
_selectNumeric = JSONUtilities.getBoolean(o, "selectNumeric", true);
_selectNonNumeric = JSONUtilities.getBoolean(o, "selectNonNumeric", true);
_selectBlank = JSONUtilities.getBoolean(o, "selectBlank", true);
_selectError = JSONUtilities.getBoolean(o, "selectError", true);
if (!_selectNumeric || !_selectNonNumeric || !_selectBlank || !_selectError) {
_selected = true;
}
}
public RowFilter getRowFilter(Project project) {
if (_eval != null && _errorMessage == null && _selected) {
return new ExpressionNumberComparisonRowFilter(
getRowEvaluable(project), _selectNumeric, _selectNonNumeric, _selectBlank, _selectError) {
protected boolean checkValue(double d) {
return d >= _from && d < _to;
};
};
} else {
return null;
}
}
@Override
public RecordFilter getRecordFilter(Project project) {
RowFilter rowFilter = getRowFilter(project);
return rowFilter == null ? null : new AnyRowRecordFilter(rowFilter);
}
public void computeChoices(Project project, FilteredRows filteredRows) {
if (_eval != null && _errorMessage == null) {
RowEvaluable rowEvaluable = getRowEvaluable(project);
Column column = project.columnModel.getColumnByCellIndex(_cellIndex);
String key = "numeric-bin:row-based:" + _expression;
NumericBinIndex index = (NumericBinIndex) column.getPrecompute(key);
if (index == null) {
index = new NumericBinRowIndex(project, rowEvaluable);
column.setPrecompute(key, index);
}
retrieveDataFromBaseBinIndex(index);
ExpressionNumericValueBinner binner =
new ExpressionNumericValueBinner(rowEvaluable, index);
filteredRows.accept(project, binner);
retrieveDataFromBinner(binner);
}
}
public void computeChoices(Project project, FilteredRecords filteredRecords) {
if (_eval != null && _errorMessage == null) {
RowEvaluable rowEvaluable = getRowEvaluable(project);
Column column = project.columnModel.getColumnByCellIndex(_cellIndex);
String key = "numeric-bin:record-based:" + _expression;
NumericBinIndex index = (NumericBinIndex) column.getPrecompute(key);
if (index == null) {
index = new NumericBinRecordIndex(project, rowEvaluable);
column.setPrecompute(key, index);
}
retrieveDataFromBaseBinIndex(index);
ExpressionNumericValueBinner binner =
new ExpressionNumericValueBinner(rowEvaluable, index);
filteredRecords.accept(project, binner);
retrieveDataFromBinner(binner);
}
}
protected RowEvaluable getRowEvaluable(Project project) {
return new ExpressionBasedRowEvaluable(_columnName, _cellIndex, _eval);
}
protected void retrieveDataFromBaseBinIndex(NumericBinIndex index) {
_min = index.getMin();
_max = index.getMax();
_step = index.getStep();
_baseBins = index.getBins();
_baseNumericCount = index.getNumericRowCount();
_baseNonNumericCount = index.getNonNumericRowCount();
_baseBlankCount = index.getBlankRowCount();
_baseErrorCount = index.getErrorRowCount();
if (_selected) {
_from = Math.max(_from, _min);
_to = Math.min(_to, _max);
} else {
_from = _min;
_to = _max;
}
}
protected void retrieveDataFromBinner(ExpressionNumericValueBinner binner) {
_bins = binner.bins;
_numericCount = binner.numericCount;
_nonNumericCount = binner.nonNumericCount;
_blankCount = binner.blankCount;
_errorCount = binner.errorCount;
}
}
| true | true | public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("name"); writer.value(_name);
writer.key("expression"); writer.value(_expression);
writer.key("columnName"); writer.value(_columnName);
if (_errorMessage != null) {
writer.key("error"); writer.value(_errorMessage);
} else {
if (!Double.isInfinite(_min) && !Double.isInfinite(_max)) {
writer.key(MIN); writer.value(_min);
writer.key(MAX); writer.value(_max);
writer.key("step"); writer.value(_step);
writer.key("bins"); writer.array();
for (int b : _bins) {
writer.value(b);
}
writer.endArray();
writer.key("baseBins"); writer.array();
for (int b : _baseBins) {
writer.value(b);
}
writer.endArray();
writer.key(FROM); writer.value(_from);
writer.key(TO); writer.value(_to);
}
writer.key("baseNumericCount"); writer.value(_baseNumericCount);
writer.key("baseNonNumericCount"); writer.value(_baseNonNumericCount);
writer.key("baseBlankCount"); writer.value(_baseBlankCount);
writer.key("baseErrorCount"); writer.value(_baseErrorCount);
writer.key("numericCount"); writer.value(_numericCount);
writer.key("nonNumericCount"); writer.value(_nonNumericCount);
writer.key("blankCount"); writer.value(_blankCount);
writer.key("errorCount"); writer.value(_errorCount);
}
writer.endObject();
}
| public void write(JSONWriter writer, Properties options)
throws JSONException {
writer.object();
writer.key("name"); writer.value(_name);
writer.key("expression"); writer.value(_expression);
writer.key("columnName"); writer.value(_columnName);
if (_errorMessage != null) {
writer.key("error"); writer.value(_errorMessage);
} else {
if (!Double.isInfinite(_min) && !Double.isInfinite(_max)) {
writer.key(MIN); writer.value(_min);
writer.key(MAX); writer.value(_max);
writer.key("step"); writer.value(_step);
writer.key("bins"); writer.array();
for (int b : _bins) {
writer.value(b);
}
writer.endArray();
writer.key("baseBins"); writer.array();
for (int b : _baseBins) {
writer.value(b);
}
writer.endArray();
writer.key(FROM); writer.value(_from);
writer.key(TO); writer.value(_to);
} else {
writer.key("error"); writer.value("No numeric value present.");
}
writer.key("baseNumericCount"); writer.value(_baseNumericCount);
writer.key("baseNonNumericCount"); writer.value(_baseNonNumericCount);
writer.key("baseBlankCount"); writer.value(_baseBlankCount);
writer.key("baseErrorCount"); writer.value(_baseErrorCount);
writer.key("numericCount"); writer.value(_numericCount);
writer.key("nonNumericCount"); writer.value(_nonNumericCount);
writer.key("blankCount"); writer.value(_blankCount);
writer.key("errorCount"); writer.value(_errorCount);
}
writer.endObject();
}
|
diff --git a/clitest/src/com/redhat/qe/jon/clitest/tests/plugins/eap6/standalone/DiscoveryTest.java b/clitest/src/com/redhat/qe/jon/clitest/tests/plugins/eap6/standalone/DiscoveryTest.java
index 3b90326a..a3ab0be3 100644
--- a/clitest/src/com/redhat/qe/jon/clitest/tests/plugins/eap6/standalone/DiscoveryTest.java
+++ b/clitest/src/com/redhat/qe/jon/clitest/tests/plugins/eap6/standalone/DiscoveryTest.java
@@ -1,116 +1,116 @@
package com.redhat.qe.jon.clitest.tests.plugins.eap6.standalone;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.redhat.qe.jon.clitest.tasks.CliTasksException;
import com.redhat.qe.jon.clitest.tests.plugins.eap6.AS7CliTest;
import com.redhat.qe.jon.clitest.tests.plugins.eap6.ServerStartConfig;
import com.redhat.qe.jon.common.util.AS7SSHClient;
/**
* this test starts up AS7 in standalone mode with different configurations (standalone.sh parameters)
* and checks whether AS7 was detected correctly
* @author [email protected]
*
*/
public class DiscoveryTest extends AS7CliTest {
@BeforeClass()
public void beforeClass() {
sshClient = new AS7SSHClient(standalone1Home,"hudson",standalone1HostName,"hudson");
}
@DataProvider
public Object[][] createStartupConfigurations() {
List<ServerStartConfig> configs = new ArrayList<ServerStartConfig>();
// listen on all intefraces (currently default .. it is safe to keep this test as first)
configs.add(new ServerStartConfig("standalone.sh", "hostname=0.0.0.0"));
// listen on localhost
configs.add(new ServerStartConfig("standalone.sh -bmanagement localhost", "hostname=localhost"));
configs.add(new ServerStartConfig(
"standalone.sh -c=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// listen on IPv6 all localhost
- configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -b management ::1", "hostname=::1"));
+ configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -bmanagement ::1", "hostname=::1"));
// BZ 820570
configs.add(new ServerStartConfig(
"standalone.sh -P file://${HOME}/"+sshClient.getAsHome()+"/bin/props.properties",
"port=29990",
"echo \"jboss.management.http.port=29990\" > bin/props.properties")
);
// listen on IPv6 all interfaces
- configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -b management ::", "hostname=::"));
+ configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -bmanagement ::", "hostname=::"));
// listen on particular port
configs.add(new ServerStartConfig("standalone.sh -Djboss.management.http.port=29990","port=29990"));
// start with port offset we assume default http management port is 9990
configs.add(new ServerStartConfig("standalone.sh -Djboss.socket.binding.port-offset=1000","port=10990"));
configs.add(new ServerStartConfig(
"standalone.sh --server-config=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// BZ 820570
configs.add(new ServerStartConfig(
"standalone.sh --properties file://${HOME}/"+sshClient.getAsHome()+"/props.properties",
"port=10990",
"echo \"jboss.socket.binding.port-offset=1000\" > props.properties")
);
// override config dir
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.config.dir=${HOME}/"+sshClient.getAsHome()+"/standalone/configuration2",
"configuration2",
"cp -a standalone/configuration standalone/configuration2")
);
// BZ 820570 using relative path
configs.add(new ServerStartConfig(
"standalone.sh -P=props.properties",
"port=10990",
"echo \"jboss.socket.binding.port-offset=1000\" > bin/props.properties")
);
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.default.config=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// override basedir
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.base.dir=${HOME}/"+sshClient.getAsHome()+"/standalone2",
"standalone2",
"cp -a standalone standalone2")
);
// start in full profile - more ways doing it
configs.add(new ServerStartConfig(
"standalone.sh -c=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
Object[][] output = new Object[configs.size()][];
for (int i=0;i<configs.size();i++) {
output[i] = new Object[] {configs.get(i)};
}
return output;
}
@Test(
dataProvider="createStartupConfigurations",
description="This test starts up AS7 in standalone mode with particular configuration and runs eap6/standalone/discoveryTest.js to detect and import it"
)
public void serverStartupTest(ServerStartConfig start) throws IOException, CliTasksException {
serverStartup(start,"eap6/standalone/discoveryTest.js");
}
@AfterClass
public void teardown() {
// we start AS with all defaults (as it was before)
log.info("Starting server with default (none) parameters");
sshClient.restart("standalone.sh");
}
}
| false | true | public Object[][] createStartupConfigurations() {
List<ServerStartConfig> configs = new ArrayList<ServerStartConfig>();
// listen on all intefraces (currently default .. it is safe to keep this test as first)
configs.add(new ServerStartConfig("standalone.sh", "hostname=0.0.0.0"));
// listen on localhost
configs.add(new ServerStartConfig("standalone.sh -bmanagement localhost", "hostname=localhost"));
configs.add(new ServerStartConfig(
"standalone.sh -c=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// listen on IPv6 all localhost
configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -b management ::1", "hostname=::1"));
// BZ 820570
configs.add(new ServerStartConfig(
"standalone.sh -P file://${HOME}/"+sshClient.getAsHome()+"/bin/props.properties",
"port=29990",
"echo \"jboss.management.http.port=29990\" > bin/props.properties")
);
// listen on IPv6 all interfaces
configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -b management ::", "hostname=::"));
// listen on particular port
configs.add(new ServerStartConfig("standalone.sh -Djboss.management.http.port=29990","port=29990"));
// start with port offset we assume default http management port is 9990
configs.add(new ServerStartConfig("standalone.sh -Djboss.socket.binding.port-offset=1000","port=10990"));
configs.add(new ServerStartConfig(
"standalone.sh --server-config=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// BZ 820570
configs.add(new ServerStartConfig(
"standalone.sh --properties file://${HOME}/"+sshClient.getAsHome()+"/props.properties",
"port=10990",
"echo \"jboss.socket.binding.port-offset=1000\" > props.properties")
);
// override config dir
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.config.dir=${HOME}/"+sshClient.getAsHome()+"/standalone/configuration2",
"configuration2",
"cp -a standalone/configuration standalone/configuration2")
);
// BZ 820570 using relative path
configs.add(new ServerStartConfig(
"standalone.sh -P=props.properties",
"port=10990",
"echo \"jboss.socket.binding.port-offset=1000\" > bin/props.properties")
);
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.default.config=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// override basedir
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.base.dir=${HOME}/"+sshClient.getAsHome()+"/standalone2",
"standalone2",
"cp -a standalone standalone2")
);
// start in full profile - more ways doing it
configs.add(new ServerStartConfig(
"standalone.sh -c=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
Object[][] output = new Object[configs.size()][];
for (int i=0;i<configs.size();i++) {
output[i] = new Object[] {configs.get(i)};
}
return output;
}
| public Object[][] createStartupConfigurations() {
List<ServerStartConfig> configs = new ArrayList<ServerStartConfig>();
// listen on all intefraces (currently default .. it is safe to keep this test as first)
configs.add(new ServerStartConfig("standalone.sh", "hostname=0.0.0.0"));
// listen on localhost
configs.add(new ServerStartConfig("standalone.sh -bmanagement localhost", "hostname=localhost"));
configs.add(new ServerStartConfig(
"standalone.sh -c=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// listen on IPv6 all localhost
configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -bmanagement ::1", "hostname=::1"));
// BZ 820570
configs.add(new ServerStartConfig(
"standalone.sh -P file://${HOME}/"+sshClient.getAsHome()+"/bin/props.properties",
"port=29990",
"echo \"jboss.management.http.port=29990\" > bin/props.properties")
);
// listen on IPv6 all interfaces
configs.add(new ServerStartConfig("standalone.sh -Djava.net.preferIPv4Stack=false -bmanagement ::", "hostname=::"));
// listen on particular port
configs.add(new ServerStartConfig("standalone.sh -Djboss.management.http.port=29990","port=29990"));
// start with port offset we assume default http management port is 9990
configs.add(new ServerStartConfig("standalone.sh -Djboss.socket.binding.port-offset=1000","port=10990"));
configs.add(new ServerStartConfig(
"standalone.sh --server-config=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// BZ 820570
configs.add(new ServerStartConfig(
"standalone.sh --properties file://${HOME}/"+sshClient.getAsHome()+"/props.properties",
"port=10990",
"echo \"jboss.socket.binding.port-offset=1000\" > props.properties")
);
// override config dir
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.config.dir=${HOME}/"+sshClient.getAsHome()+"/standalone/configuration2",
"configuration2",
"cp -a standalone/configuration standalone/configuration2")
);
// BZ 820570 using relative path
configs.add(new ServerStartConfig(
"standalone.sh -P=props.properties",
"port=10990",
"echo \"jboss.socket.binding.port-offset=1000\" > bin/props.properties")
);
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.default.config=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
// override basedir
configs.add(new ServerStartConfig(
"standalone.sh -Djboss.server.base.dir=${HOME}/"+sshClient.getAsHome()+"/standalone2",
"standalone2",
"cp -a standalone standalone2")
);
// start in full profile - more ways doing it
configs.add(new ServerStartConfig(
"standalone.sh -c=standalone-full.xml",
"hostXmlFileName=standalone-full.xml")
);
Object[][] output = new Object[configs.size()][];
for (int i=0;i<configs.size();i++) {
output[i] = new Object[] {configs.get(i)};
}
return output;
}
|
diff --git a/src/java/org/wings/plaf/css/TextFieldCG.java b/src/java/org/wings/plaf/css/TextFieldCG.java
index e2de1034..2d58d89a 100644
--- a/src/java/org/wings/plaf/css/TextFieldCG.java
+++ b/src/java/org/wings/plaf/css/TextFieldCG.java
@@ -1,100 +1,100 @@
/*
* $Id$
* Copyright 2000,2005 wingS development team.
*
* This file is part of wingS (http://www.j-wings.org).
*
* wingS is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* Please see COPYING for the complete licence.
*/
package org.wings.plaf.css;
import org.wings.SComponent;
import org.wings.SFormattedTextField;
import org.wings.STextField;
import org.wings.io.Device;
import org.wings.plaf.css.dwr.CallableManager;
import org.wings.script.JavaScriptEvent;
import org.wings.script.ScriptListener;
import org.wings.text.SAbstractFormatter;
import java.io.IOException;
public final class TextFieldCG extends AbstractComponentCG implements
org.wings.plaf.TextFieldCG {
private static final long serialVersionUID = 1L;
public void componentChanged(SComponent component) {
final STextField textField = (STextField) component;
if (textField instanceof SFormattedTextField) {
SFormattedTextField formattedTextField = (SFormattedTextField) textField;
SAbstractFormatter formatter = formattedTextField.getFormatter();
String name = "formatter_" + System.identityHashCode(formatter);
if (!CallableManager.getInstance().containsCallable(name)) {
CallableManager.getInstance().registerCallable(name, formatter);
textField.putClientProperty("callable", name);
// keep a reference to the name, otherwise the callable will get garbage collected
ScriptListener[] scriptListeners = textField.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof DWRScriptListener)
textField.removeScriptListener(scriptListener);
}
textField.addScriptListener(new DWRScriptListener(JavaScriptEvent.ON_BLUR,
- "document.getElementById('{0}').getElementsByTagName('INPUT')[0].style.color = '';" +
+ "document.getElementById('{0}').style.color = '';" +
name +
- ".validate(callback_{0}, document.getElementById('{0}').getElementsByTagName('INPUT')[0].value)",
+ ".validate(callback_{0}, document.getElementById('{0}').value)",
"function callback_{0}(data) {\n" +
" if (!data && data != '') {\n" +
- " document.getElementById('{0}').getElementsByTagName('INPUT')[0].focus();\n" +
- " document.getElementById('{0}').getElementsByTagName('INPUT')[0].style.color = '#ff0000';\n" +
+ " document.getElementById('{0}').focus();\n" +
+ " document.getElementById('{0}').style.color = '#ff0000';\n" +
" }\n" +
" else\n" +
- " document.getElementById('{0}').getElementsByTagName('INPUT')[0].value = data;\n" +
+ " document.getElementById('{0}').value = data;\n" +
"}\n", new SComponent[] { textField }));
}
}
else {
super.componentChanged(component);
}
}
public void writeInternal(final Device device,
final SComponent component)
throws IOException {
final STextField textField = (STextField) component;
device.print("<input type=\"text\"");
writeAllAttributes(device, component);
Utils.optAttribute(device, "tabindex", textField.getFocusTraversalIndex());
Utils.optAttribute(device, "size", textField.getColumns());
Utils.optAttribute(device, "maxlength", textField.getMaxColumns());
Utils.writeEvents(device, textField, null);
if (textField.isFocusOwner())
Utils.optAttribute(device, "foc", textField.getName());
if (!textField.isEditable() || !textField.isEnabled()) {
device.print(" readonly=\"true\"");
}
if (textField.isEnabled()) {
device.print(" name=\"");
Utils.write(device, Utils.event(textField));
device.print("\"");
} else {
device.print(" disabled=\"true\"");
}
Utils.optAttribute(device, "value", textField.getText());
device.print("/>");
}
}
| false | true | public void componentChanged(SComponent component) {
final STextField textField = (STextField) component;
if (textField instanceof SFormattedTextField) {
SFormattedTextField formattedTextField = (SFormattedTextField) textField;
SAbstractFormatter formatter = formattedTextField.getFormatter();
String name = "formatter_" + System.identityHashCode(formatter);
if (!CallableManager.getInstance().containsCallable(name)) {
CallableManager.getInstance().registerCallable(name, formatter);
textField.putClientProperty("callable", name);
// keep a reference to the name, otherwise the callable will get garbage collected
ScriptListener[] scriptListeners = textField.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof DWRScriptListener)
textField.removeScriptListener(scriptListener);
}
textField.addScriptListener(new DWRScriptListener(JavaScriptEvent.ON_BLUR,
"document.getElementById('{0}').getElementsByTagName('INPUT')[0].style.color = '';" +
name +
".validate(callback_{0}, document.getElementById('{0}').getElementsByTagName('INPUT')[0].value)",
"function callback_{0}(data) {\n" +
" if (!data && data != '') {\n" +
" document.getElementById('{0}').getElementsByTagName('INPUT')[0].focus();\n" +
" document.getElementById('{0}').getElementsByTagName('INPUT')[0].style.color = '#ff0000';\n" +
" }\n" +
" else\n" +
" document.getElementById('{0}').getElementsByTagName('INPUT')[0].value = data;\n" +
"}\n", new SComponent[] { textField }));
}
}
else {
super.componentChanged(component);
}
}
| public void componentChanged(SComponent component) {
final STextField textField = (STextField) component;
if (textField instanceof SFormattedTextField) {
SFormattedTextField formattedTextField = (SFormattedTextField) textField;
SAbstractFormatter formatter = formattedTextField.getFormatter();
String name = "formatter_" + System.identityHashCode(formatter);
if (!CallableManager.getInstance().containsCallable(name)) {
CallableManager.getInstance().registerCallable(name, formatter);
textField.putClientProperty("callable", name);
// keep a reference to the name, otherwise the callable will get garbage collected
ScriptListener[] scriptListeners = textField.getScriptListeners();
for (int i = 0; i < scriptListeners.length; i++) {
ScriptListener scriptListener = scriptListeners[i];
if (scriptListener instanceof DWRScriptListener)
textField.removeScriptListener(scriptListener);
}
textField.addScriptListener(new DWRScriptListener(JavaScriptEvent.ON_BLUR,
"document.getElementById('{0}').style.color = '';" +
name +
".validate(callback_{0}, document.getElementById('{0}').value)",
"function callback_{0}(data) {\n" +
" if (!data && data != '') {\n" +
" document.getElementById('{0}').focus();\n" +
" document.getElementById('{0}').style.color = '#ff0000';\n" +
" }\n" +
" else\n" +
" document.getElementById('{0}').value = data;\n" +
"}\n", new SComponent[] { textField }));
}
}
else {
super.componentChanged(component);
}
}
|
diff --git a/src/org/wonderly/doclets/TableInfo.java b/src/org/wonderly/doclets/TableInfo.java
index 5bc9644..bdb8b1d 100644
--- a/src/org/wonderly/doclets/TableInfo.java
+++ b/src/org/wonderly/doclets/TableInfo.java
@@ -1,296 +1,295 @@
package org.wonderly.doclets;
import java.util.Enumeration;
import java.util.Properties;
/**
* This class provides support for converting HTML tables into LaTeX tables.
* Some of the things <b>NOT</b> implemented include the following:
* <ul>
* <li>valign attributes are not procesed, but align= is.
* <li>rowspan attributes are not processed, but colspan= is.
* <li>the argument to border= in the table tag is not used to control line size
* </ul>
* <br>
* Here is an example table.
* <p>
* <table border>
* <tr><th>Column 1 Heading<th>Column two heading<th>Column three heading
* <tr><td>data<td colspan=2>Span two columns
* <tr><td><i>more data</i><td align=right>right<td align=left>left
* <tr><td colspan=3><table border>
* <tr><th colspan=3>A nested table example
* <tr><th>Column 1 Heading</th><th>Column two heading</th><th>Column three heading</th>
* <tr><td>data</td><td colspan=2>Span two columns</td>
* <tr><td><i>more data</i></td><td align=right>right</td><td align=left>left</td>
* <tr><td><pre>
* 1
* 2
* 3
* 4
* </pre></td>
* <td><pre>
* first line
* second line
* third line
* fourth line
* </pre></td>
* </table>
* </table>
* </p>
*
* @version 1.0
* @author <a href="mailto:[email protected]">Gregg Wonderly</a>
*/
public class TableInfo {
private int rowcnt = 0;
private int colcnt = 0;
private boolean border = false;
private boolean colopen = false;
private int bordwid;
private boolean parboxed;
private boolean rowopen;
static int tblcnt;
int tblno;
String tc;
String hasProp(String prop, Properties p) {
if (p == null)
return null;
Enumeration<Object> e = p.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String val = p.getProperty(key);
if (key.equalsIgnoreCase(prop)) {
return val;
}
}
return null;
}
int hasNumProp(String prop, Properties p) {
String val = hasProp(prop, p);
if (val == null)
return -1;
try {
return Integer.parseInt(val);
} catch (Exception ex) {
}
return -1;
}
/**
* Constructs a new table object and starts processing of the table by
* scanning the <code><table></code> passed to count columns.
*
* @param p
* properties found on the <code><table></code> tag
* @param ret
* the result buffer that will contain the output
* @param table
* the input string that has the entire table definition in it.
* @param off
* the offset into <code><table></code> where scanning
* should start
*/
public TableInfo(Properties p, StringBuffer ret, String table, int off) {
tblno = tblcnt++;
tc = "" + (char) ('a' + (tblno / (26 * 26)))
+ (char) ((tblno / 26) + 'a') + (char) ((tblno % 26) + 'a');
if (p == null)
return;
String val = hasProp("border", p);
border = false;
if (val != null) {
border = true;
bordwid = 2;
if (val.equals("") == false) {
try {
bordwid = Integer.parseInt(val);
} catch (Exception ex) {
}
if (bordwid == 0)
border = false;
}
}
ret.append("\n% Table #" + tblno + "\n");
- byte[] b = table.getBytes();
int col = 0;
int row = 0;
- for (int i = off; i < b.length; ++i) {
- if (b[i] == '<') {
+ for (int i = off; i < table.length(); ++i) {
+ if (table.charAt(i) == '<') {
if (table.substring(i, i + 7).equalsIgnoreCase("</table")) {
break;
} else if (table.substring(i, i + 4).equalsIgnoreCase("</tr")) {
break;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<tr")) {
if (row++ > 0)
break;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<td")) {
Properties pp = new Properties();
int idx = HTMLToTex.getTagAttrs(table, pp, i + 3);
int v = hasNumProp("colspan", pp);
if (v > 0)
col += v;
else
col++;
i = idx - 1;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<th")) {
Properties pp = new Properties();
int idx = HTMLToTex.getTagAttrs(table, pp, i + 3);
int v = hasNumProp("colspan", pp);
if (v > 0)
col += v;
else
col++;
i = idx - 1;
}
}
}
if (col == 0)
col = 1;
for (int i = 0; i < col; ++i) {
String cc = "" + (char) ('a' + (i / (26 * 26)))
+ (char) ((i / 26) + 'a') + (char) ((i % 26) + 'a');
ret.append("\\newlength{\\tbl" + tc + "c" + cc + "w}\n");
ret.append("\\setlength{\\tbl" + tc + "c" + cc + "w}{"
+ (1.0 / col) + "\\hsize}\n");
}
ret.append("\\begin{tabular}{");
if (border)
ret.append("|");
for (int i = 0; i < col; ++i) {
String cc = "" + (char) ('a' + (i / (26 * 26)))
+ (char) ((i / 26) + 'a') + (char) ((i % 26) + 'a');
ret.append("p{\\tbl" + tc + "c" + cc + "w}");
if (border)
ret.append("|");
}
ret.append("}\n");
}
/**
* Starts a new column, possibly closing the current column if needed
*
* @param ret
* the output buffer to put LaTeX into
* @param p
* the properties from the <code><td></code> tag
*/
public void startCol(StringBuffer ret, Properties p) {
endCol(ret);
int span = hasNumProp("colspan", p);
if (colcnt > 0) {
ret.append(" & ");
}
String align = hasProp("align", p);
if (align != null && span < 0)
span = 1;
if (span > 0) {
ret.append("\\multicolumn{" + span + "}{");
if (border && colcnt == 0)
ret.append("|");
String cc = "" + (char) ('a' + (colcnt / (26 * 26)))
+ (char) ((colcnt / 26) + 'a')
+ (char) ((colcnt % 26) + 'a');
if (align != null) {
String h = align.substring(0, 1);
if ("rR".indexOf(h) >= 0)
ret.append("r");
else if ("lL".indexOf(h) >= 0)
ret.append("p{\\tbl" + tc + "c" + cc + "w}");
else if ("cC".indexOf(h) >= 0)
ret.append("p{\\tbl" + tc + "c" + cc + "w}");
} else
ret.append("p{\\tbl" + tc + "c" + cc + "w}");
if (border)
ret.append("|");
ret.append("}");
}
String wid = p.getProperty("texwidth");
ret.append("{");
if (wid != null) {
ret.append("\\parbox{" + wid + "}{\\vskip 1ex ");
parboxed = true;
}
colcnt++;
colopen = true;
}
/**
* Starts a new Heading column, possibly closing the current column if
* needed. A Heading column has a Bold Face font directive around it.
*
* @param ret
* the output buffer to put LaTeX into
* @param p
* the properties from the <code><th></code> tag
*/
public void startHeadCol(StringBuffer ret, Properties p) {
startCol(ret, p);
ret.append("\\bf ");
}
/**
* Ends the current column.
*
* @param ret
* the output buffer to put LaTeX into
*/
public void endCol(StringBuffer ret) {
if (colopen) {
colopen = false;
if (parboxed)
ret.append("\\vskip 1ex}");
parboxed = false;
ret.append("}");
}
}
/**
* Starts a new row, possibly closing the current row if needed
*
* @param ret
* the output buffer to put LaTeX into
* @param p
* the properties from the <code><tr></code> tag
*/
public void startRow(StringBuffer ret, Properties p) {
endRow(ret);
if (rowcnt == 0) {
if (border)
ret.append(" \\hline ");
}
colcnt = 0;
++rowcnt;
rowopen = true;
}
/**
* Ends the current row.
*
* @param ret
* the output buffer to put LaTeX into
*/
public void endRow(StringBuffer ret) {
if (rowopen) {
endCol(ret);
ret.append(" \\\\");
if (border)
ret.append(" \\hline");
rowopen = false;
ret.append("\n");
}
}
/**
* Ends the table, closing the last row as needed
*
* @param ret
* the output buffer to put LaTeX into
*/
public void endTable(StringBuffer ret) {
endRow(ret);
ret.append("\\end{tabular}\n");
}
}
| false | true | public TableInfo(Properties p, StringBuffer ret, String table, int off) {
tblno = tblcnt++;
tc = "" + (char) ('a' + (tblno / (26 * 26)))
+ (char) ((tblno / 26) + 'a') + (char) ((tblno % 26) + 'a');
if (p == null)
return;
String val = hasProp("border", p);
border = false;
if (val != null) {
border = true;
bordwid = 2;
if (val.equals("") == false) {
try {
bordwid = Integer.parseInt(val);
} catch (Exception ex) {
}
if (bordwid == 0)
border = false;
}
}
ret.append("\n% Table #" + tblno + "\n");
byte[] b = table.getBytes();
int col = 0;
int row = 0;
for (int i = off; i < b.length; ++i) {
if (b[i] == '<') {
if (table.substring(i, i + 7).equalsIgnoreCase("</table")) {
break;
} else if (table.substring(i, i + 4).equalsIgnoreCase("</tr")) {
break;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<tr")) {
if (row++ > 0)
break;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<td")) {
Properties pp = new Properties();
int idx = HTMLToTex.getTagAttrs(table, pp, i + 3);
int v = hasNumProp("colspan", pp);
if (v > 0)
col += v;
else
col++;
i = idx - 1;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<th")) {
Properties pp = new Properties();
int idx = HTMLToTex.getTagAttrs(table, pp, i + 3);
int v = hasNumProp("colspan", pp);
if (v > 0)
col += v;
else
col++;
i = idx - 1;
}
}
}
if (col == 0)
col = 1;
for (int i = 0; i < col; ++i) {
String cc = "" + (char) ('a' + (i / (26 * 26)))
+ (char) ((i / 26) + 'a') + (char) ((i % 26) + 'a');
ret.append("\\newlength{\\tbl" + tc + "c" + cc + "w}\n");
ret.append("\\setlength{\\tbl" + tc + "c" + cc + "w}{"
+ (1.0 / col) + "\\hsize}\n");
}
ret.append("\\begin{tabular}{");
if (border)
ret.append("|");
for (int i = 0; i < col; ++i) {
String cc = "" + (char) ('a' + (i / (26 * 26)))
+ (char) ((i / 26) + 'a') + (char) ((i % 26) + 'a');
ret.append("p{\\tbl" + tc + "c" + cc + "w}");
if (border)
ret.append("|");
}
ret.append("}\n");
}
| public TableInfo(Properties p, StringBuffer ret, String table, int off) {
tblno = tblcnt++;
tc = "" + (char) ('a' + (tblno / (26 * 26)))
+ (char) ((tblno / 26) + 'a') + (char) ((tblno % 26) + 'a');
if (p == null)
return;
String val = hasProp("border", p);
border = false;
if (val != null) {
border = true;
bordwid = 2;
if (val.equals("") == false) {
try {
bordwid = Integer.parseInt(val);
} catch (Exception ex) {
}
if (bordwid == 0)
border = false;
}
}
ret.append("\n% Table #" + tblno + "\n");
int col = 0;
int row = 0;
for (int i = off; i < table.length(); ++i) {
if (table.charAt(i) == '<') {
if (table.substring(i, i + 7).equalsIgnoreCase("</table")) {
break;
} else if (table.substring(i, i + 4).equalsIgnoreCase("</tr")) {
break;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<tr")) {
if (row++ > 0)
break;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<td")) {
Properties pp = new Properties();
int idx = HTMLToTex.getTagAttrs(table, pp, i + 3);
int v = hasNumProp("colspan", pp);
if (v > 0)
col += v;
else
col++;
i = idx - 1;
} else if (table.substring(i, i + 3).equalsIgnoreCase("<th")) {
Properties pp = new Properties();
int idx = HTMLToTex.getTagAttrs(table, pp, i + 3);
int v = hasNumProp("colspan", pp);
if (v > 0)
col += v;
else
col++;
i = idx - 1;
}
}
}
if (col == 0)
col = 1;
for (int i = 0; i < col; ++i) {
String cc = "" + (char) ('a' + (i / (26 * 26)))
+ (char) ((i / 26) + 'a') + (char) ((i % 26) + 'a');
ret.append("\\newlength{\\tbl" + tc + "c" + cc + "w}\n");
ret.append("\\setlength{\\tbl" + tc + "c" + cc + "w}{"
+ (1.0 / col) + "\\hsize}\n");
}
ret.append("\\begin{tabular}{");
if (border)
ret.append("|");
for (int i = 0; i < col; ++i) {
String cc = "" + (char) ('a' + (i / (26 * 26)))
+ (char) ((i / 26) + 'a') + (char) ((i % 26) + 'a');
ret.append("p{\\tbl" + tc + "c" + cc + "w}");
if (border)
ret.append("|");
}
ret.append("}\n");
}
|
diff --git a/src/tconstruct/client/block/TankAirRender.java b/src/tconstruct/client/block/TankAirRender.java
index a4a4f36e7..4c9640e09 100644
--- a/src/tconstruct/client/block/TankAirRender.java
+++ b/src/tconstruct/client/block/TankAirRender.java
@@ -1,80 +1,82 @@
package tconstruct.client.block;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
import net.minecraft.world.IBlockAccess;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidStack;
import tconstruct.TConstruct;
import tconstruct.blocks.logic.TankAirLogic;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
public class TankAirRender implements ISimpleBlockRenderingHandler
{
public static int model = RenderingRegistry.getNextAvailableRenderId();
private static final double capacity = TConstruct.ingotLiquidValue * 18;
@Override
public void renderInventoryBlock (Block block, int metadata, int modelID, RenderBlocks renderer)
{
//No inventory block
}
@Override
public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelID, RenderBlocks renderer)
{
if (modelID == model)
{
TankAirLogic logic = (TankAirLogic) world.getBlockTileEntity(x, y, z);
if (logic.hasItem())
{
ItemStack item = logic.getStackInSlot(0);
if (item.getItem() instanceof ItemBlock)
{
Block inv = Block.blocksList[item.itemID];
+ renderer.setOverrideBlockTexture(inv.getIcon(1, item.getItemDamage()));
renderer.renderBlockByRenderType(inv, x, y, z);
+ renderer.clearOverrideBlockTexture();
}
}
else if (logic.hasFluids())
{
int base = 0;
for (FluidStack fluidstack : logic.getFluids())
{
Fluid fluid = fluidstack.getFluid();
renderer.setRenderBounds(0.0, getBaseAmount(base), 0.0, 1.0, getHeightAmount(base, fluidstack.amount), 1.0);
if (fluid.canBePlacedInWorld())
BlockSkinRenderHelper.renderMetadataBlock(Block.blocksList[fluid.getBlockID()], 0, x, y, z, renderer, world);
else
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
base += fluidstack.amount;
}
}
}
return true;
}
private double getBaseAmount (int base)
{
return base / capacity;
}
private double getHeightAmount (int base, int amount)
{
return (base + amount) / capacity;
}
@Override
public boolean shouldRender3DInInventory ()
{
return true;
}
@Override
public int getRenderId ()
{
return model;
}
}
| false | true | public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelID, RenderBlocks renderer)
{
if (modelID == model)
{
TankAirLogic logic = (TankAirLogic) world.getBlockTileEntity(x, y, z);
if (logic.hasItem())
{
ItemStack item = logic.getStackInSlot(0);
if (item.getItem() instanceof ItemBlock)
{
Block inv = Block.blocksList[item.itemID];
renderer.renderBlockByRenderType(inv, x, y, z);
}
}
else if (logic.hasFluids())
{
int base = 0;
for (FluidStack fluidstack : logic.getFluids())
{
Fluid fluid = fluidstack.getFluid();
renderer.setRenderBounds(0.0, getBaseAmount(base), 0.0, 1.0, getHeightAmount(base, fluidstack.amount), 1.0);
if (fluid.canBePlacedInWorld())
BlockSkinRenderHelper.renderMetadataBlock(Block.blocksList[fluid.getBlockID()], 0, x, y, z, renderer, world);
else
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
base += fluidstack.amount;
}
}
}
return true;
}
| public boolean renderWorldBlock (IBlockAccess world, int x, int y, int z, Block block, int modelID, RenderBlocks renderer)
{
if (modelID == model)
{
TankAirLogic logic = (TankAirLogic) world.getBlockTileEntity(x, y, z);
if (logic.hasItem())
{
ItemStack item = logic.getStackInSlot(0);
if (item.getItem() instanceof ItemBlock)
{
Block inv = Block.blocksList[item.itemID];
renderer.setOverrideBlockTexture(inv.getIcon(1, item.getItemDamage()));
renderer.renderBlockByRenderType(inv, x, y, z);
renderer.clearOverrideBlockTexture();
}
}
else if (logic.hasFluids())
{
int base = 0;
for (FluidStack fluidstack : logic.getFluids())
{
Fluid fluid = fluidstack.getFluid();
renderer.setRenderBounds(0.0, getBaseAmount(base), 0.0, 1.0, getHeightAmount(base, fluidstack.amount), 1.0);
if (fluid.canBePlacedInWorld())
BlockSkinRenderHelper.renderMetadataBlock(Block.blocksList[fluid.getBlockID()], 0, x, y, z, renderer, world);
else
BlockSkinRenderHelper.renderLiquidBlock(fluid.getStillIcon(), fluid.getFlowingIcon(), x, y, z, renderer, world);
base += fluidstack.amount;
}
}
}
return true;
}
|
diff --git a/src/com/android/settings/TextToSpeechSettings.java b/src/com/android/settings/TextToSpeechSettings.java
index 94b256f62..ec0fc8cde 100644
--- a/src/com/android/settings/TextToSpeechSettings.java
+++ b/src/com/android/settings/TextToSpeechSettings.java
@@ -1,387 +1,387 @@
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import static android.provider.Settings.Secure.TTS_USE_DEFAULTS;
import static android.provider.Settings.Secure.TTS_DEFAULT_RATE;
import static android.provider.Settings.Secure.TTS_DEFAULT_LANG;
import static android.provider.Settings.Secure.TTS_DEFAULT_COUNTRY;
import static android.provider.Settings.Secure.TTS_DEFAULT_VARIANT;
import static android.provider.Settings.Secure.TTS_DEFAULT_SYNTH;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.CheckBoxPreference;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import java.util.List;
import java.util.StringTokenizer;
public class TextToSpeechSettings extends PreferenceActivity implements
Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener,
TextToSpeech.OnInitListener {
private static final String TAG = "TextToSpeechSettings";
private static final String KEY_TTS_PLAY_EXAMPLE = "tts_play_example";
private static final String KEY_TTS_INSTALL_DATA = "tts_install_data";
private static final String KEY_TTS_USE_DEFAULT = "toggle_use_default_tts_settings";
private static final String KEY_TTS_DEFAULT_RATE = "tts_default_rate";
private static final String KEY_TTS_DEFAULT_LANG = "tts_default_lang";
private static final String KEY_TTS_DEFAULT_COUNTRY = "tts_default_country";
private static final String KEY_TTS_DEFAULT_VARIANT = "tts_default_variant";
private static final String LOCALE_DELIMITER = "-";
// TODO move this to android.speech.tts.TextToSpeech.Engine
private static final String FALLBACK_TTS_DEFAULT_SYNTH = "com.svox.pico";
private Preference mPlayExample = null;
private Preference mInstallData = null;
private CheckBoxPreference mUseDefaultPref = null;
private ListPreference mDefaultRatePref = null;
private ListPreference mDefaultLocPref = null;
private String mDefaultLanguage = null;
private String mDefaultCountry = null;
private String mDefaultLocVariant = null;
private String mDefaultEng = "";
private boolean mEnableDemo = false;
private TextToSpeech mTts = null;
/**
* Request code (arbitrary value) for voice data check through
* startActivityForResult.
*/
private static final int VOICE_DATA_INTEGRITY_CHECK = 1977;
/**
* Request code (arbitrary value) for voice data installation through
* startActivityForResult.
*/
private static final int VOICE_DATA_INSTALLATION = 1980;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.tts_settings);
mEnableDemo = false;
initClickers();
initDefaultSettings();
}
@Override
protected void onStart() {
super.onStart();
// whenever we return to this screen, we don't know the state of the
// system, so we have to recheck that we can play the demo, or it must be disabled.
// TODO make the TTS service listen to "changes in the system", i.e. sd card un/mount
initClickers();
updateWidgetState();
checkVoiceData();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTts != null) {
mTts.shutdown();
}
}
private void initClickers() {
mPlayExample = findPreference(KEY_TTS_PLAY_EXAMPLE);
mPlayExample.setOnPreferenceClickListener(this);
mInstallData = findPreference(KEY_TTS_INSTALL_DATA);
mInstallData.setOnPreferenceClickListener(this);
}
private void initDefaultSettings() {
ContentResolver resolver = getContentResolver();
int intVal = 0;
// Find the default TTS values in the settings, initialize and store the
// settings if they are not found.
// "Use Defaults"
mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT);
try {
intVal = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS);
} catch (SettingNotFoundException e) {
// "use default" setting not found, initialize it
intVal = TextToSpeech.Engine.FALLBACK_TTS_USE_DEFAULTS;
Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, intVal);
}
mUseDefaultPref.setChecked(intVal == 1);
mUseDefaultPref.setOnPreferenceChangeListener(this);
// Default engine
String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH);
if (engine == null) {
// TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech
engine = FALLBACK_TTS_DEFAULT_SYNTH;
Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine);
}
mDefaultEng = engine;
// Default rate
mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE);
try {
intVal = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE);
} catch (SettingNotFoundException e) {
// default rate setting not found, initialize it
intVal = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_RATE;
Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, intVal);
}
mDefaultRatePref.setValue(String.valueOf(intVal));
mDefaultRatePref.setOnPreferenceChangeListener(this);
// Default language / country / variant : these three values map to a single ListPref
// representing the matching Locale
String language = null;
String country = null;
String variant = null;
mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG);
language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG);
if (language != null) {
mDefaultLanguage = language;
} else {
// default language setting not found, initialize it, as well as the country and variant
language = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_LANG;
country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY;
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, language);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
if (country == null) {
// country wasn't initialized yet because a default language was found
country = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY);
- if (country.compareTo("null") != 0) {
+ if (country != null) {
mDefaultCountry = country;
} else {
// default country setting not found, initialize it, as well as the variant;
country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY;
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
}
if (variant == null) {
// variant wasn't initialized yet because a default country was found
variant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT);
- if (variant.compareTo("null") != 0) {
+ if (variant != null) {
mDefaultLocVariant = variant;
} else {
// default variant setting not found, initialize it
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
}
// we now have the default lang/country/variant trio, build a string value from it
String localeString = new String(language);
if (country.compareTo("") != 0) {
localeString += LOCALE_DELIMITER + country;
} else {
localeString += LOCALE_DELIMITER + " ";
}
if (variant.compareTo("") != 0) {
localeString += LOCALE_DELIMITER + variant;
}
Log.v(TAG, "In initDefaultSettings: localeString=" + localeString);
// TODO handle the case where localeString isn't in the existing entries
mDefaultLocPref.setValue(localeString);
mDefaultLocPref.setOnPreferenceChangeListener(this);
}
/**
* Ask the current default engine to launch the matching CHECK_TTS_DATA activity
* to check the required TTS files are properly installed.
*/
private void checkVoiceData() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction("android.intent.action.CHECK_TTS_DATA");
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivityForResult(intent, VOICE_DATA_INTEGRITY_CHECK);
}
}
}
/**
* Ask the current default engine to launch the matching INSTALL_TTS_DATA activity
* so the required TTS files are properly installed.
*/
private void installVoiceData() {
PackageManager pm = getPackageManager();
Intent intent = new Intent();
intent.setAction("android.intent.action.INSTALL_TTS_DATA");
List<ResolveInfo> resolveInfos = pm.queryIntentActivities(intent, 0);
// query only the package that matches that of the default engine
for (int i = 0; i < resolveInfos.size(); i++) {
ActivityInfo currentActivityInfo = resolveInfos.get(i).activityInfo;
if (mDefaultEng.equals(currentActivityInfo.packageName)) {
intent.setClassName(mDefaultEng, currentActivityInfo.name);
this.startActivityForResult(intent, VOICE_DATA_INSTALLATION);
}
}
}
/**
* Called when the TTS engine is initialized.
*/
public void onInit(int status) {
if (status == TextToSpeech.TTS_SUCCESS) {
Log.v(TAG, "TTS engine for settings screen initialized.");
mEnableDemo = true;
} else {
Log.v(TAG, "TTS engine for settings screen failed to initialize successfully.");
mEnableDemo = false;
}
updateWidgetState();
}
/**
* Called when voice data integrity check returns
*/
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == VOICE_DATA_INTEGRITY_CHECK) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
Log.v(TAG, "Voice data check passed");
if (mTts == null) {
mTts = new TextToSpeech(this, this);
}
} else {
Log.v(TAG, "Voice data check failed");
mEnableDemo = false;
updateWidgetState();
}
}
}
public boolean onPreferenceChange(Preference preference, Object objValue) {
if (KEY_TTS_USE_DEFAULT.equals(preference.getKey())) {
// "Use Defaults"
int value = (Boolean)objValue ? 1 : 0;
Settings.Secure.putInt(getContentResolver(), TTS_USE_DEFAULTS,
value);
Log.i(TAG, "TTS use default settings is "+objValue.toString());
} else if (KEY_TTS_DEFAULT_RATE.equals(preference.getKey())) {
// Default rate
int value = Integer.parseInt((String) objValue);
try {
Settings.Secure.putInt(getContentResolver(),
TTS_DEFAULT_RATE, value);
if (mTts != null) {
mTts.setSpeechRate(value);
}
Log.i(TAG, "TTS default rate is "+value);
} catch (NumberFormatException e) {
Log.e(TAG, "could not persist default TTS rate setting", e);
}
} else if (KEY_TTS_DEFAULT_LANG.equals(preference.getKey())) {
// Default locale
ContentResolver resolver = getContentResolver();
parseLocaleInfo((String) objValue);
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, mDefaultLanguage);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, mDefaultCountry);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, mDefaultLocVariant);
Log.v(TAG, "TTS default lang/country/variant set to "
+ mDefaultLanguage + "/" + mDefaultCountry + "/" + mDefaultLocVariant);
}
return true;
}
/**
* Called when mPlayExample or mInstallData is clicked
*/
public boolean onPreferenceClick(Preference preference) {
if (preference == mPlayExample) {
// Play example
if (mTts != null) {
mTts.speak(getResources().getString(R.string.tts_demo),
TextToSpeech.TTS_QUEUE_FLUSH, null);
}
return true;
}
if (preference == mInstallData) {
installVoiceData();
// quit this activity so it needs to be restarted after installation of the voice data
finish();
return true;
}
return false;
}
private void updateWidgetState() {
mPlayExample.setEnabled(mEnableDemo);
mUseDefaultPref.setEnabled(mEnableDemo);
mDefaultRatePref.setEnabled(mEnableDemo);
mDefaultLocPref.setEnabled(mEnableDemo);
mInstallData.setEnabled(!mEnableDemo);
}
private void parseLocaleInfo(String locale) {
StringTokenizer tokenizer = new StringTokenizer(locale, LOCALE_DELIMITER);
mDefaultLanguage = "";
mDefaultCountry = "";
mDefaultLocVariant = "";
if (tokenizer.hasMoreTokens()) {
mDefaultLanguage = tokenizer.nextToken().trim();
}
if (tokenizer.hasMoreTokens()) {
mDefaultCountry = tokenizer.nextToken().trim();
}
if (tokenizer.hasMoreTokens()) {
mDefaultLocVariant = tokenizer.nextToken().trim();
}
}
}
| false | true | private void initDefaultSettings() {
ContentResolver resolver = getContentResolver();
int intVal = 0;
// Find the default TTS values in the settings, initialize and store the
// settings if they are not found.
// "Use Defaults"
mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT);
try {
intVal = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS);
} catch (SettingNotFoundException e) {
// "use default" setting not found, initialize it
intVal = TextToSpeech.Engine.FALLBACK_TTS_USE_DEFAULTS;
Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, intVal);
}
mUseDefaultPref.setChecked(intVal == 1);
mUseDefaultPref.setOnPreferenceChangeListener(this);
// Default engine
String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH);
if (engine == null) {
// TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech
engine = FALLBACK_TTS_DEFAULT_SYNTH;
Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine);
}
mDefaultEng = engine;
// Default rate
mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE);
try {
intVal = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE);
} catch (SettingNotFoundException e) {
// default rate setting not found, initialize it
intVal = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_RATE;
Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, intVal);
}
mDefaultRatePref.setValue(String.valueOf(intVal));
mDefaultRatePref.setOnPreferenceChangeListener(this);
// Default language / country / variant : these three values map to a single ListPref
// representing the matching Locale
String language = null;
String country = null;
String variant = null;
mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG);
language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG);
if (language != null) {
mDefaultLanguage = language;
} else {
// default language setting not found, initialize it, as well as the country and variant
language = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_LANG;
country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY;
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, language);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
if (country == null) {
// country wasn't initialized yet because a default language was found
country = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY);
if (country.compareTo("null") != 0) {
mDefaultCountry = country;
} else {
// default country setting not found, initialize it, as well as the variant;
country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY;
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
}
if (variant == null) {
// variant wasn't initialized yet because a default country was found
variant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT);
if (variant.compareTo("null") != 0) {
mDefaultLocVariant = variant;
} else {
// default variant setting not found, initialize it
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
}
// we now have the default lang/country/variant trio, build a string value from it
String localeString = new String(language);
if (country.compareTo("") != 0) {
localeString += LOCALE_DELIMITER + country;
} else {
localeString += LOCALE_DELIMITER + " ";
}
if (variant.compareTo("") != 0) {
localeString += LOCALE_DELIMITER + variant;
}
Log.v(TAG, "In initDefaultSettings: localeString=" + localeString);
// TODO handle the case where localeString isn't in the existing entries
mDefaultLocPref.setValue(localeString);
mDefaultLocPref.setOnPreferenceChangeListener(this);
}
| private void initDefaultSettings() {
ContentResolver resolver = getContentResolver();
int intVal = 0;
// Find the default TTS values in the settings, initialize and store the
// settings if they are not found.
// "Use Defaults"
mUseDefaultPref = (CheckBoxPreference) findPreference(KEY_TTS_USE_DEFAULT);
try {
intVal = Settings.Secure.getInt(resolver, TTS_USE_DEFAULTS);
} catch (SettingNotFoundException e) {
// "use default" setting not found, initialize it
intVal = TextToSpeech.Engine.FALLBACK_TTS_USE_DEFAULTS;
Settings.Secure.putInt(resolver, TTS_USE_DEFAULTS, intVal);
}
mUseDefaultPref.setChecked(intVal == 1);
mUseDefaultPref.setOnPreferenceChangeListener(this);
// Default engine
String engine = Settings.Secure.getString(resolver, TTS_DEFAULT_SYNTH);
if (engine == null) {
// TODO move FALLBACK_TTS_DEFAULT_SYNTH to TextToSpeech
engine = FALLBACK_TTS_DEFAULT_SYNTH;
Settings.Secure.putString(resolver, TTS_DEFAULT_SYNTH, engine);
}
mDefaultEng = engine;
// Default rate
mDefaultRatePref = (ListPreference) findPreference(KEY_TTS_DEFAULT_RATE);
try {
intVal = Settings.Secure.getInt(resolver, TTS_DEFAULT_RATE);
} catch (SettingNotFoundException e) {
// default rate setting not found, initialize it
intVal = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_RATE;
Settings.Secure.putInt(resolver, TTS_DEFAULT_RATE, intVal);
}
mDefaultRatePref.setValue(String.valueOf(intVal));
mDefaultRatePref.setOnPreferenceChangeListener(this);
// Default language / country / variant : these three values map to a single ListPref
// representing the matching Locale
String language = null;
String country = null;
String variant = null;
mDefaultLocPref = (ListPreference) findPreference(KEY_TTS_DEFAULT_LANG);
language = Settings.Secure.getString(resolver, TTS_DEFAULT_LANG);
if (language != null) {
mDefaultLanguage = language;
} else {
// default language setting not found, initialize it, as well as the country and variant
language = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_LANG;
country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY;
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_LANG, language);
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
if (country == null) {
// country wasn't initialized yet because a default language was found
country = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_COUNTRY);
if (country != null) {
mDefaultCountry = country;
} else {
// default country setting not found, initialize it, as well as the variant;
country = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_COUNTRY;
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_COUNTRY, country);
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
}
if (variant == null) {
// variant wasn't initialized yet because a default country was found
variant = Settings.Secure.getString(resolver, KEY_TTS_DEFAULT_VARIANT);
if (variant != null) {
mDefaultLocVariant = variant;
} else {
// default variant setting not found, initialize it
variant = TextToSpeech.Engine.FALLBACK_TTS_DEFAULT_VARIANT;
Settings.Secure.putString(resolver, TTS_DEFAULT_VARIANT, variant);
}
}
// we now have the default lang/country/variant trio, build a string value from it
String localeString = new String(language);
if (country.compareTo("") != 0) {
localeString += LOCALE_DELIMITER + country;
} else {
localeString += LOCALE_DELIMITER + " ";
}
if (variant.compareTo("") != 0) {
localeString += LOCALE_DELIMITER + variant;
}
Log.v(TAG, "In initDefaultSettings: localeString=" + localeString);
// TODO handle the case where localeString isn't in the existing entries
mDefaultLocPref.setValue(localeString);
mDefaultLocPref.setOnPreferenceChangeListener(this);
}
|
diff --git a/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java b/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java
index 3db7eda45..e47e4a3eb 100644
--- a/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java
+++ b/maven-core/src/main/java/org/apache/maven/exception/DefaultExceptionHandler.java
@@ -1,121 +1,121 @@
package org.apache.maven.exception;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.lifecycle.NoPluginFoundForPrefixException;
import org.apache.maven.plugin.CycleDetectedInPluginGraphException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugin.MojoNotFoundException;
import org.apache.maven.plugin.PluginDescriptorParsingException;
import org.apache.maven.plugin.PluginNotFoundException;
import org.apache.maven.plugin.PluginResolutionException;
import org.codehaus.plexus.component.annotations.Component;
/*
- test projects for each of these
- how to categorize the problems so that the id of the problem can be match to a page with descriptive help and the test project
- nice little sample projects that could be run in the core as well as integration tests
All Possible Errors
- invalid lifecycle phase (maybe same as bad CLI param, though you were talking about embedder too)
- <module> specified is not found
- malformed settings
- malformed POM
- local repository not writable
- remote repositories not available
- artifact metadata missing
- extension metadata missing
- extension artifact missing
- artifact metadata retrieval problem
- version range violation
- circular dependency
- artifact missing
- artifact retrieval exception
- md5 checksum doesn't match for local artifact, need to redownload this
- POM doesn't exist for a goal that requires one
- parent POM missing (in both the repository + relative path)
- component not found
Plugins:
- plugin metadata missing
- plugin metadata retrieval problem
- plugin artifact missing
- plugin artifact retrieval problem
- plugin dependency metadata missing
- plugin dependency metadata retrieval problem
- plugin configuration problem
- plugin execution failure due to something that is know to possibly go wrong (like compilation failure)
- plugin execution error due to something that is not expected to go wrong (the compiler executable missing)
- asking to use a plugin for which you do not have a version defined - tools to easily select versions
- goal not found in a plugin (probably could list the ones that are)
*/
//PluginNotFoundException, PluginResolutionException, PluginDescriptorParsingException, CycleDetectedInPluginGraphException;
@Component(role=ExceptionHandler.class)
public class DefaultExceptionHandler
implements ExceptionHandler
{
public ExceptionSummary handleException( Exception exception )
{
String message;
String reference = "http://";
// Plugin problems
if ( exception instanceof PluginNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof PluginResolutionException )
{
message = exception.getMessage();
}
else if ( exception instanceof PluginDescriptorParsingException )
{
message = exception.getMessage();
}
else if ( exception instanceof CycleDetectedInPluginGraphException )
{
message = exception.getMessage();
}
else if ( exception instanceof NoPluginFoundForPrefixException )
{
message = exception.getMessage();
}
// Project dependency downloading problems.
else if ( exception instanceof ArtifactNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof ArtifactResolutionException )
{
- message = ((MojoExecutionException)exception).getLongMessage();
+ message = exception.getMessage();
}
// Mojo problems
else if ( exception instanceof MojoNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof MojoFailureException )
{
message = ((MojoFailureException)exception).getLongMessage();
}
else if ( exception instanceof MojoExecutionException )
{
message = ((MojoExecutionException)exception).getLongMessage();
}
else
{
message = exception.getMessage();
}
return new ExceptionSummary( exception, message, reference );
}
}
| true | true | public ExceptionSummary handleException( Exception exception )
{
String message;
String reference = "http://";
// Plugin problems
if ( exception instanceof PluginNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof PluginResolutionException )
{
message = exception.getMessage();
}
else if ( exception instanceof PluginDescriptorParsingException )
{
message = exception.getMessage();
}
else if ( exception instanceof CycleDetectedInPluginGraphException )
{
message = exception.getMessage();
}
else if ( exception instanceof NoPluginFoundForPrefixException )
{
message = exception.getMessage();
}
// Project dependency downloading problems.
else if ( exception instanceof ArtifactNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof ArtifactResolutionException )
{
message = ((MojoExecutionException)exception).getLongMessage();
}
// Mojo problems
else if ( exception instanceof MojoNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof MojoFailureException )
{
message = ((MojoFailureException)exception).getLongMessage();
}
else if ( exception instanceof MojoExecutionException )
{
message = ((MojoExecutionException)exception).getLongMessage();
}
else
{
message = exception.getMessage();
}
return new ExceptionSummary( exception, message, reference );
}
| public ExceptionSummary handleException( Exception exception )
{
String message;
String reference = "http://";
// Plugin problems
if ( exception instanceof PluginNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof PluginResolutionException )
{
message = exception.getMessage();
}
else if ( exception instanceof PluginDescriptorParsingException )
{
message = exception.getMessage();
}
else if ( exception instanceof CycleDetectedInPluginGraphException )
{
message = exception.getMessage();
}
else if ( exception instanceof NoPluginFoundForPrefixException )
{
message = exception.getMessage();
}
// Project dependency downloading problems.
else if ( exception instanceof ArtifactNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof ArtifactResolutionException )
{
message = exception.getMessage();
}
// Mojo problems
else if ( exception instanceof MojoNotFoundException )
{
message = exception.getMessage();
}
else if ( exception instanceof MojoFailureException )
{
message = ((MojoFailureException)exception).getLongMessage();
}
else if ( exception instanceof MojoExecutionException )
{
message = ((MojoExecutionException)exception).getLongMessage();
}
else
{
message = exception.getMessage();
}
return new ExceptionSummary( exception, message, reference );
}
|
diff --git a/SleepClock/src/com/pps/sleepcalc/showGraphActivity.java b/SleepClock/src/com/pps/sleepcalc/showGraphActivity.java
index 5f04d6c..3bbcf0b 100644
--- a/SleepClock/src/com/pps/sleepcalc/showGraphActivity.java
+++ b/SleepClock/src/com/pps/sleepcalc/showGraphActivity.java
@@ -1,29 +1,30 @@
package com.pps.sleepcalc;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
public class showGraphActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graph);
final WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
+ //webview.getSettings().set
webview.loadUrl("file:///android_asset/test.html");
}
@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;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graph);
final WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/test.html");
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graph);
final WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
//webview.getSettings().set
webview.loadUrl("file:///android_asset/test.html");
}
|
diff --git a/src/com/podevs/android/pokemononline/battle/Battle.java b/src/com/podevs/android/pokemononline/battle/Battle.java
index 27623436..1ea41fcd 100644
--- a/src/com/podevs/android/pokemononline/battle/Battle.java
+++ b/src/com/podevs/android/pokemononline/battle/Battle.java
@@ -1,305 +1,305 @@
package com.podevs.android.pokemononline.battle;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.Html;
import android.util.Log;
import com.podevs.android.pokemononline.DataBaseHelper;
import com.podevs.android.pokemononline.NetworkService;
import com.podevs.android.pokemononline.player.PlayerInfo;
import com.podevs.android.pokemononline.poke.PokeEnums.Status;
import com.podevs.android.pokemononline.poke.ShallowBattlePoke;
import com.podevs.android.pokemononline.poke.UniqueID;
import com.podevs.android.pokemononline.pokeinfo.PokemonInfo;
import com.podevs.android.utilities.Bais;
import com.podevs.android.utilities.Baos;
import com.podevs.android.utilities.StringUtilities;
public class Battle extends SpectatingBattle {
static private final String TAG = "Battle";
public BattleTeam myTeam;
public ShallowShownTeam oppTeam;
public boolean allowSwitch, allowAttack, clicked = false;
public boolean[] allowAttacks = new boolean[4];
public boolean shouldStruggle = false;
public BattleMove[] displayedMoves = new BattleMove[4];
public Battle(BattleConf bc, Bais msg, PlayerInfo p1, PlayerInfo p2, int meID, int bID, NetworkService ns) {
super(bc, p1, p2, bID, ns);
myTeam = new BattleTeam(msg, netServ.db, conf.gen);
// Only supporting singles for now
numberOfSlots = 2;
players[0] = p1;
players[1] = p2;
// Figure out who's who
if(players[0].id != meID) {
me = 1;
opp = 0;
}
for (int i = 0; i < 4; i++)
displayedMoves[i] = new BattleMove();
}
public Baos constructCancel() {
Baos b = new Baos();
b.putInt(bID);
b.putBaos(new BattleChoice(me, ChoiceType.CancelType));
return b;
}
public Baos constructAttack(byte attack) {
Baos b = new Baos();
b.putInt(bID);
AttackChoice ac = new AttackChoice(attack, opp);
b.putBaos(new BattleChoice(me, ac, ChoiceType.AttackType));
return b;
}
public Baos constructSwitch(byte toSpot) {
Baos b = new Baos();
b.putInt(bID);
SwitchChoice sc = new SwitchChoice(toSpot);
b.putBaos(new BattleChoice(me, sc, ChoiceType.SwitchType));
return b;
}
public Baos constructRearrange() {
Baos b = new Baos();
b.putInt(bID);
RearrangeChoice rc = new RearrangeChoice(myTeam);
b.putBaos(new BattleChoice(me, rc, ChoiceType.RearrangeType));
return b;
}
public Baos constructDraw() {
Baos b = new Baos();
b.putInt(bID);
b.putBaos(new BattleChoice(me, ChoiceType.DrawType));
return b;
}
@Override
public void dealWithCommand(BattleCommand bc, byte player, Bais msg) {
switch(bc) {
case SendOut: {
if (player != me) {
super.dealWithCommand(bc, player, msg);
return;
}
boolean silent = msg.readBool();
byte fromSpot = msg.readByte();
BattlePoke temp = myTeam.pokes[0];
myTeam.pokes[0] = myTeam.pokes[fromSpot];
myTeam.pokes[fromSpot] = temp;
for (int i=0; i < 4; i++) {
displayedMoves[i] = new BattleMove(myTeam.pokes[0].moves[i]);
}
ShallowBattlePoke tempPoke = pokes[player][0];
pokes[player][0] = pokes[player][fromSpot];
pokes[player][fromSpot] = tempPoke;
if(msg.available() > 0) // this is the first time you've seen it
pokes[player][0] = new ShallowBattlePoke(msg, (player == me) ? true : false, netServ.db, conf.gen);
if(activity != null) {
activity.updatePokes(player);
activity.updatePokeballs();
}
SharedPreferences prefs = netServ.getSharedPreferences("battle", Context.MODE_PRIVATE);
if (prefs.getBoolean("pokemon_cries", true)) {
try {
synchronized (this) {
netServ.playCry(this, currentPoke(player));
wait(5000);
}
} catch (InterruptedException e) { Log.e(TAG, "INTERRUPTED"); }
}
if(!silent)
writeToHist("\n" + tu((players[player].nick() + " sent out " +
currentPoke(player).rnick + "!")));
break;
} case AbsStatusChange: {
byte poke = msg.readByte();
byte status = msg.readByte();
if (poke < 0 || poke >= 6)
break;
if (status != Status.Confused.poValue()) {
pokes[player][poke].changeStatus(status);
if (player == me)
myTeam.pokes[poke].changeStatus(status);
if (activity != null) {
if (isOut(poke))
activity.updatePokes(player);
activity.updatePokeballs();
}
}
break;
} case TempPokeChange: {
byte id = msg.readByte();
switch(TempPokeChange.values()[id]) {
case TempMove:
case DefMove:
byte slot = msg.readByte();
BattleMove newMove = new BattleMove(msg.readShort(), netServ.db);
displayedMoves[slot] = newMove;
if (id == TempPokeChange.DefMove.ordinal()) {
myTeam.pokes[0].moves[slot] = newMove;
}
if (activity != null) {
activity.updatePokes(player);
}
break;
case TempPP:
slot = msg.readByte();
byte PP = msg.readByte();
displayedMoves[slot].currentPP = PP;
if (activity !=null) {
activity.updateMovePP(slot);
}
break;
case TempSprite:
UniqueID sprite = new UniqueID(msg);
if (sprite.pokeNum != 0)
currentPoke(player).specialSprites.addFirst(sprite);
- else
+ else if (currentPoke(player).specialSprites.size() > 0)
currentPoke(player).specialSprites.removeFirst();
if (activity !=null) {
activity.updatePokes(player);
}
break;
case DefiniteForme:
byte poke = msg.readByte();
short newForm = msg.readShort();
pokes[player][poke].uID.pokeNum = newForm;
if (isOut(poke)) {
currentPoke(slot(player, poke)).uID.pokeNum = newForm;
if (activity !=null) {
activity.updatePokes(player);
}
}
break;
case AestheticForme:
newForm = msg.readShort();
currentPoke(player).uID.subNum = (byte) newForm;
if (activity !=null) {
activity.updatePokes(player);
}
default: break;
}
break;
} case MakeYourChoice: {
if (activity != null) {
activity.updateButtons();
if (allowSwitch && !allowAttack)
activity.switchToPokeViewer();
}
break;
} case OfferChoice: {
@SuppressWarnings("unused")
byte numSlot = msg.readByte(); //Which poke the choice is for
allowSwitch = msg.readBool();
System.out.println("Switch allowed: " + allowSwitch);
allowAttack = msg.readBool();
System.out.println("Attacks allowed: " + allowAttack);
for (int i = 0; i < 4; i++) {
allowAttacks[i] = msg.readBool();
System.out.print("Allow attack " + i + ": ");
System.out.println(allowAttacks[i]);
}
if (allowAttack && !allowAttacks[0] && !allowAttacks[1] && !allowAttacks[2] && !allowAttacks[3])
shouldStruggle = true;
else
shouldStruggle = false;
clicked = false;
if (activity != null)
activity.updateButtons();
break;
} case CancelMove: {
clicked = false;
if (activity != null)
activity.updateButtons();
break;
} case ChangeHp: {
short newHP = msg.readShort();
if(player == me) {
myTeam.pokes[0].currentHP = newHP;
currentPoke(player).lastKnownPercent = currentPoke(player).lifePercent;
currentPoke(player).lifePercent = (byte)(newHP * 100 / myTeam.pokes[0].totalHP);
}
else {
currentPoke(player).lastKnownPercent = currentPoke(player).lifePercent;
currentPoke(player).lifePercent = (byte)newHP;
}
if(activity != null) {
// Block until the hp animation has finished
// Timeout after 10s
try {
synchronized (this) {
activity.animateHpBarTo(player, currentPoke(player).lifePercent);
wait(10000);
}
} catch (InterruptedException e) {}
activity.updateCurrentPokeListEntry();
}
break;
} case StraightDamage: {
if (player != me) {
super.dealWithCommand(bc, player, msg);
} else {
short damage = msg.readShort();
writeToHist("\n" + tu(currentPoke(player).nick + " lost " + damage + "HP! (" + (damage*100/myTeam.pokes[player/2].totalHP) + "% of its health)"));
}
break;
} case SpotShifts: {
// TODO
break;
} case RearrangeTeam: {
oppTeam = new ShallowShownTeam(msg);
shouldShowPreview = true;
if(activity != null)
activity.notifyRearrangeTeamDialog();
DataBaseHelper db = netServ.db;
String names[] = {PokemonInfo.name(db, oppTeam.poke(0).uID), PokemonInfo.name(db, oppTeam.poke(1).uID),
PokemonInfo.name(db, oppTeam.poke(2).uID), PokemonInfo.name(db, oppTeam.poke(3).uID),
PokemonInfo.name(db, oppTeam.poke(4).uID), PokemonInfo.name(db, oppTeam.poke(5).uID)};
writeToHist(Html.fromHtml("<br><font color=\"blue\"><b>Opponent's team: </b></font>" + StringUtilities.join(names, " / ")));
break;
} case ChangePP: {
byte moveNum = msg.readByte();
byte newPP = msg.readByte();
displayedMoves[moveNum].currentPP = myTeam.pokes[0].moves[moveNum].currentPP = newPP;
if(activity != null)
activity.updateMovePP(moveNum);
break;
} case DynamicStats: {
for (int i = 0; i < 5; i++)
myTeam.pokes[player / 2].stats[i] = msg.readShort();
break;
} default: {
super.dealWithCommand(bc, player, msg);
break;
}
}
}
}
| true | true | public void dealWithCommand(BattleCommand bc, byte player, Bais msg) {
switch(bc) {
case SendOut: {
if (player != me) {
super.dealWithCommand(bc, player, msg);
return;
}
boolean silent = msg.readBool();
byte fromSpot = msg.readByte();
BattlePoke temp = myTeam.pokes[0];
myTeam.pokes[0] = myTeam.pokes[fromSpot];
myTeam.pokes[fromSpot] = temp;
for (int i=0; i < 4; i++) {
displayedMoves[i] = new BattleMove(myTeam.pokes[0].moves[i]);
}
ShallowBattlePoke tempPoke = pokes[player][0];
pokes[player][0] = pokes[player][fromSpot];
pokes[player][fromSpot] = tempPoke;
if(msg.available() > 0) // this is the first time you've seen it
pokes[player][0] = new ShallowBattlePoke(msg, (player == me) ? true : false, netServ.db, conf.gen);
if(activity != null) {
activity.updatePokes(player);
activity.updatePokeballs();
}
SharedPreferences prefs = netServ.getSharedPreferences("battle", Context.MODE_PRIVATE);
if (prefs.getBoolean("pokemon_cries", true)) {
try {
synchronized (this) {
netServ.playCry(this, currentPoke(player));
wait(5000);
}
} catch (InterruptedException e) { Log.e(TAG, "INTERRUPTED"); }
}
if(!silent)
writeToHist("\n" + tu((players[player].nick() + " sent out " +
currentPoke(player).rnick + "!")));
break;
} case AbsStatusChange: {
byte poke = msg.readByte();
byte status = msg.readByte();
if (poke < 0 || poke >= 6)
break;
if (status != Status.Confused.poValue()) {
pokes[player][poke].changeStatus(status);
if (player == me)
myTeam.pokes[poke].changeStatus(status);
if (activity != null) {
if (isOut(poke))
activity.updatePokes(player);
activity.updatePokeballs();
}
}
break;
} case TempPokeChange: {
byte id = msg.readByte();
switch(TempPokeChange.values()[id]) {
case TempMove:
case DefMove:
byte slot = msg.readByte();
BattleMove newMove = new BattleMove(msg.readShort(), netServ.db);
displayedMoves[slot] = newMove;
if (id == TempPokeChange.DefMove.ordinal()) {
myTeam.pokes[0].moves[slot] = newMove;
}
if (activity != null) {
activity.updatePokes(player);
}
break;
case TempPP:
slot = msg.readByte();
byte PP = msg.readByte();
displayedMoves[slot].currentPP = PP;
if (activity !=null) {
activity.updateMovePP(slot);
}
break;
case TempSprite:
UniqueID sprite = new UniqueID(msg);
if (sprite.pokeNum != 0)
currentPoke(player).specialSprites.addFirst(sprite);
else
currentPoke(player).specialSprites.removeFirst();
if (activity !=null) {
activity.updatePokes(player);
}
break;
case DefiniteForme:
byte poke = msg.readByte();
short newForm = msg.readShort();
pokes[player][poke].uID.pokeNum = newForm;
if (isOut(poke)) {
currentPoke(slot(player, poke)).uID.pokeNum = newForm;
if (activity !=null) {
activity.updatePokes(player);
}
}
break;
case AestheticForme:
newForm = msg.readShort();
currentPoke(player).uID.subNum = (byte) newForm;
if (activity !=null) {
activity.updatePokes(player);
}
default: break;
}
break;
} case MakeYourChoice: {
if (activity != null) {
activity.updateButtons();
if (allowSwitch && !allowAttack)
activity.switchToPokeViewer();
}
break;
} case OfferChoice: {
@SuppressWarnings("unused")
byte numSlot = msg.readByte(); //Which poke the choice is for
allowSwitch = msg.readBool();
System.out.println("Switch allowed: " + allowSwitch);
allowAttack = msg.readBool();
System.out.println("Attacks allowed: " + allowAttack);
for (int i = 0; i < 4; i++) {
allowAttacks[i] = msg.readBool();
System.out.print("Allow attack " + i + ": ");
System.out.println(allowAttacks[i]);
}
if (allowAttack && !allowAttacks[0] && !allowAttacks[1] && !allowAttacks[2] && !allowAttacks[3])
shouldStruggle = true;
else
shouldStruggle = false;
clicked = false;
if (activity != null)
activity.updateButtons();
break;
} case CancelMove: {
clicked = false;
if (activity != null)
activity.updateButtons();
break;
} case ChangeHp: {
short newHP = msg.readShort();
if(player == me) {
myTeam.pokes[0].currentHP = newHP;
currentPoke(player).lastKnownPercent = currentPoke(player).lifePercent;
currentPoke(player).lifePercent = (byte)(newHP * 100 / myTeam.pokes[0].totalHP);
}
else {
currentPoke(player).lastKnownPercent = currentPoke(player).lifePercent;
currentPoke(player).lifePercent = (byte)newHP;
}
if(activity != null) {
// Block until the hp animation has finished
// Timeout after 10s
try {
synchronized (this) {
activity.animateHpBarTo(player, currentPoke(player).lifePercent);
wait(10000);
}
} catch (InterruptedException e) {}
activity.updateCurrentPokeListEntry();
}
break;
} case StraightDamage: {
if (player != me) {
super.dealWithCommand(bc, player, msg);
} else {
short damage = msg.readShort();
writeToHist("\n" + tu(currentPoke(player).nick + " lost " + damage + "HP! (" + (damage*100/myTeam.pokes[player/2].totalHP) + "% of its health)"));
}
break;
} case SpotShifts: {
// TODO
break;
} case RearrangeTeam: {
oppTeam = new ShallowShownTeam(msg);
shouldShowPreview = true;
if(activity != null)
activity.notifyRearrangeTeamDialog();
DataBaseHelper db = netServ.db;
String names[] = {PokemonInfo.name(db, oppTeam.poke(0).uID), PokemonInfo.name(db, oppTeam.poke(1).uID),
PokemonInfo.name(db, oppTeam.poke(2).uID), PokemonInfo.name(db, oppTeam.poke(3).uID),
PokemonInfo.name(db, oppTeam.poke(4).uID), PokemonInfo.name(db, oppTeam.poke(5).uID)};
writeToHist(Html.fromHtml("<br><font color=\"blue\"><b>Opponent's team: </b></font>" + StringUtilities.join(names, " / ")));
break;
} case ChangePP: {
byte moveNum = msg.readByte();
byte newPP = msg.readByte();
displayedMoves[moveNum].currentPP = myTeam.pokes[0].moves[moveNum].currentPP = newPP;
if(activity != null)
activity.updateMovePP(moveNum);
break;
} case DynamicStats: {
for (int i = 0; i < 5; i++)
myTeam.pokes[player / 2].stats[i] = msg.readShort();
break;
} default: {
super.dealWithCommand(bc, player, msg);
break;
}
}
}
| public void dealWithCommand(BattleCommand bc, byte player, Bais msg) {
switch(bc) {
case SendOut: {
if (player != me) {
super.dealWithCommand(bc, player, msg);
return;
}
boolean silent = msg.readBool();
byte fromSpot = msg.readByte();
BattlePoke temp = myTeam.pokes[0];
myTeam.pokes[0] = myTeam.pokes[fromSpot];
myTeam.pokes[fromSpot] = temp;
for (int i=0; i < 4; i++) {
displayedMoves[i] = new BattleMove(myTeam.pokes[0].moves[i]);
}
ShallowBattlePoke tempPoke = pokes[player][0];
pokes[player][0] = pokes[player][fromSpot];
pokes[player][fromSpot] = tempPoke;
if(msg.available() > 0) // this is the first time you've seen it
pokes[player][0] = new ShallowBattlePoke(msg, (player == me) ? true : false, netServ.db, conf.gen);
if(activity != null) {
activity.updatePokes(player);
activity.updatePokeballs();
}
SharedPreferences prefs = netServ.getSharedPreferences("battle", Context.MODE_PRIVATE);
if (prefs.getBoolean("pokemon_cries", true)) {
try {
synchronized (this) {
netServ.playCry(this, currentPoke(player));
wait(5000);
}
} catch (InterruptedException e) { Log.e(TAG, "INTERRUPTED"); }
}
if(!silent)
writeToHist("\n" + tu((players[player].nick() + " sent out " +
currentPoke(player).rnick + "!")));
break;
} case AbsStatusChange: {
byte poke = msg.readByte();
byte status = msg.readByte();
if (poke < 0 || poke >= 6)
break;
if (status != Status.Confused.poValue()) {
pokes[player][poke].changeStatus(status);
if (player == me)
myTeam.pokes[poke].changeStatus(status);
if (activity != null) {
if (isOut(poke))
activity.updatePokes(player);
activity.updatePokeballs();
}
}
break;
} case TempPokeChange: {
byte id = msg.readByte();
switch(TempPokeChange.values()[id]) {
case TempMove:
case DefMove:
byte slot = msg.readByte();
BattleMove newMove = new BattleMove(msg.readShort(), netServ.db);
displayedMoves[slot] = newMove;
if (id == TempPokeChange.DefMove.ordinal()) {
myTeam.pokes[0].moves[slot] = newMove;
}
if (activity != null) {
activity.updatePokes(player);
}
break;
case TempPP:
slot = msg.readByte();
byte PP = msg.readByte();
displayedMoves[slot].currentPP = PP;
if (activity !=null) {
activity.updateMovePP(slot);
}
break;
case TempSprite:
UniqueID sprite = new UniqueID(msg);
if (sprite.pokeNum != 0)
currentPoke(player).specialSprites.addFirst(sprite);
else if (currentPoke(player).specialSprites.size() > 0)
currentPoke(player).specialSprites.removeFirst();
if (activity !=null) {
activity.updatePokes(player);
}
break;
case DefiniteForme:
byte poke = msg.readByte();
short newForm = msg.readShort();
pokes[player][poke].uID.pokeNum = newForm;
if (isOut(poke)) {
currentPoke(slot(player, poke)).uID.pokeNum = newForm;
if (activity !=null) {
activity.updatePokes(player);
}
}
break;
case AestheticForme:
newForm = msg.readShort();
currentPoke(player).uID.subNum = (byte) newForm;
if (activity !=null) {
activity.updatePokes(player);
}
default: break;
}
break;
} case MakeYourChoice: {
if (activity != null) {
activity.updateButtons();
if (allowSwitch && !allowAttack)
activity.switchToPokeViewer();
}
break;
} case OfferChoice: {
@SuppressWarnings("unused")
byte numSlot = msg.readByte(); //Which poke the choice is for
allowSwitch = msg.readBool();
System.out.println("Switch allowed: " + allowSwitch);
allowAttack = msg.readBool();
System.out.println("Attacks allowed: " + allowAttack);
for (int i = 0; i < 4; i++) {
allowAttacks[i] = msg.readBool();
System.out.print("Allow attack " + i + ": ");
System.out.println(allowAttacks[i]);
}
if (allowAttack && !allowAttacks[0] && !allowAttacks[1] && !allowAttacks[2] && !allowAttacks[3])
shouldStruggle = true;
else
shouldStruggle = false;
clicked = false;
if (activity != null)
activity.updateButtons();
break;
} case CancelMove: {
clicked = false;
if (activity != null)
activity.updateButtons();
break;
} case ChangeHp: {
short newHP = msg.readShort();
if(player == me) {
myTeam.pokes[0].currentHP = newHP;
currentPoke(player).lastKnownPercent = currentPoke(player).lifePercent;
currentPoke(player).lifePercent = (byte)(newHP * 100 / myTeam.pokes[0].totalHP);
}
else {
currentPoke(player).lastKnownPercent = currentPoke(player).lifePercent;
currentPoke(player).lifePercent = (byte)newHP;
}
if(activity != null) {
// Block until the hp animation has finished
// Timeout after 10s
try {
synchronized (this) {
activity.animateHpBarTo(player, currentPoke(player).lifePercent);
wait(10000);
}
} catch (InterruptedException e) {}
activity.updateCurrentPokeListEntry();
}
break;
} case StraightDamage: {
if (player != me) {
super.dealWithCommand(bc, player, msg);
} else {
short damage = msg.readShort();
writeToHist("\n" + tu(currentPoke(player).nick + " lost " + damage + "HP! (" + (damage*100/myTeam.pokes[player/2].totalHP) + "% of its health)"));
}
break;
} case SpotShifts: {
// TODO
break;
} case RearrangeTeam: {
oppTeam = new ShallowShownTeam(msg);
shouldShowPreview = true;
if(activity != null)
activity.notifyRearrangeTeamDialog();
DataBaseHelper db = netServ.db;
String names[] = {PokemonInfo.name(db, oppTeam.poke(0).uID), PokemonInfo.name(db, oppTeam.poke(1).uID),
PokemonInfo.name(db, oppTeam.poke(2).uID), PokemonInfo.name(db, oppTeam.poke(3).uID),
PokemonInfo.name(db, oppTeam.poke(4).uID), PokemonInfo.name(db, oppTeam.poke(5).uID)};
writeToHist(Html.fromHtml("<br><font color=\"blue\"><b>Opponent's team: </b></font>" + StringUtilities.join(names, " / ")));
break;
} case ChangePP: {
byte moveNum = msg.readByte();
byte newPP = msg.readByte();
displayedMoves[moveNum].currentPP = myTeam.pokes[0].moves[moveNum].currentPP = newPP;
if(activity != null)
activity.updateMovePP(moveNum);
break;
} case DynamicStats: {
for (int i = 0; i < 5; i++)
myTeam.pokes[player / 2].stats[i] = msg.readShort();
break;
} default: {
super.dealWithCommand(bc, player, msg);
break;
}
}
}
|
diff --git a/org/postgresql/test/jdbc2/optional/OptionalTestSuite.java b/org/postgresql/test/jdbc2/optional/OptionalTestSuite.java
index 980ff68..d740a5a 100644
--- a/org/postgresql/test/jdbc2/optional/OptionalTestSuite.java
+++ b/org/postgresql/test/jdbc2/optional/OptionalTestSuite.java
@@ -1,27 +1,27 @@
package org.postgresql.test.jdbc2.optional;
import junit.framework.TestSuite;
/**
* Test suite for the JDBC 2.0 Optional Package implementation. This
* includes the DataSource, ConnectionPoolDataSource, and
* PooledConnection implementations.
*
* @author Aaron Mulder ([email protected])
* @version $Revision$
*/
public class OptionalTestSuite extends TestSuite
{
/**
* Gets the test suite for the entire JDBC 2.0 Optional Package
* implementation.
*/
public static TestSuite suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(SimpleDataSourceTest.class);
suite.addTestSuite(ConnectionPoolTest.class);
- suite.addTestSuite(ConnectionPoolTest.class);
+ suite.addTestSuite(PoolingDataSourceTest.class);
return suite;
}
}
| true | true | public static TestSuite suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(SimpleDataSourceTest.class);
suite.addTestSuite(ConnectionPoolTest.class);
suite.addTestSuite(ConnectionPoolTest.class);
return suite;
}
| public static TestSuite suite()
{
TestSuite suite = new TestSuite();
suite.addTestSuite(SimpleDataSourceTest.class);
suite.addTestSuite(ConnectionPoolTest.class);
suite.addTestSuite(PoolingDataSourceTest.class);
return suite;
}
|
diff --git a/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/FileUtil.java b/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/FileUtil.java
index fe5c49913..0c786e79a 100644
--- a/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/FileUtil.java
+++ b/core/tests/org.eclipse.dltk.core.tests/src/org/eclipse/dltk/core/tests/FileUtil.java
@@ -1,86 +1,88 @@
/*******************************************************************************
* Copyright (c) 2005, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
package org.eclipse.dltk.core.tests;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Collections;
import java.util.Set;
public class FileUtil {
public static void copyDirectory(File source, File target)
throws IOException {
copyDirectory(source, target, Collections.<File> emptySet());
}
public static void copyDirectory(File source, File target,
Set<File> excludes) throws IOException {
if (!target.exists()) {
target.mkdirs();
}
final File[] files = source.listFiles();
if (files == null) {
throw new IllegalStateException("Source directory " + source
+ " doesn't exist");
}
for (int i = 0; i < files.length; i++) {
final File sourceChild = files[i];
final String name = sourceChild.getName();
if (name.equals("CVS") || name.equals(".svn"))
continue;
+ if (excludes.contains(sourceChild))
+ continue;
final File targetChild = new File(target, name);
if (sourceChild.isDirectory()) {
copyDirectory(sourceChild, targetChild, excludes);
} else {
if (".emptydir".equals(name)) {
continue;
}
copyFile(sourceChild, targetChild);
}
}
}
/**
* Copy file from src (path to the original file) to dest (path to the
* destination file).
*/
public static void copyFile(File src, File dest) throws IOException {
InputStream in = null;
OutputStream out = null;
byte[] buffer = new byte[12 * 1024];
int read;
try {
in = new FileInputStream(src);
try {
out = new FileOutputStream(dest);
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} finally {
if (out != null) {
out.close();
}
}
} finally {
if (in != null) {
in.close();
}
}
}
}
| true | true | public static void copyDirectory(File source, File target,
Set<File> excludes) throws IOException {
if (!target.exists()) {
target.mkdirs();
}
final File[] files = source.listFiles();
if (files == null) {
throw new IllegalStateException("Source directory " + source
+ " doesn't exist");
}
for (int i = 0; i < files.length; i++) {
final File sourceChild = files[i];
final String name = sourceChild.getName();
if (name.equals("CVS") || name.equals(".svn"))
continue;
final File targetChild = new File(target, name);
if (sourceChild.isDirectory()) {
copyDirectory(sourceChild, targetChild, excludes);
} else {
if (".emptydir".equals(name)) {
continue;
}
copyFile(sourceChild, targetChild);
}
}
}
| public static void copyDirectory(File source, File target,
Set<File> excludes) throws IOException {
if (!target.exists()) {
target.mkdirs();
}
final File[] files = source.listFiles();
if (files == null) {
throw new IllegalStateException("Source directory " + source
+ " doesn't exist");
}
for (int i = 0; i < files.length; i++) {
final File sourceChild = files[i];
final String name = sourceChild.getName();
if (name.equals("CVS") || name.equals(".svn"))
continue;
if (excludes.contains(sourceChild))
continue;
final File targetChild = new File(target, name);
if (sourceChild.isDirectory()) {
copyDirectory(sourceChild, targetChild, excludes);
} else {
if (".emptydir".equals(name)) {
continue;
}
copyFile(sourceChild, targetChild);
}
}
}
|
diff --git a/src/test/java/org/zenoss/zep/impl/TriggerPluginImplTest.java b/src/test/java/org/zenoss/zep/impl/TriggerPluginImplTest.java
index 7bee601..8c50af6 100644
--- a/src/test/java/org/zenoss/zep/impl/TriggerPluginImplTest.java
+++ b/src/test/java/org/zenoss/zep/impl/TriggerPluginImplTest.java
@@ -1,114 +1,112 @@
/*
* This program is part of Zenoss Core, an open source monitoring platform.
* Copyright (C) 2010, Zenoss Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* For complete information please visit: http://www.zenoss.com/oss/
*/
package org.zenoss.zep.impl;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.zenoss.protobufs.model.Model.ModelElementType;
import org.zenoss.protobufs.zep.Zep;
import org.zenoss.protobufs.zep.Zep.Event;
import org.zenoss.protobufs.zep.Zep.EventActor;
import org.zenoss.protobufs.zep.Zep.EventSummary;
import org.zenoss.zep.ZepException;
import org.zenoss.zep.dao.EventSignalSpool;
import org.zenoss.zep.dao.EventSignalSpoolDao;
public class TriggerPluginImplTest {
public TriggerPlugin triggerPlugin = null;
private EventSignalSpoolDao spoolDaoMock;
@Before
public void testInit() throws IOException, ZepException {
Map<String,String> props = new HashMap<String,String>();
this.triggerPlugin = new TriggerPlugin();
spoolDaoMock = createMock(EventSignalSpoolDao.class);
expect(spoolDaoMock.findAllDue()).andReturn(Collections.<EventSignalSpool> emptyList()).anyTimes();
replay(spoolDaoMock);
this.triggerPlugin.setSignalSpoolDao(this.spoolDaoMock);
this.triggerPlugin.init(props);
}
@After
public void shutdown() throws InterruptedException {
this.triggerPlugin.shutdown();
verify(this.spoolDaoMock);
}
@Test
public void testTriggerRules() throws IOException {
EventActor.Builder actorBuilder = EventActor.newBuilder();
actorBuilder.setElementTypeId(ModelElementType.DEVICE);
actorBuilder.setElementIdentifier("BHM1000");
actorBuilder.setElementSubTypeId(ModelElementType.COMPONENT);
actorBuilder.setElementSubIdentifier("Fuse-10A");
// build test Event to add to EventSummary as occurrence[0]
Event.Builder evtBuilder = Event.newBuilder();
evtBuilder.setActor(actorBuilder.build());
evtBuilder.setMessage("TEST - 1-2-check");
evtBuilder.setEventClass("/Defcon/1");
evtBuilder.setSeverity(Zep.EventSeverity.SEVERITY_WARNING);
Event evt = evtBuilder.build();
// build test EventSummary
EventSummary.Builder evtSumBuilder = EventSummary.newBuilder();
evtSumBuilder.setCount(10);
evtSumBuilder.setStatus(Zep.EventStatus.STATUS_NEW);
evtSumBuilder.addOccurrence(evt);
EventSummary evtSummary = evtSumBuilder.build();
// test various rules
String[] true_rules = {
"1 == 1",
"evt.message.startswith('TEST')",
"evt.severity == 'warning'",
"evt.event_class == '/Defcon/1'",
"evt.count > 5",
- "evt.status == 'new'",
"dev.name == 'BHM1000'",
"component.name.lower().startswith('fuse')",
};
String[] false_rules = {
"1 = 0", // try a syntax error
"", // try empty string
"evt.msg == 'fail!'", // nonexistent attribute
"1 == 0",
"evt.message.startswith('BEST')",
"evt.count > 15",
"evt.severity = 'critical'",
- "evt.status == 'acked'",
"dev.name == 'BHM1001'",
};
for(String rule: true_rules) {
assertTrue(rule + " (should evaluate True)",
this.triggerPlugin.eventSatisfiesRule(evtSummary, rule));
}
for(String rule: false_rules) {
assertFalse(rule + " (should evaluate False)",
this.triggerPlugin.eventSatisfiesRule(evtSummary, rule));
}
}
}
| false | true | public void testTriggerRules() throws IOException {
EventActor.Builder actorBuilder = EventActor.newBuilder();
actorBuilder.setElementTypeId(ModelElementType.DEVICE);
actorBuilder.setElementIdentifier("BHM1000");
actorBuilder.setElementSubTypeId(ModelElementType.COMPONENT);
actorBuilder.setElementSubIdentifier("Fuse-10A");
// build test Event to add to EventSummary as occurrence[0]
Event.Builder evtBuilder = Event.newBuilder();
evtBuilder.setActor(actorBuilder.build());
evtBuilder.setMessage("TEST - 1-2-check");
evtBuilder.setEventClass("/Defcon/1");
evtBuilder.setSeverity(Zep.EventSeverity.SEVERITY_WARNING);
Event evt = evtBuilder.build();
// build test EventSummary
EventSummary.Builder evtSumBuilder = EventSummary.newBuilder();
evtSumBuilder.setCount(10);
evtSumBuilder.setStatus(Zep.EventStatus.STATUS_NEW);
evtSumBuilder.addOccurrence(evt);
EventSummary evtSummary = evtSumBuilder.build();
// test various rules
String[] true_rules = {
"1 == 1",
"evt.message.startswith('TEST')",
"evt.severity == 'warning'",
"evt.event_class == '/Defcon/1'",
"evt.count > 5",
"evt.status == 'new'",
"dev.name == 'BHM1000'",
"component.name.lower().startswith('fuse')",
};
String[] false_rules = {
"1 = 0", // try a syntax error
"", // try empty string
"evt.msg == 'fail!'", // nonexistent attribute
"1 == 0",
"evt.message.startswith('BEST')",
"evt.count > 15",
"evt.severity = 'critical'",
"evt.status == 'acked'",
"dev.name == 'BHM1001'",
};
for(String rule: true_rules) {
assertTrue(rule + " (should evaluate True)",
this.triggerPlugin.eventSatisfiesRule(evtSummary, rule));
}
for(String rule: false_rules) {
assertFalse(rule + " (should evaluate False)",
this.triggerPlugin.eventSatisfiesRule(evtSummary, rule));
}
}
| public void testTriggerRules() throws IOException {
EventActor.Builder actorBuilder = EventActor.newBuilder();
actorBuilder.setElementTypeId(ModelElementType.DEVICE);
actorBuilder.setElementIdentifier("BHM1000");
actorBuilder.setElementSubTypeId(ModelElementType.COMPONENT);
actorBuilder.setElementSubIdentifier("Fuse-10A");
// build test Event to add to EventSummary as occurrence[0]
Event.Builder evtBuilder = Event.newBuilder();
evtBuilder.setActor(actorBuilder.build());
evtBuilder.setMessage("TEST - 1-2-check");
evtBuilder.setEventClass("/Defcon/1");
evtBuilder.setSeverity(Zep.EventSeverity.SEVERITY_WARNING);
Event evt = evtBuilder.build();
// build test EventSummary
EventSummary.Builder evtSumBuilder = EventSummary.newBuilder();
evtSumBuilder.setCount(10);
evtSumBuilder.setStatus(Zep.EventStatus.STATUS_NEW);
evtSumBuilder.addOccurrence(evt);
EventSummary evtSummary = evtSumBuilder.build();
// test various rules
String[] true_rules = {
"1 == 1",
"evt.message.startswith('TEST')",
"evt.severity == 'warning'",
"evt.event_class == '/Defcon/1'",
"evt.count > 5",
"dev.name == 'BHM1000'",
"component.name.lower().startswith('fuse')",
};
String[] false_rules = {
"1 = 0", // try a syntax error
"", // try empty string
"evt.msg == 'fail!'", // nonexistent attribute
"1 == 0",
"evt.message.startswith('BEST')",
"evt.count > 15",
"evt.severity = 'critical'",
"dev.name == 'BHM1001'",
};
for(String rule: true_rules) {
assertTrue(rule + " (should evaluate True)",
this.triggerPlugin.eventSatisfiesRule(evtSummary, rule));
}
for(String rule: false_rules) {
assertFalse(rule + " (should evaluate False)",
this.triggerPlugin.eventSatisfiesRule(evtSummary, rule));
}
}
|
diff --git a/votable/src/main/uk/ac/starlink/votable/FitsPlusTableBuilder.java b/votable/src/main/uk/ac/starlink/votable/FitsPlusTableBuilder.java
index 86e6c0d0b..639037c51 100644
--- a/votable/src/main/uk/ac/starlink/votable/FitsPlusTableBuilder.java
+++ b/votable/src/main/uk/ac/starlink/votable/FitsPlusTableBuilder.java
@@ -1,515 +1,515 @@
package uk.ac.starlink.votable;
import java.awt.datatransfer.DataFlavor;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import nom.tam.fits.FitsException;
import nom.tam.fits.Header;
import nom.tam.fits.HeaderCard;
import nom.tam.util.ArrayDataInput;
import nom.tam.util.BufferedDataInputStream;
import nom.tam.util.RandomAccess;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import uk.ac.starlink.fits.BintableStarTable;
import uk.ac.starlink.fits.FitsConstants;
import uk.ac.starlink.fits.FitsTableBuilder;
import uk.ac.starlink.table.ColumnInfo;
import uk.ac.starlink.table.MultiTableBuilder;
import uk.ac.starlink.table.StarTable;
import uk.ac.starlink.table.StoragePolicy;
import uk.ac.starlink.table.TableBuilder;
import uk.ac.starlink.table.TableFormatException;
import uk.ac.starlink.table.TableSink;
import uk.ac.starlink.util.DOMUtils;
import uk.ac.starlink.util.DataSource;
import uk.ac.starlink.util.IOUtils;
/**
* Table builder which can read files in 'fits-plus' format (as written
* by {@link FitsPlusTableWriter}). This looks for a primary header
* in the FITS file which contains the VOTMETA header (in fact it is
* quite inflexible about what it recognises as this format -
* see {@link #isMagic}) and tries to interpret the data array as a
* 1-d array of bytes representing the XML of a VOTable document.
* This VOTable document should have one or more TABLE elements with no DATA
* content - the table data is got from the extension extension HDUs,
* one per table, and they must be BINTABLE extensions matching the
* metadata described by the VOTable.
*
* <p>The point of all this is so that you can store VOTables in
* the efficient FITS format (it can be mapped if it's on local disk,
* which makes table creation practically instantaneous, even for
* random access) without sacrificing any of the metadata that you
* want to encode in VOTable format.
*
* @author Mark Taylor (Starlink)
* @since 27 Aug 2004
* @see FitsPlusTableWriter
*/
public class FitsPlusTableBuilder implements TableBuilder, MultiTableBuilder {
private static Logger logger = Logger.getLogger( "uk.ac.starlink.votable" );
public String getFormatName() {
return "FITS-plus";
}
public StarTable makeStarTable( DataSource datsrc, boolean wantRandom,
StoragePolicy storagePolicy )
throws IOException {
/* See if this looks like a fits-plus table. */
if ( ! isMagic( datsrc.getIntro() ) ) {
throw new TableFormatException(
"Doesn't look like a FITS-plus file" );
}
/* Get an input stream. */
ArrayDataInput strm = FitsConstants.getInputStreamStart( datsrc );
try {
/* Read the metadata from the primary HDU. */
long[] pos = new long[ 1 ];
TableElement[] tabels = readMetadata( strm, pos );
/* Get the metadata for the table we are interested in. */
int iTable = getTableIndex( datsrc.getPosition(), tabels.length );
TableElement tabel = tabels[ iTable ];
/* Skip HDUs if required. They should all be BINTABLE HDUs
* corresponding to tables earlier than the one we need. */
pos[ 0 ] += FitsConstants.skipHDUs( strm, iTable );
/* Now get the StarTable from the next HDU. */
StarTable starTable =
FitsTableBuilder.attemptReadTable( strm, wantRandom,
datsrc, pos );
if ( starTable == null ) {
throw new TableFormatException( "No BINTABLE HDU found" );
}
/* Return a StarTable with data from the BINTABLE but metadata
* from the VOTable header. */
return createFitsPlusTable( tabel, starTable );
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
catch ( NullPointerException e ) { // don't like this
throw new TableFormatException( "Table not quite in " +
"fits-plus format", e );
}
}
public StarTable[] makeStarTables( DataSource datsrc,
StoragePolicy storagePolicy)
throws IOException {
/* If there is a position, use makeStarTable. Otherwise, we want
* all the tables. */
String srcpos = datsrc.getPosition();
if ( srcpos != null && srcpos.trim().length() > 0 ) {
return new StarTable[] { makeStarTable( datsrc, false,
storagePolicy ) };
}
/* See if this looks like a fits-plus table. */
if ( ! isMagic( datsrc.getIntro() ) ) {
throw new TableFormatException(
"Doesn't look like a FITS-plus file" );
}
/* Get an input stream. */
ArrayDataInput in = FitsConstants.getInputStreamStart( datsrc );
try {
/* Read the metadata from the primary HDU. */
long[] posptr = new long[ 1 ];
TableElement[] tabEls = readMetadata( in, posptr );
long pos = posptr[ 0 ];
int nTable = tabEls.length;
StarTable[] outTables = new StarTable[ nTable ];
/* Read each table HDU in turn. */
for ( int itab = 0; itab < nTable; itab++ ) {
/* Make sure we have a usable stream positioned at the start
* of the right HDU. */
if ( in == null ) {
in = FitsConstants.getInputStreamStart( datsrc );
if ( pos > 0 ) {
if ( in instanceof RandomAccess ) {
((RandomAccess) in).seek( pos );
}
else {
IOUtils.skipBytes( in, pos );
}
}
}
/* Read the HDU header. */
Header hdr = new Header();
int headsize = FitsConstants.readHeader( hdr, in );
long datasize = FitsConstants.getDataSize( hdr );
long datpos = pos + headsize;
if ( ! "BINTABLE".equals( hdr.getStringValue( "XTENSION" ) ) ) {
throw new TableFormatException( "Non-BINTABLE at ext #"
+ itab + " - not FITS-plus" );
}
/* Read the BINTABLE. */
final StarTable dataTable;
if ( in instanceof RandomAccess ) {
dataTable = BintableStarTable
.makeRandomStarTable( hdr, (RandomAccess) in );
}
else {
dataTable = BintableStarTable
.makeSequentialStarTable( hdr, datsrc, datpos );
- in = null;
}
+ in = null;
/* Combine the data from the BINTABLE with the header from
* the VOTable to create an output table. */
outTables[ itab ] =
createFitsPlusTable( tabEls[ itab ], dataTable );
pos += headsize + datasize;
}
return outTables;
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
}
public void streamStarTable( InputStream in, final TableSink sink,
String pos )
throws IOException {
ArrayDataInput strm = new BufferedDataInputStream( in );
try {
/* Read the metadata from the primary HDU. */
TableElement[] tabels = readMetadata( strm, new long[ 1 ] );
/* Get the metadata for the table we are interested in. */
int iTable = getTableIndex( pos, tabels.length );
TableElement tabel = tabels[ iTable ];
/* Skip HDUs if required. They should all be BINTABLE HDUs
* corresponding to tables earlier than the one we need. */
FitsConstants.skipHDUs( strm, iTable );
/* Prepare a modified sink which behaves like the one we were
* given but will pass on the VOTable metadata rather than that
* from the BINTABLE extension. */
final StarTable voMeta = new VOStarTable( tabel );
TableSink wsink = new TableSink() {
public void acceptMetadata( StarTable fitsMeta )
throws TableFormatException {
sink.acceptMetadata( voMeta );
}
public void acceptRow( Object[] row ) throws IOException {
sink.acceptRow( row );
}
public void endRows() throws IOException {
sink.endRows();
}
};
/* Write the table data from the upcoming BINTABLE element to the
* sink. */
Header hdr = new Header();
FitsConstants.readHeader( hdr, strm );
BintableStarTable.streamStarTable( hdr, strm, wsink );
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
finally {
strm.close();
}
}
/**
* Reads the primary HDU of a FITS stream, checking it is of the
* correct FITS-plus format, and returns the VOTable TABLE elements
* which are encoded in it. On successful exit, the stream will
* be positioned at the start of the first non-primary HDU
* (which should contain a BINTABLE).
*
* @param strm stream holding the data (positioned at the start)
* @param pos 1-element array for returning the number of bytes read
* into the stream
* @return array of TABLE elements in the primary HDU
*/
private static TableElement[] readMetadata( ArrayDataInput strm,
long[] pos )
throws IOException {
/* Read the first FITS block from the stream into a buffer.
* This should contain the entire header of the primary HDU. */
byte[] headBuf = new byte[ 2880 ];
strm.readFully( headBuf );
/* Check it seems to have the right form. */
if ( ! isMagic( headBuf ) ) {
throw new TableFormatException( "Primary header not FITS-plus" );
}
try {
/* Turn it into a header and find out the length of the
* data unit. */
Header hdr = new Header();
ArrayDataInput hstrm =
new BufferedDataInputStream(
new ByteArrayInputStream( headBuf ) );
int headsize = FitsConstants.readHeader( hdr, hstrm );
int datasize = (int) FitsConstants.getDataSize( hdr );
pos[ 0 ] = headsize + datasize;
assert headsize == 2880;
assert hdr.getIntValue( "NAXIS" ) == 1;
assert hdr.getIntValue( "BITPIX" ) == 8;
int nbyte = hdr.getIntValue( "NAXIS1" );
/* Read the data from the primary HDU into a byte buffer. */
byte[] vobuf = new byte[ nbyte ];
strm.readFully( vobuf );
/* Advance to the end of the primary HDU. */
int pad = datasize - nbyte;
IOUtils.skipBytes( strm, pad );
/* Read XML from the byte buffer, performing a custom
* parse to DOM. */
VOElementFactory vofact = new VOElementFactory();
DOMSource domsrc =
vofact.transformToDOM(
new StreamSource( new ByteArrayInputStream( vobuf ) ),
false );
/* Obtain the TABLE elements, which ought to be empty. */
VODocument doc = (VODocument) domsrc.getNode();
VOElement topel = (VOElement) doc.getDocumentElement();
NodeList tlist = topel.getElementsByVOTagName( "TABLE" );
int nTable = tlist.getLength();
TableElement[] tabels = new TableElement[ nTable ];
for ( int i = 0; i < nTable; i++ ) {
tabels[ i ] = (TableElement) tlist.item( i );
if ( tabels[ i ].getChildByName( "DATA" ) != null ) {
throw new TableFormatException(
"TABLE #" + ( i + i ) + " in embedded VOTable document "
+ "has unexpected DATA element" );
}
}
return tabels;
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
catch ( SAXException e ) {
throw new TableFormatException( e.getMessage(), e );
}
}
/**
* Returns the index of the table requested by a data source position
* string. The first table is represented by position string "1".
* The returned value is the 0-based index of the table,
* which corresponds to the 1-based HDU number (the primary HDU is
* excluded). If the supplied position string does not correspond
* to a known table, a TableFormatException is thrown.
*
* @param pos position string (first is "1")
* @param nTable number of tables in the whole file
*/
private static int getTableIndex( String pos, int nTable )
throws TableFormatException {
if ( nTable <= 0 ) {
throw new TableFormatException( "No tables present "
+ "in FITS-plus container" );
}
if ( pos == null || pos.trim().length() == 0 ) {
return 0;
}
else {
try {
int index = Integer.parseInt( pos.trim() );
if ( index >= 1 && index <= nTable ) {
return index - 1;
}
else if ( index == 0 ) {
throw new TableFormatException( "No table with position "
+ pos + "; first table is "
+ "#1" );
}
else {
throw new TableFormatException( "No table with position "
+ pos + "; there are " +
+ nTable );
}
}
catch ( NumberFormatException e ) {
throw new TableFormatException( "Can't interpret position "
+ pos + " (not a number)", e );
}
}
}
/**
* Combines the metadata from a VOTable TABLE element and the data
* from a corresponding FITS BINTABLE HDU to construct a StarTable.
* If the two don't seem to match sufficiently, an error may be thrown.
*
* @param tabEl metadata-bearing TABLE element
* @param dataTable data-bearing StarTable
* @return combined table
*/
private static StarTable createFitsPlusTable( TableElement tabEl,
StarTable dataTable )
throws IOException {
/* Check that the FIELD elements look consistent with the
* FITS data. If not, the FITS file has probably been
* messed about with somehow, and attempting to interpret this
* file as FITS-plus is probably a bad idea. */
/* The implementation of this test is a bit desperate.
* It is doing some of the same work as the consistency
* adjustment below, but trying to be more stringent.
* It tries to avoid the issue noted below concerning strings
* and characters - but I don't remember the details of what
* that was :-(. This part was written later. */
FieldElement[] fields = tabEl.getFields();
if ( fields.length != dataTable.getColumnCount() ) {
throw new TableFormatException( "FITS/VOTable metadata mismatch"
+ " - column counts differ" );
}
for ( int ic = 0; ic < fields.length; ic++ ) {
Class fclazz = dataTable.getColumnInfo( ic ).getContentClass();
Class vclazz = fields[ ic ].getDecoder().getContentClass();
if ( fclazz.equals( vclazz )
|| ( ( fclazz.equals( String.class ) ||
fclazz.equals( Character.class ) ||
fclazz.equals( char[].class ) )
&& ( vclazz.equals( String.class ) ||
vclazz.equals( Character.class ) ||
vclazz.equals( char[].class ) ) ) ) {
// ok
}
else {
throw new TableFormatException( "FITS/VOTable metadata "
+ "mismatch"
+ " - column types differ" );
}
}
/* Turn it into a TabularData element associated it with its
* TABLE DOM element as if the DOM builder had found the table
* data in a DATA element within the TABLE element. */
tabEl.setData( new TableBodies.StarTableTabularData( dataTable ) );
/* Now create and return a StarTable based on the TABLE element;
* its metadata comes from the VOTable, but its data comes from
* the FITS table we've just read. */
VOStarTable outTable = new VOStarTable( tabEl );
/* Ensure column type consistency. There can occasionally by
* some nasty issues with Character/String types. */
int ncol = dataTable.getColumnCount();
assert ncol == outTable.getColumnCount();
for ( int icol = 0; icol < ncol; icol++ ) {
ColumnInfo fInfo = dataTable.getColumnInfo( icol );
ColumnInfo vInfo = outTable.getColumnInfo( icol );
if ( ! vInfo.getContentClass()
.isAssignableFrom( fInfo.getContentClass() ) ) {
vInfo.setContentClass( fInfo.getContentClass() );
}
}
return outTable;
}
/**
* Returns <tt>true</tt> for a flavor with the MIME type "application/fits".
*/
public boolean canImport( DataFlavor flavor ) {
if ( flavor.getPrimaryType().equals( "application" ) &&
flavor.getSubType().equals( "fits" ) ) {
return true;
}
return false;
}
/**
* Tests whether a given buffer contains bytes which might be the
* first few bytes of a FitsPlus table.
* The criterion is that it looks like the start of a FITS header,
* and the first few cards look roughly like this:
* <pre>
* SIMPLE = T
* BITPIX = 8
* NAXIS = 1
* NAXIS1 = ???
* VOTMETA = T
* </pre>
*
* @param buffer byte buffer containing leading few bytes of data
* @return true if it looks like a FitsPlus file
*/
public static boolean isMagic( byte[] buffer ) {
final int ntest = 5;
int pos = 0;
int ncard = 0;
boolean ok = true;
for ( int il = 0; ok && il < ntest; il++ ) {
if ( buffer.length > pos + 80 ) {
char[] cbuf = new char[ 80 ];
for ( int ic = 0; ic < 80; ic++ ) {
cbuf[ ic ] = (char) ( buffer[ pos++ ] & 0xff );
}
try {
HeaderCard card = new HeaderCard( new String( cbuf ) );
ok = ok && cardOK( il, card );
}
catch ( FitsException e ) {
ok = false;
}
}
}
return ok;
}
/**
* Checks whether the i'th card looks like it should do for the file
* to be readable by this handler.
*
* @param icard card index
* @param card header card
* @return true if <tt>card</tt> looks like the <tt>icard</tt>'th
* header card of a FitsPlus primary header should do
*/
private static boolean cardOK( int icard, HeaderCard card )
throws FitsException {
String key = card.getKey();
String value = card.getValue();
switch ( icard ) {
case 0:
return "SIMPLE".equals( key ) && "T".equals( value );
case 1:
return "BITPIX".equals( key ) && "8".equals( value );
case 2:
return "NAXIS".equals( key ) && "1".equals( value );
case 3:
return "NAXIS1".equals( key );
case 4:
return "VOTMETA".equals( key ) && "T".equals( value );
default:
return true;
}
}
}
| false | true | public StarTable[] makeStarTables( DataSource datsrc,
StoragePolicy storagePolicy)
throws IOException {
/* If there is a position, use makeStarTable. Otherwise, we want
* all the tables. */
String srcpos = datsrc.getPosition();
if ( srcpos != null && srcpos.trim().length() > 0 ) {
return new StarTable[] { makeStarTable( datsrc, false,
storagePolicy ) };
}
/* See if this looks like a fits-plus table. */
if ( ! isMagic( datsrc.getIntro() ) ) {
throw new TableFormatException(
"Doesn't look like a FITS-plus file" );
}
/* Get an input stream. */
ArrayDataInput in = FitsConstants.getInputStreamStart( datsrc );
try {
/* Read the metadata from the primary HDU. */
long[] posptr = new long[ 1 ];
TableElement[] tabEls = readMetadata( in, posptr );
long pos = posptr[ 0 ];
int nTable = tabEls.length;
StarTable[] outTables = new StarTable[ nTable ];
/* Read each table HDU in turn. */
for ( int itab = 0; itab < nTable; itab++ ) {
/* Make sure we have a usable stream positioned at the start
* of the right HDU. */
if ( in == null ) {
in = FitsConstants.getInputStreamStart( datsrc );
if ( pos > 0 ) {
if ( in instanceof RandomAccess ) {
((RandomAccess) in).seek( pos );
}
else {
IOUtils.skipBytes( in, pos );
}
}
}
/* Read the HDU header. */
Header hdr = new Header();
int headsize = FitsConstants.readHeader( hdr, in );
long datasize = FitsConstants.getDataSize( hdr );
long datpos = pos + headsize;
if ( ! "BINTABLE".equals( hdr.getStringValue( "XTENSION" ) ) ) {
throw new TableFormatException( "Non-BINTABLE at ext #"
+ itab + " - not FITS-plus" );
}
/* Read the BINTABLE. */
final StarTable dataTable;
if ( in instanceof RandomAccess ) {
dataTable = BintableStarTable
.makeRandomStarTable( hdr, (RandomAccess) in );
}
else {
dataTable = BintableStarTable
.makeSequentialStarTable( hdr, datsrc, datpos );
in = null;
}
/* Combine the data from the BINTABLE with the header from
* the VOTable to create an output table. */
outTables[ itab ] =
createFitsPlusTable( tabEls[ itab ], dataTable );
pos += headsize + datasize;
}
return outTables;
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
}
| public StarTable[] makeStarTables( DataSource datsrc,
StoragePolicy storagePolicy)
throws IOException {
/* If there is a position, use makeStarTable. Otherwise, we want
* all the tables. */
String srcpos = datsrc.getPosition();
if ( srcpos != null && srcpos.trim().length() > 0 ) {
return new StarTable[] { makeStarTable( datsrc, false,
storagePolicy ) };
}
/* See if this looks like a fits-plus table. */
if ( ! isMagic( datsrc.getIntro() ) ) {
throw new TableFormatException(
"Doesn't look like a FITS-plus file" );
}
/* Get an input stream. */
ArrayDataInput in = FitsConstants.getInputStreamStart( datsrc );
try {
/* Read the metadata from the primary HDU. */
long[] posptr = new long[ 1 ];
TableElement[] tabEls = readMetadata( in, posptr );
long pos = posptr[ 0 ];
int nTable = tabEls.length;
StarTable[] outTables = new StarTable[ nTable ];
/* Read each table HDU in turn. */
for ( int itab = 0; itab < nTable; itab++ ) {
/* Make sure we have a usable stream positioned at the start
* of the right HDU. */
if ( in == null ) {
in = FitsConstants.getInputStreamStart( datsrc );
if ( pos > 0 ) {
if ( in instanceof RandomAccess ) {
((RandomAccess) in).seek( pos );
}
else {
IOUtils.skipBytes( in, pos );
}
}
}
/* Read the HDU header. */
Header hdr = new Header();
int headsize = FitsConstants.readHeader( hdr, in );
long datasize = FitsConstants.getDataSize( hdr );
long datpos = pos + headsize;
if ( ! "BINTABLE".equals( hdr.getStringValue( "XTENSION" ) ) ) {
throw new TableFormatException( "Non-BINTABLE at ext #"
+ itab + " - not FITS-plus" );
}
/* Read the BINTABLE. */
final StarTable dataTable;
if ( in instanceof RandomAccess ) {
dataTable = BintableStarTable
.makeRandomStarTable( hdr, (RandomAccess) in );
}
else {
dataTable = BintableStarTable
.makeSequentialStarTable( hdr, datsrc, datpos );
}
in = null;
/* Combine the data from the BINTABLE with the header from
* the VOTable to create an output table. */
outTables[ itab ] =
createFitsPlusTable( tabEls[ itab ], dataTable );
pos += headsize + datasize;
}
return outTables;
}
catch ( FitsException e ) {
throw new TableFormatException( e.getMessage(), e );
}
}
|
diff --git a/platform/com.subgraph.vega.scanner/src/com/subgraph/vega/impl/scanner/Scanner.java b/platform/com.subgraph.vega.scanner/src/com/subgraph/vega/impl/scanner/Scanner.java
index daab28fc..43d7627a 100644
--- a/platform/com.subgraph.vega.scanner/src/com/subgraph/vega/impl/scanner/Scanner.java
+++ b/platform/com.subgraph.vega.scanner/src/com/subgraph/vega/impl/scanner/Scanner.java
@@ -1,198 +1,200 @@
package com.subgraph.vega.impl.scanner;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import com.subgraph.vega.api.analysis.IContentAnalyzerFactory;
import com.subgraph.vega.api.crawler.IWebCrawlerFactory;
import com.subgraph.vega.api.events.IEvent;
import com.subgraph.vega.api.events.IEventHandler;
import com.subgraph.vega.api.http.requests.IHttpRequestEngine;
import com.subgraph.vega.api.http.requests.IHttpRequestEngineConfig;
import com.subgraph.vega.api.http.requests.IHttpRequestEngineFactory;
import com.subgraph.vega.api.model.IModel;
import com.subgraph.vega.api.model.IWorkspace;
import com.subgraph.vega.api.model.WorkspaceCloseEvent;
import com.subgraph.vega.api.model.WorkspaceOpenEvent;
import com.subgraph.vega.api.model.alerts.IScanInstance;
import com.subgraph.vega.api.scanner.IScanner;
import com.subgraph.vega.api.scanner.IScannerConfig;
import com.subgraph.vega.api.scanner.modules.IBasicModuleScript;
import com.subgraph.vega.api.scanner.modules.IResponseProcessingModule;
import com.subgraph.vega.api.scanner.modules.IScannerModule;
import com.subgraph.vega.api.scanner.modules.IScannerModuleRegistry;
public class Scanner implements IScanner {
private IModel model;
private IScanInstance currentScan;
private IScannerConfig persistentConfig;
private IWebCrawlerFactory crawlerFactory;
private IHttpRequestEngineFactory requestEngineFactory;
private IScannerModuleRegistry moduleRegistry;
private ScannerTask scannerTask;
private Thread scannerThread;
private IWorkspace currentWorkspace;
private IContentAnalyzerFactory contentAnalyzerFactory;
private List<IResponseProcessingModule> responseProcessingModules;
private List<IBasicModuleScript> basicModules;
private List<IScannerModule> allModules;
protected void activate() {
currentWorkspace = model.addWorkspaceListener(new IEventHandler() {
@Override
public void handleEvent(IEvent event) {
if(event instanceof WorkspaceOpenEvent)
handleWorkspaceOpen((WorkspaceOpenEvent) event);
else if(event instanceof WorkspaceCloseEvent)
handleWorkspaceClose((WorkspaceCloseEvent) event);
}
});
reloadModules();
}
private void reloadModules() {
if(responseProcessingModules == null || basicModules == null) {
responseProcessingModules = moduleRegistry.getResponseProcessingModules();
basicModules = moduleRegistry.getBasicModules();
} else {
responseProcessingModules = moduleRegistry.updateResponseProcessingModules(responseProcessingModules);
basicModules = moduleRegistry.updateBasicModules(basicModules);
}
allModules = new ArrayList<IScannerModule>();
allModules.addAll(responseProcessingModules);
allModules.addAll(basicModules);
}
private void resetModuleTimestamps() {
for(IScannerModule m: allModules) {
m.getRunningTimeProfile().reset();
}
}
private void handleWorkspaceOpen(WorkspaceOpenEvent event) {
this.currentWorkspace = event.getWorkspace();
}
private void handleWorkspaceClose(WorkspaceCloseEvent event) {
this.currentWorkspace = null;
}
protected void deactivate() {
}
IWebCrawlerFactory getCrawlerFactory() {
return crawlerFactory;
}
IModel getModel() {
return model;
}
@Override
public IScannerConfig getScannerConfig() {
return persistentConfig;
}
@Override
public List<IScannerModule> getAllModules() {
reloadModules();
return allModules;
}
@Override
public IScannerConfig createScannerConfig() {
return new ScannerConfig();
}
@Override
public void setScannerConfig(IScannerConfig config) {
persistentConfig = config;
}
@Override
public synchronized void startScanner(IScannerConfig config) {
if(currentScan != null && currentScan.getScanStatus() != IScanInstance.SCAN_COMPLETED && currentScan.getScanStatus() != IScanInstance.SCAN_CANCELLED) {
throw new IllegalStateException("Scanner is already running. Verify scanner is not running with getScannerStatus() before trying to start.");
}
if(config.getBaseURI() == null)
throw new IllegalArgumentException("Cannot start scan because no baseURI was specified");
IHttpRequestEngineConfig requestEngineConfig = requestEngineFactory.createConfig();
- CookieStore cookieStore = requestEngineConfig.getCookieStore();
- for (Cookie c: config.getCookieList()) {
- cookieStore.addCookie(c);
+ if (config.getCookieList() != null) {
+ CookieStore cookieStore = requestEngineConfig.getCookieStore();
+ for (Cookie c: config.getCookieList()) {
+ cookieStore.addCookie(c);
+ }
}
final IHttpRequestEngine requestEngine = requestEngineFactory.createRequestEngine(requestEngineConfig);
reloadModules();
resetModuleTimestamps();
currentWorkspace.lock();
currentScan = currentWorkspace.getScanAlertRepository().createNewScanInstance();
scannerTask = new ScannerTask(currentScan, this, config, requestEngine,
currentWorkspace, contentAnalyzerFactory.createContentAnalyzer(currentScan),
responseProcessingModules, basicModules);
scannerThread = new Thread(scannerTask);
currentWorkspace.getScanAlertRepository().setActiveScanInstance(currentScan);
currentScan.updateScanStatus(IScanInstance.SCAN_STARTING);
scannerThread.start();
}
@Override
public void stopScanner() {
if(scannerTask != null)
scannerTask.stop();
}
@Override
public void runDomTests() {
moduleRegistry.runDomTests();
}
protected void setCrawlerFactory(IWebCrawlerFactory crawlerFactory) {
this.crawlerFactory = crawlerFactory;
}
protected void unsetCrawlerFactory(IWebCrawlerFactory crawlerFactory) {
this.crawlerFactory = null;
}
protected void setRequestEngineFactory(IHttpRequestEngineFactory factory) {
this.requestEngineFactory = factory;
}
protected void unsetRequestEngineFactory(IHttpRequestEngineFactory factory) {
this.requestEngineFactory = null;
}
protected void setModuleRegistry(IScannerModuleRegistry registry) {
this.moduleRegistry = registry;
}
protected void unsetModuleRegistry(IScannerModuleRegistry registry) {
this.moduleRegistry = null;
}
protected void setModel(IModel model) {
this.model = model;
}
protected void unsetModel(IModel model) {
this.model = null;
}
protected void setContentAnalyzerFactory(IContentAnalyzerFactory factory) {
this.contentAnalyzerFactory = factory;
}
protected void unsetContentAnalyzerFactory(IContentAnalyzerFactory factory) {
this.contentAnalyzerFactory = null;
}
}
| true | true | public synchronized void startScanner(IScannerConfig config) {
if(currentScan != null && currentScan.getScanStatus() != IScanInstance.SCAN_COMPLETED && currentScan.getScanStatus() != IScanInstance.SCAN_CANCELLED) {
throw new IllegalStateException("Scanner is already running. Verify scanner is not running with getScannerStatus() before trying to start.");
}
if(config.getBaseURI() == null)
throw new IllegalArgumentException("Cannot start scan because no baseURI was specified");
IHttpRequestEngineConfig requestEngineConfig = requestEngineFactory.createConfig();
CookieStore cookieStore = requestEngineConfig.getCookieStore();
for (Cookie c: config.getCookieList()) {
cookieStore.addCookie(c);
}
final IHttpRequestEngine requestEngine = requestEngineFactory.createRequestEngine(requestEngineConfig);
reloadModules();
resetModuleTimestamps();
currentWorkspace.lock();
currentScan = currentWorkspace.getScanAlertRepository().createNewScanInstance();
scannerTask = new ScannerTask(currentScan, this, config, requestEngine,
currentWorkspace, contentAnalyzerFactory.createContentAnalyzer(currentScan),
responseProcessingModules, basicModules);
scannerThread = new Thread(scannerTask);
currentWorkspace.getScanAlertRepository().setActiveScanInstance(currentScan);
currentScan.updateScanStatus(IScanInstance.SCAN_STARTING);
scannerThread.start();
}
| public synchronized void startScanner(IScannerConfig config) {
if(currentScan != null && currentScan.getScanStatus() != IScanInstance.SCAN_COMPLETED && currentScan.getScanStatus() != IScanInstance.SCAN_CANCELLED) {
throw new IllegalStateException("Scanner is already running. Verify scanner is not running with getScannerStatus() before trying to start.");
}
if(config.getBaseURI() == null)
throw new IllegalArgumentException("Cannot start scan because no baseURI was specified");
IHttpRequestEngineConfig requestEngineConfig = requestEngineFactory.createConfig();
if (config.getCookieList() != null) {
CookieStore cookieStore = requestEngineConfig.getCookieStore();
for (Cookie c: config.getCookieList()) {
cookieStore.addCookie(c);
}
}
final IHttpRequestEngine requestEngine = requestEngineFactory.createRequestEngine(requestEngineConfig);
reloadModules();
resetModuleTimestamps();
currentWorkspace.lock();
currentScan = currentWorkspace.getScanAlertRepository().createNewScanInstance();
scannerTask = new ScannerTask(currentScan, this, config, requestEngine,
currentWorkspace, contentAnalyzerFactory.createContentAnalyzer(currentScan),
responseProcessingModules, basicModules);
scannerThread = new Thread(scannerTask);
currentWorkspace.getScanAlertRepository().setActiveScanInstance(currentScan);
currentScan.updateScanStatus(IScanInstance.SCAN_STARTING);
scannerThread.start();
}
|
diff --git a/appjar/src/main/java/com/google/gerrit/server/patch/PatchDetailServiceImpl.java b/appjar/src/main/java/com/google/gerrit/server/patch/PatchDetailServiceImpl.java
index 829335253..7a9b4a26e 100644
--- a/appjar/src/main/java/com/google/gerrit/server/patch/PatchDetailServiceImpl.java
+++ b/appjar/src/main/java/com/google/gerrit/server/patch/PatchDetailServiceImpl.java
@@ -1,294 +1,294 @@
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.patch;
import com.google.gerrit.client.data.ApprovalType;
import com.google.gerrit.client.data.SideBySidePatchDetail;
import com.google.gerrit.client.data.UnifiedPatchDetail;
import com.google.gerrit.client.patches.PatchDetailService;
import com.google.gerrit.client.reviewdb.Account;
import com.google.gerrit.client.reviewdb.ApprovalCategory;
import com.google.gerrit.client.reviewdb.ApprovalCategoryValue;
import com.google.gerrit.client.reviewdb.Change;
import com.google.gerrit.client.reviewdb.ChangeApproval;
import com.google.gerrit.client.reviewdb.ChangeMessage;
import com.google.gerrit.client.reviewdb.Patch;
import com.google.gerrit.client.reviewdb.PatchLineComment;
import com.google.gerrit.client.reviewdb.PatchSet;
import com.google.gerrit.client.reviewdb.PatchSetInfo;
import com.google.gerrit.client.reviewdb.ReviewDb;
import com.google.gerrit.client.rpc.BaseServiceImplementation;
import com.google.gerrit.client.rpc.Common;
import com.google.gerrit.client.rpc.NoSuchEntityException;
import com.google.gerrit.git.RepositoryCache;
import com.google.gerrit.server.ChangeMail;
import com.google.gerrit.server.ChangeUtil;
import com.google.gerrit.server.GerritJsonServlet;
import com.google.gerrit.server.GerritServer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwtjsonrpc.client.VoidResult;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.OrmRunnable;
import com.google.gwtorm.client.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.mail.MessagingException;
public class PatchDetailServiceImpl extends BaseServiceImplementation implements
PatchDetailService {
private final Logger log = LoggerFactory.getLogger(getClass());
private final GerritServer server;
public PatchDetailServiceImpl(final GerritServer gs) {
server = gs;
}
public void sideBySidePatchDetail(final Patch.Key key,
final List<PatchSet.Id> versions,
final AsyncCallback<SideBySidePatchDetail> callback) {
final RepositoryCache rc = server.getRepositoryCache();
if (rc == null) {
callback.onFailure(new Exception("No Repository Cache configured"));
return;
}
run(callback, new SideBySidePatchDetailAction(rc, key, versions));
}
public void unifiedPatchDetail(final Patch.Key key,
final AsyncCallback<UnifiedPatchDetail> callback) {
run(callback, new UnifiedPatchDetailAction(key));
}
public void myDrafts(final Patch.Key key,
final AsyncCallback<List<PatchLineComment>> callback) {
run(callback, new Action<List<PatchLineComment>>() {
public List<PatchLineComment> run(ReviewDb db) throws OrmException {
return db.patchComments().draft(key, Common.getAccountId()).toList();
}
});
}
public void saveDraft(final PatchLineComment comment,
final AsyncCallback<PatchLineComment> callback) {
run(callback, new Action<PatchLineComment>() {
public PatchLineComment run(ReviewDb db) throws OrmException, Failure {
if (comment.getStatus() != PatchLineComment.Status.DRAFT) {
throw new Failure(new IllegalStateException("Comment published"));
}
final Patch patch = db.patches().get(comment.getKey().getParentKey());
final Change change;
if (patch == null) {
throw new Failure(new NoSuchEntityException());
}
change = db.changes().get(patch.getKey().getParentKey().getParentKey());
assertCanRead(change);
final Account.Id me = Common.getAccountId();
if (comment.getKey().get() == null) {
final PatchLineComment nc =
new PatchLineComment(new PatchLineComment.Key(patch.getKey(),
ChangeUtil.messageUUID(db)), comment.getLine(), me);
nc.setSide(comment.getSide());
nc.setMessage(comment.getMessage());
db.patchComments().insert(Collections.singleton(nc));
return nc;
} else {
if (!me.equals(comment.getAuthor())) {
throw new Failure(new NoSuchEntityException());
}
comment.updated();
db.patchComments().update(Collections.singleton(comment));
return comment;
}
}
});
}
public void deleteDraft(final PatchLineComment.Key commentKey,
final AsyncCallback<VoidResult> callback) {
run(callback, new Action<VoidResult>() {
public VoidResult run(ReviewDb db) throws OrmException, Failure {
final PatchLineComment comment = db.patchComments().get(commentKey);
if (comment == null) {
throw new Failure(new NoSuchEntityException());
}
if (!Common.getAccountId().equals(comment.getAuthor())) {
throw new Failure(new NoSuchEntityException());
}
if (comment.getStatus() != PatchLineComment.Status.DRAFT) {
throw new Failure(new IllegalStateException("Comment published"));
}
db.patchComments().delete(Collections.singleton(comment));
return VoidResult.INSTANCE;
}
});
}
public void publishComments(final PatchSet.Id psid, final String message,
final Set<ApprovalCategoryValue.Id> approvals,
final AsyncCallback<VoidResult> callback) {
run(callback, new Action<VoidResult>() {
public VoidResult run(ReviewDb db) throws OrmException, Failure {
final PublishResult r;
r = db.run(new OrmRunnable<PublishResult, ReviewDb>() {
public PublishResult run(ReviewDb db, Transaction txn, boolean retry)
throws OrmException {
return doPublishComments(psid, message, approvals, db, txn);
}
});
try {
final ChangeMail cm = new ChangeMail(server, r.change);
cm.setFrom(Common.getAccountId());
cm.setPatchSet(r.patchSet, r.info);
cm.setChangeMessage(r.message);
cm.setPatchLineComments(r.comments);
cm.setReviewDb(db);
cm.setHttpServletRequest(GerritJsonServlet.getCurrentCall()
.getHttpServletRequest());
cm.sendComment();
} catch (MessagingException e) {
log.error("Cannot send comments by email for patch set " + psid, e);
throw new Failure(e);
}
return VoidResult.INSTANCE;
}
});
}
private static class PublishResult {
Change change;
PatchSet patchSet;
PatchSetInfo info;
ChangeMessage message;
List<PatchLineComment> comments;
}
private PublishResult doPublishComments(final PatchSet.Id psid,
final String messageText, final Set<ApprovalCategoryValue.Id> approvals,
final ReviewDb db, final Transaction txn) throws OrmException {
final PublishResult r = new PublishResult();
final Account.Id me = Common.getAccountId();
r.change = db.changes().get(psid.getParentKey());
r.patchSet = db.patchSets().get(psid);
r.info = db.patchSetInfo().get(psid);
if (r.change == null || r.patchSet == null || r.info == null) {
throw new OrmException(new NoSuchEntityException());
}
r.comments = db.patchComments().draft(psid, me).toList();
final Set<Patch.Key> patchKeys = new HashSet<Patch.Key>();
for (final PatchLineComment c : r.comments) {
patchKeys.add(c.getKey().getParentKey());
}
final Map<Patch.Key, Patch> patches =
db.patches().toMap(db.patches().get(patchKeys));
for (final PatchLineComment c : r.comments) {
final Patch p = patches.get(c.getKey().getParentKey());
if (p != null) {
p.setCommentCount(p.getCommentCount() + 1);
}
c.setStatus(PatchLineComment.Status.PUBLISHED);
c.updated();
}
db.patches().update(patches.values(), txn);
db.patchComments().update(r.comments, txn);
final StringBuilder msgbuf = new StringBuilder();
final Map<ApprovalCategory.Id, ApprovalCategoryValue.Id> values =
new HashMap<ApprovalCategory.Id, ApprovalCategoryValue.Id>();
for (final ApprovalCategoryValue.Id v : approvals) {
values.put(v.getParentKey(), v);
}
final boolean open = r.change.getStatus().isOpen();
final Map<ApprovalCategory.Id, ChangeApproval> have =
new HashMap<ApprovalCategory.Id, ChangeApproval>();
for (final ChangeApproval a : db.changeApprovals().byChangeUser(
r.change.getId(), me)) {
have.put(a.getCategoryId(), a);
}
for (final ApprovalType at : Common.getGerritConfig().getApprovalTypes()) {
final ApprovalCategoryValue.Id v = values.get(at.getCategory().getId());
if (v == null) {
continue;
}
final ApprovalCategoryValue val = at.getValue(v.get());
if (val == null) {
continue;
}
ChangeApproval mycatpp = have.remove(v.getParentKey());
if (mycatpp == null) {
if (msgbuf.length() > 0) {
msgbuf.append("; ");
}
msgbuf.append(val.getName());
if (open) {
mycatpp =
new ChangeApproval(new ChangeApproval.Key(r.change.getId(), me, v
.getParentKey()), v.get());
db.changeApprovals().insert(Collections.singleton(mycatpp), txn);
}
} else if (mycatpp.getValue() != v.get()) {
if (msgbuf.length() > 0) {
msgbuf.append("; ");
}
msgbuf.append(val.getName());
if (open) {
mycatpp.setValue(v.get());
mycatpp.setGranted();
db.changeApprovals().update(Collections.singleton(mycatpp), txn);
}
}
}
if (open) {
db.changeApprovals().delete(have.values(), txn);
}
if (msgbuf.length() > 0) {
msgbuf.insert(0, "Patch Set " + psid.get() + ": ");
- msgbuf.append("\n");
+ msgbuf.append("\n\n");
}
if (messageText != null) {
msgbuf.append(messageText);
}
if (msgbuf.length() > 0) {
r.message =
new ChangeMessage(new ChangeMessage.Key(r.change.getId(), ChangeUtil
.messageUUID(db)), me);
r.message.setMessage(msgbuf.toString());
db.changeMessages().insert(Collections.singleton(r.message), txn);
}
ChangeUtil.updated(r.change);
db.changes().update(Collections.singleton(r.change), txn);
return r;
}
}
| true | true | private PublishResult doPublishComments(final PatchSet.Id psid,
final String messageText, final Set<ApprovalCategoryValue.Id> approvals,
final ReviewDb db, final Transaction txn) throws OrmException {
final PublishResult r = new PublishResult();
final Account.Id me = Common.getAccountId();
r.change = db.changes().get(psid.getParentKey());
r.patchSet = db.patchSets().get(psid);
r.info = db.patchSetInfo().get(psid);
if (r.change == null || r.patchSet == null || r.info == null) {
throw new OrmException(new NoSuchEntityException());
}
r.comments = db.patchComments().draft(psid, me).toList();
final Set<Patch.Key> patchKeys = new HashSet<Patch.Key>();
for (final PatchLineComment c : r.comments) {
patchKeys.add(c.getKey().getParentKey());
}
final Map<Patch.Key, Patch> patches =
db.patches().toMap(db.patches().get(patchKeys));
for (final PatchLineComment c : r.comments) {
final Patch p = patches.get(c.getKey().getParentKey());
if (p != null) {
p.setCommentCount(p.getCommentCount() + 1);
}
c.setStatus(PatchLineComment.Status.PUBLISHED);
c.updated();
}
db.patches().update(patches.values(), txn);
db.patchComments().update(r.comments, txn);
final StringBuilder msgbuf = new StringBuilder();
final Map<ApprovalCategory.Id, ApprovalCategoryValue.Id> values =
new HashMap<ApprovalCategory.Id, ApprovalCategoryValue.Id>();
for (final ApprovalCategoryValue.Id v : approvals) {
values.put(v.getParentKey(), v);
}
final boolean open = r.change.getStatus().isOpen();
final Map<ApprovalCategory.Id, ChangeApproval> have =
new HashMap<ApprovalCategory.Id, ChangeApproval>();
for (final ChangeApproval a : db.changeApprovals().byChangeUser(
r.change.getId(), me)) {
have.put(a.getCategoryId(), a);
}
for (final ApprovalType at : Common.getGerritConfig().getApprovalTypes()) {
final ApprovalCategoryValue.Id v = values.get(at.getCategory().getId());
if (v == null) {
continue;
}
final ApprovalCategoryValue val = at.getValue(v.get());
if (val == null) {
continue;
}
ChangeApproval mycatpp = have.remove(v.getParentKey());
if (mycatpp == null) {
if (msgbuf.length() > 0) {
msgbuf.append("; ");
}
msgbuf.append(val.getName());
if (open) {
mycatpp =
new ChangeApproval(new ChangeApproval.Key(r.change.getId(), me, v
.getParentKey()), v.get());
db.changeApprovals().insert(Collections.singleton(mycatpp), txn);
}
} else if (mycatpp.getValue() != v.get()) {
if (msgbuf.length() > 0) {
msgbuf.append("; ");
}
msgbuf.append(val.getName());
if (open) {
mycatpp.setValue(v.get());
mycatpp.setGranted();
db.changeApprovals().update(Collections.singleton(mycatpp), txn);
}
}
}
if (open) {
db.changeApprovals().delete(have.values(), txn);
}
if (msgbuf.length() > 0) {
msgbuf.insert(0, "Patch Set " + psid.get() + ": ");
msgbuf.append("\n");
}
if (messageText != null) {
msgbuf.append(messageText);
}
if (msgbuf.length() > 0) {
r.message =
new ChangeMessage(new ChangeMessage.Key(r.change.getId(), ChangeUtil
.messageUUID(db)), me);
r.message.setMessage(msgbuf.toString());
db.changeMessages().insert(Collections.singleton(r.message), txn);
}
ChangeUtil.updated(r.change);
db.changes().update(Collections.singleton(r.change), txn);
return r;
}
| private PublishResult doPublishComments(final PatchSet.Id psid,
final String messageText, final Set<ApprovalCategoryValue.Id> approvals,
final ReviewDb db, final Transaction txn) throws OrmException {
final PublishResult r = new PublishResult();
final Account.Id me = Common.getAccountId();
r.change = db.changes().get(psid.getParentKey());
r.patchSet = db.patchSets().get(psid);
r.info = db.patchSetInfo().get(psid);
if (r.change == null || r.patchSet == null || r.info == null) {
throw new OrmException(new NoSuchEntityException());
}
r.comments = db.patchComments().draft(psid, me).toList();
final Set<Patch.Key> patchKeys = new HashSet<Patch.Key>();
for (final PatchLineComment c : r.comments) {
patchKeys.add(c.getKey().getParentKey());
}
final Map<Patch.Key, Patch> patches =
db.patches().toMap(db.patches().get(patchKeys));
for (final PatchLineComment c : r.comments) {
final Patch p = patches.get(c.getKey().getParentKey());
if (p != null) {
p.setCommentCount(p.getCommentCount() + 1);
}
c.setStatus(PatchLineComment.Status.PUBLISHED);
c.updated();
}
db.patches().update(patches.values(), txn);
db.patchComments().update(r.comments, txn);
final StringBuilder msgbuf = new StringBuilder();
final Map<ApprovalCategory.Id, ApprovalCategoryValue.Id> values =
new HashMap<ApprovalCategory.Id, ApprovalCategoryValue.Id>();
for (final ApprovalCategoryValue.Id v : approvals) {
values.put(v.getParentKey(), v);
}
final boolean open = r.change.getStatus().isOpen();
final Map<ApprovalCategory.Id, ChangeApproval> have =
new HashMap<ApprovalCategory.Id, ChangeApproval>();
for (final ChangeApproval a : db.changeApprovals().byChangeUser(
r.change.getId(), me)) {
have.put(a.getCategoryId(), a);
}
for (final ApprovalType at : Common.getGerritConfig().getApprovalTypes()) {
final ApprovalCategoryValue.Id v = values.get(at.getCategory().getId());
if (v == null) {
continue;
}
final ApprovalCategoryValue val = at.getValue(v.get());
if (val == null) {
continue;
}
ChangeApproval mycatpp = have.remove(v.getParentKey());
if (mycatpp == null) {
if (msgbuf.length() > 0) {
msgbuf.append("; ");
}
msgbuf.append(val.getName());
if (open) {
mycatpp =
new ChangeApproval(new ChangeApproval.Key(r.change.getId(), me, v
.getParentKey()), v.get());
db.changeApprovals().insert(Collections.singleton(mycatpp), txn);
}
} else if (mycatpp.getValue() != v.get()) {
if (msgbuf.length() > 0) {
msgbuf.append("; ");
}
msgbuf.append(val.getName());
if (open) {
mycatpp.setValue(v.get());
mycatpp.setGranted();
db.changeApprovals().update(Collections.singleton(mycatpp), txn);
}
}
}
if (open) {
db.changeApprovals().delete(have.values(), txn);
}
if (msgbuf.length() > 0) {
msgbuf.insert(0, "Patch Set " + psid.get() + ": ");
msgbuf.append("\n\n");
}
if (messageText != null) {
msgbuf.append(messageText);
}
if (msgbuf.length() > 0) {
r.message =
new ChangeMessage(new ChangeMessage.Key(r.change.getId(), ChangeUtil
.messageUUID(db)), me);
r.message.setMessage(msgbuf.toString());
db.changeMessages().insert(Collections.singleton(r.message), txn);
}
ChangeUtil.updated(r.change);
db.changes().update(Collections.singleton(r.change), txn);
return r;
}
|
diff --git a/src/com/android/exchange/SyncManager.java b/src/com/android/exchange/SyncManager.java
index 17cfdaf..9a02aeb 100644
--- a/src/com/android/exchange/SyncManager.java
+++ b/src/com/android/exchange/SyncManager.java
@@ -1,1959 +1,1960 @@
/*
* Copyright (C) 2008-2009 Marc Blank
* Licensed to The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.exchange;
import com.android.email.AccountBackupRestore;
import com.android.email.Email;
import com.android.email.SecurityPolicy;
import com.android.email.mail.MessagingException;
import com.android.email.mail.store.TrustManagerFactory;
import com.android.email.provider.EmailContent;
import com.android.email.provider.EmailContent.Account;
import com.android.email.provider.EmailContent.Attachment;
import com.android.email.provider.EmailContent.HostAuth;
import com.android.email.provider.EmailContent.HostAuthColumns;
import com.android.email.provider.EmailContent.Mailbox;
import com.android.email.provider.EmailContent.MailboxColumns;
import com.android.email.provider.EmailContent.Message;
import com.android.email.provider.EmailContent.SyncColumns;
import com.android.email.service.IEmailService;
import com.android.email.service.IEmailServiceCallback;
import com.android.exchange.utility.FileLogger;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerPNames;
import org.apache.http.conn.params.ConnPerRoute;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import android.accounts.AccountManager;
import android.accounts.OnAccountsUpdateListener;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SyncStatusObserver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.os.PowerManager.WakeLock;
import android.provider.ContactsContract;
import android.util.Log;
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.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
* The SyncManager handles all aspects of starting, maintaining, and stopping the various sync
* adapters used by Exchange. However, it is capable of handing any kind of email sync, and it
* would be appropriate to use for IMAP push, when that functionality is added to the Email
* application.
*
* The Email application communicates with EAS sync adapters via SyncManager's binder interface,
* which exposes UI-related functionality to the application (see the definitions below)
*
* SyncManager uses ContentObservers to detect changes to accounts, mailboxes, and messages in
* order to maintain proper 2-way syncing of data. (More documentation to follow)
*
*/
public class SyncManager extends Service implements Runnable {
private static final String TAG = "EAS SyncManager";
// The SyncManager's mailbox "id"
private static final int SYNC_MANAGER_ID = -1;
private static final int SECONDS = 1000;
private static final int MINUTES = 60*SECONDS;
private static final int ONE_DAY_MINUTES = 1440;
private static final int SYNC_MANAGER_HEARTBEAT_TIME = 15*MINUTES;
private static final int CONNECTIVITY_WAIT_TIME = 10*MINUTES;
// Sync hold constants for services with transient errors
private static final int HOLD_DELAY_MAXIMUM = 4*MINUTES;
// Reason codes when SyncManager.kick is called (mainly for debugging)
// UI has changed data, requiring an upsync of changes
public static final int SYNC_UPSYNC = 0;
// A scheduled sync (when not using push)
public static final int SYNC_SCHEDULED = 1;
// Mailbox was marked push
public static final int SYNC_PUSH = 2;
// A ping (EAS push signal) was received
public static final int SYNC_PING = 3;
// startSync was requested of SyncManager
public static final int SYNC_SERVICE_START_SYNC = 4;
// A part request (attachment load, for now) was sent to SyncManager
public static final int SYNC_SERVICE_PART_REQUEST = 5;
// Misc.
public static final int SYNC_KICK = 6;
private static final String WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX =
MailboxColumns.ACCOUNT_KEY + "=? and " + MailboxColumns.TYPE + "!=" +
Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + " and " + MailboxColumns.SYNC_INTERVAL +
" IN (" + Mailbox.CHECK_INTERVAL_PING + ',' + Mailbox.CHECK_INTERVAL_PUSH + ')';
protected static final String WHERE_IN_ACCOUNT_AND_PUSHABLE =
MailboxColumns.ACCOUNT_KEY + "=? and type in (" + Mailbox.TYPE_INBOX + ','
+ Mailbox.TYPE_EAS_ACCOUNT_MAILBOX + ',' + Mailbox.TYPE_CONTACTS + ')';
private static final String WHERE_MAILBOX_KEY = Message.MAILBOX_KEY + "=?";
private static final String WHERE_PROTOCOL_EAS = HostAuthColumns.PROTOCOL + "=\"" +
AbstractSyncService.EAS_PROTOCOL + "\"";
private static final String WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN =
"(" + MailboxColumns.TYPE + '=' + Mailbox.TYPE_OUTBOX
+ " or " + MailboxColumns.SYNC_INTERVAL + "!=" + Mailbox.CHECK_INTERVAL_NEVER + ')'
+ " and " + MailboxColumns.ACCOUNT_KEY + " in (";
private static final String ACCOUNT_KEY_IN = MailboxColumns.ACCOUNT_KEY + " in (";
// Offsets into the syncStatus data for EAS that indicate type, exit status, and change count
// The format is S<type_char>:<exit_char>:<change_count>
public static final int STATUS_TYPE_CHAR = 1;
public static final int STATUS_EXIT_CHAR = 3;
public static final int STATUS_CHANGE_COUNT_OFFSET = 5;
// Ready for ping
public static final int PING_STATUS_OK = 0;
// Service already running (can't ping)
public static final int PING_STATUS_RUNNING = 1;
// Service waiting after I/O error (can't ping)
public static final int PING_STATUS_WAITING = 2;
// Service had a fatal error; can't run
public static final int PING_STATUS_UNABLE = 3;
// We synchronize on this for all actions affecting the service and error maps
private static Object sSyncToken = new Object();
// All threads can use this lock to wait for connectivity
public static Object sConnectivityLock = new Object();
public static boolean sConnectivityHold = false;
// Keeps track of running services (by mailbox id)
private HashMap<Long, AbstractSyncService> mServiceMap =
new HashMap<Long, AbstractSyncService>();
// Keeps track of services whose last sync ended with an error (by mailbox id)
/*package*/ HashMap<Long, SyncError> mSyncErrorMap = new HashMap<Long, SyncError>();
// Keeps track of which services require a wake lock (by mailbox id)
private HashMap<Long, Boolean> mWakeLocks = new HashMap<Long, Boolean>();
// Keeps track of PendingIntents for mailbox alarms (by mailbox id)
private HashMap<Long, PendingIntent> mPendingIntents = new HashMap<Long, PendingIntent>();
// The actual WakeLock obtained by SyncManager
private WakeLock mWakeLock = null;
private static final AccountList EMPTY_ACCOUNT_LIST = new AccountList();
// Observers that we use to look for changed mail-related data
private Handler mHandler = new Handler();
private AccountObserver mAccountObserver;
private MailboxObserver mMailboxObserver;
private SyncedMessageObserver mSyncedMessageObserver;
private MessageObserver mMessageObserver;
private EasSyncStatusObserver mSyncStatusObserver;
private EasAccountsUpdatedListener mAccountsUpdatedListener;
/*package*/ ContentResolver mResolver;
// The singleton SyncManager object, with its thread and stop flag
protected static SyncManager INSTANCE;
private static Thread sServiceThread = null;
// Cached unique device id
private static String sDeviceId = null;
// ConnectionManager that all EAS threads can use
private static ClientConnectionManager sClientConnectionManager = null;
private boolean mStop = false;
// The reason for SyncManager's next wakeup call
private String mNextWaitReason;
// Whether we have an unsatisfied "kick" pending
private boolean mKicked = false;
// Receiver of connectivity broadcasts
private ConnectivityReceiver mConnectivityReceiver = null;
// The callback sent in from the UI using setCallback
private IEmailServiceCallback mCallback;
private RemoteCallbackList<IEmailServiceCallback> mCallbackList =
new RemoteCallbackList<IEmailServiceCallback>();
/**
* Proxy that can be used by various sync adapters to tie into SyncManager's callback system.
* Used this way: SyncManager.callback().callbackMethod(args...);
* The proxy wraps checking for existence of a SyncManager instance and an active callback.
* Failures of these callbacks can be safely ignored.
*/
static private final IEmailServiceCallback.Stub sCallbackProxy =
new IEmailServiceCallback.Stub() {
public void loadAttachmentStatus(long messageId, long attachmentId, int statusCode,
int progress) throws RemoteException {
IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback;
if (cb != null) {
cb.loadAttachmentStatus(messageId, attachmentId, statusCode, progress);
}
}
public void sendMessageStatus(long messageId, String subject, int statusCode, int progress)
throws RemoteException {
IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback;
if (cb != null) {
cb.sendMessageStatus(messageId, subject, statusCode, progress);
}
}
public void syncMailboxListStatus(long accountId, int statusCode, int progress)
throws RemoteException {
IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback;
if (cb != null) {
cb.syncMailboxListStatus(accountId, statusCode, progress);
}
}
public void syncMailboxStatus(long mailboxId, int statusCode, int progress)
throws RemoteException {
IEmailServiceCallback cb = INSTANCE == null ? null: INSTANCE.mCallback;
if (cb != null) {
cb.syncMailboxStatus(mailboxId, statusCode, progress);
} else if (INSTANCE != null) {
INSTANCE.log("orphan syncMailboxStatus, id=" + mailboxId + " status=" + statusCode);
}
}
};
/**
* Create our EmailService implementation here.
*/
private final IEmailService.Stub mBinder = new IEmailService.Stub() {
public int validate(String protocol, String host, String userName, String password,
int port, boolean ssl, boolean trustCertificates) throws RemoteException {
try {
AbstractSyncService.validate(EasSyncService.class, host, userName, password, port,
ssl, trustCertificates, SyncManager.this);
return MessagingException.NO_ERROR;
} catch (MessagingException e) {
return e.getExceptionType();
}
}
public Bundle autoDiscover(String userName, String password) throws RemoteException {
return new EasSyncService().tryAutodiscover(userName, password);
}
public void startSync(long mailboxId) throws RemoteException {
checkSyncManagerServiceRunning();
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId);
if (m.mType == Mailbox.TYPE_OUTBOX) {
// We're using SERVER_ID to indicate an error condition (it has no other use for
// sent mail) Upon request to sync the Outbox, we clear this so that all messages
// are candidates for sending.
ContentValues cv = new ContentValues();
cv.put(SyncColumns.SERVER_ID, 0);
INSTANCE.getContentResolver().update(Message.CONTENT_URI,
cv, WHERE_MAILBOX_KEY, new String[] {Long.toString(mailboxId)});
// Clear the error state; the Outbox sync will be started from checkMailboxes
INSTANCE.mSyncErrorMap.remove(mailboxId);
kick("start outbox");
// Outbox can't be synced in EAS
return;
} else if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_TRASH) {
// Drafts & Trash can't be synced in EAS
return;
}
startManualSync(mailboxId, SyncManager.SYNC_SERVICE_START_SYNC, null);
}
public void stopSync(long mailboxId) throws RemoteException {
stopManualSync(mailboxId);
}
public void loadAttachment(long attachmentId, String destinationFile,
String contentUriString) throws RemoteException {
Attachment att = Attachment.restoreAttachmentWithId(SyncManager.this, attachmentId);
sendMessageRequest(new PartRequest(att, destinationFile, contentUriString));
}
public void updateFolderList(long accountId) throws RemoteException {
reloadFolderList(SyncManager.this, accountId, false);
}
public void hostChanged(long accountId) throws RemoteException {
if (INSTANCE != null) {
synchronized (sSyncToken) {
HashMap<Long, SyncError> syncErrorMap = INSTANCE.mSyncErrorMap;
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
// Go through the various error mailboxes
for (long mailboxId: syncErrorMap.keySet()) {
SyncError error = syncErrorMap.get(mailboxId);
// If it's a login failure, look a little harder
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId);
// If it's for the account whose host has changed, clear the error
// If the mailbox is no longer around, remove the entry in the map
if (m == null) {
deletedMailboxes.add(mailboxId);
} else if (m.mAccountKey == accountId) {
error.fatal = false;
error.holdEndTime = 0;
}
}
for (long mailboxId: deletedMailboxes) {
syncErrorMap.remove(mailboxId);
}
}
// Stop any running syncs
INSTANCE.stopAccountSyncs(accountId, true);
// Kick SyncManager
kick("host changed");
}
}
public void setLogging(int on) throws RemoteException {
Eas.setUserDebug(on);
}
public void sendMeetingResponse(long messageId, int response) throws RemoteException {
sendMessageRequest(new MeetingResponseRequest(messageId, response));
}
public void loadMore(long messageId) throws RemoteException {
}
// The following three methods are not implemented in this version
public boolean createFolder(long accountId, String name) throws RemoteException {
return false;
}
public boolean deleteFolder(long accountId, String name) throws RemoteException {
return false;
}
public boolean renameFolder(long accountId, String oldName, String newName)
throws RemoteException {
return false;
}
public void setCallback(IEmailServiceCallback cb) throws RemoteException {
if (mCallback != null) {
mCallbackList.unregister(mCallback);
}
mCallback = cb;
mCallbackList.register(cb);
}
};
static class AccountList extends ArrayList<Account> {
private static final long serialVersionUID = 1L;
public boolean contains(long id) {
for (Account account: this) {
if (account.mId == id) {
return true;
}
}
return false;
}
public Account getById(long id) {
for (Account account: this) {
if (account.mId == id) {
return account;
}
}
return null;
}
}
class AccountObserver extends ContentObserver {
// mAccounts keeps track of Accounts that we care about (EAS for now)
AccountList mAccounts = new AccountList();
String mSyncableEasMailboxSelector = null;
String mEasAccountSelector = null;
public AccountObserver(Handler handler) {
super(handler);
// At startup, we want to see what EAS accounts exist and cache them
Cursor c = getContentResolver().query(Account.CONTENT_URI, Account.CONTENT_PROJECTION,
null, null, null);
try {
collectEasAccounts(c, mAccounts);
} finally {
c.close();
}
// Create the account mailbox for any account that doesn't have one
Context context = getContext();
for (Account account: mAccounts) {
int cnt = Mailbox.count(context, Mailbox.CONTENT_URI, "accountKey=" + account.mId,
null);
if (cnt == 0) {
addAccountMailbox(account.mId);
}
}
}
/**
* Returns a String suitable for appending to a where clause that selects for all syncable
* mailboxes in all eas accounts
* @return a complex selection string that is not to be cached
*/
public String getSyncableEasMailboxWhere() {
if (mSyncableEasMailboxSelector == null) {
StringBuilder sb = new StringBuilder(WHERE_NOT_INTERVAL_NEVER_AND_ACCOUNT_KEY_IN);
boolean first = true;
for (Account account: mAccounts) {
if (!first) {
sb.append(',');
} else {
first = false;
}
sb.append(account.mId);
}
sb.append(')');
mSyncableEasMailboxSelector = sb.toString();
}
return mSyncableEasMailboxSelector;
}
/**
* Returns a String suitable for appending to a where clause that selects for all eas
* accounts.
* @return a String in the form "accountKey in (a, b, c...)" that is not to be cached
*/
public String getAccountKeyWhere() {
if (mEasAccountSelector == null) {
StringBuilder sb = new StringBuilder(ACCOUNT_KEY_IN);
boolean first = true;
for (Account account: mAccounts) {
if (!first) {
sb.append(',');
} else {
first = false;
}
sb.append(account.mId);
}
sb.append(')');
mEasAccountSelector = sb.toString();
}
return mEasAccountSelector;
}
private boolean onSecurityHold(Account account) {
return (account.mFlags & Account.FLAGS_SECURITY_HOLD) != 0;
}
@Override
public void onChange(boolean selfChange) {
maybeStartSyncManagerThread();
Context context = getContext();
// A change to the list requires us to scan for deletions (to stop running syncs)
// At startup, we want to see what accounts exist and cache them
AccountList currentAccounts = new AccountList();
Cursor c = getContentResolver().query(Account.CONTENT_URI, Account.CONTENT_PROJECTION,
null, null, null);
try {
collectEasAccounts(c, currentAccounts);
for (Account account : mAccounts) {
// Ignore accounts not fully created
if ((account.mFlags & Account.FLAGS_INCOMPLETE) != 0) {
log("Account observer noticed incomplete account; ignoring");
continue;
} else if (!currentAccounts.contains(account.mId)) {
// This is a deletion; shut down any account-related syncs
stopAccountSyncs(account.mId, true);
// Delete this from AccountManager...
android.accounts.Account acct =
new android.accounts.Account(account.mEmailAddress,
Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
AccountManager.get(SyncManager.this).removeAccount(acct, null, null);
mSyncableEasMailboxSelector = null;
mEasAccountSelector = null;
} else {
// An account has changed
Account updatedAccount = Account.restoreAccountWithId(context, account.mId);
if (account.mSyncInterval != updatedAccount.mSyncInterval ||
account.mSyncLookback != updatedAccount.mSyncLookback) {
// Set pushable boxes' sync interval to the sync interval of the Account
ContentValues cv = new ContentValues();
cv.put(MailboxColumns.SYNC_INTERVAL, updatedAccount.mSyncInterval);
getContentResolver().update(Mailbox.CONTENT_URI, cv,
WHERE_IN_ACCOUNT_AND_PUSHABLE,
new String[] {Long.toString(account.mId)});
// Stop all current syncs; the appropriate ones will restart
log("Account " + account.mDisplayName + " changed; stop syncs");
stopAccountSyncs(account.mId, true);
}
// See if this account is no longer on security hold
if (onSecurityHold(account) && !onSecurityHold(updatedAccount)) {
releaseSyncHolds(SyncManager.this,
AbstractSyncService.EXIT_SECURITY_FAILURE, account);
}
// Put current values into our cached account
account.mSyncInterval = updatedAccount.mSyncInterval;
account.mSyncLookback = updatedAccount.mSyncLookback;
account.mFlags = updatedAccount.mFlags;
}
}
// Look for new accounts
for (Account account: currentAccounts) {
if (!mAccounts.contains(account.mId)) {
// This is an addition; create our magic hidden mailbox...
log("Account observer found new account: " + account.mDisplayName);
addAccountMailbox(account.mId);
// Don't forget to cache the HostAuth
HostAuth ha =
HostAuth.restoreHostAuthWithId(getContext(), account.mHostAuthKeyRecv);
account.mHostAuthRecv = ha;
mAccounts.add(account);
mSyncableEasMailboxSelector = null;
mEasAccountSelector = null;
}
}
// Finally, make sure mAccounts is up to date
mAccounts = currentAccounts;
} finally {
c.close();
}
// See if there's anything to do...
kick("account changed");
}
private void collectEasAccounts(Cursor c, ArrayList<Account> accounts) {
Context context = getContext();
if (context == null) return;
while (c.moveToNext()) {
long hostAuthId = c.getLong(Account.CONTENT_HOST_AUTH_KEY_RECV_COLUMN);
if (hostAuthId > 0) {
HostAuth ha = HostAuth.restoreHostAuthWithId(context, hostAuthId);
if (ha != null && ha.mProtocol.equals("eas")) {
Account account = new Account().restore(c);
// Cache the HostAuth
account.mHostAuthRecv = ha;
accounts.add(account);
}
}
}
}
private void addAccountMailbox(long acctId) {
Account acct = Account.restoreAccountWithId(getContext(), acctId);
Mailbox main = new Mailbox();
main.mDisplayName = Eas.ACCOUNT_MAILBOX;
main.mServerId = Eas.ACCOUNT_MAILBOX + System.nanoTime();
main.mAccountKey = acct.mId;
main.mType = Mailbox.TYPE_EAS_ACCOUNT_MAILBOX;
main.mSyncInterval = Mailbox.CHECK_INTERVAL_PUSH;
main.mFlagVisible = false;
main.save(getContext());
INSTANCE.log("Initializing account: " + acct.mDisplayName);
}
}
class MailboxObserver extends ContentObserver {
public MailboxObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
// See if there's anything to do...
if (!selfChange) {
kick("mailbox changed");
}
}
}
class SyncedMessageObserver extends ContentObserver {
Intent syncAlarmIntent = new Intent(INSTANCE, EmailSyncAlarmReceiver.class);
PendingIntent syncAlarmPendingIntent =
PendingIntent.getBroadcast(INSTANCE, 0, syncAlarmIntent, 0);
AlarmManager alarmManager = (AlarmManager)INSTANCE.getSystemService(Context.ALARM_SERVICE);
public SyncedMessageObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
INSTANCE.log("SyncedMessage changed: (re)setting alarm for 10s");
alarmManager.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 10*SECONDS, syncAlarmPendingIntent);
}
}
class MessageObserver extends ContentObserver {
public MessageObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
// A rather blunt instrument here. But we don't have information about the URI that
// triggered this, though it must have been an insert
if (!selfChange) {
kick(null);
}
}
}
static public IEmailServiceCallback callback() {
return sCallbackProxy;
}
static public AccountList getAccountList() {
if (INSTANCE != null) {
return INSTANCE.mAccountObserver.mAccounts;
} else {
return EMPTY_ACCOUNT_LIST;
}
}
static public String getEasAccountSelector() {
if (INSTANCE != null) {
return INSTANCE.mAccountObserver.getAccountKeyWhere();
} else {
return null;
}
}
private Account getAccountById(long accountId) {
return mAccountObserver.mAccounts.getById(accountId);
}
public class SyncStatus {
static public final int NOT_RUNNING = 0;
static public final int DIED = 1;
static public final int SYNC = 2;
static public final int IDLE = 3;
}
class SyncError {
int reason;
boolean fatal = false;
long holdDelay = 15*SECONDS;
long holdEndTime = System.currentTimeMillis() + holdDelay;
SyncError(int _reason, boolean _fatal) {
reason = _reason;
fatal = _fatal;
}
/**
* We double the holdDelay from 15 seconds through 4 mins
*/
void escalate() {
if (holdDelay < HOLD_DELAY_MAXIMUM) {
holdDelay *= 2;
}
holdEndTime = System.currentTimeMillis() + holdDelay;
}
}
/**
* Release a specific type of hold (the reason) for the specified Account; if the account
* is null, mailboxes from all accounts with the specified hold will be released
* @param reason the reason for the SyncError (AbstractSyncService.EXIT_XXX)
* @param account an Account whose mailboxes should be released (or all if null)
*/
/*package*/ void releaseSyncHolds(Context context, int reason, Account account) {
releaseSyncHoldsImpl(context, reason, account);
kick("security release");
}
private void releaseSyncHoldsImpl(Context context, int reason, Account account) {
synchronized(sSyncToken) {
ArrayList<Long> releaseList = new ArrayList<Long>();
for (long mailboxId: mSyncErrorMap.keySet()) {
if (account != null) {
Mailbox m = Mailbox.restoreMailboxWithId(context, mailboxId);
if (m == null) {
releaseList.add(mailboxId);
} else if (m.mAccountKey != account.mId) {
continue;
}
}
SyncError error = mSyncErrorMap.get(mailboxId);
if (error.reason == reason) {
releaseList.add(mailboxId);
}
}
for (long mailboxId: releaseList) {
mSyncErrorMap.remove(mailboxId);
}
}
}
public class EasSyncStatusObserver implements SyncStatusObserver {
public void onStatusChanged(int which) {
// We ignore the argument (we can only get called in one case - when settings change)
// TODO Go through each account and see if sync is enabled and/or automatic for
// the Contacts authority, and set syncInterval accordingly. Then kick ourselves.
if (INSTANCE != null) {
checkPIMSyncSettings();
}
}
}
public class EasAccountsUpdatedListener implements OnAccountsUpdateListener {
public void onAccountsUpdated(android.accounts.Account[] accounts) {
reconcileAccountsWithAccountManager(INSTANCE, getAccountList(),
AccountManager.get(INSTANCE).getAccountsByType(
Email.EXCHANGE_ACCOUNT_MANAGER_TYPE));
}
}
static public void smLog(String str) {
if (INSTANCE != null) {
INSTANCE.log(str);
}
}
protected void log(String str) {
if (Eas.USER_LOG) {
Log.d(TAG, str);
if (Eas.FILE_LOG) {
FileLogger.log(TAG, str);
}
}
}
protected void alwaysLog(String str) {
if (!Eas.USER_LOG) {
Log.d(TAG, str);
} else {
log(str);
}
}
/**
* EAS requires a unique device id, so that sync is possible from a variety of different
* devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other
* device that doesn't provide one, we can create it as droid<n> where <n> is system time.
* This would work on a real device as well, but it would be better to use the "real" id if
* it's available
*/
static public String getDeviceId() throws IOException {
return getDeviceId(null);
}
static public synchronized String getDeviceId(Context context) throws IOException {
if (sDeviceId != null) {
return sDeviceId;
} else if (INSTANCE == null && context == null) {
throw new IOException("No context for getDeviceId");
} else if (context == null) {
context = INSTANCE;
}
// Otherwise, we'll read the id file or create one if it's not found
try {
File f = context.getFileStreamPath("deviceName");
BufferedReader rdr = null;
String id;
if (f.exists() && f.canRead()) {
rdr = new BufferedReader(new FileReader(f), 128);
id = rdr.readLine();
rdr.close();
return id;
} else if (f.createNewFile()) {
BufferedWriter w = new BufferedWriter(new FileWriter(f), 128);
id = "android" + System.currentTimeMillis();
w.write(id);
w.close();
sDeviceId = id;
return id;
}
} catch (IOException e) {
}
throw new IOException("Can't get device name");
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
/**
* Note that there are two ways the EAS SyncManager service can be created:
*
* 1) as a background service instantiated via startService (which happens on boot, when the
* first EAS account is created, etc), in which case the service thread is spun up, mailboxes
* sync, etc. and
* 2) to execute an RPC call from the UI, in which case the background service will already be
* running most of the time (unless we're creating a first EAS account)
*
* If the running background service detects that there are no EAS accounts (on boot, if none
* were created, or afterward if the last remaining EAS account is deleted), it will call
* stopSelf() to terminate operation.
*
* The goal is to ensure that the background service is running at all times when there is at
* least one EAS account in existence
*
* Because there are edge cases in which our process can crash (typically, this has been seen
* in UI crashes, ANR's, etc.), it's possible for the UI to start up again without the
* background service having been started. We explicitly try to start the service in Welcome
* (to handle the case of the app having been reloaded). We also start the service on any
* startSync call (if it isn't already running)
*/
@Override
public void onCreate() {
alwaysLog("!!! EAS SyncManager, onCreate");
if (INSTANCE == null) {
INSTANCE = this;
mResolver = getContentResolver();
mAccountObserver = new AccountObserver(mHandler);
mResolver.registerContentObserver(Account.CONTENT_URI, true, mAccountObserver);
mMailboxObserver = new MailboxObserver(mHandler);
mSyncedMessageObserver = new SyncedMessageObserver(mHandler);
mMessageObserver = new MessageObserver(mHandler);
mSyncStatusObserver = new EasSyncStatusObserver();
} else {
alwaysLog("!!! EAS SyncManager onCreated, but INSTANCE not null??");
}
if (sDeviceId == null) {
try {
getDeviceId(this);
} catch (IOException e) {
// We can't run in this situation
throw new RuntimeException();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
alwaysLog("!!! EAS SyncManager, onStartCommand");
// Restore accounts, if it has not happened already
AccountBackupRestore.restoreAccountsIfNeeded(this);
maybeStartSyncManagerThread();
if (sServiceThread == null) {
alwaysLog("!!! EAS SyncManager, stopping self");
stopSelf();
}
return Service.START_STICKY;
}
@Override
public void onDestroy() {
alwaysLog("!!! EAS SyncManager, onDestroy");
if (INSTANCE != null) {
INSTANCE = null;
mResolver.unregisterContentObserver(mAccountObserver);
mResolver = null;
mAccountObserver = null;
mMailboxObserver = null;
mSyncedMessageObserver = null;
mMessageObserver = null;
mSyncStatusObserver = null;
mAccountsUpdatedListener = null;
}
}
void maybeStartSyncManagerThread() {
// Start our thread...
// See if there are any EAS accounts; otherwise, just go away
if (EmailContent.count(this, HostAuth.CONTENT_URI, WHERE_PROTOCOL_EAS, null) > 0) {
if (sServiceThread == null || !sServiceThread.isAlive()) {
log(sServiceThread == null ? "Starting thread..." : "Restarting thread...");
sServiceThread = new Thread(this, "SyncManager");
sServiceThread.start();
}
}
}
static void checkSyncManagerServiceRunning() {
// Get the service thread running if it isn't
// This is a stopgap for cases in which SyncManager died (due to a crash somewhere in
// com.android.email) and hasn't been restarted
// See the comment for onCreate for details
if (INSTANCE == null) return;
if (sServiceThread == null) {
INSTANCE.alwaysLog("!!! checkSyncManagerServiceRunning; starting service...");
INSTANCE.startService(new Intent(INSTANCE, SyncManager.class));
}
}
static public ConnPerRoute sConnPerRoute = new ConnPerRoute() {
public int getMaxForRoute(HttpRoute route) {
return 8;
}
};
static public synchronized ClientConnectionManager getClientConnectionManager() {
if (sClientConnectionManager == null) {
// Create a registry for our three schemes; http and https will use built-in factories
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http",
PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// Create a new SSLSocketFactory for our "trusted ssl"
// Get the unsecure trust manager from the factory
X509TrustManager trustManager = TrustManagerFactory.get(null, false);
TrustManager[] trustManagers = new TrustManager[] {trustManager};
SSLContext sslcontext;
try {
sslcontext = SSLContext.getInstance("TLS");
try {
sslcontext.init(null, trustManagers, null);
} catch (KeyManagementException e) {
throw new AssertionError(e);
}
// Ok, now make our factory
SSLSocketFactory sf = new SSLSocketFactory(sslcontext.getSocketFactory());
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
// Register the httpts scheme with our factory
registry.register(new Scheme("httpts", sf, 443));
// And create a ccm with our registry
HttpParams params = new BasicHttpParams();
params.setIntParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 25);
params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, sConnPerRoute);
sClientConnectionManager = new ThreadSafeClientConnManager(params, registry);
} catch (NoSuchAlgorithmException e2) {
}
}
// Null is a valid return result if we get an exception
return sClientConnectionManager;
}
public static void stopAccountSyncs(long acctId) {
if (INSTANCE != null) {
INSTANCE.stopAccountSyncs(acctId, true);
}
}
private void stopAccountSyncs(long acctId, boolean includeAccountMailbox) {
synchronized (sSyncToken) {
List<Long> deletedBoxes = new ArrayList<Long>();
for (Long mid : INSTANCE.mServiceMap.keySet()) {
Mailbox box = Mailbox.restoreMailboxWithId(INSTANCE, mid);
if (box != null) {
if (box.mAccountKey == acctId) {
if (!includeAccountMailbox &&
box.mType == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
AbstractSyncService svc = INSTANCE.mServiceMap.get(mid);
if (svc != null) {
svc.stop();
}
continue;
}
AbstractSyncService svc = INSTANCE.mServiceMap.get(mid);
if (svc != null) {
svc.stop();
Thread t = svc.mThread;
if (t != null) {
t.interrupt();
}
}
deletedBoxes.add(mid);
}
}
}
for (Long mid : deletedBoxes) {
releaseMailbox(mid);
}
}
}
static public void reloadFolderList(Context context, long accountId, boolean force) {
if (INSTANCE == null) return;
Cursor c = context.getContentResolver().query(Mailbox.CONTENT_URI,
Mailbox.CONTENT_PROJECTION, MailboxColumns.ACCOUNT_KEY + "=? AND " +
MailboxColumns.TYPE + "=?",
new String[] {Long.toString(accountId),
Long.toString(Mailbox.TYPE_EAS_ACCOUNT_MAILBOX)}, null);
try {
if (c.moveToFirst()) {
synchronized(sSyncToken) {
Mailbox m = new Mailbox().restore(c);
Account acct = Account.restoreAccountWithId(context, accountId);
if (acct == null) {
return;
}
String syncKey = acct.mSyncKey;
// No need to reload the list if we don't have one
if (!force && (syncKey == null || syncKey.equals("0"))) {
return;
}
// Change all ping/push boxes to push/hold
ContentValues cv = new ContentValues();
cv.put(Mailbox.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH_HOLD);
context.getContentResolver().update(Mailbox.CONTENT_URI, cv,
WHERE_PUSH_OR_PING_NOT_ACCOUNT_MAILBOX,
new String[] {Long.toString(accountId)});
INSTANCE.log("Set push/ping boxes to push/hold");
long id = m.mId;
AbstractSyncService svc = INSTANCE.mServiceMap.get(id);
// Tell the service we're done
if (svc != null) {
synchronized (svc.getSynchronizer()) {
svc.stop();
}
// Interrupt the thread so that it can stop
Thread thread = svc.mThread;
thread.setName(thread.getName() + " (Stopped)");
thread.interrupt();
// Abandon the service
INSTANCE.releaseMailbox(id);
// And have it start naturally
kick("reload folder list");
}
}
}
} finally {
c.close();
}
}
/**
* Informs SyncManager that an account has a new folder list; as a result, any existing folder
* might have become invalid. Therefore, we act as if the account has been deleted, and then
* we reinitialize it.
*
* @param acctId
*/
static public void folderListReloaded(long acctId) {
if (INSTANCE != null) {
INSTANCE.stopAccountSyncs(acctId, false);
kick("reload folder list");
}
}
// private void logLocks(String str) {
// StringBuilder sb = new StringBuilder(str);
// boolean first = true;
// for (long id: mWakeLocks.keySet()) {
// if (!first) {
// sb.append(", ");
// } else {
// first = false;
// }
// sb.append(id);
// }
// log(sb.toString());
// }
private void acquireWakeLock(long id) {
synchronized (mWakeLocks) {
Boolean lock = mWakeLocks.get(id);
if (lock == null) {
if (id > 0) {
//log("+WakeLock requested for " + alarmOwner(id));
}
if (mWakeLock == null) {
PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MAIL_SERVICE");
mWakeLock.acquire();
log("+WAKE LOCK ACQUIRED");
}
mWakeLocks.put(id, true);
//logLocks("Post-acquire of WakeLock for " + alarmOwner(id) + ": ");
}
}
}
private void releaseWakeLock(long id) {
synchronized (mWakeLocks) {
Boolean lock = mWakeLocks.get(id);
if (lock != null) {
if (id > 0) {
//log("+WakeLock not needed for " + alarmOwner(id));
}
mWakeLocks.remove(id);
if (mWakeLocks.isEmpty()) {
if (mWakeLock != null) {
mWakeLock.release();
}
mWakeLock = null;
log("+WAKE LOCK RELEASED");
} else {
//logLocks("Post-release of WakeLock for " + alarmOwner(id) + ": ");
}
}
}
}
static public String alarmOwner(long id) {
if (id == SYNC_MANAGER_ID) {
return "SyncManager";
} else {
String name = Long.toString(id);
if (Eas.USER_LOG && INSTANCE != null) {
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id);
if (m != null) {
name = m.mDisplayName + '(' + m.mAccountKey + ')';
}
}
return "Mailbox " + name;
}
}
private void clearAlarm(long id) {
synchronized (mPendingIntents) {
PendingIntent pi = mPendingIntents.get(id);
if (pi != null) {
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pi);
log("+Alarm cleared for " + alarmOwner(id));
mPendingIntents.remove(id);
}
}
}
private void setAlarm(long id, long millis) {
synchronized (mPendingIntents) {
PendingIntent pi = mPendingIntents.get(id);
if (pi == null) {
Intent i = new Intent(this, MailboxAlarmReceiver.class);
i.putExtra("mailbox", id);
i.setData(Uri.parse("Box" + id));
pi = PendingIntent.getBroadcast(this, 0, i, 0);
mPendingIntents.put(id, pi);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millis, pi);
log("+Alarm set for " + alarmOwner(id) + ", " + millis/1000 + "s");
}
}
}
private void clearAlarms() {
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
synchronized (mPendingIntents) {
for (PendingIntent pi : mPendingIntents.values()) {
alarmManager.cancel(pi);
}
mPendingIntents.clear();
}
}
static public void runAwake(long id) {
if (INSTANCE == null) return;
INSTANCE.acquireWakeLock(id);
INSTANCE.clearAlarm(id);
}
static public void runAsleep(long id, long millis) {
if (INSTANCE == null) return;
INSTANCE.setAlarm(id, millis);
INSTANCE.releaseWakeLock(id);
}
static public void ping(Context context, long id) {
checkSyncManagerServiceRunning();
if (id < 0) {
kick("ping SyncManager");
} else if (INSTANCE == null) {
context.startService(new Intent(context, SyncManager.class));
} else {
AbstractSyncService service = INSTANCE.mServiceMap.get(id);
if (service != null) {
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, id);
if (m != null) {
// We ignore drafts completely (doesn't sync). Changes in Outbox are handled
// in the checkMailboxes loop, so we can ignore these pings.
if (m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
String[] args = new String[] {Long.toString(m.mId)};
ContentResolver resolver = INSTANCE.mResolver;
resolver.delete(Message.DELETED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
resolver.delete(Message.UPDATED_CONTENT_URI, WHERE_MAILBOX_KEY, args);
return;
}
service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
service.mMailbox = m;
service.ping();
}
}
}
}
/**
* See if we need to change the syncInterval for any of our PIM mailboxes based on changes
* to settings in the AccountManager (sync settings).
* This code is called 1) when SyncManager starts, and 2) when SyncManager is running and there
* are changes made (this is detected via a SyncStatusObserver)
*/
private void checkPIMSyncSettings() {
ContentValues cv = new ContentValues();
// For now, just Contacts
// First, walk through our list of accounts
List<Account> easAccounts = getAccountList();
for (Account easAccount: easAccounts) {
// Find the contacts mailbox
long contactsId =
Mailbox.findMailboxOfType(this, easAccount.mId, Mailbox.TYPE_CONTACTS);
// Presumably there is one, but if not, it's ok. Just move on...
if (contactsId != Mailbox.NO_MAILBOX) {
// Create an AccountManager style Account
android.accounts.Account acct =
new android.accounts.Account(easAccount.mEmailAddress,
Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
// Get the Contacts mailbox; this happens rarely so it's ok to get it all
Mailbox contacts = Mailbox.restoreMailboxWithId(this, contactsId);
int syncInterval = contacts.mSyncInterval;
// If we're syncable, look further...
if (ContentResolver.getIsSyncable(acct, ContactsContract.AUTHORITY) > 0) {
// If we're supposed to sync automatically (push), set to push if it's not
if (ContentResolver.getSyncAutomatically(acct, ContactsContract.AUTHORITY)) {
if (syncInterval == Mailbox.CHECK_INTERVAL_NEVER || syncInterval > 0) {
log("Sync setting: Contacts for " + acct.name + " changed to push");
cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
}
// If we're NOT supposed to push, and we're not set up that way, change it
} else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) {
log("Sync setting: Contacts for " + acct.name + " changed to manual");
cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER);
}
// If not, set it to never check
} else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) {
log("Sync setting: Contacts for " + acct.name + " changed to manual");
cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER);
}
// If we've made a change, update the Mailbox, and kick
if (cv.containsKey(MailboxColumns.SYNC_INTERVAL)) {
mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, contactsId),
cv,null, null);
kick("sync settings change");
}
}
}
}
/**
* Compare our account list (obtained from EmailProvider) with the account list owned by
* AccountManager. If there are any orphans (an account in one list without a corresponding
* account in the other list), delete the orphan, as these must remain in sync.
*
* Note that the duplication of account information is caused by the Email application's
* incomplete integration with AccountManager.
*/
/*package*/ void reconcileAccountsWithAccountManager(Context context,
List<Account> cachedEasAccounts, android.accounts.Account[] accountManagerAccounts) {
// First, look through our cached EAS Accounts (from EmailProvider) to make sure there's a
// corresponding AccountManager account
boolean accountsDeleted = false;
for (Account providerAccount: cachedEasAccounts) {
String providerAccountName = providerAccount.mEmailAddress;
boolean found = false;
for (android.accounts.Account accountManagerAccount: accountManagerAccounts) {
if (accountManagerAccount.name.equalsIgnoreCase(providerAccountName)) {
found = true;
break;
}
}
if (!found) {
if ((providerAccount.mFlags & Account.FLAGS_INCOMPLETE) != 0) {
log("Account reconciler noticed incomplete account; ignoring");
continue;
}
// This account has been deleted in the AccountManager!
alwaysLog("Account deleted in AccountManager; deleting from provider: " +
providerAccountName);
// TODO This will orphan downloaded attachments; need to handle this
mResolver.delete(ContentUris.withAppendedId(Account.CONTENT_URI,
providerAccount.mId), null, null);
accountsDeleted = true;
}
}
// Now, look through AccountManager accounts to make sure we have a corresponding cached EAS
// account from EmailProvider
for (android.accounts.Account accountManagerAccount: accountManagerAccounts) {
String accountManagerAccountName = accountManagerAccount.name;
boolean found = false;
for (Account cachedEasAccount: cachedEasAccounts) {
if (cachedEasAccount.mEmailAddress.equalsIgnoreCase(accountManagerAccountName)) {
found = true;
}
}
if (!found) {
// This account has been deleted from the EmailProvider database
alwaysLog("Account deleted from provider; deleting from AccountManager: " +
accountManagerAccountName);
// Delete the account
AccountManager.get(context).removeAccount(accountManagerAccount, null, null);
accountsDeleted = true;
}
}
// If we changed the list of accounts, refresh the backup & security settings
if (accountsDeleted) {
AccountBackupRestore.backupAccounts(getContext());
SecurityPolicy.getInstance(context).reducePolicies();
}
}
private void releaseConnectivityLock(String reason) {
// Clear i/o error holds for all accounts
releaseSyncHolds(this, AbstractSyncService.EXIT_IO_ERROR, null);
synchronized (sConnectivityLock) {
sConnectivityLock.notifyAll();
}
kick(reason);
}
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle b = intent.getExtras();
if (b != null) {
NetworkInfo a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_NETWORK_INFO);
String info = "Connectivity alert for " + a.getTypeName();
State state = a.getState();
if (state == State.CONNECTED) {
info += " CONNECTED";
log(info);
releaseConnectivityLock("connected");
} else if (state == State.DISCONNECTED) {
info += " DISCONNECTED";
a = (NetworkInfo)b.get(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if (a != null && a.getState() == State.CONNECTED) {
info += " (OTHER CONNECTED)";
releaseConnectivityLock("disconnect/other");
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm != null) {
NetworkInfo i = cm.getActiveNetworkInfo();
if (i == null || i.getState() != State.CONNECTED) {
log("CM says we're connected, but no active info?");
}
}
} else {
log(info);
kick("disconnected");
}
}
}
}
}
private void startService(AbstractSyncService service, Mailbox m) {
synchronized (sSyncToken) {
String mailboxName = m.mDisplayName;
String accountName = service.mAccount.mDisplayName;
Thread thread = new Thread(service, mailboxName + "(" + accountName + ")");
log("Starting thread for " + mailboxName + " in account " + accountName);
thread.start();
mServiceMap.put(m.mId, service);
runAwake(m.mId);
}
}
private void startService(Mailbox m, int reason, Request req) {
// Don't sync if there's no connectivity
if (sConnectivityHold) return;
synchronized (sSyncToken) {
Account acct = Account.restoreAccountWithId(this, m.mAccountKey);
if (acct != null) {
// Always make sure there's not a running instance of this service
AbstractSyncService service = mServiceMap.get(m.mId);
if (service == null) {
service = new EasSyncService(this, m);
if (!((EasSyncService)service).mIsValid) return;
service.mSyncReason = reason;
if (req != null) {
service.addRequest(req);
}
startService(service, m);
}
}
}
}
private void stopServices() {
synchronized (sSyncToken) {
ArrayList<Long> toStop = new ArrayList<Long>();
// Keep track of which services to stop
for (Long mailboxId : mServiceMap.keySet()) {
toStop.add(mailboxId);
}
// Shut down all of those running services
for (Long mailboxId : toStop) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc != null) {
log("Stopping " + svc.mAccount.mDisplayName + '/' + svc.mMailbox.mDisplayName);
svc.stop();
if (svc.mThread != null) {
svc.mThread.interrupt();
}
}
releaseWakeLock(mailboxId);
}
}
}
private void waitForConnectivity() {
int cnt = 0;
while (!mStop) {
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
//log("NetworkInfo: " + info.getTypeName() + ", " + info.getState().name());
return;
} else {
// If we're waiting for the long haul, shut down running service threads
if (++cnt > 1) {
stopServices();
}
// Wait until a network is connected, but let the device sleep
// We'll set an alarm just in case we don't get notified (bugs happen)
synchronized (sConnectivityLock) {
runAsleep(SYNC_MANAGER_ID, CONNECTIVITY_WAIT_TIME+5*SECONDS);
try {
log("Connectivity lock...");
sConnectivityHold = true;
sConnectivityLock.wait(CONNECTIVITY_WAIT_TIME);
log("Connectivity lock released...");
} catch (InterruptedException e) {
} finally {
sConnectivityHold = false;
}
runAwake(SYNC_MANAGER_ID);
}
}
}
}
public void run() {
mStop = false;
// If we're really debugging, turn on all logging
if (Eas.DEBUG) {
Eas.USER_LOG = true;
Eas.PARSER_LOG = true;
Eas.FILE_LOG = true;
}
// If we need to wait for the debugger, do so
if (Eas.WAIT_DEBUG) {
Debug.waitForDebugger();
}
// Set up our observers; we need them to know when to start/stop various syncs based
// on the insert/delete/update of mailboxes and accounts
// We also observe synced messages to trigger upsyncs at the appropriate time
mResolver.registerContentObserver(Mailbox.CONTENT_URI, false, mMailboxObserver);
mResolver.registerContentObserver(Message.SYNCED_CONTENT_URI, true, mSyncedMessageObserver);
mResolver.registerContentObserver(Message.CONTENT_URI, true, mMessageObserver);
// TODO SYNC_OBSERVER_TYPE_SETTINGS is hidden. Waiting for b/2337197
ContentResolver.addStatusChangeListener(ContentResolver.SYNC_OBSERVER_TYPE_SETTINGS,
mSyncStatusObserver);
mAccountsUpdatedListener = new EasAccountsUpdatedListener();
AccountManager.get(getApplication())
.addOnAccountsUpdatedListener(mAccountsUpdatedListener, mHandler, true);
mConnectivityReceiver = new ConnectivityReceiver();
registerReceiver(mConnectivityReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
// See if any settings have changed while we weren't running...
checkPIMSyncSettings();
try {
while (!mStop) {
runAwake(SYNC_MANAGER_ID);
waitForConnectivity();
mNextWaitReason = "Heartbeat";
long nextWait = checkMailboxes();
try {
synchronized (this) {
if (!mKicked) {
if (nextWait < 0) {
log("Negative wait? Setting to 1s");
nextWait = 1*SECONDS;
}
if (nextWait > 10*SECONDS) {
log("Next awake in " + nextWait / 1000 + "s: " + mNextWaitReason);
runAsleep(SYNC_MANAGER_ID, nextWait + (3*SECONDS));
}
wait(nextWait);
}
}
} catch (InterruptedException e) {
// Needs to be caught, but causes no problem
} finally {
synchronized (this) {
if (mKicked) {
//log("Wait deferred due to kick");
mKicked = false;
}
}
}
}
stopServices();
log("Shutdown requested");
} finally {
// Lots of cleanup here
// Stop our running syncs
stopServices();
// Stop receivers and content observers
if (mConnectivityReceiver != null) {
unregisterReceiver(mConnectivityReceiver);
}
if (INSTANCE != null) {
ContentResolver resolver = getContentResolver();
resolver.unregisterContentObserver(mAccountObserver);
resolver.unregisterContentObserver(mMailboxObserver);
resolver.unregisterContentObserver(mSyncedMessageObserver);
resolver.unregisterContentObserver(mMessageObserver);
}
// Don't leak the Intent associated with this listener
if (mAccountsUpdatedListener != null) {
AccountManager.get(this).removeOnAccountsUpdatedListener(mAccountsUpdatedListener);
mAccountsUpdatedListener = null;
}
// Clear pending alarms and associated Intents
clearAlarms();
// Release our wake lock, if we have one
synchronized (mWakeLocks) {
if (mWakeLock != null) {
mWakeLock.release();
mWakeLock = null;
}
}
log("Goodbye");
}
if (!mStop) {
// If this wasn't intentional, try to restart the service
throw new RuntimeException("EAS SyncManager crash; please restart me...");
}
}
private void releaseMailbox(long mailboxId) {
mServiceMap.remove(mailboxId);
releaseWakeLock(mailboxId);
}
private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncToken) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_MANAGER_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
+ if (mAccountObserver == null) return nextWait;
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableEasMailboxWhere(), null, null);
try {
while (c.moveToNext()) {
long mid = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncToken) {
service = mServiceMap.get(mid);
}
if (service == null) {
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mid);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// We handle a few types of mailboxes specially
int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (type == Mailbox.TYPE_CONTACTS) {
// See if "sync automatically" is set
Account account =
getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account != null) {
android.accounts.Account a =
new android.accounts.Account(account.mEmailAddress,
Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
if (!ContentResolver.getSyncAutomatically(a,
ContactsContract.AUTHORITY)) {
continue;
}
}
} else if (type == Mailbox.TYPE_TRASH) {
continue;
}
// Otherwise, we use the sync interval
long interval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (interval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(m, SYNC_PUSH, null);
} else if (type == Mailbox.TYPE_OUTBOX) {
int cnt = EmailContent.count(this, Message.CONTENT_URI,
EasOutboxService.MAILBOX_KEY_AND_NOT_SEND_FAILED,
new String[] {Long.toString(mid)});
if (cnt > 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(new EasOutboxService(this, m), m);
}
} else if (interval > 0 && interval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
if (sinceLastSync < 0) {
log("WHOA! lastSync in the future for mailbox: " + mid);
sinceLastSync = interval*MINUTES;
}
long toNextSync = interval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (Eas.USER_LOG) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (Eas.USER_LOG) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died but aren't in an error state
if (thread != null && !thread.isAlive() && !mSyncErrorMap.containsKey(mid)) {
releaseMailbox(mid);
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (service instanceof AbstractSyncService && timeToRequest <= 0) {
service.mRequestTime = 0;
service.ping();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
static public void serviceRequest(long mailboxId, int reason) {
serviceRequest(mailboxId, 5*SECONDS, reason);
}
static public void serviceRequest(long mailboxId, long ms, int reason) {
if (INSTANCE == null) return;
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId);
// Never allow manual start of Drafts or Outbox via serviceRequest
if (m == null || m.mType == Mailbox.TYPE_DRAFTS || m.mType == Mailbox.TYPE_OUTBOX) {
INSTANCE.log("Ignoring serviceRequest for drafts/outbox");
return;
}
try {
AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId);
if (service != null) {
service.mRequestTime = System.currentTimeMillis() + ms;
kick("service request");
} else {
startManualSync(mailboxId, reason, null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
static public void serviceRequestImmediate(long mailboxId) {
if (INSTANCE == null) return;
AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId);
if (service != null) {
service.mRequestTime = System.currentTimeMillis();
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId);
if (m != null) {
service.mAccount = Account.restoreAccountWithId(INSTANCE, m.mAccountKey);
service.mMailbox = m;
kick("service request immediate");
}
}
}
static public void sendMessageRequest(Request req) {
if (INSTANCE == null) return;
Message msg = Message.restoreMessageWithId(INSTANCE, req.mMessageId);
if (msg == null) {
return;
}
long mailboxId = msg.mMailboxKey;
AbstractSyncService service = INSTANCE.mServiceMap.get(mailboxId);
if (service == null) {
service = startManualSync(mailboxId, SYNC_SERVICE_PART_REQUEST, req);
kick("part request");
} else {
service.addRequest(req);
}
}
/**
* Determine whether a given Mailbox can be synced, i.e. is not already syncing and is not in
* an error state
*
* @param mailboxId
* @return whether or not the Mailbox is available for syncing (i.e. is a valid push target)
*/
static public int pingStatus(long mailboxId) {
// Already syncing...
if (INSTANCE.mServiceMap.get(mailboxId) != null) {
return PING_STATUS_RUNNING;
}
// No errors or a transient error, don't ping...
SyncError error = INSTANCE.mSyncErrorMap.get(mailboxId);
if (error != null) {
if (error.fatal) {
return PING_STATUS_UNABLE;
} else if (error.holdEndTime > 0) {
return PING_STATUS_WAITING;
}
}
return PING_STATUS_OK;
}
static public AbstractSyncService startManualSync(long mailboxId, int reason, Request req) {
if (INSTANCE == null || INSTANCE.mServiceMap == null) return null;
synchronized (sSyncToken) {
if (INSTANCE.mServiceMap.get(mailboxId) == null) {
INSTANCE.mSyncErrorMap.remove(mailboxId);
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId);
if (m != null) {
INSTANCE.log("Starting sync for " + m.mDisplayName);
INSTANCE.startService(m, reason, req);
}
}
}
return INSTANCE.mServiceMap.get(mailboxId);
}
// DO NOT CALL THIS IN A LOOP ON THE SERVICEMAP
static private void stopManualSync(long mailboxId) {
if (INSTANCE == null || INSTANCE.mServiceMap == null) return;
synchronized (sSyncToken) {
AbstractSyncService svc = INSTANCE.mServiceMap.get(mailboxId);
if (svc != null) {
INSTANCE.log("Stopping sync for " + svc.mMailboxName);
svc.stop();
svc.mThread.interrupt();
INSTANCE.releaseWakeLock(mailboxId);
}
}
}
/**
* Wake up SyncManager to check for mailboxes needing service
*/
static public void kick(String reason) {
if (INSTANCE != null) {
synchronized (INSTANCE) {
INSTANCE.mKicked = true;
INSTANCE.notify();
}
}
if (sConnectivityLock != null) {
synchronized (sConnectivityLock) {
sConnectivityLock.notify();
}
}
}
static public void accountUpdated(long acctId) {
if (INSTANCE == null) return;
synchronized (sSyncToken) {
for (AbstractSyncService svc : INSTANCE.mServiceMap.values()) {
if (svc.mAccount.mId == acctId) {
svc.mAccount = Account.restoreAccountWithId(INSTANCE, acctId);
}
}
}
}
/**
* Sent by services indicating that their thread is finished; action depends on the exitStatus
* of the service.
*
* @param svc the service that is finished
*/
static public void done(AbstractSyncService svc) {
if (INSTANCE == null) return;
synchronized(sSyncToken) {
long mailboxId = svc.mMailboxId;
HashMap<Long, SyncError> errorMap = INSTANCE.mSyncErrorMap;
SyncError syncError = errorMap.get(mailboxId);
INSTANCE.releaseMailbox(mailboxId);
int exitStatus = svc.mExitStatus;
switch (exitStatus) {
case AbstractSyncService.EXIT_DONE:
if (!svc.mRequests.isEmpty()) {
// TODO Handle this case
}
errorMap.remove(mailboxId);
break;
// I/O errors get retried at increasing intervals
case AbstractSyncService.EXIT_IO_ERROR:
Mailbox m = Mailbox.restoreMailboxWithId(INSTANCE, mailboxId);
if (m == null) return;
if (syncError != null) {
syncError.escalate();
INSTANCE.log(m.mDisplayName + " held for " + syncError.holdDelay + "ms");
} else {
errorMap.put(mailboxId, INSTANCE.new SyncError(exitStatus, false));
INSTANCE.log(m.mDisplayName + " added to syncErrorMap, hold for 15s");
}
break;
// These errors are not retried automatically
case AbstractSyncService.EXIT_SECURITY_FAILURE:
case AbstractSyncService.EXIT_LOGIN_FAILURE:
case AbstractSyncService.EXIT_EXCEPTION:
errorMap.put(mailboxId, INSTANCE.new SyncError(exitStatus, true));
break;
}
kick("sync completed");
}
}
/**
* Given the status string from a Mailbox, return the type code for the last sync
* @param status the syncStatus column of a Mailbox
* @return
*/
static public int getStatusType(String status) {
if (status == null) {
return -1;
} else {
return status.charAt(STATUS_TYPE_CHAR) - '0';
}
}
/**
* Given the status string from a Mailbox, return the change count for the last sync
* The change count is the number of adds + deletes + changes in the last sync
* @param status the syncStatus column of a Mailbox
* @return
*/
static public int getStatusChangeCount(String status) {
try {
String s = status.substring(STATUS_CHANGE_COUNT_OFFSET);
return Integer.parseInt(s);
} catch (RuntimeException e) {
return -1;
}
}
static public Context getContext() {
return INSTANCE;
}
}
| true | true | private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncToken) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_MANAGER_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableEasMailboxWhere(), null, null);
try {
while (c.moveToNext()) {
long mid = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncToken) {
service = mServiceMap.get(mid);
}
if (service == null) {
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mid);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// We handle a few types of mailboxes specially
int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (type == Mailbox.TYPE_CONTACTS) {
// See if "sync automatically" is set
Account account =
getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account != null) {
android.accounts.Account a =
new android.accounts.Account(account.mEmailAddress,
Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
if (!ContentResolver.getSyncAutomatically(a,
ContactsContract.AUTHORITY)) {
continue;
}
}
} else if (type == Mailbox.TYPE_TRASH) {
continue;
}
// Otherwise, we use the sync interval
long interval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (interval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(m, SYNC_PUSH, null);
} else if (type == Mailbox.TYPE_OUTBOX) {
int cnt = EmailContent.count(this, Message.CONTENT_URI,
EasOutboxService.MAILBOX_KEY_AND_NOT_SEND_FAILED,
new String[] {Long.toString(mid)});
if (cnt > 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(new EasOutboxService(this, m), m);
}
} else if (interval > 0 && interval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
if (sinceLastSync < 0) {
log("WHOA! lastSync in the future for mailbox: " + mid);
sinceLastSync = interval*MINUTES;
}
long toNextSync = interval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (Eas.USER_LOG) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (Eas.USER_LOG) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died but aren't in an error state
if (thread != null && !thread.isAlive() && !mSyncErrorMap.containsKey(mid)) {
releaseMailbox(mid);
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (service instanceof AbstractSyncService && timeToRequest <= 0) {
service.mRequestTime = 0;
service.ping();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
| private long checkMailboxes () {
// First, see if any running mailboxes have been deleted
ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
synchronized (sSyncToken) {
for (long mailboxId: mServiceMap.keySet()) {
Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
if (m == null) {
deletedMailboxes.add(mailboxId);
}
}
// If so, stop them or remove them from the map
for (Long mailboxId: deletedMailboxes) {
AbstractSyncService svc = mServiceMap.get(mailboxId);
if (svc == null || svc.mThread == null) {
releaseMailbox(mailboxId);
continue;
} else {
boolean alive = svc.mThread.isAlive();
log("Deleted mailbox: " + svc.mMailboxName);
if (alive) {
stopManualSync(mailboxId);
} else {
log("Removing from serviceMap");
releaseMailbox(mailboxId);
}
}
}
}
long nextWait = SYNC_MANAGER_HEARTBEAT_TIME;
long now = System.currentTimeMillis();
// Start up threads that need it; use a query which finds eas mailboxes where the
// the sync interval is not "never". This is the set of mailboxes that we control
if (mAccountObserver == null) return nextWait;
Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
mAccountObserver.getSyncableEasMailboxWhere(), null, null);
try {
while (c.moveToNext()) {
long mid = c.getLong(Mailbox.CONTENT_ID_COLUMN);
AbstractSyncService service = null;
synchronized (sSyncToken) {
service = mServiceMap.get(mid);
}
if (service == null) {
// Check whether we're in a hold (temporary or permanent)
SyncError syncError = mSyncErrorMap.get(mid);
if (syncError != null) {
// Nothing we can do about fatal errors
if (syncError.fatal) continue;
if (now < syncError.holdEndTime) {
// If release time is earlier than next wait time,
// move next wait time up to the release time
if (syncError.holdEndTime < now + nextWait) {
nextWait = syncError.holdEndTime - now;
mNextWaitReason = "Release hold";
}
continue;
} else {
// Keep the error around, but clear the end time
syncError.holdEndTime = 0;
}
}
// We handle a few types of mailboxes specially
int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
if (type == Mailbox.TYPE_CONTACTS) {
// See if "sync automatically" is set
Account account =
getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
if (account != null) {
android.accounts.Account a =
new android.accounts.Account(account.mEmailAddress,
Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
if (!ContentResolver.getSyncAutomatically(a,
ContactsContract.AUTHORITY)) {
continue;
}
}
} else if (type == Mailbox.TYPE_TRASH) {
continue;
}
// Otherwise, we use the sync interval
long interval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
if (interval == Mailbox.CHECK_INTERVAL_PUSH) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(m, SYNC_PUSH, null);
} else if (type == Mailbox.TYPE_OUTBOX) {
int cnt = EmailContent.count(this, Message.CONTENT_URI,
EasOutboxService.MAILBOX_KEY_AND_NOT_SEND_FAILED,
new String[] {Long.toString(mid)});
if (cnt > 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(new EasOutboxService(this, m), m);
}
} else if (interval > 0 && interval <= ONE_DAY_MINUTES) {
long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
long sinceLastSync = now - lastSync;
if (sinceLastSync < 0) {
log("WHOA! lastSync in the future for mailbox: " + mid);
sinceLastSync = interval*MINUTES;
}
long toNextSync = interval*MINUTES - sinceLastSync;
String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
if (toNextSync <= 0) {
Mailbox m = EmailContent.getContent(c, Mailbox.class);
startService(m, SYNC_SCHEDULED, null);
} else if (toNextSync < nextWait) {
nextWait = toNextSync;
if (Eas.USER_LOG) {
log("Next sync for " + name + " in " + nextWait/1000 + "s");
}
mNextWaitReason = "Scheduled sync, " + name;
} else if (Eas.USER_LOG) {
log("Next sync for " + name + " in " + toNextSync/1000 + "s");
}
}
} else {
Thread thread = service.mThread;
// Look for threads that have died but aren't in an error state
if (thread != null && !thread.isAlive() && !mSyncErrorMap.containsKey(mid)) {
releaseMailbox(mid);
// Restart this if necessary
if (nextWait > 3*SECONDS) {
nextWait = 3*SECONDS;
mNextWaitReason = "Clean up dead thread(s)";
}
} else {
long requestTime = service.mRequestTime;
if (requestTime > 0) {
long timeToRequest = requestTime - now;
if (service instanceof AbstractSyncService && timeToRequest <= 0) {
service.mRequestTime = 0;
service.ping();
} else if (requestTime > 0 && timeToRequest < nextWait) {
if (timeToRequest < 11*MINUTES) {
nextWait = timeToRequest < 250 ? 250 : timeToRequest;
mNextWaitReason = "Sync data change";
} else {
log("Illegal timeToRequest: " + timeToRequest);
}
}
}
}
}
}
} finally {
c.close();
}
return nextWait;
}
|
diff --git a/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java b/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java
index 970d11d..8b89364 100644
--- a/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java
+++ b/Dreamworld/src/de/blablubbabc/dreamworld/managers/ConfigManager.java
@@ -1,181 +1,181 @@
package de.blablubbabc.dreamworld.managers;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import de.blablubbabc.dreamworld.objects.SoftLocation;
public class ConfigManager {
private Plugin plugin;
private boolean wasConfigValid = false;
// world settings:
public String dreamWorldName;
public boolean noAnimalSpawning;
public boolean noMonsterSpawning;
public int dreamChance;
public int minDurationSeconds;
public int maxDurationSeconds;
// spawning:
public boolean spawnRandomly;
public List<SoftLocation> dreamSpawns;
public boolean applyInitialGamemode;
public boolean applyInitialHealth;
public boolean applyInitialHunger;
public boolean applyInitialPotionEffects;
public GameMode initialGamemode;
public double initialHealth;
public int initialHunger;
public List<PotionEffect> initialPotionEffects;
public boolean clearAndRestorePlayer;
public int purgeAfterMinutes;
public int ignoreIfRemainingTimeIsLowerThan;
// fake time
public boolean fakeTimeEnabled;
public int fakeTime;
public int fakeTimeRandomBounds;
public boolean fakeTimeFixed;
// fake weather
public boolean fakeRain;
// disabled:
public boolean hungerDisabled;
public boolean fallDamageDisabled;
public boolean entityDamageDisabled;
public boolean allDamageDisabled;
public boolean weatherDisabled;
public boolean itemDroppingDisabled;
public boolean itemPickupDisabled;
public boolean blockPlacingDisabled;
public boolean blockBreakingDisabled;
// allowed commands:
public List<String> allowedCommands;
public ConfigManager(Plugin plugin) {
this.plugin = plugin;
// default config:
+ plugin.saveDefaultConfig();
FileConfiguration config = plugin.getConfig();
config.options().copyDefaults(true);
- plugin.saveDefaultConfig();
// load values:
try {
ConfigurationSection dreamSection = config.getConfigurationSection("dream");
// world settings:
dreamWorldName = dreamSection.getString("world name");
noAnimalSpawning = dreamSection.getBoolean("no animal spawning");
noMonsterSpawning = dreamSection.getBoolean("no monster spawning");
dreamChance = dreamSection.getInt("chance");
minDurationSeconds = dreamSection.getInt("min duration in seconds");
maxDurationSeconds = dreamSection.getInt("max duration in seconds");
// spawning:
spawnRandomly = dreamSection.getBoolean("spawn randomly each time");
dreamSpawns = SoftLocation.getFromStringList(dreamSection.getStringList("random spawns"));
// some initial values:
applyInitialGamemode = dreamSection.getBoolean("gamemode.apply");
initialGamemode = GameMode.getByValue(dreamSection.getInt("gamemode.initial gamemode"));
applyInitialHealth = dreamSection.getBoolean("health.apply");
initialHealth = dreamSection.getInt("health.initial health");
applyInitialHunger = dreamSection.getBoolean("hunger.apply");
initialHunger = dreamSection.getInt("hunger.initial hunger");
applyInitialPotionEffects = dreamSection.getBoolean("potion effects.apply");
initialPotionEffects = new ArrayList<PotionEffect>();
ConfigurationSection potionsSection = dreamSection.getConfigurationSection("potion effects.initial potion effects");
if (potionsSection != null) {
for (String type : potionsSection.getKeys(false)) {
ConfigurationSection potionSection = potionsSection.getConfigurationSection(type);
if (potionSection == null) continue;
PotionEffectType potionType = PotionEffectType.getByName(type);
if (potionType == null) {
plugin.getLogger().warning("Invalid potion effect type '" + type + "'. Skipping this effect now. You can find a list of all possible PotionEffectTypes by googling 'bukkit PotionEffectType'.");
continue;
}
- initialPotionEffects.add(new PotionEffect(potionType, potionSection.getInt("duration"), potionSection.getInt("level", 1)));
+ initialPotionEffects.add(new PotionEffect(potionType, potionSection.getInt("duration"), potionSection.getInt("level")));
}
}
clearAndRestorePlayer = dreamSection.getBoolean("clear and restore player");
purgeAfterMinutes = dreamSection.getInt("purge saved dream data after x minutes");
ignoreIfRemainingTimeIsLowerThan = dreamSection.getInt("ignore if remaining seconds is lower than");
// fake time
ConfigurationSection fakeTimeSection = dreamSection.getConfigurationSection("fake client time");
fakeTimeEnabled = fakeTimeSection.getBoolean("enabled") ;
fakeTime = fakeTimeSection.getInt("time (in ticks)");
fakeTimeRandomBounds = fakeTimeSection.getInt("random bounds");
fakeTimeFixed = fakeTimeSection.getBoolean("fixed time");
// fake weather
fakeRain = dreamSection.getBoolean("fake client weather.raining");
// disabled:
ConfigurationSection disabledSection = dreamSection.getConfigurationSection("disabled");
hungerDisabled = disabledSection.getBoolean("hunger");
fallDamageDisabled = disabledSection.getBoolean("fall damage");
entityDamageDisabled = disabledSection.getBoolean("entity damage");
allDamageDisabled = disabledSection.getBoolean("all damage");
weatherDisabled = disabledSection.getBoolean("weather");
itemDroppingDisabled = disabledSection.getBoolean("item dropping");
itemPickupDisabled = disabledSection.getBoolean("item pickup");
blockPlacingDisabled = disabledSection.getBoolean("block placing");
blockBreakingDisabled = disabledSection.getBoolean("block breaking");
// allowed commands:
allowedCommands = dreamSection.getStringList("allowed commands");
wasConfigValid = true;
} catch (Exception e) {
e.printStackTrace();
wasConfigValid = false;
}
}
public boolean wasConfigValid() {
return wasConfigValid;
}
public void addSpawnLocation(Location location) {
dreamSpawns.add(new SoftLocation(location));
saveSpawns();
}
public void removeAllSpawnLocations() {
dreamSpawns.clear();
saveSpawns();
}
private void saveSpawns() {
plugin.getConfig().set("random spawns", SoftLocation.toStringList(dreamSpawns));
plugin.saveConfig();
}
}
| false | true | public ConfigManager(Plugin plugin) {
this.plugin = plugin;
// default config:
FileConfiguration config = plugin.getConfig();
config.options().copyDefaults(true);
plugin.saveDefaultConfig();
// load values:
try {
ConfigurationSection dreamSection = config.getConfigurationSection("dream");
// world settings:
dreamWorldName = dreamSection.getString("world name");
noAnimalSpawning = dreamSection.getBoolean("no animal spawning");
noMonsterSpawning = dreamSection.getBoolean("no monster spawning");
dreamChance = dreamSection.getInt("chance");
minDurationSeconds = dreamSection.getInt("min duration in seconds");
maxDurationSeconds = dreamSection.getInt("max duration in seconds");
// spawning:
spawnRandomly = dreamSection.getBoolean("spawn randomly each time");
dreamSpawns = SoftLocation.getFromStringList(dreamSection.getStringList("random spawns"));
// some initial values:
applyInitialGamemode = dreamSection.getBoolean("gamemode.apply");
initialGamemode = GameMode.getByValue(dreamSection.getInt("gamemode.initial gamemode"));
applyInitialHealth = dreamSection.getBoolean("health.apply");
initialHealth = dreamSection.getInt("health.initial health");
applyInitialHunger = dreamSection.getBoolean("hunger.apply");
initialHunger = dreamSection.getInt("hunger.initial hunger");
applyInitialPotionEffects = dreamSection.getBoolean("potion effects.apply");
initialPotionEffects = new ArrayList<PotionEffect>();
ConfigurationSection potionsSection = dreamSection.getConfigurationSection("potion effects.initial potion effects");
if (potionsSection != null) {
for (String type : potionsSection.getKeys(false)) {
ConfigurationSection potionSection = potionsSection.getConfigurationSection(type);
if (potionSection == null) continue;
PotionEffectType potionType = PotionEffectType.getByName(type);
if (potionType == null) {
plugin.getLogger().warning("Invalid potion effect type '" + type + "'. Skipping this effect now. You can find a list of all possible PotionEffectTypes by googling 'bukkit PotionEffectType'.");
continue;
}
initialPotionEffects.add(new PotionEffect(potionType, potionSection.getInt("duration"), potionSection.getInt("level", 1)));
}
}
clearAndRestorePlayer = dreamSection.getBoolean("clear and restore player");
purgeAfterMinutes = dreamSection.getInt("purge saved dream data after x minutes");
ignoreIfRemainingTimeIsLowerThan = dreamSection.getInt("ignore if remaining seconds is lower than");
// fake time
ConfigurationSection fakeTimeSection = dreamSection.getConfigurationSection("fake client time");
fakeTimeEnabled = fakeTimeSection.getBoolean("enabled") ;
fakeTime = fakeTimeSection.getInt("time (in ticks)");
fakeTimeRandomBounds = fakeTimeSection.getInt("random bounds");
fakeTimeFixed = fakeTimeSection.getBoolean("fixed time");
// fake weather
fakeRain = dreamSection.getBoolean("fake client weather.raining");
// disabled:
ConfigurationSection disabledSection = dreamSection.getConfigurationSection("disabled");
hungerDisabled = disabledSection.getBoolean("hunger");
fallDamageDisabled = disabledSection.getBoolean("fall damage");
entityDamageDisabled = disabledSection.getBoolean("entity damage");
allDamageDisabled = disabledSection.getBoolean("all damage");
weatherDisabled = disabledSection.getBoolean("weather");
itemDroppingDisabled = disabledSection.getBoolean("item dropping");
itemPickupDisabled = disabledSection.getBoolean("item pickup");
blockPlacingDisabled = disabledSection.getBoolean("block placing");
blockBreakingDisabled = disabledSection.getBoolean("block breaking");
// allowed commands:
allowedCommands = dreamSection.getStringList("allowed commands");
wasConfigValid = true;
} catch (Exception e) {
e.printStackTrace();
wasConfigValid = false;
}
}
| public ConfigManager(Plugin plugin) {
this.plugin = plugin;
// default config:
plugin.saveDefaultConfig();
FileConfiguration config = plugin.getConfig();
config.options().copyDefaults(true);
// load values:
try {
ConfigurationSection dreamSection = config.getConfigurationSection("dream");
// world settings:
dreamWorldName = dreamSection.getString("world name");
noAnimalSpawning = dreamSection.getBoolean("no animal spawning");
noMonsterSpawning = dreamSection.getBoolean("no monster spawning");
dreamChance = dreamSection.getInt("chance");
minDurationSeconds = dreamSection.getInt("min duration in seconds");
maxDurationSeconds = dreamSection.getInt("max duration in seconds");
// spawning:
spawnRandomly = dreamSection.getBoolean("spawn randomly each time");
dreamSpawns = SoftLocation.getFromStringList(dreamSection.getStringList("random spawns"));
// some initial values:
applyInitialGamemode = dreamSection.getBoolean("gamemode.apply");
initialGamemode = GameMode.getByValue(dreamSection.getInt("gamemode.initial gamemode"));
applyInitialHealth = dreamSection.getBoolean("health.apply");
initialHealth = dreamSection.getInt("health.initial health");
applyInitialHunger = dreamSection.getBoolean("hunger.apply");
initialHunger = dreamSection.getInt("hunger.initial hunger");
applyInitialPotionEffects = dreamSection.getBoolean("potion effects.apply");
initialPotionEffects = new ArrayList<PotionEffect>();
ConfigurationSection potionsSection = dreamSection.getConfigurationSection("potion effects.initial potion effects");
if (potionsSection != null) {
for (String type : potionsSection.getKeys(false)) {
ConfigurationSection potionSection = potionsSection.getConfigurationSection(type);
if (potionSection == null) continue;
PotionEffectType potionType = PotionEffectType.getByName(type);
if (potionType == null) {
plugin.getLogger().warning("Invalid potion effect type '" + type + "'. Skipping this effect now. You can find a list of all possible PotionEffectTypes by googling 'bukkit PotionEffectType'.");
continue;
}
initialPotionEffects.add(new PotionEffect(potionType, potionSection.getInt("duration"), potionSection.getInt("level")));
}
}
clearAndRestorePlayer = dreamSection.getBoolean("clear and restore player");
purgeAfterMinutes = dreamSection.getInt("purge saved dream data after x minutes");
ignoreIfRemainingTimeIsLowerThan = dreamSection.getInt("ignore if remaining seconds is lower than");
// fake time
ConfigurationSection fakeTimeSection = dreamSection.getConfigurationSection("fake client time");
fakeTimeEnabled = fakeTimeSection.getBoolean("enabled") ;
fakeTime = fakeTimeSection.getInt("time (in ticks)");
fakeTimeRandomBounds = fakeTimeSection.getInt("random bounds");
fakeTimeFixed = fakeTimeSection.getBoolean("fixed time");
// fake weather
fakeRain = dreamSection.getBoolean("fake client weather.raining");
// disabled:
ConfigurationSection disabledSection = dreamSection.getConfigurationSection("disabled");
hungerDisabled = disabledSection.getBoolean("hunger");
fallDamageDisabled = disabledSection.getBoolean("fall damage");
entityDamageDisabled = disabledSection.getBoolean("entity damage");
allDamageDisabled = disabledSection.getBoolean("all damage");
weatherDisabled = disabledSection.getBoolean("weather");
itemDroppingDisabled = disabledSection.getBoolean("item dropping");
itemPickupDisabled = disabledSection.getBoolean("item pickup");
blockPlacingDisabled = disabledSection.getBoolean("block placing");
blockBreakingDisabled = disabledSection.getBoolean("block breaking");
// allowed commands:
allowedCommands = dreamSection.getStringList("allowed commands");
wasConfigValid = true;
} catch (Exception e) {
e.printStackTrace();
wasConfigValid = false;
}
}
|
diff --git a/src/org/mozilla/javascript/v8dtoa/DiyFp.java b/src/org/mozilla/javascript/v8dtoa/DiyFp.java
index 6fde580d..1e639111 100644
--- a/src/org/mozilla/javascript/v8dtoa/DiyFp.java
+++ b/src/org/mozilla/javascript/v8dtoa/DiyFp.java
@@ -1,150 +1,150 @@
// Copyright 2010 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package org.mozilla.javascript.v8dtoa;
// This "Do It Yourself Floating Point" class implements a floating-point number
// with a uint64 significand and an int exponent. Normalized DiyFp numbers will
// have the most significant bit of the significand set.
// Multiplication and Subtraction do not normalize their results.
// DiyFp are not designed to contain special doubles (NaN and Infinity).
class DiyFp implements Cloneable {
private long f;
private int e;
static final int kSignificandSize = 64;
static final long kUint64MSB = 0x8000000000000000L;
DiyFp() {
this.f = 0;
this.e = 0;
}
DiyFp(long f, int e) {
this.f = f;
this.e = e;
}
// this = this - other.
// The exponents of both numbers must be the same and the significand of this
// must be bigger than the significand of other.
// The result will not be normalized.
void subtract(DiyFp other) {
assert (e == other.e);
assert (f >= other.f);
f -= other.f;
}
// Returns a - b.
// The exponents of both numbers must be the same and this must be bigger
// than other. The result will not be normalized.
static DiyFp minus(DiyFp a, DiyFp b) {
DiyFp result = a.clone();
result.subtract(b);
return result;
}
// this = this * other.
void multiply(DiyFp other) {
// Simply "emulates" a 128 bit multiplication.
// However: the resulting number only contains 64 bits. The least
// significant 64 bits are only used for rounding the most significant 64
// bits.
final long kM32 = 0xFFFFFFFFL;
long a = f >>> 32;
long b = f & kM32;
long c = other.f >>> 32;
long d = other.f & kM32;
long ac = a * c;
long bc = b * c;
long ad = a * d;
long bd = b * d;
long tmp = (bd >>> 32) + (ad & kM32) + (bc & kM32);
// By adding 1U << 31 to tmp we round the final result.
// Halfway cases will be round up.
- tmp += 1 << 31;
+ tmp += 1L << 31;
long result_f = ac + (ad >>> 32) + (bc >>> 32) + (tmp >>> 32);
e += other.e + 64;
f = result_f;
}
// returns a * b;
static DiyFp times(DiyFp a, DiyFp b) {
DiyFp result = a.clone();
result.multiply(b);
return result;
}
void normalize() {
assert(f != 0);
long f = this.f;
int e = this.e;
// This method is mainly called for normalizing boundaries. In general
// boundaries need to be shifted by 10 bits. We thus optimize for this case.
final long k10MSBits = 0xFFC00000L << 32;
while ((f & k10MSBits) == 0) {
f <<= 10;
e -= 10;
}
while ((f & kUint64MSB) == 0) {
f <<= 1;
e--;
}
this.f = f;
this.e = e;
}
static DiyFp normalize(DiyFp a) {
DiyFp result = a.clone();
result.normalize();
return result;
}
long f() { return f; }
int e() { return e; }
void setF(long new_value) { f = new_value; }
void setE(int new_value) { e = new_value; }
public DiyFp clone() {
try {
return (DiyFp) super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException(); // won't happen
}
}
@Override
public String toString() {
return "[DiyFp f:" + f + ", e:" + e + "]";
}
}
| true | true | void multiply(DiyFp other) {
// Simply "emulates" a 128 bit multiplication.
// However: the resulting number only contains 64 bits. The least
// significant 64 bits are only used for rounding the most significant 64
// bits.
final long kM32 = 0xFFFFFFFFL;
long a = f >>> 32;
long b = f & kM32;
long c = other.f >>> 32;
long d = other.f & kM32;
long ac = a * c;
long bc = b * c;
long ad = a * d;
long bd = b * d;
long tmp = (bd >>> 32) + (ad & kM32) + (bc & kM32);
// By adding 1U << 31 to tmp we round the final result.
// Halfway cases will be round up.
tmp += 1 << 31;
long result_f = ac + (ad >>> 32) + (bc >>> 32) + (tmp >>> 32);
e += other.e + 64;
f = result_f;
}
| void multiply(DiyFp other) {
// Simply "emulates" a 128 bit multiplication.
// However: the resulting number only contains 64 bits. The least
// significant 64 bits are only used for rounding the most significant 64
// bits.
final long kM32 = 0xFFFFFFFFL;
long a = f >>> 32;
long b = f & kM32;
long c = other.f >>> 32;
long d = other.f & kM32;
long ac = a * c;
long bc = b * c;
long ad = a * d;
long bd = b * d;
long tmp = (bd >>> 32) + (ad & kM32) + (bc & kM32);
// By adding 1U << 31 to tmp we round the final result.
// Halfway cases will be round up.
tmp += 1L << 31;
long result_f = ac + (ad >>> 32) + (bc >>> 32) + (tmp >>> 32);
e += other.e + 64;
f = result_f;
}
|
diff --git a/cortege/src/test/java/com/rumba/cortege/examples/ExampleCortege.java b/cortege/src/test/java/com/rumba/cortege/examples/ExampleCortege.java
index 28e3227..0c009f9 100644
--- a/cortege/src/test/java/com/rumba/cortege/examples/ExampleCortege.java
+++ b/cortege/src/test/java/com/rumba/cortege/examples/ExampleCortege.java
@@ -1,38 +1,38 @@
/**
* Copyright (c) 2012 Kiselyov A.V., All Rights Reserved
*
* For information about the licensing and copyright of this document please
* contact Alexey Kiselyov. at [email protected]
*
* @Project: Cortege
*/
package com.rumba.cortege.examples;
import com.rumba.cortege.Cortege;
import com.rumba.cortege.CortegeChain;
/**
* User: kiselyov
* Date: 21.05.12
*/
public class ExampleCortege {
public static void main(String[] args) {
Cortege<Long, Cortege<String, Cortege.End>> cortegeLS = CortegeChain.create(2);
// заполнение элементов значениями
// 1-й вариант (заполняем первый элемент в кортеже, с контролем типа)
cortegeLS.setValue(4L);
cortegeLS.nextElement().setValue("str");
// 2-й вариант (заполняем подряд цепью, с контролем типа)
cortegeLS.setValue(4L).setValue("str");
- // 3-й вариант (заполняем массивом, с без контроля типа)
+ // 3-й вариант (заполняем массивом, без контроля типа)
cortegeLS.setValues(4L, "str");
// 1-й вариант (чтение первого элемента в кортеже, с контролем типа)
Long valueA = cortegeLS.getValue();
// 2-й вариант (чтение выбранного элемента в кортеже, с контролем типа)
String valueB = cortegeLS.nextElement().getValue();
// 3-й вариант (чтение выбранного элемента в кортеже, без контроля типа)
Long valueC = cortegeLS.getValue(1);
String valueD = cortegeLS.getValue(2);
}
}
| true | true | public static void main(String[] args) {
Cortege<Long, Cortege<String, Cortege.End>> cortegeLS = CortegeChain.create(2);
// заполнение элементов значениями
// 1-й вариант (заполняем первый элемент в кортеже, с контролем типа)
cortegeLS.setValue(4L);
cortegeLS.nextElement().setValue("str");
// 2-й вариант (заполняем подряд цепью, с контролем типа)
cortegeLS.setValue(4L).setValue("str");
// 3-й вариант (заполняем массивом, с без контроля типа)
cortegeLS.setValues(4L, "str");
// 1-й вариант (чтение первого элемента в кортеже, с контролем типа)
Long valueA = cortegeLS.getValue();
// 2-й вариант (чтение выбранного элемента в кортеже, с контролем типа)
String valueB = cortegeLS.nextElement().getValue();
// 3-й вариант (чтение выбранного элемента в кортеже, без контроля типа)
Long valueC = cortegeLS.getValue(1);
String valueD = cortegeLS.getValue(2);
}
| public static void main(String[] args) {
Cortege<Long, Cortege<String, Cortege.End>> cortegeLS = CortegeChain.create(2);
// заполнение элементов значениями
// 1-й вариант (заполняем первый элемент в кортеже, с контролем типа)
cortegeLS.setValue(4L);
cortegeLS.nextElement().setValue("str");
// 2-й вариант (заполняем подряд цепью, с контролем типа)
cortegeLS.setValue(4L).setValue("str");
// 3-й вариант (заполняем массивом, без контроля типа)
cortegeLS.setValues(4L, "str");
// 1-й вариант (чтение первого элемента в кортеже, с контролем типа)
Long valueA = cortegeLS.getValue();
// 2-й вариант (чтение выбранного элемента в кортеже, с контролем типа)
String valueB = cortegeLS.nextElement().getValue();
// 3-й вариант (чтение выбранного элемента в кортеже, без контроля типа)
Long valueC = cortegeLS.getValue(1);
String valueD = cortegeLS.getValue(2);
}
|
diff --git a/filter-impl/src/main/java/org/cytoscape/filter/internal/filters/view/FilterMainPanel.java b/filter-impl/src/main/java/org/cytoscape/filter/internal/filters/view/FilterMainPanel.java
index 98f3a3abf..eb9a10f7b 100644
--- a/filter-impl/src/main/java/org/cytoscape/filter/internal/filters/view/FilterMainPanel.java
+++ b/filter-impl/src/main/java/org/cytoscape/filter/internal/filters/view/FilterMainPanel.java
@@ -1,1421 +1,1422 @@
/*
Copyright (c) 2006, 2007, 2009, 2010, The Cytoscape Consortium (www.cytoscape.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package org.cytoscape.filter.internal.filters.view;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Collection;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Vector;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import org.cytoscape.application.CyApplicationManager;
import org.cytoscape.application.events.SetCurrentNetworkViewEvent;
import org.cytoscape.application.events.SetCurrentNetworkViewListener;
import org.cytoscape.event.CyEventHelper;
import org.cytoscape.filter.internal.filters.CompositeFilter;
import org.cytoscape.filter.internal.filters.EdgeInteractionFilter;
import org.cytoscape.filter.internal.filters.FilterPlugin;
import org.cytoscape.filter.internal.filters.InteractionFilter;
import org.cytoscape.filter.internal.filters.NodeInteractionFilter;
import org.cytoscape.filter.internal.filters.TopologyFilter;
import org.cytoscape.filter.internal.filters.util.FilterUtil;
import org.cytoscape.filter.internal.filters.util.SelectUtil;
import org.cytoscape.filter.internal.filters.util.WidestStringComboBoxModel;
import org.cytoscape.filter.internal.filters.util.WidestStringComboBoxPopupMenuListener;
import org.cytoscape.filter.internal.filters.util.WidestStringProvider;
import org.cytoscape.filter.internal.quickfind.util.CyAttributesUtil;
import org.cytoscape.filter.internal.quickfind.util.QuickFind;
import org.cytoscape.filter.internal.quickfind.util.QuickFindFactory;
import org.cytoscape.filter.internal.quickfind.util.TaskMonitorBase;
import org.cytoscape.model.CyColumn;
import org.cytoscape.model.CyNetwork;
import org.cytoscape.model.CyNetworkManager;
import org.cytoscape.model.CyTableEntry;
import org.cytoscape.model.CyTableUtil;
import org.cytoscape.model.events.NetworkAboutToBeDestroyedEvent;
import org.cytoscape.model.events.NetworkAboutToBeDestroyedListener;
import org.cytoscape.model.events.NetworkAddedEvent;
import org.cytoscape.model.events.NetworkAddedListener;
import org.cytoscape.model.events.RowSetRecord;
import org.cytoscape.model.events.RowsCreatedEvent;
import org.cytoscape.model.events.RowsCreatedListener;
import org.cytoscape.model.events.RowsSetEvent;
import org.cytoscape.model.events.RowsSetListener;
import org.cytoscape.service.util.CyServiceRegistrar;
import org.cytoscape.session.events.SessionLoadedEvent;
import org.cytoscape.session.events.SessionLoadedListener;
import org.cytoscape.util.swing.DropDownMenuButton;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.model.events.NetworkViewAddedEvent;
import org.cytoscape.view.model.events.NetworkViewAddedListener;
import org.cytoscape.view.presentation.RenderingEngine;
import org.cytoscape.work.Task;
import org.cytoscape.work.TaskManager;
public class FilterMainPanel extends JPanel implements ActionListener,
ItemListener, SetCurrentNetworkViewListener, NetworkAddedListener,
NetworkAboutToBeDestroyedListener, SessionLoadedListener, RowsSetListener,
RowsCreatedListener, NetworkViewAddedListener
{
private static final long serialVersionUID = -6554492076361739485L;
// String constants used for separator entries in the attribute combobox
private static final String filtersSeperator = "-- Filters --";
private static final String attributesSeperator = "-- Attributes --";
private static JPopupMenu optionMenu;
private static JMenuItem newFilterMenuItem;
private static JMenuItem newTopologyFilterMenuItem;
private static JMenuItem newNodeInteractionFilterMenuItem;
private static JMenuItem newEdgeInteractionFilterMenuItem;
private static JMenuItem renameFilterMenuItem;
private static JMenuItem deleteFilterMenuItem;
private static JMenuItem duplicateFilterMenuItem;
private DropDownMenuButton optionButton;
private FilterSettingPanel currentFilterSettingPanel = null;
private HashMap<CompositeFilter,FilterSettingPanel> filter2SettingPanelMap = new HashMap<CompositeFilter,FilterSettingPanel>();
/*
* Icons used in this panel.
*/
private final ImageIcon optionIcon = new ImageIcon(getClass().getResource("/images/properties.png"));
private final ImageIcon delIcon = new ImageIcon(getClass().getResource("/images/delete.png"));
private final ImageIcon addIcon = new ImageIcon(getClass().getResource("/images/add.png"));
private final ImageIcon renameIcon = new ImageIcon(getClass().getResource("/images/rename.png"));
private final ImageIcon duplicateIcon = new ImageIcon(getClass().getResource("/images/duplicate.png"));
private final CyApplicationManager applicationManager;
private final FilterPlugin filterPlugin;
private final CyNetworkManager networkManager;
private final CyServiceRegistrar serviceRegistrar;
private final CyEventHelper eventHelper;
private final TaskManager taskManager;
public FilterMainPanel(final CyApplicationManager applicationManager,
final FilterPlugin filterPlugin,
final CyNetworkManager networkManager,
final CyServiceRegistrar serviceRegistrar,
final CyEventHelper eventHelper,
final TaskManager taskManager)
{
this.applicationManager = applicationManager;
this.filterPlugin = filterPlugin;
this.networkManager = networkManager;
this.serviceRegistrar = serviceRegistrar;
this.eventHelper = eventHelper;
this.taskManager = taskManager;
final Dictionary emptyProps = new Hashtable();
//Initialize the option menu with menuItems
setupOptionMenu();
optionButton = new DropDownMenuButton(new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
DropDownMenuButton b = (DropDownMenuButton) ae.getSource();
optionMenu.show(b, 0, b.getHeight());
}
});
optionButton.setToolTipText("Options...");
optionButton.setIcon(optionIcon);
optionButton.setMargin(new Insets(2, 2, 2, 2));
optionButton.setComponentPopupMenu(optionMenu);
//Initialize the UI components
initComponents();
this.btnSelectAll.setEnabled(false);
this.btnDeSelect.setEnabled(false);
// reduce the text font to fit three buttons within visible window
this.btnSelectAll.setFont(new Font("Tahoma", 0, 9));
this.btnDeSelect.setFont(new Font("Tahoma", 0, 9));
this.btnApplyFilter.setFont(new Font("Tahoma", 0, 9));
//
String[][] data = {{"","",""}};
String[] col = {"Network","Nodes","Edges"};
DefaultTableModel model = new DefaultTableModel(data,col);
tblFeedBack.setModel(model);
addEventListeners();
//btnApplyFilter.setVisible(false);
//Update the status of interactionMenuItems if this panel become visible
MyComponentAdapter cmpAdpt = new MyComponentAdapter();
addComponentListener(cmpAdpt);
}
@Override
public void handleEvent(RowsSetEvent e) {
// Handle selection events
if (this.applicationManager.getCurrentNetworkView() == null){
return;
}
boolean isSelection = true;
for (RowSetRecord change : e.getPayloadCollection()) {
if (!change.getColumn().equals(CyNetwork.SELECTED)) {
isSelection = false;
break;
}
}
if (isSelection) {
return;
}
handleAttributesChanged();
updateFeedbackTableModel();
}
@Override
public void handleEvent(RowsCreatedEvent e) {
handleAttributesChanged();
}
void handleAttributesChanged() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
refreshAttributeCMB();
replaceFilterSettingPanel((CompositeFilter)cmbSelectFilter.getSelectedItem());
FilterSettingPanel theSettingPanel= filter2SettingPanelMap.get(cmbSelectFilter.getSelectedItem());
if (theSettingPanel != null) {
theSettingPanel.refreshIndicesForWidgets();
}
updateFeedbackTableModel();
}
});
}
@Override
public void handleEvent(SessionLoadedEvent e) {
updateFeedbackTableModel();
}
public void handleNetworkFocused(CyNetworkView view) {
if (view == null) {
return;
}
// If FilterPanel is not selected, do nothing
if (cmbSelectFilter.getSelectedItem() == null) {
return;
}
//Refresh indices for UI widgets after network switch
CompositeFilter selectedFilter = (CompositeFilter) cmbSelectFilter.getSelectedItem();
selectedFilter.setNetwork(view.getModel());
FilterSettingPanel theSettingPanel= filter2SettingPanelMap.get(selectedFilter);
theSettingPanel.refreshIndicesForWidgets();
updateFeedbackTableModel();
}
@Override
public void handleEvent(SetCurrentNetworkViewEvent e) {
handleNetworkFocused(e.getNetworkView());
updateFeedbackTableModel();
}
@Override
public void handleEvent(NetworkAboutToBeDestroyedEvent e) {
CyNetwork network = e.getNetwork();
if (!networkManager.networkExists(network.getSUID())) {
return;
}
enableForNetwork();
updateFeedbackTableModel();
}
@Override
public void handleEvent(NetworkAddedEvent e) {
CyNetwork network = e.getNetwork();
if (!networkManager.networkExists(network.getSUID())) {
return;
}
enableForNetwork();
updateFeedbackTableModel();
}
public void updateFeedbackTableModel(){
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
CyNetworkView view = applicationManager.getCurrentNetworkView();
RenderingEngine<CyNetwork> engine = applicationManager.getCurrentRenderingEngine();
if (cyNetwork == null || view == null || engine == null) {
return;
}
//VisualLexicon lexicon = engine.getVisualLexicon();
//String title = VisualPropertyUtil.get(lexicon, view, "NETWORK_TITLE", MinimalVisualLexicon.NETWORK, String.class);
tblFeedBack.getModel().setValueAt(cyNetwork.getCyRow().get("name", String.class), 0, 0);
String nodeStr = "" + cyNetwork.getNodeCount() + "(" + CyTableUtil.getNodesInState(cyNetwork,"selected",true).size() + ")";
tblFeedBack.getModel().setValueAt(nodeStr, 0, 1);
String edgeStr = "" + cyNetwork.getEdgeCount() + "(" + CyTableUtil.getEdgesInState(cyNetwork,"selected",true).size() + ")";
tblFeedBack.getModel().setValueAt(edgeStr, 0, 2);
}
/**
* Enable select/deselect buttons if the current network exists and is not null.
*/
public void enableForNetwork() {
CyNetwork n = applicationManager.getCurrentNetwork();
if ( n == null ) {
this.btnSelectAll.setEnabled(false);
this.btnDeSelect.setEnabled(false);
}
else {
this.btnSelectAll.setEnabled(true);
this.btnDeSelect.setEnabled(true);
}
}
// Target network to watch selection
private CyNetwork currentNetwork;
public void refreshFilterSelectCMB() {
ComboBoxModel cbm;
// Whatever change caused the refresh may have altered the longest display String
// so need to have the model recalculate it.
cbm = cmbSelectFilter.getModel();
if (cbm instanceof WidestStringProvider) {
((WidestStringProvider)cbm).resetWidest();
}
this.cmbSelectFilter.repaint();
}
private void refreshAttributeCMB() {
updateCMBAttributes();
cmbAttributes.repaint();
}
/*
* Get the list of attribute names for either "node" or "edge". The attribute names will be
* prefixed either with "node." or "edge.". Those attributes whose data type is neither
* "String" nor "numeric" will be excluded
*/
private List<Object> getCyAttributesList(CyNetwork network, String pType) {
Vector<String> attributeList = new Vector<String>();
Collection<? extends CyTableEntry> entries;
if (pType.equalsIgnoreCase("node")) {
entries = network.getNodeList();
}
else if (pType.equalsIgnoreCase("edge")){
entries = network.getEdgeList();
} else {
return Collections.emptyList();
}
if (entries.size() == 0) {
return Collections.emptyList();
}
CyTableEntry tableEntry = entries.iterator().next();
final Collection<CyColumn> columns = tableEntry.getCyRow().getTable().getColumns();
for (final CyColumn column : columns) {
// Show all attributes, with type of String or Number
Class<?> type = column.getType();
// only show user visible attributes,with type = Number/String/List
if ((type == Integer.class)||(type == Double.class)||(type == Boolean.class)||(type == String.class)||(type == List.class)) {
attributeList.add(pType + "." + column.getName());
}
// Alphabetical sort
Collections.sort(attributeList);
}
// type conversion
Vector<Object> retList = new Vector<Object>();
for (int i=0; i<attributeList.size(); i++) {
retList.add(attributeList.elementAt(i));
}
return retList;
}
/*
* Hide the visible filterSettingPanel, if any, and show the new FilterSettingPanel for
* the given filter.
*/
private void replaceFilterSettingPanel(CompositeFilter pNewFilter) {
if (pNewFilter == null) {
pnlFilterDefinition.setVisible(false);
lbPlaceHolder_pnlFilterDefinition.setVisible(true);
return;
}
FilterSettingPanel next;
next = filter2SettingPanelMap.get(pNewFilter);
// When the next panel exists and is the same as the current one,
// we can exit now and avoid hiding and showing the same panel.
//
if ((next != null) && (next == currentFilterSettingPanel)) {
return;
}
//Hide the existing FilterSettingPanel, if any
if (currentFilterSettingPanel != null) {
currentFilterSettingPanel.setVisible(false);
}
currentFilterSettingPanel = next;
if (currentFilterSettingPanel == null || currentFilterSettingPanel.hasNullIndexChildFilter()) {
currentFilterSettingPanel = new FilterSettingPanel(this, pNewFilter, applicationManager, filterPlugin, eventHelper);
//Update the HashMap
filter2SettingPanelMap.put(pNewFilter, currentFilterSettingPanel);
}
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
gridBagConstraints.insets = new Insets(7, 0, 0, 0);
if (pNewFilter instanceof TopologyFilter) {
lbAttribute.setVisible(false);
btnAddFilterWidget.setVisible(false);
cmbAttributes.setVisible(false);
pnlFilterDefinition.setBorder(BorderFactory
.createTitledBorder("Topology Filter Definition"));
}
else if (pNewFilter instanceof InteractionFilter) {
lbAttribute.setVisible(false);
btnAddFilterWidget.setVisible(false);
cmbAttributes.setVisible(false);
pnlFilterDefinition.setBorder(BorderFactory
.createTitledBorder("Interaction Filter Definition"));
}
else {
lbAttribute.setVisible(true);
btnAddFilterWidget.setVisible(true);
cmbAttributes.setVisible(true);
pnlFilterDefinition.setBorder(BorderFactory
.createTitledBorder("Filter Definition"));
}
pnlFilterDefinition.add(currentFilterSettingPanel, gridBagConstraints);
pnlFilterDefinition.setVisible(true);
currentFilterSettingPanel.setVisible(true);
lbPlaceHolder_pnlFilterDefinition.setVisible(false);
this.repaint();
}
private void addEventListeners() {
btnApplyFilter.addActionListener(this);
btnAddFilterWidget.addActionListener(this);
newFilterMenuItem.addActionListener(this);
newTopologyFilterMenuItem.addActionListener(this);
newNodeInteractionFilterMenuItem.addActionListener(this);
newEdgeInteractionFilterMenuItem.addActionListener(this);
deleteFilterMenuItem.addActionListener(this);
renameFilterMenuItem.addActionListener(this);
duplicateFilterMenuItem.addActionListener(this);
cmbSelectFilter.addItemListener(this);
cmbAttributes.addItemListener(this);
btnSelectAll.addActionListener(this);
btnDeSelect.addActionListener(this);
}
public void initCMBSelectFilter(){
Vector<CompositeFilter> allFilterVect = filterPlugin.getAllFilterVect();
ComboBoxModel theModel = new FilterSelectWidestStringComboBoxModel(allFilterVect);
cmbSelectFilter.setModel(theModel);
cmbSelectFilter.setRenderer(new FilterRenderer());
if (allFilterVect.size() == 0) {
this.btnApplyFilter.setEnabled(false);
this.btnAddFilterWidget.setEnabled(false);
}
for (int i=0; i<allFilterVect.size(); i++) {
filter2SettingPanelMap.put(allFilterVect.elementAt(i), null);
}
// Force the first filter in the model to be selected, so that it's panel will be shown
if (theModel.getSize() > 0) {
cmbSelectFilter.setSelectedIndex(0);
}
replaceFilterSettingPanel((CompositeFilter)cmbSelectFilter.getSelectedItem());
}
public void handlePanelSelected() {
updateIndex();
}
private void updateIndex() {
final CyNetworkView currentView = applicationManager.getCurrentNetworkView();
if (currentView == null)
return;
final CyNetwork network = currentView.getModel();
taskManager.execute(new FilterIndexingTaskFactory(network));
if (cmbSelectFilter.getModel().getSize() == 0) {
// CMBSelectFilter will not be initialize until the Filter Panel has been selected
initCMBSelectFilter();
}
updateCMBAttributes();
}
/*
* Update the attribute list in the attribute combobox based on the settings in the
* current selected filter
*/
private void updateCMBAttributes() {
DefaultComboBoxModel cbm;
cbm = ((DefaultComboBoxModel)cmbAttributes.getModel());
cbm.removeAllElements();
cbm.addElement(attributesSeperator);
CompositeFilter selectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (selectedFilter == null) {
return;
}
CyNetwork network = selectedFilter.getNetwork();
if (network == null) {
return;
}
List<Object> av;
av = getCyAttributesList(network, "node");
for (int i = 0; i < av.size(); i++) {
cbm.addElement(av.get(i));
}
av = getCyAttributesList(network, "edge");
for (int i = 0; i < av.size(); i++) {
cbm.addElement(av.get(i));
}
cbm.addElement(filtersSeperator);
Vector<CompositeFilter> allFilterVect = filterPlugin.getAllFilterVect();
if (allFilterVect != null) {
for (int i = 0; i < allFilterVect.size(); i++) {
Object fi;
fi = allFilterVect.elementAt(i);
if (fi != selectedFilter) {
cbm.addElement(fi);
}
}
}
}
/**
* Setup menu items.
*
*/
private void setupOptionMenu() {
/*
* Option Menu
*/
newFilterMenuItem = new JMenuItem("Create new filter...");
newFilterMenuItem.setIcon(addIcon);
newTopologyFilterMenuItem = new JMenuItem("Create new topology filter...");
newTopologyFilterMenuItem.setIcon(addIcon);
newNodeInteractionFilterMenuItem = new JMenuItem("Create new NodeInteraction filter...");
newNodeInteractionFilterMenuItem.setIcon(addIcon);
newNodeInteractionFilterMenuItem.setEnabled(false);
newEdgeInteractionFilterMenuItem = new JMenuItem("Create new EdgeInteraction filter...");
newEdgeInteractionFilterMenuItem.setIcon(addIcon);
newEdgeInteractionFilterMenuItem.setEnabled(false);
deleteFilterMenuItem = new JMenuItem("Delete filter...");
deleteFilterMenuItem.setIcon(delIcon);
renameFilterMenuItem = new JMenuItem("Rename filter...");
renameFilterMenuItem.setIcon(renameIcon);
duplicateFilterMenuItem = new JMenuItem("Copy existing filter...");
duplicateFilterMenuItem.setIcon(duplicateIcon);
// Hide copy icon for now, we may need it in the future
duplicateFilterMenuItem.setVisible(false);
optionMenu = new JPopupMenu();
optionMenu.add(newFilterMenuItem);
optionMenu.add(newTopologyFilterMenuItem);
optionMenu.add(newNodeInteractionFilterMenuItem);
optionMenu.add(newEdgeInteractionFilterMenuItem);
optionMenu.add(deleteFilterMenuItem);
optionMenu.add(renameFilterMenuItem);
optionMenu.add(duplicateFilterMenuItem);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc=" Generated Code ">
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
pnlCurrentFilter = new JPanel();
cmbSelectFilter = new JComboBox();
cmbSelectFilter.addPopupMenuListener(new WidestStringComboBoxPopupMenuListener());
// optionButton = new javax.swing.JButton();
pnlFilterDefinition = new JPanel();
WidestStringComboBoxModel wscbm = new AttributeSelectWidestStringComboBoxModel();
cmbAttributes = new JComboBox(wscbm);
cmbAttributes.addPopupMenuListener(new WidestStringComboBoxPopupMenuListener());
btnAddFilterWidget = new JButton();
lbAttribute = new JLabel();
lbPlaceHolder = new JLabel();
pnlButton = new JPanel();
btnApplyFilter = new JButton();
lbPlaceHolder_pnlFilterDefinition = new JLabel();
pnlFeedBack = new JPanel();
tblFeedBack = new JTable();
pnlSelectButtons = new JPanel();
btnSelectAll = new JButton();
btnDeSelect = new JButton();
pnlScroll = new JScrollPane();
setLayout(new GridBagLayout());
pnlCurrentFilter.setLayout(new GridBagLayout());
pnlCurrentFilter.setBorder(BorderFactory
.createTitledBorder("Current Filter"));
// cmbSelectFilter.setModel(new javax.swing.DefaultComboBoxModel(new
// String[] { "My First filter", "My second Filter" }));
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.anchor = GridBagConstraints.WEST;
gridBagConstraints.weightx = 0.5;
gridBagConstraints.insets = new Insets(5, 10, 5, 10);
pnlCurrentFilter.add(cmbSelectFilter, gridBagConstraints);
optionButton.setText("Option");
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.insets = new Insets(0, 0, 0, 5);
pnlCurrentFilter.add(optionButton, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.ipady = 4;
gridBagConstraints.anchor = GridBagConstraints.NORTHWEST;
gridBagConstraints.weightx = 1.0;
add(pnlCurrentFilter, gridBagConstraints);
pnlFilterDefinition.setLayout(new GridBagLayout());
pnlFilterDefinition.setBorder(BorderFactory
.createTitledBorder("Filter Definition"));
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new Insets(10, 10, 0, 10);
pnlFilterDefinition.add(cmbAttributes, gridBagConstraints);
btnAddFilterWidget.setText("Add");
btnAddFilterWidget.setEnabled(false);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridy = 0;
gridBagConstraints.insets = new Insets(10, 0, 0, 5);
pnlFilterDefinition.add(btnAddFilterWidget, gridBagConstraints);
lbAttribute.setText("Attribute/Filter");
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
gridBagConstraints.anchor = GridBagConstraints.WEST;
gridBagConstraints.insets = new Insets(10, 5, 0, 0);
pnlFilterDefinition.add(lbAttribute, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridy = 1;
gridBagConstraints.gridwidth = 3;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
pnlFilterDefinition.add(lbPlaceHolder, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(pnlFilterDefinition, gridBagConstraints);
///
pnlButton.setLayout(new FlowLayout());
btnApplyFilter.setText("Apply Filter");
pnlButton.add(btnApplyFilter);
btnSelectAll.setText("Select All");
pnlButton.add(btnSelectAll);
btnDeSelect.setText("Deselect All");
pnlButton.add(btnDeSelect);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 2;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new Insets(10, 0, 10, 0);
add(pnlButton, gridBagConstraints);
// lbPlaceHolder_pnlFilterDefinition.setText("jLabel1");
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
add(lbPlaceHolder_pnlFilterDefinition, gridBagConstraints);
// feedback panel
pnlFeedBack.setLayout(new GridBagLayout());
pnlFeedBack.setBorder(BorderFactory.createTitledBorder(""));
pnlFeedBack.setMinimumSize(new Dimension(pnlFeedBack.getWidth(),52));
//pnlFeedBack.setMinimumSize(new java.awt.Dimension(300,52));
pnlScroll.setViewportView(tblFeedBack);
//tblFeedBack.setAutoCreateColumnsFromModel(true);
//tblFeedBack.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
tblFeedBack.setEnabled(false);
tblFeedBack.setFocusable(false);
//tblFeedBack.setRequestFocusEnabled(false);
//tblFeedBack.setRowSelectionAllowed(false);
//tblFeedBack.setTableHeader(null);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH; //.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.weighty = 1.0;
//gridBagConstraints.insets = new java.awt.Insets(0, 0, 1, 1);
pnlFeedBack.add(pnlScroll, gridBagConstraints);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.gridy = 3;
gridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
gridBagConstraints.weightx = 1.0;
gridBagConstraints.insets = new Insets(1, 1, 2, 1);
add(pnlFeedBack, gridBagConstraints);
// Set customized renderer for attributes/filter combobox
cmbAttributes.setRenderer(new AttributeFilterRenderer());
}// </editor-fold>
// Variables declaration - do not modify
private JButton btnAddFilterWidget;
private JButton btnApplyFilter;
private JComboBox cmbAttributes;
private JComboBox cmbSelectFilter;
private JLabel lbAttribute;
private JLabel lbPlaceHolder;
private JLabel lbPlaceHolder_pnlFilterDefinition;
// private javax.swing.JButton optionButton;
private JPanel pnlButton;
private JPanel pnlCurrentFilter;
private JPanel pnlFilterDefinition;
private JPanel pnlFeedBack;
private JTable tblFeedBack;
private JPanel pnlSelectButtons;
private JButton btnDeSelect;
private JButton btnSelectAll;
private JScrollPane pnlScroll;
// End of variables declaration
public JComboBox getCMBAttributes()
{
return cmbAttributes;
}
/**
* DOCUMENT ME!
*
* @param e
* DOCUMENT ME!
*/
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
//System.out.println("Entering FilterMainPanel.itemStateChnaged() ...");
if (source instanceof JComboBox) {
JComboBox cmb = (JComboBox) source;
if (cmb == cmbSelectFilter) {
CompositeFilter selectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (selectedFilter == null) {
this.btnApplyFilter.setEnabled(false);
this.btnAddFilterWidget.setEnabled(false);
return;
}
else {
this.btnAddFilterWidget.setEnabled(true);
this.btnApplyFilter.setEnabled(true);
}
replaceFilterSettingPanel(selectedFilter);
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
if (cmbSelectFilter.getSelectedItem() instanceof TopologyFilter || cmbSelectFilter.getSelectedItem() instanceof InteractionFilter) {
// do not apply TopologyFilter or InteractionFilter automatically
return;
}
// If network size is greater than pre-defined threshold, don't apply it automatically
if (FilterUtil.isDynamicFilter(selectedFilter)) {
FilterUtil.doSelection(selectedFilter, applicationManager);
}
updateView();
refreshAttributeCMB();
}
else if (cmb == cmbAttributes) {
Object selectObject = cmbAttributes.getSelectedItem();
if (selectObject != null) {
String selectItem = selectObject.toString();
// Disable the Add button if "--Attribute--" or "-- Filter ---" is selected
if (selectItem.equalsIgnoreCase(filtersSeperator) ||selectItem.equalsIgnoreCase(attributesSeperator)) {
btnAddFilterWidget.setEnabled(false);
}
else {
btnAddFilterWidget.setEnabled(true);
}
}
}
}
}
public void actionPerformed(ActionEvent e) {
Object _actionObject = e.getSource();
// handle Button events
if (_actionObject instanceof JButton) {
JButton _btn = (JButton) _actionObject;
if (_btn == btnApplyFilter) {
- //System.out.println("\nApplyButton is clicked!");
- //System.out.println("\tThe Filter to apply is \n" + cmbSelectFilter.getSelectedItem().toString()+"\n");
CompositeFilter theFilterToApply = (CompositeFilter) cmbSelectFilter.getSelectedItem();
- theFilterToApply.setNetwork(applicationManager.getCurrentNetwork());
+ final CyNetwork currentNetwork = applicationManager.getCurrentNetwork();
+ if (currentNetwork == null)
+ return;
+ theFilterToApply.setNetwork(currentNetwork);
FilterUtil.doSelection(theFilterToApply, applicationManager);
}
if (_btn == btnAddFilterWidget) {
//btnAddFilterWidget is clicked!
CompositeFilter selectedFilter = (CompositeFilter) cmbSelectFilter.getSelectedItem();
FilterSettingPanel theSettingPanel = filter2SettingPanelMap.get(selectedFilter);
if (cmbAttributes.getSelectedItem() instanceof String) {
String selectItem = (String) cmbAttributes.getSelectedItem();
if (selectItem.equalsIgnoreCase(filtersSeperator) ||selectItem.equalsIgnoreCase(attributesSeperator)) {
return;
}
}
String attributeType = cmbAttributes.getSelectedItem().toString().substring(0,4);// "node" or "edge"
String attributeName = cmbAttributes.getSelectedItem().toString().substring(5);
if(CyAttributesUtil.isNullAttribute(applicationManager.getCurrentNetwork(), attributeType, attributeName)){
JOptionPane.showMessageDialog(this, "All the values for this attribute are NULL!", "Can not create filter", JOptionPane.ERROR_MESSAGE);
}
else {
theSettingPanel.addNewWidget(cmbAttributes.getSelectedItem());
}
}
if (_btn == btnSelectAll){
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
SelectUtil.selectAllNodes(cyNetwork);
SelectUtil.selectAllEdges(cyNetwork);
}
if (_btn == btnDeSelect){
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
SelectUtil.unselectAllNodes(cyNetwork);
SelectUtil.unselectAllEdges(cyNetwork);
}
} // JButton event
if (_actionObject instanceof JMenuItem) {
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
JMenuItem _menuItem = (JMenuItem) _actionObject;
if (_menuItem == newFilterMenuItem || _menuItem == newTopologyFilterMenuItem
|| _menuItem == newNodeInteractionFilterMenuItem || _menuItem == newEdgeInteractionFilterMenuItem) {
String filterType = "Composite";
//boolean isTopoFilter = false;
//boolean isInteractionFilter = false;
if (_menuItem == newTopologyFilterMenuItem) {
filterType = "Topology";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
if (_menuItem == newNodeInteractionFilterMenuItem) {
filterType = "NodeInteraction";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
if (_menuItem == newEdgeInteractionFilterMenuItem) {
filterType = "EdgeInteraction";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
String newFilterName = "";
while (true) {
newFilterName = JOptionPane.showInputDialog(
this, "New filter name", "New Filter Name",
JOptionPane.INFORMATION_MESSAGE);
if (newFilterName == null) { // user clicked "cancel"
break;
}
if (newFilterName.trim().equals("")) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name is empty!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
if (org.cytoscape.filter.internal.filters.util.FilterUtil
.isFilterNameDuplicated(filterPlugin, newFilterName)) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name already existed!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
break;
}// while loop
if ((newFilterName != null)
&& (!newFilterName.trim().equals(""))) {
createNewFilter(newFilterName, filterType);
//System.out.println("FilterMainPanel.firePropertyChange() -- NEW_FILTER_CREATED");
//pcs.firePropertyChange("NEW_FILTER_CREATED", "", "");
// // TODO: Port this
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "NEW_FILTER_CREATED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
}
} else if (_menuItem == deleteFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
Object[] options = { "YES", "CANCEL" };
int userChoice = JOptionPane.showOptionDialog(this,
"Are you sure you want to delete " + theSelectedFilter.getName()
+ "?", "Warning", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (userChoice == 1) { // user clicked CANCEL
return;
}
deleteFilter(theSelectedFilter);
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_DELETED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
} else if (_menuItem == renameFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
renameFilter();
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_RENAMED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
} else if (_menuItem == duplicateFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
duplicateFilter();
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_DUPLICATED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
}
} // JMenuItem event
updateInteractionMenuItemStatus();
updateView();
}
private void updateView() {
eventHelper.flushPayloadEvents();
final CyNetworkView currentView = applicationManager.getCurrentNetworkView();
if (currentView != null)
currentView.updateView();
}
private void updateInteractionMenuItemStatus() {
Vector<CompositeFilter> allFilterVect = filterPlugin.getAllFilterVect();
//Disable interactionMenuItem if there is no other filters to depend on
if (allFilterVect == null || allFilterVect.size() == 0) {
newNodeInteractionFilterMenuItem.setEnabled(false);
newEdgeInteractionFilterMenuItem.setEnabled(false);
return;
}
// Set newEdgeInteractionFilterMenuItem on only if there are at least one
// Node Filter
if (hasNodeFilter(allFilterVect)) {
newEdgeInteractionFilterMenuItem.setEnabled(true);
}
else {
newEdgeInteractionFilterMenuItem.setEnabled(false);
}
// Set newNodeInteractionFilterMenuItem on only if there are at least one
// Edge Filter
if (hasEdgeFilter(allFilterVect)) {
newNodeInteractionFilterMenuItem.setEnabled(true);
}
else {
newNodeInteractionFilterMenuItem.setEnabled(false);
}
}
// Check if there are any NodeFilter in the AllFilterVect
private boolean hasNodeFilter(Vector<CompositeFilter> pAllFilterVect) {
boolean selectNode = false;
for (int i=0; i< pAllFilterVect.size(); i++) {
CompositeFilter curFilter = pAllFilterVect.elementAt(i);
if (curFilter.getAdvancedSetting().isNodeChecked()) {
selectNode = true;
}
}//end of for loop
return selectNode;
}
// Check if there are any NodeFilter in the AllFilterVect
private boolean hasEdgeFilter(Vector<CompositeFilter> pAllFilterVect) {
boolean selectEdge = false;
for (int i=0; i< pAllFilterVect.size(); i++) {
CompositeFilter curFilter = pAllFilterVect.elementAt(i);
if (curFilter.getAdvancedSetting().isEdgeChecked()) {
selectEdge = true;
}
}//end of for loop
return selectEdge;
}
//Each time, the FilterMainPanel become visible, update the status of InteractionMaenuItems
class MyComponentAdapter extends ComponentAdapter {
public void componentShown(ComponentEvent e) {
updateInteractionMenuItemStatus();
}
}
private void duplicateFilter(){
CompositeFilter theFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
String tmpName = "Copy of " + theFilter.getName();
String newFilterName = null;
while (true) {
Vector<String> nameVect = new Vector<String>();
nameVect.add(tmpName);
EditNameDialog theDialog = new EditNameDialog("Copy Filter", "Please enter a new Filter name:", nameVect, 300,170);
theDialog.setLocationRelativeTo(this);
theDialog.setVisible(true);
newFilterName = nameVect.elementAt(0);
if ((newFilterName == null)) { // cancel buton is clicked
return;
}
if (org.cytoscape.filter.internal.filters.util.FilterUtil
.isFilterNameDuplicated(filterPlugin, newFilterName)) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name already existed!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
break;
}// while loop
CompositeFilter newFilter = (CompositeFilter) theFilter.clone();
newFilter.setName(newFilterName);
Vector<CompositeFilter> allFilterVect = filterPlugin.getAllFilterVect();
allFilterVect.add(newFilter);
FilterSettingPanel newFilterSettingPanel = new FilterSettingPanel(this, newFilter, applicationManager, filterPlugin, eventHelper);
filter2SettingPanelMap.put(newFilter, newFilterSettingPanel);
// set the new filter in the combobox selected
cmbSelectFilter.setSelectedItem(newFilter);
}
private void renameFilter(){
CompositeFilter theFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
String oldFilterName = theFilter.getName();
String newFilterName = "";
while (true) {
Vector<String> nameVect = new Vector<String>();
nameVect.add(oldFilterName);
EditNameDialog theDialog = new EditNameDialog("Edit Filter Name", "Please enter a new Filter name:", nameVect, 300,170);
theDialog.setLocationRelativeTo(this);
theDialog.setVisible(true);
newFilterName = nameVect.elementAt(0);
if ((newFilterName == null) || newFilterName.trim().equals("")
||newFilterName.equals(oldFilterName)) {
return;
}
if (org.cytoscape.filter.internal.filters.util.FilterUtil
.isFilterNameDuplicated(filterPlugin, newFilterName)) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name already existed!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
break;
}// while loop
theFilter.setName(newFilterName);
cmbSelectFilter.setSelectedItem(theFilter);
refreshFilterSelectCMB();
}
private void deleteFilter(CompositeFilter pFilter) {
filter2SettingPanelMap.remove(pFilter);
cmbSelectFilter.removeItem(pFilter);
Vector<CompositeFilter> allFilterVect = filterPlugin.getAllFilterVect();
if (allFilterVect == null || allFilterVect.size() == 0) {
replaceFilterSettingPanel(null);
}
this.validate();
this.repaint();
}
private void createNewFilter(String pFilterName, String pFilterType) {
// Create an empty filter, add it to the current filter list
CompositeFilter newFilter = null;
if (pFilterType.equalsIgnoreCase("Topology")) {
newFilter = new TopologyFilter(applicationManager);
newFilter.getAdvancedSetting().setEdge(false);
newFilter.setName(pFilterName);
}
else if (pFilterType.equalsIgnoreCase("NodeInteraction")) {
newFilter = new NodeInteractionFilter(applicationManager);
//newFilter.getAdvancedSetting().setEdge(false);
newFilter.setName(pFilterName);
}
else if (pFilterType.equalsIgnoreCase("EdgeInteraction")) {
newFilter = new EdgeInteractionFilter(applicationManager);
//newFilter.getAdvancedSetting().setEdge(false);
newFilter.setName(pFilterName);
}
else {
newFilter = new CompositeFilter(pFilterName);
}
newFilter.setNetwork(applicationManager.getCurrentNetwork());
Vector<CompositeFilter> allFilterVect = filterPlugin.getAllFilterVect();
allFilterVect.add(newFilter);
FilterSettingPanel newFilterSettingPanel = new FilterSettingPanel(this, newFilter, applicationManager, filterPlugin, eventHelper);
filter2SettingPanelMap.put(newFilter, newFilterSettingPanel);
// set the new filter in the combobox selected
cmbSelectFilter.setSelectedItem(newFilter);
refreshFilterSelectCMB();
if (pFilterType.equalsIgnoreCase("Composite")) {
updateCMBAttributes();
}
}
@Override
public void handleEvent(final NetworkViewAddedEvent e) {
if (!isShowing())
return;
updateIndex();
}
class AttributeFilterRenderer extends JLabel implements ListCellRenderer {
/**
*
*/
private static final long serialVersionUID = -9137647911856857211L;
public AttributeFilterRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) {
if (value instanceof String) {
setText((String)value);
}
else if (value instanceof CompositeFilter) {
CompositeFilter theFilter = (CompositeFilter) value;
setText(theFilter.getName());
}
}
else { // value == null
setText("");
}
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}// AttributeRenderer
class FilterRenderer extends JLabel implements ListCellRenderer {
private static final long serialVersionUID = -2396393425644165756L;
public FilterRenderer() {
setOpaque(true);
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus) {
if (value != null) {
CompositeFilter theFilter = (CompositeFilter) value;
setText(theFilter.getLabel());
}
else { // value == null
setText("");
}
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
return this;
}
}// FilterRenderer
class FilterSelectWidestStringComboBoxModel extends WidestStringComboBoxModel {
private static final long serialVersionUID = -1311538859326314189L;
public FilterSelectWidestStringComboBoxModel() {
super();
}
public FilterSelectWidestStringComboBoxModel(Object[] items) {
super(items);
}
public FilterSelectWidestStringComboBoxModel(Vector<?> v) {
super(v);
}
@Override
protected String getLabel(Object anObject) {
return (anObject != null) ? ((CompositeFilter)anObject).getLabel() : "";
}
}
class AttributeSelectWidestStringComboBoxModel extends WidestStringComboBoxModel {
private static final long serialVersionUID = -7287008568486671513L;
public AttributeSelectWidestStringComboBoxModel() {
super();
}
public AttributeSelectWidestStringComboBoxModel(Object[] items) {
super(items);
}
public AttributeSelectWidestStringComboBoxModel(Vector<?> v) {
super(v);
}
@Override
protected String getLabel(Object anObject) {
String rv = "";
if (anObject != null) {
if (anObject instanceof CompositeFilter) {
rv = ((CompositeFilter)anObject).getLabel();
}
else {
rv = anObject.toString();
}
}
return rv;
}
}
}
| false | true | public void actionPerformed(ActionEvent e) {
Object _actionObject = e.getSource();
// handle Button events
if (_actionObject instanceof JButton) {
JButton _btn = (JButton) _actionObject;
if (_btn == btnApplyFilter) {
//System.out.println("\nApplyButton is clicked!");
//System.out.println("\tThe Filter to apply is \n" + cmbSelectFilter.getSelectedItem().toString()+"\n");
CompositeFilter theFilterToApply = (CompositeFilter) cmbSelectFilter.getSelectedItem();
theFilterToApply.setNetwork(applicationManager.getCurrentNetwork());
FilterUtil.doSelection(theFilterToApply, applicationManager);
}
if (_btn == btnAddFilterWidget) {
//btnAddFilterWidget is clicked!
CompositeFilter selectedFilter = (CompositeFilter) cmbSelectFilter.getSelectedItem();
FilterSettingPanel theSettingPanel = filter2SettingPanelMap.get(selectedFilter);
if (cmbAttributes.getSelectedItem() instanceof String) {
String selectItem = (String) cmbAttributes.getSelectedItem();
if (selectItem.equalsIgnoreCase(filtersSeperator) ||selectItem.equalsIgnoreCase(attributesSeperator)) {
return;
}
}
String attributeType = cmbAttributes.getSelectedItem().toString().substring(0,4);// "node" or "edge"
String attributeName = cmbAttributes.getSelectedItem().toString().substring(5);
if(CyAttributesUtil.isNullAttribute(applicationManager.getCurrentNetwork(), attributeType, attributeName)){
JOptionPane.showMessageDialog(this, "All the values for this attribute are NULL!", "Can not create filter", JOptionPane.ERROR_MESSAGE);
}
else {
theSettingPanel.addNewWidget(cmbAttributes.getSelectedItem());
}
}
if (_btn == btnSelectAll){
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
SelectUtil.selectAllNodes(cyNetwork);
SelectUtil.selectAllEdges(cyNetwork);
}
if (_btn == btnDeSelect){
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
SelectUtil.unselectAllNodes(cyNetwork);
SelectUtil.unselectAllEdges(cyNetwork);
}
} // JButton event
if (_actionObject instanceof JMenuItem) {
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
JMenuItem _menuItem = (JMenuItem) _actionObject;
if (_menuItem == newFilterMenuItem || _menuItem == newTopologyFilterMenuItem
|| _menuItem == newNodeInteractionFilterMenuItem || _menuItem == newEdgeInteractionFilterMenuItem) {
String filterType = "Composite";
//boolean isTopoFilter = false;
//boolean isInteractionFilter = false;
if (_menuItem == newTopologyFilterMenuItem) {
filterType = "Topology";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
if (_menuItem == newNodeInteractionFilterMenuItem) {
filterType = "NodeInteraction";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
if (_menuItem == newEdgeInteractionFilterMenuItem) {
filterType = "EdgeInteraction";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
String newFilterName = "";
while (true) {
newFilterName = JOptionPane.showInputDialog(
this, "New filter name", "New Filter Name",
JOptionPane.INFORMATION_MESSAGE);
if (newFilterName == null) { // user clicked "cancel"
break;
}
if (newFilterName.trim().equals("")) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name is empty!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
if (org.cytoscape.filter.internal.filters.util.FilterUtil
.isFilterNameDuplicated(filterPlugin, newFilterName)) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name already existed!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
break;
}// while loop
if ((newFilterName != null)
&& (!newFilterName.trim().equals(""))) {
createNewFilter(newFilterName, filterType);
//System.out.println("FilterMainPanel.firePropertyChange() -- NEW_FILTER_CREATED");
//pcs.firePropertyChange("NEW_FILTER_CREATED", "", "");
// // TODO: Port this
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "NEW_FILTER_CREATED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
}
} else if (_menuItem == deleteFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
Object[] options = { "YES", "CANCEL" };
int userChoice = JOptionPane.showOptionDialog(this,
"Are you sure you want to delete " + theSelectedFilter.getName()
+ "?", "Warning", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (userChoice == 1) { // user clicked CANCEL
return;
}
deleteFilter(theSelectedFilter);
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_DELETED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
} else if (_menuItem == renameFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
renameFilter();
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_RENAMED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
} else if (_menuItem == duplicateFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
duplicateFilter();
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_DUPLICATED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
}
} // JMenuItem event
updateInteractionMenuItemStatus();
updateView();
}
| public void actionPerformed(ActionEvent e) {
Object _actionObject = e.getSource();
// handle Button events
if (_actionObject instanceof JButton) {
JButton _btn = (JButton) _actionObject;
if (_btn == btnApplyFilter) {
CompositeFilter theFilterToApply = (CompositeFilter) cmbSelectFilter.getSelectedItem();
final CyNetwork currentNetwork = applicationManager.getCurrentNetwork();
if (currentNetwork == null)
return;
theFilterToApply.setNetwork(currentNetwork);
FilterUtil.doSelection(theFilterToApply, applicationManager);
}
if (_btn == btnAddFilterWidget) {
//btnAddFilterWidget is clicked!
CompositeFilter selectedFilter = (CompositeFilter) cmbSelectFilter.getSelectedItem();
FilterSettingPanel theSettingPanel = filter2SettingPanelMap.get(selectedFilter);
if (cmbAttributes.getSelectedItem() instanceof String) {
String selectItem = (String) cmbAttributes.getSelectedItem();
if (selectItem.equalsIgnoreCase(filtersSeperator) ||selectItem.equalsIgnoreCase(attributesSeperator)) {
return;
}
}
String attributeType = cmbAttributes.getSelectedItem().toString().substring(0,4);// "node" or "edge"
String attributeName = cmbAttributes.getSelectedItem().toString().substring(5);
if(CyAttributesUtil.isNullAttribute(applicationManager.getCurrentNetwork(), attributeType, attributeName)){
JOptionPane.showMessageDialog(this, "All the values for this attribute are NULL!", "Can not create filter", JOptionPane.ERROR_MESSAGE);
}
else {
theSettingPanel.addNewWidget(cmbAttributes.getSelectedItem());
}
}
if (_btn == btnSelectAll){
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
SelectUtil.selectAllNodes(cyNetwork);
SelectUtil.selectAllEdges(cyNetwork);
}
if (_btn == btnDeSelect){
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
SelectUtil.unselectAllNodes(cyNetwork);
SelectUtil.unselectAllEdges(cyNetwork);
}
} // JButton event
if (_actionObject instanceof JMenuItem) {
CyNetwork cyNetwork = applicationManager.getCurrentNetwork();
JMenuItem _menuItem = (JMenuItem) _actionObject;
if (_menuItem == newFilterMenuItem || _menuItem == newTopologyFilterMenuItem
|| _menuItem == newNodeInteractionFilterMenuItem || _menuItem == newEdgeInteractionFilterMenuItem) {
String filterType = "Composite";
//boolean isTopoFilter = false;
//boolean isInteractionFilter = false;
if (_menuItem == newTopologyFilterMenuItem) {
filterType = "Topology";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
if (_menuItem == newNodeInteractionFilterMenuItem) {
filterType = "NodeInteraction";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
if (_menuItem == newEdgeInteractionFilterMenuItem) {
filterType = "EdgeInteraction";
if (cyNetwork != null) {
SelectUtil.unselectAllNodes(cyNetwork);
}
}
String newFilterName = "";
while (true) {
newFilterName = JOptionPane.showInputDialog(
this, "New filter name", "New Filter Name",
JOptionPane.INFORMATION_MESSAGE);
if (newFilterName == null) { // user clicked "cancel"
break;
}
if (newFilterName.trim().equals("")) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name is empty!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
if (org.cytoscape.filter.internal.filters.util.FilterUtil
.isFilterNameDuplicated(filterPlugin, newFilterName)) {
Object[] options = { "OK" };
JOptionPane.showOptionDialog(this,
"Filter name already existed!", "Warning",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options,
options[0]);
continue;
}
break;
}// while loop
if ((newFilterName != null)
&& (!newFilterName.trim().equals(""))) {
createNewFilter(newFilterName, filterType);
//System.out.println("FilterMainPanel.firePropertyChange() -- NEW_FILTER_CREATED");
//pcs.firePropertyChange("NEW_FILTER_CREATED", "", "");
// // TODO: Port this
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "NEW_FILTER_CREATED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
}
} else if (_menuItem == deleteFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
Object[] options = { "YES", "CANCEL" };
int userChoice = JOptionPane.showOptionDialog(this,
"Are you sure you want to delete " + theSelectedFilter.getName()
+ "?", "Warning", JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[0]);
if (userChoice == 1) { // user clicked CANCEL
return;
}
deleteFilter(theSelectedFilter);
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_DELETED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
} else if (_menuItem == renameFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
renameFilter();
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_RENAMED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
} else if (_menuItem == duplicateFilterMenuItem) {
CompositeFilter theSelectedFilter = (CompositeFilter)cmbSelectFilter.getSelectedItem();
if (theSelectedFilter == null) {
return;
}
duplicateFilter();
// // TODO: Port this? No one listens for these events
// if (FilterPlugin.shouldFireFilterEvent) {
// PropertyChangeEvent evt = new PropertyChangeEvent(this, "FILTER_DUPLICATED", null, null);
// Cytoscape.getPropertyChangeSupport().firePropertyChange(evt);
// }
}
} // JMenuItem event
updateInteractionMenuItemStatus();
updateView();
}
|
diff --git a/src/org/cvstoolbox/filter/Filters.java b/src/org/cvstoolbox/filter/Filters.java
index 67dd840..260bf70 100644
--- a/src/org/cvstoolbox/filter/Filters.java
+++ b/src/org/cvstoolbox/filter/Filters.java
@@ -1,64 +1,64 @@
/*
* CVSToolBox IntelliJ IDEA Plugin
*
* Copyright (C) 2011, Łukasz Zieliński
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This plugin uses
* FAMFAMFAM Silk Icons http://www.famfamfam.com/lab/icons/silk
*/
package org.cvstoolbox.filter;
import com.intellij.cvsSupport2.CvsUtil;
import com.intellij.cvsSupport2.util.CvsVfsUtil;
import com.intellij.openapi.vcs.FilePath;
import com.intellij.openapi.vfs.VirtualFile;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
* @author Łukasz Zieliński
*/
public class Filters {
public static FilePath[] pruneLocallyAdded(FilePath[] toPrune) {
List<FilePath> paths = new ArrayList<FilePath>(Arrays.asList(toPrune));
List<FilePath> toRemove = new ArrayList<FilePath>(paths.size());
for (FilePath path : paths) {
if (CvsUtil.fileIsLocallyAdded(path.getIOFile())) {
toRemove.add(path);
}
}
paths.removeAll(toRemove);
return paths.toArray(new FilePath[paths.size()]);
}
public static VirtualFile[] pruneEmptyDirectories(VirtualFile[] toPrune) {
return pruneEmptyDirectories(Arrays.asList(toPrune));
}
public static VirtualFile[] pruneEmptyDirectories(Collection<VirtualFile> toPrune) {
List<VirtualFile> files = new ArrayList<VirtualFile>(toPrune);
List<VirtualFile> toRemove = new ArrayList<VirtualFile>(files.size());
for (VirtualFile file : files) {
- if (file.isDirectory() && file.getChildren().length == 1 &&
- file.getChildren()[0].getName().equals(CvsUtil.CVS)) {
+ if (file.isDirectory() && file.getChildren().length == 1 && file.getChildren()[0].isDirectory() &&
+ CvsUtil.CVS.equals(file.getChildren()[0].getName())) {
toRemove.add(file);
}
}
files.removeAll(toRemove);
return files.toArray(new VirtualFile[files.size()]);
}
}
| true | true | public static VirtualFile[] pruneEmptyDirectories(Collection<VirtualFile> toPrune) {
List<VirtualFile> files = new ArrayList<VirtualFile>(toPrune);
List<VirtualFile> toRemove = new ArrayList<VirtualFile>(files.size());
for (VirtualFile file : files) {
if (file.isDirectory() && file.getChildren().length == 1 &&
file.getChildren()[0].getName().equals(CvsUtil.CVS)) {
toRemove.add(file);
}
}
files.removeAll(toRemove);
return files.toArray(new VirtualFile[files.size()]);
}
| public static VirtualFile[] pruneEmptyDirectories(Collection<VirtualFile> toPrune) {
List<VirtualFile> files = new ArrayList<VirtualFile>(toPrune);
List<VirtualFile> toRemove = new ArrayList<VirtualFile>(files.size());
for (VirtualFile file : files) {
if (file.isDirectory() && file.getChildren().length == 1 && file.getChildren()[0].isDirectory() &&
CvsUtil.CVS.equals(file.getChildren()[0].getName())) {
toRemove.add(file);
}
}
files.removeAll(toRemove);
return files.toArray(new VirtualFile[files.size()]);
}
|
diff --git a/app/com/huydung/utils/SelectorUtil.java b/app/com/huydung/utils/SelectorUtil.java
index daa5242..8ea3466 100644
--- a/app/com/huydung/utils/SelectorUtil.java
+++ b/app/com/huydung/utils/SelectorUtil.java
@@ -1,66 +1,66 @@
package com.huydung.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.TimeZone;
import java.util.TreeMap;
import com.huydung.helpers.DateFormatOption;
import com.huydung.helpers.TimeZoneOption;
public class SelectorUtil {
public static ArrayList<TimeZoneOption> getTimezones(){
Date d = new Date();
SimpleDateFormat dF = new SimpleDateFormat("HH:mm''");
String[] ids = TimeZone.getAvailableIDs();
final String TIMEZONE_ID_PREFIXES =
"^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
ArrayList<TimeZoneOption> timezones = new ArrayList<TimeZoneOption>();
for( String id : ids ){
if( id.matches(TIMEZONE_ID_PREFIXES) ){
TimeZone tz = TimeZone.getTimeZone(id);
dF.setTimeZone(tz);
- TimeZoneOption tzo = new TimeZoneOption(id, "(" + dF.format(d) + ") " + id);
+ TimeZoneOption tzo = new TimeZoneOption(id, dF.format(d) + "(" + id + ")");
timezones.add(tzo);
}
}
Collections.sort(timezones, new Comparator<TimeZoneOption>() {
@Override
public int compare(TimeZoneOption o1, TimeZoneOption o2) {
int result = o1.getLabel().compareTo(o2.getLabel());
if( result == 0 ){
result = o1.getId().compareTo(o2.getId());
}
return result;
}
});
return timezones;
}
public static ArrayList<DateFormatOption> getDateFormats(){
ArrayList<DateFormatOption> formats = new ArrayList<DateFormatOption>();
formats.add(new DateFormatOption("dd/MM/YYYY", "14/06/2011"));
formats.add(new DateFormatOption("MM/dd/YYYY", "06/14/2011"));
formats.add(new DateFormatOption("dd MMM, YYYY", "14 Jun, 2011"));
formats.add(new DateFormatOption("MMMMM dd, YYYY", "June 14, 2011"));
formats.add(new DateFormatOption("dd-MM-YYYY", "14-06-2011"));
formats.add(new DateFormatOption("MM-dd-YYYY", "06-14-2011"));
formats.add(new DateFormatOption("dd.MM.YYYY", "14.06.2011"));
formats.add(new DateFormatOption("MM.dd.YYYY", "06.14.2011"));
formats.add(new DateFormatOption("dd/MM", "14/06"));
formats.add(new DateFormatOption("MM/dd", "06/14"));
formats.add(new DateFormatOption("dd-MM", "14-06"));
formats.add(new DateFormatOption("MM-dd", "06-14"));
formats.add(new DateFormatOption("dd.MM", "14.06"));
formats.add(new DateFormatOption("MM.dd", "06.14"));
return formats;
}
}
| true | true | public static ArrayList<TimeZoneOption> getTimezones(){
Date d = new Date();
SimpleDateFormat dF = new SimpleDateFormat("HH:mm''");
String[] ids = TimeZone.getAvailableIDs();
final String TIMEZONE_ID_PREFIXES =
"^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
ArrayList<TimeZoneOption> timezones = new ArrayList<TimeZoneOption>();
for( String id : ids ){
if( id.matches(TIMEZONE_ID_PREFIXES) ){
TimeZone tz = TimeZone.getTimeZone(id);
dF.setTimeZone(tz);
TimeZoneOption tzo = new TimeZoneOption(id, "(" + dF.format(d) + ") " + id);
timezones.add(tzo);
}
}
Collections.sort(timezones, new Comparator<TimeZoneOption>() {
@Override
public int compare(TimeZoneOption o1, TimeZoneOption o2) {
int result = o1.getLabel().compareTo(o2.getLabel());
if( result == 0 ){
result = o1.getId().compareTo(o2.getId());
}
return result;
}
});
return timezones;
}
| public static ArrayList<TimeZoneOption> getTimezones(){
Date d = new Date();
SimpleDateFormat dF = new SimpleDateFormat("HH:mm''");
String[] ids = TimeZone.getAvailableIDs();
final String TIMEZONE_ID_PREFIXES =
"^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.*";
ArrayList<TimeZoneOption> timezones = new ArrayList<TimeZoneOption>();
for( String id : ids ){
if( id.matches(TIMEZONE_ID_PREFIXES) ){
TimeZone tz = TimeZone.getTimeZone(id);
dF.setTimeZone(tz);
TimeZoneOption tzo = new TimeZoneOption(id, dF.format(d) + "(" + id + ")");
timezones.add(tzo);
}
}
Collections.sort(timezones, new Comparator<TimeZoneOption>() {
@Override
public int compare(TimeZoneOption o1, TimeZoneOption o2) {
int result = o1.getLabel().compareTo(o2.getLabel());
if( result == 0 ){
result = o1.getId().compareTo(o2.getId());
}
return result;
}
});
return timezones;
}
|
diff --git a/PastaHouse/src/printer/printables/PrintableInvoiceNew.java b/PastaHouse/src/printer/printables/PrintableInvoiceNew.java
index 3f85cb4..e409ed1 100644
--- a/PastaHouse/src/printer/printables/PrintableInvoiceNew.java
+++ b/PastaHouse/src/printer/printables/PrintableInvoiceNew.java
@@ -1,289 +1,289 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package printer.printables;
import database.extra.InvoiceItem;
import database.tables.Invoice;
import java.awt.Font;
import java.awt.FontMetrics;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import printer.adts.PrintableHorizontalLineObject;
import printer.adts.PrintableLine;
import printer.adts.PrintableMulti;
import printer.adts.PrintableNewline;
import printer.adts.PrintableString;
/**
*
* @author Warkst
*/
public class PrintableInvoiceNew extends MyPrintable{
/*
* Data model.
*/
private final Invoice model;
public PrintableInvoiceNew(Invoice model) {
super(new Font("Serif", Font.PLAIN, 12));
this.model = model;
}
@Override
public List<PrintableHorizontalLineObject> transformBody(int width, int margin, FontMetrics fontMetrics) {
/*
* Formatting variables
*/
int half = width/2;
width-=10; // small correction...
half-=5;
int[] tabs = new int[]{0, half, 3*width/5, 4*width/5, width};
/*
* Incremental print model
*/
List<PrintableHorizontalLineObject> printModel = new ArrayList<PrintableHorizontalLineObject>();
/*
* Actual transformation
* Start by printing header
*/
printModel.add(new PrintableLine(half, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> header = new ArrayList<PrintableHorizontalLineObject>();
header.add(new PrintableString("FACTUUR: "+model.getNumber(), half+3));
String dateString = "DATUM: "+model.getDate();
int dateAnchor = width - fontMetrics.charsWidth(dateString.toCharArray(), 0, dateString.length());
header.add(new PrintableString(dateString, dateAnchor-15));
printModel.add(new PrintableMulti(header));
printModel.add(new PrintableLine(half, width));
/*
* Print client information
*/
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableString(model.getClient().getContact(), half+3));
printModel.add(new PrintableNewline());
printModel.add(new PrintableString(model.getClient().getAddress(), half+3));
printModel.add(new PrintableNewline());
printModel.add(new PrintableString(model.getClient().getZipcode()+" "+model.getClient().getMunicipality(), half+3));
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableString(model.getClient().getTaxnumber(), half+3));
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
/*
* Print article header
*/
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> group = new ArrayList<PrintableHorizontalLineObject>();
group.add(new PrintableString("Omschrijving artikels", tabs[0]));
group.add(new PrintableString("BTW", tabs[1]));
group.add(new PrintableString("Hoeveelheid", tabs[2]));
group.add(new PrintableString("Prijs", tabs[3]));
group.add(new PrintableString("Totaal", tabs[4]-fontMetrics.charsWidth("Totaal".toCharArray(), 0, "Totaal".length())));
printModel.add(new PrintableMulti(group));
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
/*
* Print invoice articles (InvoiceItems)
*/
DecimalFormat threeFormatter = new DecimalFormat("0.000");
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols();
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.');
threeFormatter.setDecimalFormatSymbols(otherSymbols);
for (InvoiceItem invoiceItem : model.items()) {
/*
* Group per savings?
*/
ArrayList<PrintableHorizontalLineObject> ii = new ArrayList<PrintableHorizontalLineObject>();
ii.add(new PrintableString(invoiceItem.getArticle().getName(), tabs[0]));
ii.add(new PrintableString(""+(int)(invoiceItem.getArticle().getTaxes()), tabs[1]));
ii.add(new PrintableString(threeFormatter.format(invoiceItem.getAmount())+" "+invoiceItem.getArticle().getUnit(), tabs[2]));
ii.add(new PrintableString(threeFormatter.format(invoiceItem.getArticle().getPriceForCode(model.getPriceCode())), tabs[3]));
String tot = threeFormatter.format(invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount());
ii.add(new PrintableString(tot, tabs[4]-fontMetrics.charsWidth(tot.toCharArray(), 0, tot.length())));
printModel.add(new PrintableMulti(ii));
printModel.add(new PrintableNewline());
}
return printModel;
}
@Override
public List<PrintableHorizontalLineObject> transformFooter(int width, int margin, FontMetrics fontMetrics) {
width-=10;
/*
* Incremental print model
*/
List<PrintableHorizontalLineObject> printModel = new ArrayList<PrintableHorizontalLineObject>();
/*
* Formatting variables
*/
// int[] tabs = new int[]{0};
/*
* Actual transformation
* Print savings at bottom: set y from bottom upwards
* Group the invoice items per tax value
*/
Map<Double, List<InvoiceItem>> categories = new HashMap<Double, List<InvoiceItem>>();
for (InvoiceItem invoiceItem : model.items()) {
if (categories.containsKey(invoiceItem.getArticle().getTaxes())) {
categories.get(invoiceItem.getArticle().getTaxes()).add(invoiceItem);
} else {
List<InvoiceItem> items = new ArrayList<InvoiceItem>();
items.add(invoiceItem);
categories.put(invoiceItem.getArticle().getTaxes(), items);
}
}
int[] tabs = new int[categories.size()+3];
tabs[0] = margin;
int base = 30;
for (int i = 0; i < categories.size(); i++) {
- tabs[i+1] = margin + base + 30*(i+1);
+ tabs[i+1] = margin + 60*(i+1);
}
tabs[tabs.length-2] = 4*width/5;
tabs[tabs.length-1] = width;
if (model.getSave()>0) {
printModel.add(0, new PrintableNewline());
/*
* Print savings
*/
}
int threeZeroesWidth = fontMetrics.charsWidth("000".toCharArray(), 0 , 3);
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> savingsCategories = new ArrayList<PrintableHorizontalLineObject>();
savingsCategories.add(new PrintableString("BTW %", 0));
int index = 1;
for (Double savings : categories.keySet()) {
String printMe = savings+" %";
savingsCategories.add(new PrintableString(printMe, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(printMe.toCharArray(), 0, printMe.length()-4)));
index++;
}
printModel.add(new PrintableMulti(savingsCategories));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> prices = new ArrayList<PrintableHorizontalLineObject>();
prices.add(new PrintableString("Excl.", 0));
index = 1;
double pricesTot = 0.0;
for (List<InvoiceItem> list : categories.values()) {
double price = 0;
for (InvoiceItem invoiceItem : list) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
pricesTot+= price;
String pr = new DecimalFormat("0.000").format(price);
prices.add(new PrintableString(pr, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(pr.toCharArray(), 0, pr.length()-4)));
// prices.add(new PrintableString(pr, tabs[index]));
index++;
}
prices.add(new PrintableString("Tot. Excl.", tabs[tabs.length-2]));
String prTot = new DecimalFormat("0.000").format(pricesTot);
prices.add(new PrintableString(prTot, tabs[tabs.length-1]-fontMetrics.charsWidth(prTot.toCharArray(), 0, prTot.length())));
printModel.add(new PrintableMulti(prices));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> taxes = new ArrayList<PrintableHorizontalLineObject>();
taxes.add(new PrintableString("BTW", 0));
index = 1;
double taxesTot = 0.0;
for (Map.Entry<Double, List<InvoiceItem>> entry : categories.entrySet()) {
double price = 0;
for (InvoiceItem invoiceItem : entry.getValue()) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
double tax = price * entry.getKey()/100;
taxesTot+= tax;
String t = new DecimalFormat("0.000").format(tax);
taxes.add(new PrintableString(t, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(t.toCharArray(), 0, t.length()-4)));
// taxes.add(new PrintableString(t, tabs[index]));
index++;
}
taxes.add(new PrintableString("BTW", tabs[tabs.length-2]));
String tTot = new DecimalFormat("0.000").format(taxesTot);
taxes.add(new PrintableString(tTot, tabs[tabs.length-1]-fontMetrics.charsWidth(tTot.toCharArray(), 0, tTot.length())));
printModel.add(new PrintableMulti(taxes));
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> totals = new ArrayList<PrintableHorizontalLineObject>();
totals.add(new PrintableString("Totaal", 0));
double total = 0.0;
index = 1;
for (Map.Entry<Double, List<InvoiceItem>> entry : categories.entrySet()) {
double price = 0;
for (InvoiceItem invoiceItem : entry.getValue()) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
double tot = price * (1.0+entry.getKey()/100);
total+=tot;
String t = new DecimalFormat("0.00").format(tot);
totals.add(new PrintableString(t, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth((t+"0").toCharArray(), 0, t.length()-3)));
// totals.add(new PrintableString(t, tabs[index]));
index++;
}
totals.add(new PrintableString("TOTAAL", tabs[tabs.length-2]));
String tot = new DecimalFormat("0.00").format(total);
totals.add(new PrintableString(tot, tabs[tabs.length-1]-fontMetrics.charsWidth((tot+"0").toCharArray(), 0, tot.length()+1)));
printModel.add(new PrintableMulti(totals));
printModel.add(new PrintableLine(0, width));
/*
* Keep 7 white lines from the bottom
*/
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
return printModel;
}
}
| true | true | public List<PrintableHorizontalLineObject> transformFooter(int width, int margin, FontMetrics fontMetrics) {
width-=10;
/*
* Incremental print model
*/
List<PrintableHorizontalLineObject> printModel = new ArrayList<PrintableHorizontalLineObject>();
/*
* Formatting variables
*/
// int[] tabs = new int[]{0};
/*
* Actual transformation
* Print savings at bottom: set y from bottom upwards
* Group the invoice items per tax value
*/
Map<Double, List<InvoiceItem>> categories = new HashMap<Double, List<InvoiceItem>>();
for (InvoiceItem invoiceItem : model.items()) {
if (categories.containsKey(invoiceItem.getArticle().getTaxes())) {
categories.get(invoiceItem.getArticle().getTaxes()).add(invoiceItem);
} else {
List<InvoiceItem> items = new ArrayList<InvoiceItem>();
items.add(invoiceItem);
categories.put(invoiceItem.getArticle().getTaxes(), items);
}
}
int[] tabs = new int[categories.size()+3];
tabs[0] = margin;
int base = 30;
for (int i = 0; i < categories.size(); i++) {
tabs[i+1] = margin + base + 30*(i+1);
}
tabs[tabs.length-2] = 4*width/5;
tabs[tabs.length-1] = width;
if (model.getSave()>0) {
printModel.add(0, new PrintableNewline());
/*
* Print savings
*/
}
int threeZeroesWidth = fontMetrics.charsWidth("000".toCharArray(), 0 , 3);
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> savingsCategories = new ArrayList<PrintableHorizontalLineObject>();
savingsCategories.add(new PrintableString("BTW %", 0));
int index = 1;
for (Double savings : categories.keySet()) {
String printMe = savings+" %";
savingsCategories.add(new PrintableString(printMe, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(printMe.toCharArray(), 0, printMe.length()-4)));
index++;
}
printModel.add(new PrintableMulti(savingsCategories));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> prices = new ArrayList<PrintableHorizontalLineObject>();
prices.add(new PrintableString("Excl.", 0));
index = 1;
double pricesTot = 0.0;
for (List<InvoiceItem> list : categories.values()) {
double price = 0;
for (InvoiceItem invoiceItem : list) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
pricesTot+= price;
String pr = new DecimalFormat("0.000").format(price);
prices.add(new PrintableString(pr, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(pr.toCharArray(), 0, pr.length()-4)));
// prices.add(new PrintableString(pr, tabs[index]));
index++;
}
prices.add(new PrintableString("Tot. Excl.", tabs[tabs.length-2]));
String prTot = new DecimalFormat("0.000").format(pricesTot);
prices.add(new PrintableString(prTot, tabs[tabs.length-1]-fontMetrics.charsWidth(prTot.toCharArray(), 0, prTot.length())));
printModel.add(new PrintableMulti(prices));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> taxes = new ArrayList<PrintableHorizontalLineObject>();
taxes.add(new PrintableString("BTW", 0));
index = 1;
double taxesTot = 0.0;
for (Map.Entry<Double, List<InvoiceItem>> entry : categories.entrySet()) {
double price = 0;
for (InvoiceItem invoiceItem : entry.getValue()) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
double tax = price * entry.getKey()/100;
taxesTot+= tax;
String t = new DecimalFormat("0.000").format(tax);
taxes.add(new PrintableString(t, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(t.toCharArray(), 0, t.length()-4)));
// taxes.add(new PrintableString(t, tabs[index]));
index++;
}
taxes.add(new PrintableString("BTW", tabs[tabs.length-2]));
String tTot = new DecimalFormat("0.000").format(taxesTot);
taxes.add(new PrintableString(tTot, tabs[tabs.length-1]-fontMetrics.charsWidth(tTot.toCharArray(), 0, tTot.length())));
printModel.add(new PrintableMulti(taxes));
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> totals = new ArrayList<PrintableHorizontalLineObject>();
totals.add(new PrintableString("Totaal", 0));
double total = 0.0;
index = 1;
for (Map.Entry<Double, List<InvoiceItem>> entry : categories.entrySet()) {
double price = 0;
for (InvoiceItem invoiceItem : entry.getValue()) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
double tot = price * (1.0+entry.getKey()/100);
total+=tot;
String t = new DecimalFormat("0.00").format(tot);
totals.add(new PrintableString(t, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth((t+"0").toCharArray(), 0, t.length()-3)));
// totals.add(new PrintableString(t, tabs[index]));
index++;
}
totals.add(new PrintableString("TOTAAL", tabs[tabs.length-2]));
String tot = new DecimalFormat("0.00").format(total);
totals.add(new PrintableString(tot, tabs[tabs.length-1]-fontMetrics.charsWidth((tot+"0").toCharArray(), 0, tot.length()+1)));
printModel.add(new PrintableMulti(totals));
printModel.add(new PrintableLine(0, width));
/*
* Keep 7 white lines from the bottom
*/
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
return printModel;
}
| public List<PrintableHorizontalLineObject> transformFooter(int width, int margin, FontMetrics fontMetrics) {
width-=10;
/*
* Incremental print model
*/
List<PrintableHorizontalLineObject> printModel = new ArrayList<PrintableHorizontalLineObject>();
/*
* Formatting variables
*/
// int[] tabs = new int[]{0};
/*
* Actual transformation
* Print savings at bottom: set y from bottom upwards
* Group the invoice items per tax value
*/
Map<Double, List<InvoiceItem>> categories = new HashMap<Double, List<InvoiceItem>>();
for (InvoiceItem invoiceItem : model.items()) {
if (categories.containsKey(invoiceItem.getArticle().getTaxes())) {
categories.get(invoiceItem.getArticle().getTaxes()).add(invoiceItem);
} else {
List<InvoiceItem> items = new ArrayList<InvoiceItem>();
items.add(invoiceItem);
categories.put(invoiceItem.getArticle().getTaxes(), items);
}
}
int[] tabs = new int[categories.size()+3];
tabs[0] = margin;
int base = 30;
for (int i = 0; i < categories.size(); i++) {
tabs[i+1] = margin + 60*(i+1);
}
tabs[tabs.length-2] = 4*width/5;
tabs[tabs.length-1] = width;
if (model.getSave()>0) {
printModel.add(0, new PrintableNewline());
/*
* Print savings
*/
}
int threeZeroesWidth = fontMetrics.charsWidth("000".toCharArray(), 0 , 3);
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> savingsCategories = new ArrayList<PrintableHorizontalLineObject>();
savingsCategories.add(new PrintableString("BTW %", 0));
int index = 1;
for (Double savings : categories.keySet()) {
String printMe = savings+" %";
savingsCategories.add(new PrintableString(printMe, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(printMe.toCharArray(), 0, printMe.length()-4)));
index++;
}
printModel.add(new PrintableMulti(savingsCategories));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> prices = new ArrayList<PrintableHorizontalLineObject>();
prices.add(new PrintableString("Excl.", 0));
index = 1;
double pricesTot = 0.0;
for (List<InvoiceItem> list : categories.values()) {
double price = 0;
for (InvoiceItem invoiceItem : list) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
pricesTot+= price;
String pr = new DecimalFormat("0.000").format(price);
prices.add(new PrintableString(pr, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(pr.toCharArray(), 0, pr.length()-4)));
// prices.add(new PrintableString(pr, tabs[index]));
index++;
}
prices.add(new PrintableString("Tot. Excl.", tabs[tabs.length-2]));
String prTot = new DecimalFormat("0.000").format(pricesTot);
prices.add(new PrintableString(prTot, tabs[tabs.length-1]-fontMetrics.charsWidth(prTot.toCharArray(), 0, prTot.length())));
printModel.add(new PrintableMulti(prices));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> taxes = new ArrayList<PrintableHorizontalLineObject>();
taxes.add(new PrintableString("BTW", 0));
index = 1;
double taxesTot = 0.0;
for (Map.Entry<Double, List<InvoiceItem>> entry : categories.entrySet()) {
double price = 0;
for (InvoiceItem invoiceItem : entry.getValue()) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
double tax = price * entry.getKey()/100;
taxesTot+= tax;
String t = new DecimalFormat("0.000").format(tax);
taxes.add(new PrintableString(t, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth(t.toCharArray(), 0, t.length()-4)));
// taxes.add(new PrintableString(t, tabs[index]));
index++;
}
taxes.add(new PrintableString("BTW", tabs[tabs.length-2]));
String tTot = new DecimalFormat("0.000").format(taxesTot);
taxes.add(new PrintableString(tTot, tabs[tabs.length-1]-fontMetrics.charsWidth(tTot.toCharArray(), 0, tTot.length())));
printModel.add(new PrintableMulti(taxes));
printModel.add(new PrintableLine(0, width));
printModel.add(new PrintableNewline());
ArrayList<PrintableHorizontalLineObject> totals = new ArrayList<PrintableHorizontalLineObject>();
totals.add(new PrintableString("Totaal", 0));
double total = 0.0;
index = 1;
for (Map.Entry<Double, List<InvoiceItem>> entry : categories.entrySet()) {
double price = 0;
for (InvoiceItem invoiceItem : entry.getValue()) {
price += invoiceItem.getArticle().getPriceForCode(model.getPriceCode())*invoiceItem.getAmount();
}
double tot = price * (1.0+entry.getKey()/100);
total+=tot;
String t = new DecimalFormat("0.00").format(tot);
totals.add(new PrintableString(t, tabs[index]+threeZeroesWidth-fontMetrics.charsWidth((t+"0").toCharArray(), 0, t.length()-3)));
// totals.add(new PrintableString(t, tabs[index]));
index++;
}
totals.add(new PrintableString("TOTAAL", tabs[tabs.length-2]));
String tot = new DecimalFormat("0.00").format(total);
totals.add(new PrintableString(tot, tabs[tabs.length-1]-fontMetrics.charsWidth((tot+"0").toCharArray(), 0, tot.length()+1)));
printModel.add(new PrintableMulti(totals));
printModel.add(new PrintableLine(0, width));
/*
* Keep 7 white lines from the bottom
*/
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
printModel.add(new PrintableNewline());
return printModel;
}
|
diff --git a/src/org/ros/android/app_chooser/AppLauncher.java b/src/org/ros/android/app_chooser/AppLauncher.java
index 5a1e6cc..5441988 100644
--- a/src/org/ros/android/app_chooser/AppLauncher.java
+++ b/src/org/ros/android/app_chooser/AppLauncher.java
@@ -1,149 +1,149 @@
/*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, Inc.
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.ros.android.app_chooser;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import org.ros.message.app_manager.App;
import org.ros.message.app_manager.ClientApp;
import ros.android.activity.AppManager;
import android.net.Uri;
import java.util.ArrayList;
public class AppLauncher {
static private final String CLIENT_TYPE = "android";
/** Launch a client app for the given robot app. */
static public void launch(final Activity parentActivity, App app) {
ArrayList<ClientAppData> android_apps = new ArrayList<ClientAppData>();
if (parentActivity instanceof AppChooser) {
((AppChooser)parentActivity).onAppClicked(app, app.client_apps.size() > 0);
} else {
Log.i("RosAndroid", "Could not launch becase parent is not an appchooser");
if (app.client_apps.size() == 0) {
Log.e("RosAndroid", "Not launching application!!!");
return;
}
}
if (app.client_apps.size() == 0) {
return;
}
Log.i("RosAndroid", "launching robot app " + app.name + ". Found " + app.client_apps.size()
+ " client apps.");
// Loop over all possible client apps to find the android ones.
for (int i = 0; i < app.client_apps.size(); i++) {
ClientApp client_app = app.client_apps.get(i);
if (client_app.client_type != null && client_app.client_type.equals(CLIENT_TYPE)) {
android_apps.add(new ClientAppData(client_app));
}
}
Log.i("RosAndroid", "launching robot app " + app.name + ". Found " + android_apps.size()
+ " android apps.");
// TODO: filter out android apps which are not appropriate for
// this device by looking at specific entries in the manager_data_
// map of each app in android_apps.
ArrayList<ClientAppData> appropriateAndroidApps = android_apps;
// TODO: support multiple android apps
if (appropriateAndroidApps.size() != 1) {
AlertDialog.Builder dialog = new AlertDialog.Builder(parentActivity);
dialog.setTitle("Wrong Number of Android Apps");
dialog.setMessage("There are " + appropriateAndroidApps.size() + " valid android apps, not 1 as there should be.");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
dlog.dismiss();
}});
dialog.show();
return;
}
//TODO: this installs the last android app in the set.
String className = "";
// Loop over all android apps, trying to launch one.
for (int i = 0; i < appropriateAndroidApps.size(); i++) {
ClientAppData appData = appropriateAndroidApps.get(i);
Intent intent = appData.createIntent();
intent.putExtra(AppManager.PACKAGE + ".robot_app_name", app.name);
try {
className = intent.getAction();
Log.i("RosAndroid", "trying to startActivity( action: " + intent.getAction() + " )");
parentActivity.startActivity(intent);
return;
} catch (ActivityNotFoundException e) {
Log.i("RosAndroid", "activity not found for action: " + intent.getAction());
}
}
final String installPackage = className.substring(0, className.lastIndexOf("."));
Log.i("RosAndroid", "showing not-installed dialog.");
// TODO:
// Loop over all android apps, trying to install one. (??)
// For now, just show a failure dialog.
AlertDialog.Builder dialog = new AlertDialog.Builder(parentActivity);
dialog.setTitle("Android app not installed.");
dialog
.setMessage("This robot app requires a client user interface app, but none of the applicable android apps are installed. Would you like to install the app from the market place?");
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
- Uri uri = Uri.parse("market://search?q=pname:" + installPackage);
+ Uri uri = Uri.parse("market://details?id=" + installPackage);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
parentActivity.startActivity(intent);
}
});
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
dlog.dismiss();
}
});
dialog.show();
}
}
| true | true | static public void launch(final Activity parentActivity, App app) {
ArrayList<ClientAppData> android_apps = new ArrayList<ClientAppData>();
if (parentActivity instanceof AppChooser) {
((AppChooser)parentActivity).onAppClicked(app, app.client_apps.size() > 0);
} else {
Log.i("RosAndroid", "Could not launch becase parent is not an appchooser");
if (app.client_apps.size() == 0) {
Log.e("RosAndroid", "Not launching application!!!");
return;
}
}
if (app.client_apps.size() == 0) {
return;
}
Log.i("RosAndroid", "launching robot app " + app.name + ". Found " + app.client_apps.size()
+ " client apps.");
// Loop over all possible client apps to find the android ones.
for (int i = 0; i < app.client_apps.size(); i++) {
ClientApp client_app = app.client_apps.get(i);
if (client_app.client_type != null && client_app.client_type.equals(CLIENT_TYPE)) {
android_apps.add(new ClientAppData(client_app));
}
}
Log.i("RosAndroid", "launching robot app " + app.name + ". Found " + android_apps.size()
+ " android apps.");
// TODO: filter out android apps which are not appropriate for
// this device by looking at specific entries in the manager_data_
// map of each app in android_apps.
ArrayList<ClientAppData> appropriateAndroidApps = android_apps;
// TODO: support multiple android apps
if (appropriateAndroidApps.size() != 1) {
AlertDialog.Builder dialog = new AlertDialog.Builder(parentActivity);
dialog.setTitle("Wrong Number of Android Apps");
dialog.setMessage("There are " + appropriateAndroidApps.size() + " valid android apps, not 1 as there should be.");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
dlog.dismiss();
}});
dialog.show();
return;
}
//TODO: this installs the last android app in the set.
String className = "";
// Loop over all android apps, trying to launch one.
for (int i = 0; i < appropriateAndroidApps.size(); i++) {
ClientAppData appData = appropriateAndroidApps.get(i);
Intent intent = appData.createIntent();
intent.putExtra(AppManager.PACKAGE + ".robot_app_name", app.name);
try {
className = intent.getAction();
Log.i("RosAndroid", "trying to startActivity( action: " + intent.getAction() + " )");
parentActivity.startActivity(intent);
return;
} catch (ActivityNotFoundException e) {
Log.i("RosAndroid", "activity not found for action: " + intent.getAction());
}
}
final String installPackage = className.substring(0, className.lastIndexOf("."));
Log.i("RosAndroid", "showing not-installed dialog.");
// TODO:
// Loop over all android apps, trying to install one. (??)
// For now, just show a failure dialog.
AlertDialog.Builder dialog = new AlertDialog.Builder(parentActivity);
dialog.setTitle("Android app not installed.");
dialog
.setMessage("This robot app requires a client user interface app, but none of the applicable android apps are installed. Would you like to install the app from the market place?");
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
Uri uri = Uri.parse("market://search?q=pname:" + installPackage);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
parentActivity.startActivity(intent);
}
});
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
dlog.dismiss();
}
});
dialog.show();
}
| static public void launch(final Activity parentActivity, App app) {
ArrayList<ClientAppData> android_apps = new ArrayList<ClientAppData>();
if (parentActivity instanceof AppChooser) {
((AppChooser)parentActivity).onAppClicked(app, app.client_apps.size() > 0);
} else {
Log.i("RosAndroid", "Could not launch becase parent is not an appchooser");
if (app.client_apps.size() == 0) {
Log.e("RosAndroid", "Not launching application!!!");
return;
}
}
if (app.client_apps.size() == 0) {
return;
}
Log.i("RosAndroid", "launching robot app " + app.name + ". Found " + app.client_apps.size()
+ " client apps.");
// Loop over all possible client apps to find the android ones.
for (int i = 0; i < app.client_apps.size(); i++) {
ClientApp client_app = app.client_apps.get(i);
if (client_app.client_type != null && client_app.client_type.equals(CLIENT_TYPE)) {
android_apps.add(new ClientAppData(client_app));
}
}
Log.i("RosAndroid", "launching robot app " + app.name + ". Found " + android_apps.size()
+ " android apps.");
// TODO: filter out android apps which are not appropriate for
// this device by looking at specific entries in the manager_data_
// map of each app in android_apps.
ArrayList<ClientAppData> appropriateAndroidApps = android_apps;
// TODO: support multiple android apps
if (appropriateAndroidApps.size() != 1) {
AlertDialog.Builder dialog = new AlertDialog.Builder(parentActivity);
dialog.setTitle("Wrong Number of Android Apps");
dialog.setMessage("There are " + appropriateAndroidApps.size() + " valid android apps, not 1 as there should be.");
dialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
dlog.dismiss();
}});
dialog.show();
return;
}
//TODO: this installs the last android app in the set.
String className = "";
// Loop over all android apps, trying to launch one.
for (int i = 0; i < appropriateAndroidApps.size(); i++) {
ClientAppData appData = appropriateAndroidApps.get(i);
Intent intent = appData.createIntent();
intent.putExtra(AppManager.PACKAGE + ".robot_app_name", app.name);
try {
className = intent.getAction();
Log.i("RosAndroid", "trying to startActivity( action: " + intent.getAction() + " )");
parentActivity.startActivity(intent);
return;
} catch (ActivityNotFoundException e) {
Log.i("RosAndroid", "activity not found for action: " + intent.getAction());
}
}
final String installPackage = className.substring(0, className.lastIndexOf("."));
Log.i("RosAndroid", "showing not-installed dialog.");
// TODO:
// Loop over all android apps, trying to install one. (??)
// For now, just show a failure dialog.
AlertDialog.Builder dialog = new AlertDialog.Builder(parentActivity);
dialog.setTitle("Android app not installed.");
dialog
.setMessage("This robot app requires a client user interface app, but none of the applicable android apps are installed. Would you like to install the app from the market place?");
dialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
Uri uri = Uri.parse("market://details?id=" + installPackage);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
parentActivity.startActivity(intent);
}
});
dialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dlog, int i) {
dlog.dismiss();
}
});
dialog.show();
}
|
diff --git a/RandomForest/src/tree/Forest.java b/RandomForest/src/tree/Forest.java
index f69e2cc..28a7464 100644
--- a/RandomForest/src/tree/Forest.java
+++ b/RandomForest/src/tree/Forest.java
@@ -1,935 +1,936 @@
/**
*
*/
package tree;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.apache.commons.math3.linear.RealMatrix;
import org.apache.commons.math3.stat.correlation.PearsonsCorrelation;
/**
* @author Simon Bull
*
*/
public class Forest
{
/**
* A list of the trees in the forest.
*/
public List<CARTTree> forest = new ArrayList<CARTTree>();
/**
* A list where the ith element corresponds to the ith tree. The ith element of the list records
* all observations that are oob on the ith tree.
*/
public List<List<Integer>> oobObservations = new ArrayList<List<Integer>>();
/**
* The oob error estimate.
*/
public double oobErrorEstimate = 0.0;
/**
* The oob confusion matrix.
*/
public Map<String, Map<String, Double>> oobConfusionMatrix = new HashMap<String, Map<String, Double>>();
/**
* The file containing the data that the forest was grown from.
*/
public String dataFileGrownFrom = "";
/**
* The object recording the control parameters for the forest and its trees.
*/
public TreeGrowthControl ctrl;
/**
*
*/
public ProcessDataForGrowing processedData;
public Map<String, Double> weights = new HashMap<String, Double>();
public long seed;
public Forest(String dataForGrowing)
{
this.ctrl = new TreeGrowthControl();
this.seed = System.currentTimeMillis();
growForest(dataForGrowing, new HashMap<String, Double>());
}
public Forest(String dataForGrowing, Boolean isLoadingSavedPerformed)
{
if (!isLoadingSavedPerformed)
{
this.ctrl = new TreeGrowthControl();
this.seed = System.currentTimeMillis();
growForest(dataForGrowing, new HashMap<String, Double>());
}
else
{
// Loading from a saved forest.
// Load the control object.
String controllerLoadLocation = dataForGrowing + "/Controller.txt";
this.ctrl = new TreeGrowthControl(controllerLoadLocation);
// Load the processed data.
String processedDataLoadLocation = dataForGrowing + "/ProcessedData.txt";
this.processedData = new ProcessDataForGrowing(processedDataLoadLocation);
// Load the other forest attributes.
String attributeLoadLocation = dataForGrowing + "/Attributes.txt";
try (BufferedReader reader = Files.newBufferedReader(Paths.get(attributeLoadLocation), StandardCharsets.UTF_8))
{
String line = reader.readLine();
line.trim();
String[] splitLine = line.split("\t");
String[] oobSplits = splitLine[0].split(";");
for (String s : oobSplits)
{
List<Integer> currentOobs = new ArrayList<Integer>();
for (String p : s.split(","))
{
currentOobs.add(Integer.parseInt(p));
}
this.oobObservations.add(currentOobs);
}
this.oobErrorEstimate = Double.parseDouble(splitLine[1]);
String[] confMatSplits = splitLine[2].split("#");
for (String s : confMatSplits)
{
String[] subMapSplit = s.split("-");
String topLevelKey = subMapSplit[0];
this.oobConfusionMatrix.put(topLevelKey, new HashMap<String, Double>());
String[] subDirSplit = subMapSplit[1].split(";");
for (String p : subDirSplit)
{
String[] indivValues = p.split(",");
this.oobConfusionMatrix.get(topLevelKey).put(indivValues[0], Double.parseDouble(indivValues[1]));
}
}
this.dataFileGrownFrom = splitLine[3];
String[] weightSplits = splitLine[4].split(";");
for (String s : weightSplits)
{
String[] indivWeights = s.split(",");
this.weights.put(indivWeights[0], Double.parseDouble(indivWeights[1]));
}
this.seed = Long.parseLong(splitLine[5]);
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
// Load the trees.
Map<Integer, CARTTree> orderedForest = new HashMap<Integer, CARTTree>();
File forestDirectory = new File(dataForGrowing);
for (String s : forestDirectory.list())
{
if (!s.contains(".txt"))
{
// If the location is not a text file, and therefore contains the information about a tree.
String treeLoadLocation = dataForGrowing + "/" + s;
orderedForest.put(Integer.parseInt(s), new CARTTree(treeLoadLocation));
}
}
for (int i = 0; i < orderedForest.size(); i++)
{
this.forest.add(orderedForest.get(i));
}
}
}
public Forest(String dataForGrowing, TreeGrowthControl ctrl)
{
this.ctrl = ctrl;
this.seed = System.currentTimeMillis();
growForest(dataForGrowing, new HashMap<String, Double>());
}
public Forest(ProcessDataForGrowing procData, TreeGrowthControl ctrl)
{
this.ctrl = ctrl;
this.processedData = procData;
this.dataFileGrownFrom = procData.dataFileGrownFrom;
growForest(this.dataFileGrownFrom, new HashMap<String, Double>(), false);
}
public Forest(String dataForGrowing, Map<String, Double> weights)
{
this.ctrl = new TreeGrowthControl();
this.seed = System.currentTimeMillis();
growForest(dataForGrowing, weights);
}
public Forest(String dataForGrowing, TreeGrowthControl ctrl, Map<String, Double> weights)
{
this.ctrl = ctrl;
this.seed = System.currentTimeMillis();
growForest(dataForGrowing, weights);
}
public Forest(ProcessDataForGrowing procData, TreeGrowthControl ctrl, Map<String, Double> weights)
{
this.ctrl = ctrl;
this.processedData = procData;
this.dataFileGrownFrom = procData.dataFileGrownFrom;
growForest(this.dataFileGrownFrom, weights, false);
}
public Forest(String dataForGrowing, TreeGrowthControl ctrl, Map<String, Double> weights, Long seed)
{
this.ctrl = ctrl;
this.seed = seed;
growForest(dataForGrowing, weights);
}
public Map<Integer, Map<Integer, Double>> calculatProximities()
{
return calculatProximities(this.processedData);
}
public Map<Integer, Map<Integer, Double>> calculatProximities(ProcessDataForGrowing procData)
{
Map<Integer, Map<Integer, Double>> proximities = new HashMap<Integer, Map<Integer, Double>>();
for (int i = 0; i < procData.numberObservations; i++)
{
// Add a record of all the observations to the proximities.
proximities.put(i, new HashMap<Integer, Double>());
}
for (CARTTree t : this.forest)
{
List<List<Integer>> treeProximities = t.getProximities(procData); // Get the proximities for the tree.
for (List<Integer> l : treeProximities)
{
Collections.sort(l); // Sort the list of observation indices so that you only have to keep half the matrix.
for (int i = 0; i < l.size(); i++)
{
Integer obsI = l.get(i);
for (int j = i + 1; j < l.size(); j++)
{
Integer obsJ = l.get(j);
// Go through all pairs of observation indices that ended up in the same terminal node.
if (!proximities.get(obsI).containsKey(obsJ))
{
// If obsI and obsJ have never occurred in the same terminal node before.
proximities.get(obsI).put(obsJ, 1.0);
}
else
{
Double oldProximityCount = proximities.get(obsI).get(obsJ);
proximities.get(obsI).put(obsJ, oldProximityCount + 1.0);
}
}
}
}
}
// Normalise the proximites by the number of trees.
for (Integer i : proximities.keySet())
{
for (Integer j : proximities.get(i).keySet())
{
Double oldProximityCount = proximities.get(i).get(j);
proximities.get(i).put(j, oldProximityCount / this.forest.size());
}
}
return proximities;
}
public Map<Integer, Map<Integer, Double>> calculatProximities(String outputLocation)
{
return calculatProximities(this.processedData, outputLocation);
}
public Map<Integer, Map<Integer, Double>> calculatProximities(ProcessDataForGrowing procData, String outputLocation)
{
try
{
FileWriter proxOutputFile = new FileWriter(outputLocation, true);
BufferedWriter proxOutputWriter = new BufferedWriter(proxOutputFile);
for (CARTTree t : this.forest)
{
String treeProxString = "";
List<List<Integer>> treeProximities = t.getProximities(procData); // Get the proximities for the tree.
for (List<Integer> l : treeProximities)
{
for (Integer i : l)
{
treeProxString += Integer.toString(i) + ",";
}
treeProxString = treeProxString.substring(0, treeProxString.length() - 1);
treeProxString += "\t";
}
treeProxString = treeProxString.substring(0, treeProxString.length() - 1);
proxOutputWriter.write(treeProxString);
proxOutputWriter.newLine();
}
proxOutputWriter.close();
}
catch (Exception e)
{
e.printStackTrace();
System.exit(0);
}
return null;
}
public Map<String, Double> condVariableImportance()
{
return this.condVariableImportance(0.2);
}
public Map<String, Double> condVariableImportance(double maxCorrelation)
{
Map<String, Double> variableImportance = new HashMap<String, Double>();
// Determine correlations.
double[][] datasetArrays = new double[this.processedData.numberObservations][this.processedData.covariableData.size()];
List<String> covariableOrdering = new ArrayList<String>(this.processedData.covariableData.keySet());
for (int i = 0; i < covariableOrdering.size(); i++)
{
for (int j = 0; j < this.processedData.numberObservations; j++)
{
datasetArrays[j][i] = this.processedData.covariableData.get(covariableOrdering.get(i)).get(j);
}
}
PearsonsCorrelation correlationMatrix = new PearsonsCorrelation(datasetArrays);
RealMatrix correlations = correlationMatrix.getCorrelationMatrix();
Map<String, List<String>> correlatedVariables = new HashMap<String, List<String>>();
for (int i = 0; i < covariableOrdering.size(); i++)
{
String covariable = covariableOrdering.get(i);
List<String> toSimilarToI = new ArrayList<String>();
for (int j = 0; j < covariableOrdering.size(); j++)
{
if (i == j)
{
continue;
}
double correlationIJ = correlations.getEntry(i, j);
if (Math.abs(correlationIJ) >= maxCorrelation)
{
String covarJ = covariableOrdering.get(j);
toSimilarToI.add(covarJ);
}
}
correlatedVariables.put(covariable, toSimilarToI);
}
for (String s : this.processedData.covariableData.keySet())
{
Double cumulativeImportance = 0.0;
for (int i = 0; i < this.forest.size(); i++)
{
CARTTree currentTree = this.forest.get(i);
List<Integer> oobOnThisTree = this.oobObservations.get(i);
List<List<Integer>> conditionalGrid = currentTree.getConditionalGrid(this.processedData, oobOnThisTree, correlatedVariables.get(s));
// Create the permuted copy of the data.
ProcessDataForGrowing permData = new ProcessDataForGrowing(this.processedData);
List<List<Integer>> permutedCondGrid = new ArrayList<List<Integer>>();
for (List<Integer> l : conditionalGrid)
{
List<Integer> permutedGridCell = new ArrayList<Integer>(l);
Collections.shuffle(permutedGridCell);
permutedCondGrid.add(permutedGridCell);
}
for (int j = 0; j < conditionalGrid.size(); j++)
{
List<Integer> gridCell = conditionalGrid.get(j);
List<Integer> permGridCell = permutedCondGrid.get(j);
for (int k = 0; k < gridCell.size(); k++)
{
int obsIndex = gridCell.get(k); // Index of the observation that is being changed to a different value for the covariable s.
int permObsIndex = permGridCell.get(k); // Index of the observation that is having its value placed in the obsIndex index.
double permValue = this.processedData.covariableData.get(s).get(permObsIndex);
permData.covariableData.get(s).set(obsIndex, permValue);
}
}
// Determine the accuracy, and the change in it induced by the permutation.
List<Integer> treesToUse = new ArrayList<Integer>();
treesToUse.add(i);
Double originalAccuracy = 1 - predict(this.processedData, oobOnThisTree, treesToUse).first; // Determine the predictive accuracy for the non-permuted observations.
Double permutedAccuracy = 1 - predict(permData, oobOnThisTree, treesToUse).first; // Determine the predictive accuracy for the permuted observations.
cumulativeImportance += (originalAccuracy - permutedAccuracy);
}
cumulativeImportance /= this.forest.size(); // Get the mean change in the accuracy. This is the importance for the variable.
variableImportance.put(s, cumulativeImportance);
}
return variableImportance;
}
void growForest(String dataForGrowing, Map<String, Double> potentialWeights)
{
growForest(dataForGrowing, potentialWeights, true);
}
void growForest(String dataForGrowing, Map<String, Double> potentialWeights, boolean isProcessingNeeded)
{
// Seed the random generator used to control all the randomness in the algorithm,
Random randGenerator = new Random(this.seed);
if (isProcessingNeeded)
{
this.dataFileGrownFrom = dataForGrowing;
ProcessDataForGrowing procData = new ProcessDataForGrowing(dataForGrowing, this.ctrl);
this.processedData = procData;
}
// Determine if sub sampling is used, and if so record the response of each observation.
boolean isSampSizeUsed = this.ctrl.sampSize.size() > 0;
Set<String> responseClasses = new HashSet<String>(this.processedData.responseData);
if (ctrl.isStratifiedBootstrapUsed)
{
+ isSampSizeUsed = true;
for (String s : responseClasses)
{
ctrl.sampSize.put(s, Collections.frequency(this.processedData.responseData, s));
}
}
else if (isSampSizeUsed && !this.ctrl.sampSize.keySet().containsAll(responseClasses))
{
// Raise an error if sampSize is being used and does not contain all of the response classes.
System.out.println("ERROR : sampSize in the control object does not contain all of the response classes in the data.");
System.exit(0);
}
Map<String, List<Integer>> responseSplits = new HashMap<String, List<Integer>>();
if (isSampSizeUsed || ctrl.isStratifiedBootstrapUsed)
{
for (String s : responseClasses)
{
responseSplits.put(s, new ArrayList<Integer>());
}
for (int i = 0; i < this.processedData.numberObservations; i++)
{
responseSplits.get(this.processedData.responseData.get(i)).add(i);
}
}
// Generate the default weightings.
for (String s : this.processedData.responseData)
{
if (!potentialWeights.containsKey(s))
{
// Any classes without a weight are assigned a weight of 1.
potentialWeights.put(s, 1.0);
}
}
this.weights = potentialWeights;
// Setup the observation selection variables.
List<Integer> observations = new ArrayList<Integer>();
for (int i = 0; i < this.processedData.numberObservations; i++)
{
observations.add(i);
}
int numberObservationsToSelect = 0;
if (!this.ctrl.isReplacementUsed)
{
numberObservationsToSelect = (int) Math.floor(this.ctrl.selectionFraction * observations.size());
}
else
{
numberObservationsToSelect = observations.size();
}
for (int i = 0; i < ctrl.numberOfTreesToGrow; i++)
{
// Randomly determine the observations used for growing this tree.
List<Integer> observationsForTheTree = new ArrayList<Integer>();
if (isSampSizeUsed)
{
for (String s : responseClasses)
{
int observationsToSelect = this.ctrl.sampSize.get(s);
List<Integer> thisClassObservations = new ArrayList<Integer>(responseSplits.get(s));
if (!ctrl.isReplacementUsed)
{
Collections.shuffle(thisClassObservations, new Random(randGenerator.nextLong()));
for (int j = 0; j < observationsToSelect; j++)
{
observationsForTheTree.add(thisClassObservations.get(j));
}
}
else
{
int selectedObservation;
for (int j = 0; j < observationsToSelect; j++)
{
selectedObservation = randGenerator.nextInt(thisClassObservations.size());
observationsForTheTree.add(thisClassObservations.get(selectedObservation));
}
}
}
}
else
{
if (!ctrl.isReplacementUsed)
{
Collections.shuffle(observations, new Random(randGenerator.nextLong()));
for (int j = 0; j < numberObservationsToSelect; j++)
{
observationsForTheTree.add(observations.get(j));
}
}
else
{
int selectedObservation;
for (int j = 0; j < numberObservationsToSelect; j++)
{
selectedObservation = randGenerator.nextInt(observations.size());
observationsForTheTree.add(observations.get(selectedObservation));
}
}
}
// Update the list of which observations are oob on this tree.
List<Integer> oobOnThisTree = new ArrayList<Integer>();
for (Integer j : observations)
{
if (!observationsForTheTree.contains(j))
{
// If the observation is not in the observations to use when growing the tree, then it is oob for the tree.
oobOnThisTree.add(j);
}
}
this.oobObservations.add(oobOnThisTree);
// Grow this tree from the chosen observations.
long seedForTree = randGenerator.nextLong();
this.forest.add(new CARTTree(this.processedData, this.ctrl, weights, observationsForTheTree, seedForTree));
}
if (this.ctrl.isCalculateOOB)
{
// Calculate the oob error. This is done by putting each observation down the trees where it is oob.
double cumulativeErrorRate = 0.0;
Map<String, Map<String, Double>> confusionMatrix = new HashMap<String, Map<String, Double>>();
Set<String> responsePossibilities = new HashSet<String>(this.processedData.responseData);
for (String s : responsePossibilities)
{
Map<String, Double> classEntry = new HashMap<String, Double>();
classEntry.put("TruePositive", 0.0);
classEntry.put("FalsePositive", 0.0);
confusionMatrix.put(s, classEntry);
}
int numberOobObservations = 0;
for (int i = 0; i < this.processedData.numberObservations; i++)
{
boolean isIOob = false;
List<Integer> obsToPredict = new ArrayList<Integer>();
obsToPredict.add(i);
// Gather the trees or which observation i is oob.
List<Integer> treesToPredictFrom = new ArrayList<Integer>();
for (int j = 0; j < this.ctrl.numberOfTreesToGrow; j++)
{
if (this.oobObservations.get(j).contains(i))
{
// If the jth tree contains the ith observation as an oob observation.
treesToPredictFrom.add(j);
isIOob = true;
}
}
if (isIOob)
{
numberOobObservations += 1;
ImmutableTwoValues<Double, Map<String, Map<String, Double>>> oobPrediction = predict(this.processedData, obsToPredict, treesToPredictFrom);
cumulativeErrorRate += oobPrediction.first;
for (String s : oobPrediction.second.keySet())
{
for (String p : oobPrediction.second.get(s).keySet())
{
Double oldValue = confusionMatrix.get(s).get(p);
confusionMatrix.get(s).put(p, oldValue + oobPrediction.second.get(s).get(p));
}
}
}
}
this.oobErrorEstimate = cumulativeErrorRate / numberOobObservations;
this.oobConfusionMatrix = confusionMatrix;
}
}
public ImmutableTwoValues<Double, Map<String, Map<String, Double>>> predict(ProcessDataForGrowing predData)
{
List<Integer> observationsToPredict = new ArrayList<Integer>();
for (int i = 0; i < predData.numberObservations; i++)
{
observationsToPredict.add(i);
}
List<Integer> treesToUseForPrediction = new ArrayList<Integer>();
for (int i = 0; i < forest.size(); i++)
{
treesToUseForPrediction.add(i);
}
return predict(predData, observationsToPredict, treesToUseForPrediction);
}
public ImmutableTwoValues<Double, Map<String, Map<String, Double>>> predict(ProcessDataForGrowing predData, List<Integer> observationsToPredict)
{
List<Integer> treesToUseForPrediction = new ArrayList<Integer>();
for (int i = 0; i < forest.size(); i++)
{
treesToUseForPrediction.add(i);
}
return predict(predData, observationsToPredict, treesToUseForPrediction);
}
public ImmutableTwoValues<Double, Map<String, Map<String, Double>>> predict(ProcessDataForGrowing predData, List<Integer> observationsToPredict, List<Integer> treesToUseForPrediction)
{
Double errorRate = 0.0;
Map<Integer, String> observationToClassification = new HashMap<Integer, String>();
Set<String> classNames = new HashSet<String>(this.processedData.responseData); // A set containing the names of all the classes in the dataset.
// Set up the mapping from observation index to predictions. The key is the index of the observation in the dataset, the Map contains
// a mapping from each class to the weighted vote for it from the forest.
Map<Integer, Map<String, Double>> predictions = new HashMap<Integer,Map<String, Double>>();
Map<String, Double> possiblePredictions = new HashMap<String, Double>();
for (String s : classNames)
{
possiblePredictions.put(s, 0.0);
}
for (int i : observationsToPredict)
{
predictions.put(i, new HashMap<String, Double>(possiblePredictions));
}
// Get the raw predictions for each tree.
for (int i : treesToUseForPrediction)
{
Map<Integer, Map<String, Double>> predictedValues = forest.get(i).predict(predData, observationsToPredict);
for (int j : predictedValues.keySet())
{
for (String s : predictedValues.get(j).keySet())
{
Double oldPrediction = predictions.get(j).get(s);
Double newPrediction = predictedValues.get(j).get(s);
predictions.get(j).put(s, oldPrediction + newPrediction);
}
}
}
// Make sense of the prediction for each observation.
for (int i : predictions.keySet())
{
// Get the list of predictions for observation i. The predictions are ordered so that the jth value in the list
// is the prediction for the jth value in the list of treesToUseForPrediction.
Map<String, Double> predictedValues = predictions.get(i);
// Determine the majority classification for the observation.
String majorityClass = "";
double largestNumberClassifications = -Double.MAX_VALUE;
for (String s : predictedValues.keySet())
{
if (predictedValues.get(s) > largestNumberClassifications)
{
majorityClass = s;
largestNumberClassifications = predictedValues.get(s);
}
}
// Record the majority classification for the observation.
observationToClassification.put(i, majorityClass);
}
// Set up the confusion matrix.
Map<String, Map<String, Double>> confusionMatrix = new HashMap<String, Map<String, Double>>();
Set<String> responsePossibilities = new HashSet<String>(this.processedData.responseData);
for (String s : responsePossibilities)
{
Map<String, Double> classEntry = new HashMap<String, Double>();
classEntry.put("TruePositive", 0.0);
classEntry.put("FalsePositive", 0.0);
confusionMatrix.put(s, classEntry);
}
// Record the error rate for all observations.
for (int i : observationToClassification.keySet())
{
String predictedClass = observationToClassification.get(i);
if (!predData.responseData.get(i).equals(predictedClass))
{
// If the classification is not correct.
errorRate += 1.0; // Indicate that an incorrect prediction has been encountered.
// Increment the number of false positives for the predicted class.
Double currentFalsePos = confusionMatrix.get(predictedClass).get("FalsePositive");
confusionMatrix.get(predictedClass).put("FalsePositive", currentFalsePos + 1);
}
else
{
// Increment the number of true positives for the predicted class.
Double currentTruePos = confusionMatrix.get(predictedClass).get("TruePositive");
confusionMatrix.get(predictedClass).put("TruePositive", currentTruePos + 1);
}
}
// Divide the number of observations predicted incorrectly by the total number of observations in order to get the
// overall error rate of the set of observations provided on the set of trees provided.
errorRate = errorRate / observationToClassification.size();
return new ImmutableTwoValues<Double, Map<String,Map<String,Double>>>(errorRate, confusionMatrix);
}
public Map<Integer, Map<String, Double>> predictRaw(ProcessDataForGrowing predData)
{
List<Integer> observationsToPredict = new ArrayList<Integer>();
for (int i = 0; i < predData.numberObservations; i++)
{
observationsToPredict.add(i);
}
List<Integer> treesToUseForPrediction = new ArrayList<Integer>();
for (int i = 0; i < forest.size(); i++)
{
treesToUseForPrediction.add(i);
}
return predictRaw(predData, observationsToPredict, treesToUseForPrediction);
}
public Map<Integer, Map<String, Double>> predictRaw(ProcessDataForGrowing predData, List<Integer> observationsToPredict)
{
List<Integer> treesToUseForPrediction = new ArrayList<Integer>();
for (int i = 0; i < forest.size(); i++)
{
treesToUseForPrediction.add(i);
}
return predictRaw(predData, observationsToPredict, treesToUseForPrediction);
}
public Map<Integer, Map<String, Double>> predictRaw(ProcessDataForGrowing predData, List<Integer> observationsToPredict, List<Integer> treesToUseForPrediction)
{
Set<String> classNames = new HashSet<String>(this.processedData.responseData); // A set containing the names of all the classes in the dataset.
// Set up the mapping from observation index to predictions. The key is the index of the observation in the dataset, the Map contains
// a mapping from each class to the weighted vote for it from the forest.
Map<Integer, Map<String, Double>> predictions = new HashMap<Integer,Map<String, Double>>();
Map<String, Double> possiblePredictions = new HashMap<String, Double>();
for (String s : classNames)
{
possiblePredictions.put(s, 0.0);
}
for (int i : observationsToPredict)
{
predictions.put(i, new HashMap<String, Double>(possiblePredictions));
}
// Get the raw predictions for each tree.
for (Integer i : treesToUseForPrediction)
{
Map<Integer, Map<String, Double>> predictedValues = forest.get(i).predict(predData, observationsToPredict);
for (Integer j : predictedValues.keySet())
{
for (String s : predictedValues.get(j).keySet())
{
Double oldPrediction = predictions.get(j).get(s);
Double newPrediction = predictedValues.get(j).get(s);
predictions.get(j).put(s, oldPrediction + newPrediction);
}
}
}
return predictions;
}
public void regrowForest()
{
// Regrow using old seeds.
this.forest = new ArrayList<CARTTree>();
this.oobObservations = new ArrayList<List<Integer>>();
this.oobErrorEstimate = 0.0;
this.growForest(this.dataFileGrownFrom, this.weights);
}
public void regrowForest(long newSeed)
{
// Regrow using a different seed.
this.seed = newSeed;
this.regrowForest();
}
public void regrowForest(TreeGrowthControl newCtrl)
{
// Regrow with the old seed, but a different controller.
// This allows you to change replacement/mtry while keeping the random seed the same.
this.ctrl = newCtrl;
this.regrowForest();
}
public void regrowForest(long newSeed, TreeGrowthControl newCtrl)
{
// Regrow using a different seed and a new controller.
this.seed = newSeed;
this.ctrl = newCtrl;
this.regrowForest();
}
public void save(String savedirLoc)
{
File outputDirectory = new File(savedirLoc);
if (!outputDirectory.exists())
{
boolean isDirCreated = outputDirectory.mkdirs();
if (!isDirCreated)
{
System.out.println("The output directory does not exist, but could not be created.");
System.exit(0);
}
}
else if (!outputDirectory.isDirectory())
{
// Exists and is not a directory.
System.out.println("The output directory location exists, but is not a directory.");
System.exit(0);
}
// Save the trees.
for (int i = 0; i < this.forest.size(); i++)
{
String treeSaveLocation = savedirLoc + "/" + Integer.toString(i);
this.forest.get(i).save(treeSaveLocation);
}
// Save the control object.
String controllerSaveLocation = savedirLoc + "/Controller.txt";
this.ctrl.save(controllerSaveLocation);
// Save the processed data.
String processedDataSaveLocation = savedirLoc + "/ProcessedData.txt";
this.processedData.save(processedDataSaveLocation);
// Save the other forest attributes.
String attributeSaveLocation = savedirLoc + "/Attributes.txt";
try
{
FileWriter outputFile = new FileWriter(attributeSaveLocation);
BufferedWriter outputWriter = new BufferedWriter(outputFile);
String oobObsOutput = "";
for (Integer i : this.oobObservations.get(0))
{
oobObsOutput += Integer.toString(i) + ",";
}
oobObsOutput = oobObsOutput.substring(0, oobObsOutput.length() - 1); // Chop off the last ','.
for (int i = 1; i < this.oobObservations.size(); i++)
{
oobObsOutput += ";";
for (Integer j : this.oobObservations.get(i))
{
oobObsOutput += Integer.toString(j) + ",";
}
oobObsOutput = oobObsOutput.substring(0, oobObsOutput.length() - 1); // Chop off the last ','.
}
outputWriter.write(oobObsOutput + "\t");
outputWriter.write(Double.toString(this.oobErrorEstimate) + "\t");
String oobConfMatOutput = "";
for (String s : this.oobConfusionMatrix.keySet())
{
oobConfMatOutput += s + "-";
for (String p : this.oobConfusionMatrix.get(s).keySet())
{
oobConfMatOutput += p + "," + Double.toString(this.oobConfusionMatrix.get(s).get(p)) + ";";
}
oobConfMatOutput = oobConfMatOutput.substring(0, oobConfMatOutput.length() - 1); // Chop off the last ';'.
oobConfMatOutput += "#";
}
oobConfMatOutput = oobConfMatOutput.substring(0, oobConfMatOutput.length() - 1); // Chop off the last '#'.
outputWriter.write(oobConfMatOutput + "\t");
outputWriter.write(this.dataFileGrownFrom + "\t");
String weightsOutput = "";
for (String s : this.weights.keySet())
{
weightsOutput += s + "," + Double.toString(this.weights.get(s)) + ";";
}
weightsOutput = weightsOutput.substring(0, weightsOutput.length() - 1); // Chop off the last ';'.
outputWriter.write(weightsOutput + "\t");
outputWriter.write(Long.toString(this.seed));
outputWriter.close();
}
catch (Exception e)
{
System.err.println(e.getStackTrace());
System.exit(0);
}
}
public Map<String, Double> variableImportance()
{
// Determine base accuracy for each tree.
List<Double> baseOOBAccuracy = new ArrayList<Double>();
for (int i = 0; i < this.forest.size(); i++)
{
List<Integer> oobOnThisTree = this.oobObservations.get(i);
List<Integer> treesToUse = new ArrayList<Integer>();
treesToUse.add(i);
Double originalAccuracy = 1 - predict(this.processedData, oobOnThisTree, treesToUse).first;
baseOOBAccuracy.add(originalAccuracy);
}
// Determine permuted importance.
Map<String, Double> variableImportance = new HashMap<String, Double>();
for (String s : this.processedData.covariableData.keySet())
{
double cumulativeAccChange = 0.0;
for (int i = 0; i < this.forest.size(); i++)
{
List<Integer> oobOnThisTree = this.oobObservations.get(i);
List<Integer> permutedOobOnThisTree = new ArrayList<Integer>(this.oobObservations.get(i));
Collections.shuffle(permutedOobOnThisTree);
// Create the permuted copy of the data.
ProcessDataForGrowing permData = new ProcessDataForGrowing(this.processedData);
for (int j = 0; j < permutedOobOnThisTree.size(); j++)
{
int obsIndex = oobOnThisTree.get(j); // Index of the observation that is being changed to a different value for the covariable s.
int permObsIndex = permutedOobOnThisTree.get(j); // Index of the observation that is having its value placed in the obsIndex index.
double permValue = this.processedData.covariableData.get(s).get(permObsIndex);
permData.covariableData.get(s).set(obsIndex, permValue);
}
List<Integer> treesToUse = new ArrayList<Integer>();
treesToUse.add(i);
Double permutedAccuracy = 1 - predict(permData, oobOnThisTree, treesToUse).first; // Determine the predictive accuracy for the permuted observations.
cumulativeAccChange += (baseOOBAccuracy.get(i) - permutedAccuracy);
}
cumulativeAccChange /= this.forest.size(); // Get the mean change in the accuracy. This is the importance for the variable.
variableImportance.put(s, cumulativeAccChange);
}
return variableImportance;
}
}
| true | true | void growForest(String dataForGrowing, Map<String, Double> potentialWeights, boolean isProcessingNeeded)
{
// Seed the random generator used to control all the randomness in the algorithm,
Random randGenerator = new Random(this.seed);
if (isProcessingNeeded)
{
this.dataFileGrownFrom = dataForGrowing;
ProcessDataForGrowing procData = new ProcessDataForGrowing(dataForGrowing, this.ctrl);
this.processedData = procData;
}
// Determine if sub sampling is used, and if so record the response of each observation.
boolean isSampSizeUsed = this.ctrl.sampSize.size() > 0;
Set<String> responseClasses = new HashSet<String>(this.processedData.responseData);
if (ctrl.isStratifiedBootstrapUsed)
{
for (String s : responseClasses)
{
ctrl.sampSize.put(s, Collections.frequency(this.processedData.responseData, s));
}
}
else if (isSampSizeUsed && !this.ctrl.sampSize.keySet().containsAll(responseClasses))
{
// Raise an error if sampSize is being used and does not contain all of the response classes.
System.out.println("ERROR : sampSize in the control object does not contain all of the response classes in the data.");
System.exit(0);
}
Map<String, List<Integer>> responseSplits = new HashMap<String, List<Integer>>();
if (isSampSizeUsed || ctrl.isStratifiedBootstrapUsed)
{
for (String s : responseClasses)
{
responseSplits.put(s, new ArrayList<Integer>());
}
for (int i = 0; i < this.processedData.numberObservations; i++)
{
responseSplits.get(this.processedData.responseData.get(i)).add(i);
}
}
// Generate the default weightings.
for (String s : this.processedData.responseData)
{
if (!potentialWeights.containsKey(s))
{
// Any classes without a weight are assigned a weight of 1.
potentialWeights.put(s, 1.0);
}
}
this.weights = potentialWeights;
// Setup the observation selection variables.
List<Integer> observations = new ArrayList<Integer>();
for (int i = 0; i < this.processedData.numberObservations; i++)
{
observations.add(i);
}
int numberObservationsToSelect = 0;
if (!this.ctrl.isReplacementUsed)
{
numberObservationsToSelect = (int) Math.floor(this.ctrl.selectionFraction * observations.size());
}
else
{
numberObservationsToSelect = observations.size();
}
for (int i = 0; i < ctrl.numberOfTreesToGrow; i++)
{
// Randomly determine the observations used for growing this tree.
List<Integer> observationsForTheTree = new ArrayList<Integer>();
if (isSampSizeUsed)
{
for (String s : responseClasses)
{
int observationsToSelect = this.ctrl.sampSize.get(s);
List<Integer> thisClassObservations = new ArrayList<Integer>(responseSplits.get(s));
if (!ctrl.isReplacementUsed)
{
Collections.shuffle(thisClassObservations, new Random(randGenerator.nextLong()));
for (int j = 0; j < observationsToSelect; j++)
{
observationsForTheTree.add(thisClassObservations.get(j));
}
}
else
{
int selectedObservation;
for (int j = 0; j < observationsToSelect; j++)
{
selectedObservation = randGenerator.nextInt(thisClassObservations.size());
observationsForTheTree.add(thisClassObservations.get(selectedObservation));
}
}
}
}
else
{
if (!ctrl.isReplacementUsed)
{
Collections.shuffle(observations, new Random(randGenerator.nextLong()));
for (int j = 0; j < numberObservationsToSelect; j++)
{
observationsForTheTree.add(observations.get(j));
}
}
else
{
int selectedObservation;
for (int j = 0; j < numberObservationsToSelect; j++)
{
selectedObservation = randGenerator.nextInt(observations.size());
observationsForTheTree.add(observations.get(selectedObservation));
}
}
}
// Update the list of which observations are oob on this tree.
List<Integer> oobOnThisTree = new ArrayList<Integer>();
for (Integer j : observations)
{
if (!observationsForTheTree.contains(j))
{
// If the observation is not in the observations to use when growing the tree, then it is oob for the tree.
oobOnThisTree.add(j);
}
}
this.oobObservations.add(oobOnThisTree);
// Grow this tree from the chosen observations.
long seedForTree = randGenerator.nextLong();
this.forest.add(new CARTTree(this.processedData, this.ctrl, weights, observationsForTheTree, seedForTree));
}
if (this.ctrl.isCalculateOOB)
{
// Calculate the oob error. This is done by putting each observation down the trees where it is oob.
double cumulativeErrorRate = 0.0;
Map<String, Map<String, Double>> confusionMatrix = new HashMap<String, Map<String, Double>>();
Set<String> responsePossibilities = new HashSet<String>(this.processedData.responseData);
for (String s : responsePossibilities)
{
Map<String, Double> classEntry = new HashMap<String, Double>();
classEntry.put("TruePositive", 0.0);
classEntry.put("FalsePositive", 0.0);
confusionMatrix.put(s, classEntry);
}
int numberOobObservations = 0;
for (int i = 0; i < this.processedData.numberObservations; i++)
{
boolean isIOob = false;
List<Integer> obsToPredict = new ArrayList<Integer>();
obsToPredict.add(i);
// Gather the trees or which observation i is oob.
List<Integer> treesToPredictFrom = new ArrayList<Integer>();
for (int j = 0; j < this.ctrl.numberOfTreesToGrow; j++)
{
if (this.oobObservations.get(j).contains(i))
{
// If the jth tree contains the ith observation as an oob observation.
treesToPredictFrom.add(j);
isIOob = true;
}
}
if (isIOob)
{
numberOobObservations += 1;
ImmutableTwoValues<Double, Map<String, Map<String, Double>>> oobPrediction = predict(this.processedData, obsToPredict, treesToPredictFrom);
cumulativeErrorRate += oobPrediction.first;
for (String s : oobPrediction.second.keySet())
{
for (String p : oobPrediction.second.get(s).keySet())
{
Double oldValue = confusionMatrix.get(s).get(p);
confusionMatrix.get(s).put(p, oldValue + oobPrediction.second.get(s).get(p));
}
}
}
}
this.oobErrorEstimate = cumulativeErrorRate / numberOobObservations;
this.oobConfusionMatrix = confusionMatrix;
}
}
| void growForest(String dataForGrowing, Map<String, Double> potentialWeights, boolean isProcessingNeeded)
{
// Seed the random generator used to control all the randomness in the algorithm,
Random randGenerator = new Random(this.seed);
if (isProcessingNeeded)
{
this.dataFileGrownFrom = dataForGrowing;
ProcessDataForGrowing procData = new ProcessDataForGrowing(dataForGrowing, this.ctrl);
this.processedData = procData;
}
// Determine if sub sampling is used, and if so record the response of each observation.
boolean isSampSizeUsed = this.ctrl.sampSize.size() > 0;
Set<String> responseClasses = new HashSet<String>(this.processedData.responseData);
if (ctrl.isStratifiedBootstrapUsed)
{
isSampSizeUsed = true;
for (String s : responseClasses)
{
ctrl.sampSize.put(s, Collections.frequency(this.processedData.responseData, s));
}
}
else if (isSampSizeUsed && !this.ctrl.sampSize.keySet().containsAll(responseClasses))
{
// Raise an error if sampSize is being used and does not contain all of the response classes.
System.out.println("ERROR : sampSize in the control object does not contain all of the response classes in the data.");
System.exit(0);
}
Map<String, List<Integer>> responseSplits = new HashMap<String, List<Integer>>();
if (isSampSizeUsed || ctrl.isStratifiedBootstrapUsed)
{
for (String s : responseClasses)
{
responseSplits.put(s, new ArrayList<Integer>());
}
for (int i = 0; i < this.processedData.numberObservations; i++)
{
responseSplits.get(this.processedData.responseData.get(i)).add(i);
}
}
// Generate the default weightings.
for (String s : this.processedData.responseData)
{
if (!potentialWeights.containsKey(s))
{
// Any classes without a weight are assigned a weight of 1.
potentialWeights.put(s, 1.0);
}
}
this.weights = potentialWeights;
// Setup the observation selection variables.
List<Integer> observations = new ArrayList<Integer>();
for (int i = 0; i < this.processedData.numberObservations; i++)
{
observations.add(i);
}
int numberObservationsToSelect = 0;
if (!this.ctrl.isReplacementUsed)
{
numberObservationsToSelect = (int) Math.floor(this.ctrl.selectionFraction * observations.size());
}
else
{
numberObservationsToSelect = observations.size();
}
for (int i = 0; i < ctrl.numberOfTreesToGrow; i++)
{
// Randomly determine the observations used for growing this tree.
List<Integer> observationsForTheTree = new ArrayList<Integer>();
if (isSampSizeUsed)
{
for (String s : responseClasses)
{
int observationsToSelect = this.ctrl.sampSize.get(s);
List<Integer> thisClassObservations = new ArrayList<Integer>(responseSplits.get(s));
if (!ctrl.isReplacementUsed)
{
Collections.shuffle(thisClassObservations, new Random(randGenerator.nextLong()));
for (int j = 0; j < observationsToSelect; j++)
{
observationsForTheTree.add(thisClassObservations.get(j));
}
}
else
{
int selectedObservation;
for (int j = 0; j < observationsToSelect; j++)
{
selectedObservation = randGenerator.nextInt(thisClassObservations.size());
observationsForTheTree.add(thisClassObservations.get(selectedObservation));
}
}
}
}
else
{
if (!ctrl.isReplacementUsed)
{
Collections.shuffle(observations, new Random(randGenerator.nextLong()));
for (int j = 0; j < numberObservationsToSelect; j++)
{
observationsForTheTree.add(observations.get(j));
}
}
else
{
int selectedObservation;
for (int j = 0; j < numberObservationsToSelect; j++)
{
selectedObservation = randGenerator.nextInt(observations.size());
observationsForTheTree.add(observations.get(selectedObservation));
}
}
}
// Update the list of which observations are oob on this tree.
List<Integer> oobOnThisTree = new ArrayList<Integer>();
for (Integer j : observations)
{
if (!observationsForTheTree.contains(j))
{
// If the observation is not in the observations to use when growing the tree, then it is oob for the tree.
oobOnThisTree.add(j);
}
}
this.oobObservations.add(oobOnThisTree);
// Grow this tree from the chosen observations.
long seedForTree = randGenerator.nextLong();
this.forest.add(new CARTTree(this.processedData, this.ctrl, weights, observationsForTheTree, seedForTree));
}
if (this.ctrl.isCalculateOOB)
{
// Calculate the oob error. This is done by putting each observation down the trees where it is oob.
double cumulativeErrorRate = 0.0;
Map<String, Map<String, Double>> confusionMatrix = new HashMap<String, Map<String, Double>>();
Set<String> responsePossibilities = new HashSet<String>(this.processedData.responseData);
for (String s : responsePossibilities)
{
Map<String, Double> classEntry = new HashMap<String, Double>();
classEntry.put("TruePositive", 0.0);
classEntry.put("FalsePositive", 0.0);
confusionMatrix.put(s, classEntry);
}
int numberOobObservations = 0;
for (int i = 0; i < this.processedData.numberObservations; i++)
{
boolean isIOob = false;
List<Integer> obsToPredict = new ArrayList<Integer>();
obsToPredict.add(i);
// Gather the trees or which observation i is oob.
List<Integer> treesToPredictFrom = new ArrayList<Integer>();
for (int j = 0; j < this.ctrl.numberOfTreesToGrow; j++)
{
if (this.oobObservations.get(j).contains(i))
{
// If the jth tree contains the ith observation as an oob observation.
treesToPredictFrom.add(j);
isIOob = true;
}
}
if (isIOob)
{
numberOobObservations += 1;
ImmutableTwoValues<Double, Map<String, Map<String, Double>>> oobPrediction = predict(this.processedData, obsToPredict, treesToPredictFrom);
cumulativeErrorRate += oobPrediction.first;
for (String s : oobPrediction.second.keySet())
{
for (String p : oobPrediction.second.get(s).keySet())
{
Double oldValue = confusionMatrix.get(s).get(p);
confusionMatrix.get(s).put(p, oldValue + oobPrediction.second.get(s).get(p));
}
}
}
}
this.oobErrorEstimate = cumulativeErrorRate / numberOobObservations;
this.oobConfusionMatrix = confusionMatrix;
}
}
|
diff --git a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/SpawnerHandler/SpawnerHandler.java b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/SpawnerHandler/SpawnerHandler.java
index 7e5d6ee..c89d8c0 100644
--- a/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/SpawnerHandler/SpawnerHandler.java
+++ b/EasyMobArmory/src/main/java/com/runetooncraft/plugins/EasyMobArmory/SpawnerHandler/SpawnerHandler.java
@@ -1,166 +1,171 @@
package com.runetooncraft.plugins.EasyMobArmory.SpawnerHandler;
import java.util.ArrayList;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitTask;
import com.runetooncraft.plugins.EasyMobArmory.EMA;
import com.runetooncraft.plugins.EasyMobArmory.core.InventorySerializer;
import com.runetooncraft.plugins.EasyMobArmory.core.Messenger;
import com.runetooncraft.plugins.EasyMobArmory.egghandler.EggHandler;
import com.runetooncraft.plugins.EasyMobArmory.egghandler.Eggs;
public class SpawnerHandler {
public static Eggs eggs = EMA.eggs;
public static SpawnerConfig Spawners = EMA.Spawners;
public static HashMap<Location, SpawnerCache> SpawnerCache = new HashMap<Location, SpawnerCache>();
public static HashMap<SpawnerCache, BukkitTask> SpawnerCacheTimers = new HashMap<SpawnerCache, BukkitTask>();
public static Boolean IsEMASpawner(Location loc) {
if(Spawners.getList("Spawners.List").contains(Spawners.LocString(loc))) {
return true;
}else{
return false;
}
}
public static void NewEMASpawner(Block b,Player p) {
Inventory inv = Bukkit.createInventory(p, 54, "Spawnerinv");
SpawnerCache.put(b.getLocation(), new SpawnerCache(b,b.getLocation(),inv));
String LocString = Spawners.LocString(b.getLocation());
Spawners.addtolist("Spawners.List", LocString);
Spawners.SetString("Spawners." + LocString + ".Inventory", InventorySerializer.tobase64(inv));
ArrayList<String> EggList = new ArrayList<String>();
Spawners.SetList("Spawners." + LocString + ".EggList",EggList);
Spawners.SetBoolean("Spawners." + LocString + ".TimerEnabled", false);
Spawners.setInt("Spawners." + LocString + ".TimerTick", 64);
}
public static void OpenSpawnerInventory(Block b,Player p) {
String LocString = Spawners.LocString(b.getLocation());
Inventory inv = Bukkit.createInventory(p, 54, "Spawnerinv");
inv.setContents(InventorySerializer.frombase64(Spawners.getString("Spawners." + LocString + ".Inventory")).getContents());
p.openInventory(inv);
}
public static void SetSpawnerInventory(Inventory i, SpawnerCache sc) {
sc.getInventory().setContents(i.getContents());
SaveSpawnerCache(sc);
ReloadSCTimer(sc);
}
private static boolean ReloadSCTimer(SpawnerCache sc) {
if(SpawnerCache.containsKey(sc) && SpawnerCacheTimers.containsKey(SpawnerCache.get(sc))) {
int TimerTick = sc.TimerTick * 20;
SpawnerCacheTimers.get(sc).cancel();
SpawnerCacheTimers.put(sc, new MonsterSpawnTimer(sc).runTaskTimer(Bukkit.getPluginManager().getPlugin("EasyMobArmory"), TimerTick, TimerTick));
return true;
}else{
return false;
}
}
private static void LoadSpawner(Location SpawnerLocation) {
World world = SpawnerLocation.getWorld();
Block b = world.getBlockAt(SpawnerLocation);
String LocString = Spawners.LocString(SpawnerLocation);
Inventory inv = InventorySerializer.frombase64(Spawners.getString("Spawners." + LocString + ".Inventory"));
Boolean TimerEnabled = Spawners.getBoolean("Spawners." + LocString + ".TimerEnabled");
SpawnerCache sc = new SpawnerCache(b,SpawnerLocation,inv);
sc.TimerEnabled = TimerEnabled;
if(TimerEnabled) sc.TimerTick = Spawners.getInt("Spawners." + LocString + ".TimerTick");
SpawnerCache.put(SpawnerLocation, sc);
}
public static SpawnerCache getSpawner(Location SpawnerLocation) {
World world = SpawnerLocation.getWorld();
Block b = world.getBlockAt(SpawnerLocation);
String LocString = Spawners.LocString(SpawnerLocation);
Inventory inv = InventorySerializer.frombase64(Spawners.getString("Spawners." + LocString + ".Inventory"));
SpawnerCache sc = new SpawnerCache(b,SpawnerLocation,inv);
sc.TimerEnabled = Spawners.getBoolean("Spawners." + LocString + ".TimerEnabled");
sc.TimerTick = Spawners.getInt("Spawners." + LocString + ".TimerTick");
return new SpawnerCache(b,SpawnerLocation,inv);
}
public static void SaveSpawnerCache(SpawnerCache sc) {
SpawnerCache.put(sc.getLocation(), sc);
String LocString = Spawners.LocString(sc.getLocation());
Inventory i = sc.getInventory();
Spawners.SetString("Spawners." + LocString + ".Inventory", InventorySerializer.tobase64(i));
Spawners.setInt("Spawners." + LocString + ".TimerTick", sc.TimerTick);
Spawners.SetBoolean("Spawners." + LocString + ".TimerEnabled", sc.TimerEnabled);
ItemStack[] EggsStack = i.getContents();
for(ItemStack is : EggsStack) {
String id = EggHandler.getEggID(is);
if(id != null) {
if(!Spawners.getList("Spawners." + LocString + ".EggList").contains(id)) {
Spawners.addtolist("Spawners." + LocString + ".EggList", id);
}
}
}
}
public static void SetSpawnTick(Player p,String spawntick) {
if(IsInteger(spawntick)) {
Block b = p.getTargetBlock(null, 200);
if(b.getTypeId() == 52) {
if(IsEMASpawner(b.getLocation())) {
- SpawnerCache sc = getSpawner(b.getLocation());
+ SpawnerCache sc;
+ if(SpawnerCache.containsKey(b.getLocation())) {
+ sc = SpawnerCache.get(b.getLocation());
+ }else{
+ sc = getSpawner(b.getLocation());
+ }
sc.TimerTick = Integer.parseInt(spawntick);
sc.TimerEnabled = true;
SpawnerCache.put(b.getLocation(), sc);
int TimerTickActual = sc.TimerTick * 20;
if(SpawnerCacheTimers.containsKey(sc)) {
SpawnerCacheTimers.get(sc).cancel();
}
SpawnerCacheTimers.put(sc, new MonsterSpawnTimer(sc).runTaskTimer(Bukkit.getPluginManager().getPlugin("EasyMobArmory"), TimerTickActual, TimerTickActual));
SaveSpawnerCache(sc);
String LocString = Spawners.LocString(sc.getLocation());
Spawners.addtolist("Spawners.Running.List", LocString);
Messenger.playermessage("The spawner at " + LocString + " had it's TimerTick set to " + spawntick + ".", p);
Messenger.info("The spawner at " + LocString + " had it's TimerTick set to " + spawntick + " by " + p.getName() + ".");
}else{
Messenger.playermessage("The block is a Spawner, but not a EMA-Spawner.", p);
Messenger.playermessage("Select the block with a bone and with EMA enabled and add some EMA eggs to make it an EMA spawner.", p);
}
}else{
Messenger.playermessage("Please look at a EMA-Spawner before typing this command.", p);
}
}else{
Messenger.playermessage("The second argument must be an integer.", p);
}
}
private static boolean IsInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
}
return true;
}
public static void CancelSpawnTimer(Player p) {
Block b = p.getTargetBlock(null, 200);
if(b.getTypeId() == 52) {
if(IsEMASpawner(b.getLocation())) {
if (SpawnerCache.containsKey(b.getLocation())) {
SpawnerCache sc = SpawnerCache.get(b.getLocation());
Spawners.RemoveFromList("Spawners.Running.List", Spawners.LocString(sc.getLocation()));
sc.TimerEnabled = false;
try{
SpawnerCacheTimers.get(sc).cancel();
SpawnerCacheTimers.remove(sc);
}catch(NullPointerException e) {
Messenger.playermessage("Could not stop this spawners timer.", p);
}
SaveSpawnerCache(sc);
Messenger.playermessage("This spawner had it's spawn timer disabled", p);
}
}else{
Messenger.playermessage("The block is a Spawner, but not a EMA-Spawner.", p);
Messenger.playermessage("Select the block with a bone and with EMA enabled and add some EMA eggs to make it an EMA spawner.", p);
}
}else{
Messenger.playermessage("Please look at a EMA-Spawner before typing this command.", p);
}
}
}
| true | true | public static void SetSpawnTick(Player p,String spawntick) {
if(IsInteger(spawntick)) {
Block b = p.getTargetBlock(null, 200);
if(b.getTypeId() == 52) {
if(IsEMASpawner(b.getLocation())) {
SpawnerCache sc = getSpawner(b.getLocation());
sc.TimerTick = Integer.parseInt(spawntick);
sc.TimerEnabled = true;
SpawnerCache.put(b.getLocation(), sc);
int TimerTickActual = sc.TimerTick * 20;
if(SpawnerCacheTimers.containsKey(sc)) {
SpawnerCacheTimers.get(sc).cancel();
}
SpawnerCacheTimers.put(sc, new MonsterSpawnTimer(sc).runTaskTimer(Bukkit.getPluginManager().getPlugin("EasyMobArmory"), TimerTickActual, TimerTickActual));
SaveSpawnerCache(sc);
String LocString = Spawners.LocString(sc.getLocation());
Spawners.addtolist("Spawners.Running.List", LocString);
Messenger.playermessage("The spawner at " + LocString + " had it's TimerTick set to " + spawntick + ".", p);
Messenger.info("The spawner at " + LocString + " had it's TimerTick set to " + spawntick + " by " + p.getName() + ".");
}else{
Messenger.playermessage("The block is a Spawner, but not a EMA-Spawner.", p);
Messenger.playermessage("Select the block with a bone and with EMA enabled and add some EMA eggs to make it an EMA spawner.", p);
}
}else{
Messenger.playermessage("Please look at a EMA-Spawner before typing this command.", p);
}
}else{
Messenger.playermessage("The second argument must be an integer.", p);
}
}
| public static void SetSpawnTick(Player p,String spawntick) {
if(IsInteger(spawntick)) {
Block b = p.getTargetBlock(null, 200);
if(b.getTypeId() == 52) {
if(IsEMASpawner(b.getLocation())) {
SpawnerCache sc;
if(SpawnerCache.containsKey(b.getLocation())) {
sc = SpawnerCache.get(b.getLocation());
}else{
sc = getSpawner(b.getLocation());
}
sc.TimerTick = Integer.parseInt(spawntick);
sc.TimerEnabled = true;
SpawnerCache.put(b.getLocation(), sc);
int TimerTickActual = sc.TimerTick * 20;
if(SpawnerCacheTimers.containsKey(sc)) {
SpawnerCacheTimers.get(sc).cancel();
}
SpawnerCacheTimers.put(sc, new MonsterSpawnTimer(sc).runTaskTimer(Bukkit.getPluginManager().getPlugin("EasyMobArmory"), TimerTickActual, TimerTickActual));
SaveSpawnerCache(sc);
String LocString = Spawners.LocString(sc.getLocation());
Spawners.addtolist("Spawners.Running.List", LocString);
Messenger.playermessage("The spawner at " + LocString + " had it's TimerTick set to " + spawntick + ".", p);
Messenger.info("The spawner at " + LocString + " had it's TimerTick set to " + spawntick + " by " + p.getName() + ".");
}else{
Messenger.playermessage("The block is a Spawner, but not a EMA-Spawner.", p);
Messenger.playermessage("Select the block with a bone and with EMA enabled and add some EMA eggs to make it an EMA spawner.", p);
}
}else{
Messenger.playermessage("Please look at a EMA-Spawner before typing this command.", p);
}
}else{
Messenger.playermessage("The second argument must be an integer.", p);
}
}
|
diff --git a/src/main/java/org/grible/adaptor/helpers/IOHelper.java b/src/main/java/org/grible/adaptor/helpers/IOHelper.java
index 9b5d254..7159f4c 100644
--- a/src/main/java/org/grible/adaptor/helpers/IOHelper.java
+++ b/src/main/java/org/grible/adaptor/helpers/IOHelper.java
@@ -1,65 +1,65 @@
/*******************************************************************************
* Copyright (c) 2013 - 2014 Maksym Barvinskyi.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*
* Contributors:
* Maksym Barvinskyi - initial API and implementation
******************************************************************************/
package org.grible.adaptor.helpers;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.grible.adaptor.json.TableJson;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
public class IOHelper {
public static File searchFile(File dir, String fileName) {
for (File temp : dir.listFiles()) {
if (temp.isDirectory()) {
File result = searchFile(temp, fileName);
if (result != null) {
return result;
}
} else if (fileName.equalsIgnoreCase(temp.getName())) {
return temp;
}
}
return null;
}
public static File searchFileByClassName(File dir, String className) throws Exception {
for (File temp : dir.listFiles()) {
if (temp.isDirectory()) {
- File result = searchFile(temp, className);
+ File result = searchFileByClassName(temp, className);
if (result != null) {
return result;
}
} else {
try {
TableJson tableJson = parseTableJson(temp);
if (tableJson.getClassName().equals(className)) {
return temp;
}
} catch (JsonSyntaxException e) {
}
}
}
return null;
}
public static TableJson parseTableJson(File file) throws Exception {
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
TableJson tableJson = new Gson().fromJson(br, TableJson.class);
br.close();
return tableJson;
}
}
| true | true | public static File searchFileByClassName(File dir, String className) throws Exception {
for (File temp : dir.listFiles()) {
if (temp.isDirectory()) {
File result = searchFile(temp, className);
if (result != null) {
return result;
}
} else {
try {
TableJson tableJson = parseTableJson(temp);
if (tableJson.getClassName().equals(className)) {
return temp;
}
} catch (JsonSyntaxException e) {
}
}
}
return null;
}
| public static File searchFileByClassName(File dir, String className) throws Exception {
for (File temp : dir.listFiles()) {
if (temp.isDirectory()) {
File result = searchFileByClassName(temp, className);
if (result != null) {
return result;
}
} else {
try {
TableJson tableJson = parseTableJson(temp);
if (tableJson.getClassName().equals(className)) {
return temp;
}
} catch (JsonSyntaxException e) {
}
}
}
return null;
}
|
diff --git a/main/src/cgeo/geocaching/Settings.java b/main/src/cgeo/geocaching/Settings.java
index a59de1de9..8ecc0e56f 100644
--- a/main/src/cgeo/geocaching/Settings.java
+++ b/main/src/cgeo/geocaching/Settings.java
@@ -1,1391 +1,1391 @@
package cgeo.geocaching;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory.NavigationAppsEnum;
import cgeo.geocaching.connector.gc.GCConstants;
import cgeo.geocaching.connector.gc.Login;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LiveMapStrategy.Strategy;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.maps.MapProviderFactory;
import cgeo.geocaching.maps.google.GoogleMapProvider;
import cgeo.geocaching.maps.interfaces.GeoPointImpl;
import cgeo.geocaching.maps.interfaces.MapProvider;
import cgeo.geocaching.maps.interfaces.MapSource;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider;
import cgeo.geocaching.maps.mapsforge.MapsforgeMapProvider.OfflineMapSource;
import cgeo.geocaching.utils.CryptUtils;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.FileUtils.FileSelector;
import cgeo.geocaching.utils.Log;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Environment;
import android.preference.PreferenceManager;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
/**
* General c:geo preferences/settings set by the user
*/
public final class Settings {
private static final String KEY_TEMP_TOKEN_SECRET = "temp-token-secret";
private static final String KEY_TEMP_TOKEN_PUBLIC = "temp-token-public";
private static final String KEY_HELP_SHOWN = "helper";
private static final String KEY_ANYLONGITUDE = "anylongitude";
private static final String KEY_ANYLATITUDE = "anylatitude";
private static final String KEY_USE_OFFLINEMAPS = "offlinemaps";
private static final String KEY_USE_OFFLINEWPMAPS = "offlinewpmaps";
private static final String KEY_WEB_DEVICE_CODE = "webDeviceCode";
private static final String KEY_WEBDEVICE_NAME = "webDeviceName";
private static final String KEY_MAP_LIVE = "maplive";
private static final String KEY_MAP_SOURCE = "mapsource";
private static final String KEY_USE_TWITTER = "twitter";
private static final String KEY_SHOW_ADDRESS = "showaddress";
private static final String KEY_SHOW_CAPTCHA = "showcaptcha";
private static final String KEY_MAP_TRAIL = "maptrail";
private static final String KEY_LAST_MAP_ZOOM = "mapzoom";
private static final String KEY_LAST_MAP_LAT = "maplat";
private static final String KEY_LAST_MAP_LON = "maplon";
private static final String KEY_LIVE_LIST = "livelist";
private static final String KEY_METRIC_UNITS = "units";
private static final String KEY_SKIN = "skin";
private static final String KEY_LAST_USED_LIST = "lastlist";
private static final String KEY_CACHE_TYPE = "cachetype";
private static final String KEY_TWITTER_TOKEN_SECRET = "tokensecret";
private static final String KEY_TWITTER_TOKEN_PUBLIC = "tokenpublic";
private static final String KEY_VERSION = "version";
private static final String KEY_LOAD_DESCRIPTION = "autoloaddesc";
private static final String KEY_RATING_WANTED = "ratingwanted";
private static final String KEY_ELEVATION_WANTED = "elevationwanted";
private static final String KEY_FRIENDLOGS_WANTED = "friendlogswanted";
private static final String KEY_USE_ENGLISH = "useenglish";
private static final String KEY_USE_COMPASS = "usecompass";
private static final String KEY_AUTO_VISIT_TRACKABLES = "trackautovisit";
private static final String KEY_AUTO_INSERT_SIGNATURE = "sigautoinsert";
private static final String KEY_ALTITUDE_CORRECTION = "altcorrection";
private static final String KEY_USE_GOOGLE_NAVIGATION = "usegnav";
private static final String KEY_STORE_LOG_IMAGES = "logimages";
private static final String KEY_EXCLUDE_DISABLED = "excludedisabled";
private static final String KEY_EXCLUDE_OWN = "excludemine";
private static final String KEY_MAPFILE = "mfmapfile";
private static final String KEY_SIGNATURE = "signature";
private static final String KEY_GCVOTE_PASSWORD = "pass-vote";
private static final String KEY_PASSWORD = "password";
private static final String KEY_USERNAME = "username";
private static final String KEY_MEMBER_STATUS = "memberstatus";
private static final String KEY_COORD_INPUT_FORMAT = "coordinputformat";
private static final String KEY_LOG_OFFLINE = "log_offline";
private static final String KEY_LOAD_DIRECTION_IMG = "loaddirectionimg";
private static final String KEY_GC_CUSTOM_DATE = "gccustomdate";
private static final String KEY_SHOW_WAYPOINTS_THRESHOLD = "gcshowwaypointsthreshold";
private static final String KEY_COOKIE_STORE = "cookiestore";
private static final String KEY_OPEN_LAST_DETAILS_PAGE = "opendetailslastpage";
private static final String KEY_LAST_DETAILS_PAGE = "lastdetailspage";
private static final String KEY_DEFAULT_NAVIGATION_TOOL = "defaultNavigationTool";
private static final String KEY_DEFAULT_NAVIGATION_TOOL_2 = "defaultNavigationTool2";
private static final String KEY_LIVE_MAP_STRATEGY = "livemapstrategy";
private static final String KEY_DEBUG = "debug";
private static final String KEY_HIDE_LIVE_MAP_HINT = "hidelivemaphint";
private static final String KEY_LIVE_MAP_HINT_SHOW_COUNT = "livemaphintshowcount";
private static final String KEY_SETTINGS_VERSION = "settingsversion";
private static final String KEY_DB_ON_SDCARD = "dbonsdcard";
private static final String KEY_LAST_TRACKABLE_ACTION = "trackableaction";
private static final String KEY_SHARE_AFTER_EXPORT = "shareafterexport";
private static final String KEY_GPX_EXPORT_DIR = "gpxExportDir";
private static final String KEY_RENDER_THEME_BASE_FOLDER = "renderthemepath";
private static final String KEY_RENDER_THEME_FILE_PATH = "renderthemefile";
private static final String KEY_GPX_IMPORT_DIR = "gpxImportDir";
private static final String KEY_PLAIN_LOGS = "plainLogs";
private static final String KEY_NATIVE_UA = "nativeUa";
private static final String KEY_MAP_DIRECTORY = "mapDirectory";
private final static int unitsMetric = 1;
// twitter api keys
private final static String keyConsumerPublic = CryptUtils.rot13("ESnsCvAv3kEupF1GCR3jGj");
private final static String keyConsumerSecret = CryptUtils.rot13("7vQWceACV9umEjJucmlpFe9FCMZSeqIqfkQ2BnhV9x");
private interface PrefRunnable {
void edit(final Editor edit);
}
public enum coordInputFormatEnum {
Plain,
Deg,
Min,
Sec;
static coordInputFormatEnum fromInt(int id) {
final coordInputFormatEnum[] values = coordInputFormatEnum.values();
if (id < 0 || id >= values.length) {
return Min;
}
return values[id];
}
}
private static String username = null;
private static String password = null;
private static final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(cgeoapplication.getInstance().getBaseContext());
static {
migrateSettings();
Log.setDebugUnsaved(sharedPrefs.getBoolean(KEY_DEBUG, false));
}
// maps
private static MapProvider mapProvider = null;
private Settings() {
// this class is not to be instantiated;
}
private static void migrateSettings() {
// migrate from non standard file location and integer based boolean types
if (sharedPrefs.getInt(KEY_SETTINGS_VERSION, 0) < 1) {
final String oldPreferencesName = "cgeo.pref";
final SharedPreferences old = cgeoapplication.getInstance().getSharedPreferences(oldPreferencesName, Context.MODE_PRIVATE);
final Editor e = sharedPrefs.edit();
e.putString(KEY_TEMP_TOKEN_SECRET, old.getString(KEY_TEMP_TOKEN_SECRET, null));
e.putString(KEY_TEMP_TOKEN_PUBLIC, old.getString(KEY_TEMP_TOKEN_PUBLIC, null));
e.putBoolean(KEY_HELP_SHOWN, old.getInt(KEY_HELP_SHOWN, 0) != 0);
e.putFloat(KEY_ANYLONGITUDE, old.getFloat(KEY_ANYLONGITUDE, 0));
e.putFloat(KEY_ANYLATITUDE, old.getFloat(KEY_ANYLATITUDE, 0));
e.putBoolean(KEY_USE_OFFLINEMAPS, 0 != old.getInt(KEY_USE_OFFLINEMAPS, 1));
e.putBoolean(KEY_USE_OFFLINEWPMAPS, 0 != old.getInt(KEY_USE_OFFLINEWPMAPS, 0));
e.putString(KEY_WEB_DEVICE_CODE, old.getString(KEY_WEB_DEVICE_CODE, null));
e.putString(KEY_WEBDEVICE_NAME, old.getString(KEY_WEBDEVICE_NAME, null));
e.putBoolean(KEY_MAP_LIVE, old.getInt(KEY_MAP_LIVE, 1) != 0);
e.putInt(KEY_MAP_SOURCE, old.getInt(KEY_MAP_SOURCE, 0));
e.putBoolean(KEY_USE_TWITTER, 0 != old.getInt(KEY_USE_TWITTER, 0));
e.putBoolean(KEY_SHOW_ADDRESS, 0 != old.getInt(KEY_SHOW_ADDRESS, 1));
e.putBoolean(KEY_SHOW_CAPTCHA, old.getBoolean(KEY_SHOW_CAPTCHA, false));
e.putBoolean(KEY_MAP_TRAIL, old.getInt(KEY_MAP_TRAIL, 1) != 0);
e.putInt(KEY_LAST_MAP_ZOOM, old.getInt(KEY_LAST_MAP_ZOOM, 14));
e.putBoolean(KEY_LIVE_LIST, 0 != old.getInt(KEY_LIVE_LIST, 1));
e.putBoolean(KEY_METRIC_UNITS, old.getInt(KEY_METRIC_UNITS, unitsMetric) == unitsMetric);
e.putBoolean(KEY_SKIN, old.getInt(KEY_SKIN, 0) != 0);
e.putInt(KEY_LAST_USED_LIST, old.getInt(KEY_LAST_USED_LIST, StoredList.STANDARD_LIST_ID));
e.putString(KEY_CACHE_TYPE, old.getString(KEY_CACHE_TYPE, CacheType.ALL.id));
e.putString(KEY_TWITTER_TOKEN_SECRET, old.getString(KEY_TWITTER_TOKEN_SECRET, null));
e.putString(KEY_TWITTER_TOKEN_PUBLIC, old.getString(KEY_TWITTER_TOKEN_PUBLIC, null));
e.putInt(KEY_VERSION, old.getInt(KEY_VERSION, 0));
e.putBoolean(KEY_LOAD_DESCRIPTION, 0 != old.getInt(KEY_LOAD_DESCRIPTION, 0));
e.putBoolean(KEY_RATING_WANTED, old.getBoolean(KEY_RATING_WANTED, true));
e.putBoolean(KEY_ELEVATION_WANTED, old.getBoolean(KEY_ELEVATION_WANTED, true));
e.putBoolean(KEY_FRIENDLOGS_WANTED, old.getBoolean(KEY_FRIENDLOGS_WANTED, true));
e.putBoolean(KEY_USE_ENGLISH, old.getBoolean(KEY_USE_ENGLISH, false));
e.putBoolean(KEY_USE_COMPASS, 0 != old.getInt(KEY_USE_COMPASS, 1));
e.putBoolean(KEY_AUTO_VISIT_TRACKABLES, old.getBoolean(KEY_AUTO_VISIT_TRACKABLES, false));
e.putBoolean(KEY_AUTO_INSERT_SIGNATURE, old.getBoolean(KEY_AUTO_INSERT_SIGNATURE, false));
e.putInt(KEY_ALTITUDE_CORRECTION, old.getInt(KEY_ALTITUDE_CORRECTION, 0));
e.putBoolean(KEY_USE_GOOGLE_NAVIGATION, 0 != old.getInt(KEY_USE_GOOGLE_NAVIGATION, 1));
e.putBoolean(KEY_STORE_LOG_IMAGES, old.getBoolean(KEY_STORE_LOG_IMAGES, false));
e.putBoolean(KEY_EXCLUDE_DISABLED, 0 != old.getInt(KEY_EXCLUDE_DISABLED, 0));
e.putBoolean(KEY_EXCLUDE_OWN, 0 != old.getInt(KEY_EXCLUDE_OWN, 0));
e.putString(KEY_MAPFILE, old.getString(KEY_MAPFILE, null));
e.putString(KEY_SIGNATURE, old.getString(KEY_SIGNATURE, null));
e.putString(KEY_GCVOTE_PASSWORD, old.getString(KEY_GCVOTE_PASSWORD, null));
e.putString(KEY_PASSWORD, old.getString(KEY_PASSWORD, null));
e.putString(KEY_USERNAME, old.getString(KEY_USERNAME, null));
e.putString(KEY_MEMBER_STATUS, old.getString(KEY_MEMBER_STATUS, ""));
e.putInt(KEY_COORD_INPUT_FORMAT, old.getInt(KEY_COORD_INPUT_FORMAT, 0));
e.putBoolean(KEY_LOG_OFFLINE, old.getBoolean(KEY_LOG_OFFLINE, false));
e.putBoolean(KEY_LOAD_DIRECTION_IMG, old.getBoolean(KEY_LOAD_DIRECTION_IMG, true));
e.putString(KEY_GC_CUSTOM_DATE, old.getString(KEY_GC_CUSTOM_DATE, null));
e.putInt(KEY_SHOW_WAYPOINTS_THRESHOLD, old.getInt(KEY_SHOW_WAYPOINTS_THRESHOLD, 0));
e.putString(KEY_COOKIE_STORE, old.getString(KEY_COOKIE_STORE, null));
e.putBoolean(KEY_OPEN_LAST_DETAILS_PAGE, old.getBoolean(KEY_OPEN_LAST_DETAILS_PAGE, false));
e.putInt(KEY_LAST_DETAILS_PAGE, old.getInt(KEY_LAST_DETAILS_PAGE, 1));
- e.putInt(KEY_DEFAULT_NAVIGATION_TOOL, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL, 0));
- e.putInt(KEY_DEFAULT_NAVIGATION_TOOL_2, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL_2, 0));
+ e.putInt(KEY_DEFAULT_NAVIGATION_TOOL, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL, NavigationAppsEnum.COMPASS.id));
+ e.putInt(KEY_DEFAULT_NAVIGATION_TOOL_2, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL_2, NavigationAppsEnum.INTERNAL_MAP.id));
e.putInt(KEY_LIVE_MAP_STRATEGY, old.getInt(KEY_LIVE_MAP_STRATEGY, Strategy.AUTO.id));
e.putBoolean(KEY_DEBUG, old.getBoolean(KEY_DEBUG, false));
e.putBoolean(KEY_HIDE_LIVE_MAP_HINT, old.getInt(KEY_HIDE_LIVE_MAP_HINT, 0) != 0);
e.putInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, old.getInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, 0));
e.putInt(KEY_SETTINGS_VERSION, 1); // mark migrated
e.commit();
}
}
public static void setLanguage(boolean useEnglish) {
final Configuration config = new Configuration();
config.locale = useEnglish ? new Locale("en") : Locale.getDefault();
final Resources resources = cgeoapplication.getInstance().getResources();
resources.updateConfiguration(config, resources.getDisplayMetrics());
}
public static boolean isLogin() {
final String preUsername = sharedPrefs.getString(KEY_USERNAME, null);
final String prePassword = sharedPrefs.getString(KEY_PASSWORD, null);
return !StringUtils.isBlank(preUsername) && !StringUtils.isBlank(prePassword);
}
/**
* Get login and password information.
*
* @return a pair (login, password) or null if no valid information is stored
*/
public static ImmutablePair<String, String> getLogin() {
if (username == null || password == null) {
final String preUsername = sharedPrefs.getString(KEY_USERNAME, null);
final String prePassword = sharedPrefs.getString(KEY_PASSWORD, null);
if (preUsername == null || prePassword == null) {
return null;
}
username = preUsername;
password = prePassword;
}
return new ImmutablePair<String, String>(username, password);
}
public static String getUsername() {
return username != null ? username : sharedPrefs.getString(KEY_USERNAME, null);
}
public static boolean setLogin(final String username, final String password) {
Settings.username = username;
Settings.password = password;
return editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
// erase username and password
edit.remove(KEY_USERNAME);
edit.remove(KEY_PASSWORD);
} else {
// save username and password
edit.putString(KEY_USERNAME, username);
edit.putString(KEY_PASSWORD, password);
}
}
});
}
public static boolean isPremiumMember() {
// Basic Member, Premium Member, ???
String memberStatus = Settings.getMemberStatus();
if (memberStatus == null) {
return false;
}
return GCConstants.MEMBER_STATUS_PM.equalsIgnoreCase(memberStatus);
}
public static String getMemberStatus() {
return sharedPrefs.getString(KEY_MEMBER_STATUS, "");
}
public static boolean setMemberStatus(final String memberStatus) {
return editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
if (StringUtils.isBlank(memberStatus)) {
edit.remove(KEY_MEMBER_STATUS);
} else {
edit.putString(KEY_MEMBER_STATUS, memberStatus);
}
}
});
}
public static boolean isGCvoteLogin() {
final String preUsername = sharedPrefs.getString(KEY_USERNAME, null);
final String prePassword = sharedPrefs.getString(KEY_GCVOTE_PASSWORD, null);
return !StringUtils.isBlank(preUsername) && !StringUtils.isBlank(prePassword);
}
public static boolean setGCvoteLogin(final String password) {
return editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
if (StringUtils.isBlank(password)) {
// erase password
edit.remove(KEY_GCVOTE_PASSWORD);
} else {
// save password
edit.putString(KEY_GCVOTE_PASSWORD, password);
}
}
});
}
public static ImmutablePair<String, String> getGCvoteLogin() {
final String username = sharedPrefs.getString(KEY_USERNAME, null);
final String password = sharedPrefs.getString(KEY_GCVOTE_PASSWORD, null);
if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
return null;
}
return new ImmutablePair<String, String>(username, password);
}
public static boolean setSignature(final String signature) {
return editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
if (StringUtils.isBlank(signature)) {
// erase signature
edit.remove(KEY_SIGNATURE);
} else {
// save signature
edit.putString(KEY_SIGNATURE, signature);
}
}
});
}
public static String getSignature() {
return sharedPrefs.getString(KEY_SIGNATURE, null);
}
public static boolean setCookieStore(final String cookies) {
return editSharedSettings(new PrefRunnable() {
@Override
public void edit(final Editor edit) {
if (StringUtils.isBlank(cookies)) {
// erase cookies
edit.remove(KEY_COOKIE_STORE);
} else {
// save cookies
edit.putString(KEY_COOKIE_STORE, cookies);
}
}
});
}
public static String getCookieStore() {
return sharedPrefs.getString(KEY_COOKIE_STORE, null);
}
/**
* @param cacheType
* The cache type used for future filtering
*/
public static void setCacheType(final CacheType cacheType) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
if (cacheType == null) {
edit.remove(KEY_CACHE_TYPE);
} else {
edit.putString(KEY_CACHE_TYPE, cacheType.id);
}
}
});
}
public static void setLiveMap(final boolean live) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_MAP_LIVE, live);
}
});
}
public static int getLastList() {
return sharedPrefs.getInt(KEY_LAST_USED_LIST, StoredList.STANDARD_LIST_ID);
}
public static void saveLastList(final int listId) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_LAST_USED_LIST, listId);
}
});
}
public static void setWebNameCode(final String name, final String code) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_WEBDEVICE_NAME, name);
edit.putString(KEY_WEB_DEVICE_CODE, code);
}
});
}
public static MapProvider getMapProvider() {
if (mapProvider == null) {
mapProvider = getMapSource().getMapProvider();
}
return mapProvider;
}
public static String getMapFile() {
return sharedPrefs.getString(KEY_MAPFILE, null);
}
public static boolean setMapFile(final String mapFile) {
boolean result = editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_MAPFILE, mapFile);
}
});
if (mapFile != null) {
setMapFileDirectory(new File(mapFile).getParent());
}
return result;
}
public static String getMapFileDirectory() {
final String mapDir = sharedPrefs.getString(KEY_MAP_DIRECTORY, null);
if (mapDir != null) {
return mapDir;
}
final String mapFile = getMapFile();
if (mapFile != null) {
return new File(mapFile).getParent();
}
return null;
}
public static boolean setMapFileDirectory(final String mapFileDirectory) {
return editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_MAP_DIRECTORY, mapFileDirectory);
MapsforgeMapProvider.getInstance().updateOfflineMaps();
}
});
}
public static boolean isValidMapFile() {
return isValidMapFile(getMapFile());
}
public static boolean isValidMapFile(final String mapFileIn) {
return MapsforgeMapProvider.isValidMapFile(mapFileIn);
}
public static coordInputFormatEnum getCoordInputFormat() {
return coordInputFormatEnum.fromInt(sharedPrefs.getInt(KEY_COORD_INPUT_FORMAT, 0));
}
public static void setCoordInputFormat(final coordInputFormatEnum format) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_COORD_INPUT_FORMAT, format.ordinal());
}
});
}
static void setLogOffline(final boolean offline) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_LOG_OFFLINE, offline);
}
});
}
public static boolean getLogOffline() {
return sharedPrefs.getBoolean(KEY_LOG_OFFLINE, false);
}
static void setLoadDirImg(final boolean value) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_LOAD_DIRECTION_IMG, value);
}
});
}
public static boolean getLoadDirImg() {
return !isPremiumMember() && sharedPrefs.getBoolean(KEY_LOAD_DIRECTION_IMG, true);
}
public static void setGcCustomDate(final String format) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_GC_CUSTOM_DATE, format);
}
});
}
/**
* @return User selected date format on GC.com
* @see Login#gcCustomDateFormats
*/
public static String getGcCustomDate() {
return sharedPrefs.getString(KEY_GC_CUSTOM_DATE, null);
}
public static boolean isExcludeMyCaches() {
return sharedPrefs.getBoolean(KEY_EXCLUDE_OWN, false);
}
/**
* edit some settings without knowing how to get the settings editor or how to commit
*
* @param runnable
* @return
*/
private static boolean editSharedSettings(final PrefRunnable runnable) {
final SharedPreferences.Editor prefsEdit = sharedPrefs.edit();
runnable.edit(prefsEdit);
return prefsEdit.commit();
}
public static void setExcludeMine(final boolean exclude) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_EXCLUDE_OWN, exclude);
}
});
}
public static void setUseEnglish(final boolean english) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_USE_ENGLISH, english);
setLanguage(english);
}
});
}
public static boolean isUseEnglish() {
return sharedPrefs.getBoolean(KEY_USE_ENGLISH, false);
}
public static boolean isShowAddress() {
return sharedPrefs.getBoolean(KEY_SHOW_ADDRESS, true);
}
public static void setShowAddress(final boolean showAddress) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_SHOW_ADDRESS, showAddress);
}
});
}
public static boolean isShowCaptcha() {
return !isPremiumMember() && sharedPrefs.getBoolean(KEY_SHOW_CAPTCHA, false);
}
public static void setShowCaptcha(final boolean showCaptcha) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_SHOW_CAPTCHA, showCaptcha);
}
});
}
public static boolean isExcludeDisabledCaches() {
return sharedPrefs.getBoolean(KEY_EXCLUDE_DISABLED, false);
}
public static void setExcludeDisabledCaches(final boolean exclude) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_EXCLUDE_DISABLED, exclude);
}
});
}
public static boolean isStoreOfflineMaps() {
return sharedPrefs.getBoolean(KEY_USE_OFFLINEMAPS, true);
}
public static void setStoreOfflineMaps(final boolean offlineMaps) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_USE_OFFLINEMAPS, offlineMaps);
}
});
}
public static boolean isStoreOfflineWpMaps() {
return sharedPrefs.getBoolean(KEY_USE_OFFLINEWPMAPS, false);
}
public static void setStoreOfflineWpMaps(final boolean offlineMaps) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_USE_OFFLINEWPMAPS, offlineMaps);
}
});
}
public static boolean isStoreLogImages() {
return sharedPrefs.getBoolean(KEY_STORE_LOG_IMAGES, false);
}
public static void setStoreLogImages(final boolean storeLogImages) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_STORE_LOG_IMAGES, storeLogImages);
}
});
}
public static boolean isUseGoogleNavigation() {
return sharedPrefs.getBoolean(KEY_USE_GOOGLE_NAVIGATION, true);
}
public static void setUseGoogleNavigation(final boolean useGoogleNavigation) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_USE_GOOGLE_NAVIGATION, useGoogleNavigation);
}
});
}
public static boolean isAutoLoadDescription() {
return sharedPrefs.getBoolean(KEY_LOAD_DESCRIPTION, false);
}
public static void setAutoLoadDesc(final boolean autoLoad) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_LOAD_DESCRIPTION, autoLoad);
}
});
}
public static boolean isRatingWanted() {
return sharedPrefs.getBoolean(KEY_RATING_WANTED, true);
}
public static void setRatingWanted(final boolean ratingWanted) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_RATING_WANTED, ratingWanted);
}
});
}
public static boolean isElevationWanted() {
return sharedPrefs.getBoolean(KEY_ELEVATION_WANTED, true);
}
public static void setElevationWanted(final boolean elevationWanted) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_ELEVATION_WANTED, elevationWanted);
}
});
}
public static boolean isFriendLogsWanted() {
if (!isLogin()) {
// don't show a friends log if the user is anonymous
return false;
}
return sharedPrefs.getBoolean(KEY_FRIENDLOGS_WANTED, true);
}
public static void setFriendLogsWanted(final boolean friendLogsWanted) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_FRIENDLOGS_WANTED, friendLogsWanted);
}
});
}
public static boolean isLiveList() {
return sharedPrefs.getBoolean(KEY_LIVE_LIST, true);
}
public static void setLiveList(final boolean liveList) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_LIVE_LIST, liveList);
}
});
}
public static boolean isTrackableAutoVisit() {
return sharedPrefs.getBoolean(KEY_AUTO_VISIT_TRACKABLES, false);
}
public static void setTrackableAutoVisit(final boolean autoVisit) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_AUTO_VISIT_TRACKABLES, autoVisit);
}
});
}
public static boolean isAutoInsertSignature() {
return sharedPrefs.getBoolean(KEY_AUTO_INSERT_SIGNATURE, false);
}
public static void setAutoInsertSignature(final boolean autoInsert) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_AUTO_INSERT_SIGNATURE, autoInsert);
}
});
}
public static boolean isUseMetricUnits() {
return sharedPrefs.getBoolean(KEY_METRIC_UNITS, true);
}
public static void setUseMetricUnits(final boolean metric) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_METRIC_UNITS, metric);
}
});
}
public static boolean isLiveMap() {
return sharedPrefs.getBoolean(KEY_MAP_LIVE, true);
}
public static boolean isMapTrail() {
return sharedPrefs.getBoolean(KEY_MAP_TRAIL, true);
}
public static void setMapTrail(final boolean showTrail) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_MAP_TRAIL, showTrail);
}
});
}
public static int getMapZoom() {
return sharedPrefs.getInt(KEY_LAST_MAP_ZOOM, 14);
}
public static void setMapZoom(final int mapZoomLevel) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_LAST_MAP_ZOOM, mapZoomLevel);
}
});
}
public static GeoPointImpl getMapCenter() {
return getMapProvider().getMapItemFactory()
.getGeoPointBase(new Geopoint(sharedPrefs.getInt(KEY_LAST_MAP_LAT, 0) / 1e6,
sharedPrefs.getInt(KEY_LAST_MAP_LON, 0) / 1e6));
}
public static void setMapCenter(final GeoPointImpl mapViewCenter) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_LAST_MAP_LAT, mapViewCenter.getLatitudeE6());
edit.putInt(KEY_LAST_MAP_LON, mapViewCenter.getLongitudeE6());
}
});
}
public static MapSource getMapSource() {
final int id = getConvertedMapId();
final MapSource map = MapProviderFactory.getMapSource(id);
if (map != null) {
return map;
}
// fallback to first available map
return MapProviderFactory.getDefaultSource();
}
private final static int GOOGLEMAP_BASEID = 30;
private final static int MAP = 1;
private final static int SATELLITE = 2;
private final static int MFMAP_BASEID = 40;
private final static int MAPNIK = 1;
private final static int CYCLEMAP = 3;
private final static int OFFLINE = 4;
/**
* convert old preference ids for maps (based on constant values) into new hash based ids
*
* @return
*/
private static int getConvertedMapId() {
final int id = sharedPrefs.getInt(KEY_MAP_SOURCE, 0);
switch (id) {
case GOOGLEMAP_BASEID + MAP:
return GoogleMapProvider.GOOGLE_MAP_ID.hashCode();
case GOOGLEMAP_BASEID + SATELLITE:
return GoogleMapProvider.GOOGLE_SATELLITE_ID.hashCode();
case MFMAP_BASEID + MAPNIK:
return MapsforgeMapProvider.MAPSFORGE_MAPNIK_ID.hashCode();
case MFMAP_BASEID + CYCLEMAP:
return MapsforgeMapProvider.MAPSFORGE_CYCLEMAP_ID.hashCode();
case MFMAP_BASEID + OFFLINE: {
final String mapFile = Settings.getMapFile();
if (StringUtils.isNotEmpty(mapFile)) {
return mapFile.hashCode();
}
break;
}
default:
break;
}
return id;
}
public static void setMapSource(final MapSource newMapSource) {
if (!MapProviderFactory.isSameActivity(getMapSource(), newMapSource)) {
mapProvider = null;
}
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_MAP_SOURCE, newMapSource.getNumericalId());
}
});
if (newMapSource instanceof OfflineMapSource) {
setMapFile(((OfflineMapSource) newMapSource).getFileName());
}
}
public static void setAnyCoordinates(final Geopoint coords) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
if (null != coords) {
edit.putFloat(KEY_ANYLATITUDE, (float) coords.getLatitude());
edit.putFloat(KEY_ANYLONGITUDE, (float) coords.getLongitude());
} else {
edit.remove(KEY_ANYLATITUDE);
edit.remove(KEY_ANYLONGITUDE);
}
}
});
}
public static Geopoint getAnyCoordinates() {
if (sharedPrefs.contains(KEY_ANYLATITUDE) && sharedPrefs.contains(KEY_ANYLONGITUDE)) {
float lat = sharedPrefs.getFloat(KEY_ANYLATITUDE, 0);
float lon = sharedPrefs.getFloat(KEY_ANYLONGITUDE, 0);
return new Geopoint(lat, lon);
}
return null;
}
public static boolean isUseCompass() {
return sharedPrefs.getBoolean(KEY_USE_COMPASS, true);
}
public static void setUseCompass(final boolean useCompass) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_USE_COMPASS, useCompass);
}
});
}
public static boolean isHelpShown() {
return sharedPrefs.getBoolean(KEY_HELP_SHOWN, false);
}
public static void setHelpShown() {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_HELP_SHOWN, true);
}
});
}
public static boolean isLightSkin() {
return sharedPrefs.getBoolean(KEY_SKIN, false);
}
public static void setLightSkin(final boolean lightSkin) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_SKIN, lightSkin);
}
});
}
public static String getKeyConsumerPublic() {
return keyConsumerPublic;
}
public static String getKeyConsumerSecret() {
return keyConsumerSecret;
}
public static int getAltCorrection() {
return sharedPrefs.getInt(KEY_ALTITUDE_CORRECTION, 0);
}
public static boolean setAltCorrection(final int altitude) {
return editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_ALTITUDE_CORRECTION, altitude);
}
});
}
public static String getWebDeviceCode() {
return sharedPrefs.getString(KEY_WEB_DEVICE_CODE, null);
}
public static String getWebDeviceName() {
return sharedPrefs.getString(KEY_WEBDEVICE_NAME, null);
}
/**
* @return The cache type used for filtering or ALL if no filter is active. Returns never null
*/
public static CacheType getCacheType() {
return CacheType.getById(sharedPrefs.getString(KEY_CACHE_TYPE, CacheType.ALL.id));
}
/**
* The Threshold for the showing of child waypoints
*
* @return
*/
public static int getWayPointsThreshold() {
return sharedPrefs.getInt(KEY_SHOW_WAYPOINTS_THRESHOLD, 0);
}
public static void setShowWaypointsThreshold(final int threshold) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_SHOW_WAYPOINTS_THRESHOLD, threshold);
}
});
}
public static boolean isUseTwitter() {
return sharedPrefs.getBoolean(KEY_USE_TWITTER, false);
}
public static void setUseTwitter(final boolean useTwitter) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_USE_TWITTER, useTwitter);
}
});
}
public static boolean isTwitterLoginValid() {
return !StringUtils.isBlank(getTokenPublic()) && !StringUtils.isBlank(getTokenSecret());
}
public static String getTokenPublic() {
return sharedPrefs.getString(KEY_TWITTER_TOKEN_PUBLIC, null);
}
public static String getTokenSecret() {
return sharedPrefs.getString(KEY_TWITTER_TOKEN_SECRET, null);
}
public static int getVersion() {
return sharedPrefs.getInt(KEY_VERSION, 0);
}
public static void setTwitterTokens(final String tokenPublic, final String tokenSecret, boolean enableTwitter) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_TWITTER_TOKEN_PUBLIC, tokenPublic);
edit.putString(KEY_TWITTER_TOKEN_SECRET, tokenSecret);
if (tokenPublic != null) {
edit.remove(KEY_TEMP_TOKEN_PUBLIC);
edit.remove(KEY_TEMP_TOKEN_SECRET);
}
}
});
setUseTwitter(enableTwitter);
}
public static void setTwitterTempTokens(final String tokenPublic, final String tokenSecret) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_TEMP_TOKEN_PUBLIC, tokenPublic);
edit.putString(KEY_TEMP_TOKEN_SECRET, tokenSecret);
}
});
}
public static ImmutablePair<String, String> getTempToken() {
String tokenPublic = sharedPrefs.getString(KEY_TEMP_TOKEN_PUBLIC, null);
String tokenSecret = sharedPrefs.getString(KEY_TEMP_TOKEN_SECRET, null);
return new ImmutablePair<String, String>(tokenPublic, tokenSecret);
}
public static void setVersion(final int version) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_VERSION, version);
}
});
}
public static boolean isOpenLastDetailsPage() {
return sharedPrefs.getBoolean(KEY_OPEN_LAST_DETAILS_PAGE, false);
}
public static void setOpenLastDetailsPage(final boolean openLastPage) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_OPEN_LAST_DETAILS_PAGE, openLastPage);
}
});
}
public static int getLastDetailsPage() {
return sharedPrefs.getInt(KEY_LAST_DETAILS_PAGE, 1);
}
public static void setLastDetailsPage(final int index) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_LAST_DETAILS_PAGE, index);
}
});
}
public static int getDefaultNavigationTool() {
return sharedPrefs.getInt(KEY_DEFAULT_NAVIGATION_TOOL, NavigationAppsEnum.COMPASS.id);
}
public static void setDefaultNavigationTool(final int defaultNavigationTool) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_DEFAULT_NAVIGATION_TOOL, defaultNavigationTool);
}
});
}
public static int getDefaultNavigationTool2() {
return sharedPrefs.getInt(KEY_DEFAULT_NAVIGATION_TOOL_2, NavigationAppsEnum.INTERNAL_MAP.id);
}
public static void setDefaultNavigationTool2(final int defaultNavigationTool) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_DEFAULT_NAVIGATION_TOOL_2, defaultNavigationTool);
}
});
}
public static Strategy getLiveMapStrategy() {
return Strategy.getById(sharedPrefs.getInt(KEY_LIVE_MAP_STRATEGY, Strategy.AUTO.id));
}
public static void setLiveMapStrategy(final Strategy strategy) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_LIVE_MAP_STRATEGY, strategy.id);
}
});
}
public static boolean isDebug() {
return Log.isDebug();
}
public static void setDebug(final boolean debug) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_DEBUG, debug);
}
});
Log.setDebugUnsaved(debug);
}
public static boolean getHideLiveMapHint() {
return sharedPrefs.getBoolean(KEY_HIDE_LIVE_MAP_HINT, false);
}
public static void setHideLiveHint(final boolean hide) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_HIDE_LIVE_MAP_HINT, hide);
}
});
}
public static int getLiveMapHintShowCount() {
return sharedPrefs.getInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, 0);
}
public static void setLiveMapHintShowCount(final int showCount) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, showCount);
}
});
}
public static boolean isDbOnSDCard() {
return sharedPrefs.getBoolean(KEY_DB_ON_SDCARD, false);
}
public static void setDbOnSDCard(final boolean dbOnSDCard) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_DB_ON_SDCARD, dbOnSDCard);
}
});
}
public static String getGpxExportDir() {
return sharedPrefs.getString(KEY_GPX_EXPORT_DIR, Environment.getExternalStorageDirectory().getPath() + "/gpx");
}
public static void setGpxExportDir(final String gpxExportDir) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_GPX_EXPORT_DIR, gpxExportDir);
}
});
}
public static String getGpxImportDir() {
return sharedPrefs.getString(KEY_GPX_IMPORT_DIR, Environment.getExternalStorageDirectory().getPath() + "/gpx");
}
public static void setGpxImportDir(final String gpxImportDir) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_GPX_IMPORT_DIR, gpxImportDir);
}
});
}
public static boolean getShareAfterExport() {
return sharedPrefs.getBoolean(KEY_SHARE_AFTER_EXPORT, true);
}
public static void setShareAfterExport(final boolean shareAfterExport) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_SHARE_AFTER_EXPORT, shareAfterExport);
}
});
}
public static int getTrackableAction() {
return sharedPrefs.getInt(KEY_LAST_TRACKABLE_ACTION, LogType.RETRIEVED_IT.id);
}
public static void setTrackableAction(final int trackableAction) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putInt(KEY_LAST_TRACKABLE_ACTION, trackableAction);
}
});
}
public static String getCustomRenderThemeBaseFolder() {
return sharedPrefs.getString(KEY_RENDER_THEME_BASE_FOLDER, "");
}
public static void setCustomRenderThemeBaseFolder(final String customRenderThemeBaseFolder) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_RENDER_THEME_BASE_FOLDER, customRenderThemeBaseFolder);
}
});
}
public static String getCustomRenderThemeFilePath() {
return sharedPrefs.getString(KEY_RENDER_THEME_FILE_PATH, "");
}
public static void setCustomRenderThemeFile(final String customRenderThemeFile) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putString(KEY_RENDER_THEME_FILE_PATH, customRenderThemeFile);
}
});
}
public static File[] getMapThemeFiles() {
File directory = new File(Settings.getCustomRenderThemeBaseFolder());
List<File> result = new ArrayList<File>();
FileUtils.listDir(result, directory, new ExtensionsBasedFileSelector(new String[] { "xml" }), null);
return result.toArray(new File[] {});
}
private static class ExtensionsBasedFileSelector extends FileSelector {
private final String[] extensions;
public ExtensionsBasedFileSelector(String[] extensions) {
this.extensions = extensions;
}
@Override
public boolean isSelected(File file) {
String filename = file.getName();
for (String ext : extensions) {
if (StringUtils.endsWithIgnoreCase(filename, ext)) {
return true;
}
}
return false;
}
@Override
public boolean shouldEnd() {
return false;
}
}
public static String getPreferencesName() {
// there is currently no Android API to get the file name of the shared preferences
return cgeoapplication.getInstance().getPackageName() + "_preferences";
}
public static boolean getPlainLogs() {
return sharedPrefs.getBoolean(KEY_PLAIN_LOGS, false);
}
public static void setPlainLogs(final boolean plainLogs) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_PLAIN_LOGS, plainLogs);
}
});
}
public static boolean getUseNativeUa() {
return sharedPrefs.getBoolean(KEY_NATIVE_UA, false);
}
public static void setUseNativeUa(final boolean useNativeUa) {
editSharedSettings(new PrefRunnable() {
@Override
public void edit(Editor edit) {
edit.putBoolean(KEY_NATIVE_UA, useNativeUa);
}
});
}
}
| true | true | private static void migrateSettings() {
// migrate from non standard file location and integer based boolean types
if (sharedPrefs.getInt(KEY_SETTINGS_VERSION, 0) < 1) {
final String oldPreferencesName = "cgeo.pref";
final SharedPreferences old = cgeoapplication.getInstance().getSharedPreferences(oldPreferencesName, Context.MODE_PRIVATE);
final Editor e = sharedPrefs.edit();
e.putString(KEY_TEMP_TOKEN_SECRET, old.getString(KEY_TEMP_TOKEN_SECRET, null));
e.putString(KEY_TEMP_TOKEN_PUBLIC, old.getString(KEY_TEMP_TOKEN_PUBLIC, null));
e.putBoolean(KEY_HELP_SHOWN, old.getInt(KEY_HELP_SHOWN, 0) != 0);
e.putFloat(KEY_ANYLONGITUDE, old.getFloat(KEY_ANYLONGITUDE, 0));
e.putFloat(KEY_ANYLATITUDE, old.getFloat(KEY_ANYLATITUDE, 0));
e.putBoolean(KEY_USE_OFFLINEMAPS, 0 != old.getInt(KEY_USE_OFFLINEMAPS, 1));
e.putBoolean(KEY_USE_OFFLINEWPMAPS, 0 != old.getInt(KEY_USE_OFFLINEWPMAPS, 0));
e.putString(KEY_WEB_DEVICE_CODE, old.getString(KEY_WEB_DEVICE_CODE, null));
e.putString(KEY_WEBDEVICE_NAME, old.getString(KEY_WEBDEVICE_NAME, null));
e.putBoolean(KEY_MAP_LIVE, old.getInt(KEY_MAP_LIVE, 1) != 0);
e.putInt(KEY_MAP_SOURCE, old.getInt(KEY_MAP_SOURCE, 0));
e.putBoolean(KEY_USE_TWITTER, 0 != old.getInt(KEY_USE_TWITTER, 0));
e.putBoolean(KEY_SHOW_ADDRESS, 0 != old.getInt(KEY_SHOW_ADDRESS, 1));
e.putBoolean(KEY_SHOW_CAPTCHA, old.getBoolean(KEY_SHOW_CAPTCHA, false));
e.putBoolean(KEY_MAP_TRAIL, old.getInt(KEY_MAP_TRAIL, 1) != 0);
e.putInt(KEY_LAST_MAP_ZOOM, old.getInt(KEY_LAST_MAP_ZOOM, 14));
e.putBoolean(KEY_LIVE_LIST, 0 != old.getInt(KEY_LIVE_LIST, 1));
e.putBoolean(KEY_METRIC_UNITS, old.getInt(KEY_METRIC_UNITS, unitsMetric) == unitsMetric);
e.putBoolean(KEY_SKIN, old.getInt(KEY_SKIN, 0) != 0);
e.putInt(KEY_LAST_USED_LIST, old.getInt(KEY_LAST_USED_LIST, StoredList.STANDARD_LIST_ID));
e.putString(KEY_CACHE_TYPE, old.getString(KEY_CACHE_TYPE, CacheType.ALL.id));
e.putString(KEY_TWITTER_TOKEN_SECRET, old.getString(KEY_TWITTER_TOKEN_SECRET, null));
e.putString(KEY_TWITTER_TOKEN_PUBLIC, old.getString(KEY_TWITTER_TOKEN_PUBLIC, null));
e.putInt(KEY_VERSION, old.getInt(KEY_VERSION, 0));
e.putBoolean(KEY_LOAD_DESCRIPTION, 0 != old.getInt(KEY_LOAD_DESCRIPTION, 0));
e.putBoolean(KEY_RATING_WANTED, old.getBoolean(KEY_RATING_WANTED, true));
e.putBoolean(KEY_ELEVATION_WANTED, old.getBoolean(KEY_ELEVATION_WANTED, true));
e.putBoolean(KEY_FRIENDLOGS_WANTED, old.getBoolean(KEY_FRIENDLOGS_WANTED, true));
e.putBoolean(KEY_USE_ENGLISH, old.getBoolean(KEY_USE_ENGLISH, false));
e.putBoolean(KEY_USE_COMPASS, 0 != old.getInt(KEY_USE_COMPASS, 1));
e.putBoolean(KEY_AUTO_VISIT_TRACKABLES, old.getBoolean(KEY_AUTO_VISIT_TRACKABLES, false));
e.putBoolean(KEY_AUTO_INSERT_SIGNATURE, old.getBoolean(KEY_AUTO_INSERT_SIGNATURE, false));
e.putInt(KEY_ALTITUDE_CORRECTION, old.getInt(KEY_ALTITUDE_CORRECTION, 0));
e.putBoolean(KEY_USE_GOOGLE_NAVIGATION, 0 != old.getInt(KEY_USE_GOOGLE_NAVIGATION, 1));
e.putBoolean(KEY_STORE_LOG_IMAGES, old.getBoolean(KEY_STORE_LOG_IMAGES, false));
e.putBoolean(KEY_EXCLUDE_DISABLED, 0 != old.getInt(KEY_EXCLUDE_DISABLED, 0));
e.putBoolean(KEY_EXCLUDE_OWN, 0 != old.getInt(KEY_EXCLUDE_OWN, 0));
e.putString(KEY_MAPFILE, old.getString(KEY_MAPFILE, null));
e.putString(KEY_SIGNATURE, old.getString(KEY_SIGNATURE, null));
e.putString(KEY_GCVOTE_PASSWORD, old.getString(KEY_GCVOTE_PASSWORD, null));
e.putString(KEY_PASSWORD, old.getString(KEY_PASSWORD, null));
e.putString(KEY_USERNAME, old.getString(KEY_USERNAME, null));
e.putString(KEY_MEMBER_STATUS, old.getString(KEY_MEMBER_STATUS, ""));
e.putInt(KEY_COORD_INPUT_FORMAT, old.getInt(KEY_COORD_INPUT_FORMAT, 0));
e.putBoolean(KEY_LOG_OFFLINE, old.getBoolean(KEY_LOG_OFFLINE, false));
e.putBoolean(KEY_LOAD_DIRECTION_IMG, old.getBoolean(KEY_LOAD_DIRECTION_IMG, true));
e.putString(KEY_GC_CUSTOM_DATE, old.getString(KEY_GC_CUSTOM_DATE, null));
e.putInt(KEY_SHOW_WAYPOINTS_THRESHOLD, old.getInt(KEY_SHOW_WAYPOINTS_THRESHOLD, 0));
e.putString(KEY_COOKIE_STORE, old.getString(KEY_COOKIE_STORE, null));
e.putBoolean(KEY_OPEN_LAST_DETAILS_PAGE, old.getBoolean(KEY_OPEN_LAST_DETAILS_PAGE, false));
e.putInt(KEY_LAST_DETAILS_PAGE, old.getInt(KEY_LAST_DETAILS_PAGE, 1));
e.putInt(KEY_DEFAULT_NAVIGATION_TOOL, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL, 0));
e.putInt(KEY_DEFAULT_NAVIGATION_TOOL_2, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL_2, 0));
e.putInt(KEY_LIVE_MAP_STRATEGY, old.getInt(KEY_LIVE_MAP_STRATEGY, Strategy.AUTO.id));
e.putBoolean(KEY_DEBUG, old.getBoolean(KEY_DEBUG, false));
e.putBoolean(KEY_HIDE_LIVE_MAP_HINT, old.getInt(KEY_HIDE_LIVE_MAP_HINT, 0) != 0);
e.putInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, old.getInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, 0));
e.putInt(KEY_SETTINGS_VERSION, 1); // mark migrated
e.commit();
}
}
| private static void migrateSettings() {
// migrate from non standard file location and integer based boolean types
if (sharedPrefs.getInt(KEY_SETTINGS_VERSION, 0) < 1) {
final String oldPreferencesName = "cgeo.pref";
final SharedPreferences old = cgeoapplication.getInstance().getSharedPreferences(oldPreferencesName, Context.MODE_PRIVATE);
final Editor e = sharedPrefs.edit();
e.putString(KEY_TEMP_TOKEN_SECRET, old.getString(KEY_TEMP_TOKEN_SECRET, null));
e.putString(KEY_TEMP_TOKEN_PUBLIC, old.getString(KEY_TEMP_TOKEN_PUBLIC, null));
e.putBoolean(KEY_HELP_SHOWN, old.getInt(KEY_HELP_SHOWN, 0) != 0);
e.putFloat(KEY_ANYLONGITUDE, old.getFloat(KEY_ANYLONGITUDE, 0));
e.putFloat(KEY_ANYLATITUDE, old.getFloat(KEY_ANYLATITUDE, 0));
e.putBoolean(KEY_USE_OFFLINEMAPS, 0 != old.getInt(KEY_USE_OFFLINEMAPS, 1));
e.putBoolean(KEY_USE_OFFLINEWPMAPS, 0 != old.getInt(KEY_USE_OFFLINEWPMAPS, 0));
e.putString(KEY_WEB_DEVICE_CODE, old.getString(KEY_WEB_DEVICE_CODE, null));
e.putString(KEY_WEBDEVICE_NAME, old.getString(KEY_WEBDEVICE_NAME, null));
e.putBoolean(KEY_MAP_LIVE, old.getInt(KEY_MAP_LIVE, 1) != 0);
e.putInt(KEY_MAP_SOURCE, old.getInt(KEY_MAP_SOURCE, 0));
e.putBoolean(KEY_USE_TWITTER, 0 != old.getInt(KEY_USE_TWITTER, 0));
e.putBoolean(KEY_SHOW_ADDRESS, 0 != old.getInt(KEY_SHOW_ADDRESS, 1));
e.putBoolean(KEY_SHOW_CAPTCHA, old.getBoolean(KEY_SHOW_CAPTCHA, false));
e.putBoolean(KEY_MAP_TRAIL, old.getInt(KEY_MAP_TRAIL, 1) != 0);
e.putInt(KEY_LAST_MAP_ZOOM, old.getInt(KEY_LAST_MAP_ZOOM, 14));
e.putBoolean(KEY_LIVE_LIST, 0 != old.getInt(KEY_LIVE_LIST, 1));
e.putBoolean(KEY_METRIC_UNITS, old.getInt(KEY_METRIC_UNITS, unitsMetric) == unitsMetric);
e.putBoolean(KEY_SKIN, old.getInt(KEY_SKIN, 0) != 0);
e.putInt(KEY_LAST_USED_LIST, old.getInt(KEY_LAST_USED_LIST, StoredList.STANDARD_LIST_ID));
e.putString(KEY_CACHE_TYPE, old.getString(KEY_CACHE_TYPE, CacheType.ALL.id));
e.putString(KEY_TWITTER_TOKEN_SECRET, old.getString(KEY_TWITTER_TOKEN_SECRET, null));
e.putString(KEY_TWITTER_TOKEN_PUBLIC, old.getString(KEY_TWITTER_TOKEN_PUBLIC, null));
e.putInt(KEY_VERSION, old.getInt(KEY_VERSION, 0));
e.putBoolean(KEY_LOAD_DESCRIPTION, 0 != old.getInt(KEY_LOAD_DESCRIPTION, 0));
e.putBoolean(KEY_RATING_WANTED, old.getBoolean(KEY_RATING_WANTED, true));
e.putBoolean(KEY_ELEVATION_WANTED, old.getBoolean(KEY_ELEVATION_WANTED, true));
e.putBoolean(KEY_FRIENDLOGS_WANTED, old.getBoolean(KEY_FRIENDLOGS_WANTED, true));
e.putBoolean(KEY_USE_ENGLISH, old.getBoolean(KEY_USE_ENGLISH, false));
e.putBoolean(KEY_USE_COMPASS, 0 != old.getInt(KEY_USE_COMPASS, 1));
e.putBoolean(KEY_AUTO_VISIT_TRACKABLES, old.getBoolean(KEY_AUTO_VISIT_TRACKABLES, false));
e.putBoolean(KEY_AUTO_INSERT_SIGNATURE, old.getBoolean(KEY_AUTO_INSERT_SIGNATURE, false));
e.putInt(KEY_ALTITUDE_CORRECTION, old.getInt(KEY_ALTITUDE_CORRECTION, 0));
e.putBoolean(KEY_USE_GOOGLE_NAVIGATION, 0 != old.getInt(KEY_USE_GOOGLE_NAVIGATION, 1));
e.putBoolean(KEY_STORE_LOG_IMAGES, old.getBoolean(KEY_STORE_LOG_IMAGES, false));
e.putBoolean(KEY_EXCLUDE_DISABLED, 0 != old.getInt(KEY_EXCLUDE_DISABLED, 0));
e.putBoolean(KEY_EXCLUDE_OWN, 0 != old.getInt(KEY_EXCLUDE_OWN, 0));
e.putString(KEY_MAPFILE, old.getString(KEY_MAPFILE, null));
e.putString(KEY_SIGNATURE, old.getString(KEY_SIGNATURE, null));
e.putString(KEY_GCVOTE_PASSWORD, old.getString(KEY_GCVOTE_PASSWORD, null));
e.putString(KEY_PASSWORD, old.getString(KEY_PASSWORD, null));
e.putString(KEY_USERNAME, old.getString(KEY_USERNAME, null));
e.putString(KEY_MEMBER_STATUS, old.getString(KEY_MEMBER_STATUS, ""));
e.putInt(KEY_COORD_INPUT_FORMAT, old.getInt(KEY_COORD_INPUT_FORMAT, 0));
e.putBoolean(KEY_LOG_OFFLINE, old.getBoolean(KEY_LOG_OFFLINE, false));
e.putBoolean(KEY_LOAD_DIRECTION_IMG, old.getBoolean(KEY_LOAD_DIRECTION_IMG, true));
e.putString(KEY_GC_CUSTOM_DATE, old.getString(KEY_GC_CUSTOM_DATE, null));
e.putInt(KEY_SHOW_WAYPOINTS_THRESHOLD, old.getInt(KEY_SHOW_WAYPOINTS_THRESHOLD, 0));
e.putString(KEY_COOKIE_STORE, old.getString(KEY_COOKIE_STORE, null));
e.putBoolean(KEY_OPEN_LAST_DETAILS_PAGE, old.getBoolean(KEY_OPEN_LAST_DETAILS_PAGE, false));
e.putInt(KEY_LAST_DETAILS_PAGE, old.getInt(KEY_LAST_DETAILS_PAGE, 1));
e.putInt(KEY_DEFAULT_NAVIGATION_TOOL, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL, NavigationAppsEnum.COMPASS.id));
e.putInt(KEY_DEFAULT_NAVIGATION_TOOL_2, old.getInt(KEY_DEFAULT_NAVIGATION_TOOL_2, NavigationAppsEnum.INTERNAL_MAP.id));
e.putInt(KEY_LIVE_MAP_STRATEGY, old.getInt(KEY_LIVE_MAP_STRATEGY, Strategy.AUTO.id));
e.putBoolean(KEY_DEBUG, old.getBoolean(KEY_DEBUG, false));
e.putBoolean(KEY_HIDE_LIVE_MAP_HINT, old.getInt(KEY_HIDE_LIVE_MAP_HINT, 0) != 0);
e.putInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, old.getInt(KEY_LIVE_MAP_HINT_SHOW_COUNT, 0));
e.putInt(KEY_SETTINGS_VERSION, 1); // mark migrated
e.commit();
}
}
|
diff --git a/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/embeddable/EmbeddableTest.java b/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/embeddable/EmbeddableTest.java
index 8720e0986..b89f78754 100644
--- a/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/embeddable/EmbeddableTest.java
+++ b/hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/embeddable/EmbeddableTest.java
@@ -1,95 +1,95 @@
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2010, Red Hat, Inc. and/or its affiliates or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat, Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.ogm.test.embeddable;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.ogm.test.simpleentity.OgmTestCase;
/**
* @author Emmanuel Bernard
*/
public class EmbeddableTest extends OgmTestCase {
public void testEmbeddable() throws Exception {
final Session session = openSession();
Transaction transaction = session.beginTransaction();
Account account = new Account();
account.setLogin( "emmanuel" );
account.setPassword( "like I would tell ya" );
account.setHomeAddress( new Address() );
final Address address = account.getHomeAddress();
address.setCity( "Paris" );
address.setCountry( "France" );
- address.setStreet1( "1 avenue des Champs Elys�es" );
+ address.setStreet1( "1 avenue des Champs Elysees" );
address.setZipCode( "75007" );
session.persist( account );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
final Account loadedAccount = (Account) session.get( Account.class, account.getLogin() );
assertNotNull( "Cannot load persisted object", loadedAccount );
final Address loadedAddress = loadedAccount.getHomeAddress();
assertNotNull( "Embeddable should not be null", loadedAddress );
assertEquals( "persist and load fails for embeddable", loadedAddress.getCity(), address.getCity() );
assertEquals( "@Column support for embeddable does not work", loadedAddress.getZipCode(), address.getZipCode() );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
loadedAddress.setCountry( "USA" );
session.merge( loadedAccount );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
Account secondLoadedAccount = (Account) session.get( Account.class, account.getLogin() );
assertEquals(
"Merge fails for embeddable",
loadedAccount.getHomeAddress().getCity(),
secondLoadedAccount.getHomeAddress().getCity() );
session.delete( secondLoadedAccount );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
assertNull( session.get( Account.class, account.getLogin() ) );
transaction.commit();
session.close();
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Account.class
};
}
}
| true | true | public void testEmbeddable() throws Exception {
final Session session = openSession();
Transaction transaction = session.beginTransaction();
Account account = new Account();
account.setLogin( "emmanuel" );
account.setPassword( "like I would tell ya" );
account.setHomeAddress( new Address() );
final Address address = account.getHomeAddress();
address.setCity( "Paris" );
address.setCountry( "France" );
address.setStreet1( "1 avenue des Champs Elys�es" );
address.setZipCode( "75007" );
session.persist( account );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
final Account loadedAccount = (Account) session.get( Account.class, account.getLogin() );
assertNotNull( "Cannot load persisted object", loadedAccount );
final Address loadedAddress = loadedAccount.getHomeAddress();
assertNotNull( "Embeddable should not be null", loadedAddress );
assertEquals( "persist and load fails for embeddable", loadedAddress.getCity(), address.getCity() );
assertEquals( "@Column support for embeddable does not work", loadedAddress.getZipCode(), address.getZipCode() );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
loadedAddress.setCountry( "USA" );
session.merge( loadedAccount );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
Account secondLoadedAccount = (Account) session.get( Account.class, account.getLogin() );
assertEquals(
"Merge fails for embeddable",
loadedAccount.getHomeAddress().getCity(),
secondLoadedAccount.getHomeAddress().getCity() );
session.delete( secondLoadedAccount );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
assertNull( session.get( Account.class, account.getLogin() ) );
transaction.commit();
session.close();
}
| public void testEmbeddable() throws Exception {
final Session session = openSession();
Transaction transaction = session.beginTransaction();
Account account = new Account();
account.setLogin( "emmanuel" );
account.setPassword( "like I would tell ya" );
account.setHomeAddress( new Address() );
final Address address = account.getHomeAddress();
address.setCity( "Paris" );
address.setCountry( "France" );
address.setStreet1( "1 avenue des Champs Elysees" );
address.setZipCode( "75007" );
session.persist( account );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
final Account loadedAccount = (Account) session.get( Account.class, account.getLogin() );
assertNotNull( "Cannot load persisted object", loadedAccount );
final Address loadedAddress = loadedAccount.getHomeAddress();
assertNotNull( "Embeddable should not be null", loadedAddress );
assertEquals( "persist and load fails for embeddable", loadedAddress.getCity(), address.getCity() );
assertEquals( "@Column support for embeddable does not work", loadedAddress.getZipCode(), address.getZipCode() );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
loadedAddress.setCountry( "USA" );
session.merge( loadedAccount );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
Account secondLoadedAccount = (Account) session.get( Account.class, account.getLogin() );
assertEquals(
"Merge fails for embeddable",
loadedAccount.getHomeAddress().getCity(),
secondLoadedAccount.getHomeAddress().getCity() );
session.delete( secondLoadedAccount );
transaction.commit();
session.clear();
transaction = session.beginTransaction();
assertNull( session.get( Account.class, account.getLogin() ) );
transaction.commit();
session.close();
}
|
diff --git a/src/main/java/net/countercraft/movecraft/async/AsyncManager.java b/src/main/java/net/countercraft/movecraft/async/AsyncManager.java
index 189092a..dafe855 100644
--- a/src/main/java/net/countercraft/movecraft/async/AsyncManager.java
+++ b/src/main/java/net/countercraft/movecraft/async/AsyncManager.java
@@ -1,454 +1,454 @@
/*
* This file is part of Movecraft.
*
* Movecraft is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Movecraft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Movecraft. If not, see <http://www.gnu.org/licenses/>.
*/
package net.countercraft.movecraft.async;
import net.countercraft.movecraft.Movecraft;
import net.countercraft.movecraft.async.detection.DetectionTask;
import net.countercraft.movecraft.async.detection.DetectionTaskData;
import net.countercraft.movecraft.async.rotation.RotationTask;
import net.countercraft.movecraft.async.translation.TranslationTask;
import net.countercraft.movecraft.craft.Craft;
import net.countercraft.movecraft.craft.CraftManager;
import net.countercraft.movecraft.localisation.I18nSupport;
import net.countercraft.movecraft.utils.BlockUtils;
import net.countercraft.movecraft.utils.EntityUpdateCommand;
import net.countercraft.movecraft.utils.MapUpdateCommand;
import net.countercraft.movecraft.utils.MapUpdateManager;
import net.countercraft.movecraft.utils.MathUtils;
import net.countercraft.movecraft.utils.MovecraftLocation;
import org.apache.commons.collections.ListUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.util.Vector;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
public class AsyncManager extends BukkitRunnable {
private static final AsyncManager instance = new AsyncManager();
private final HashMap<AsyncTask, Craft> ownershipMap = new HashMap<AsyncTask, Craft>();
private final BlockingQueue<AsyncTask> finishedAlgorithms = new LinkedBlockingQueue<AsyncTask>();
private final HashSet<Craft> clearanceSet = new HashSet<Craft>();
private final HashMap<World, ArrayList<MovecraftLocation>> sinkingBlocks = new HashMap<World, ArrayList<MovecraftLocation>>();
private final HashMap<World, HashSet<MovecraftLocation>> waterFillBlocks = new HashMap<World, HashSet<MovecraftLocation>>();
private long lastSinkingUpdate = 0;
public static AsyncManager getInstance() {
return instance;
}
private AsyncManager() {
}
public void submitTask( AsyncTask task, Craft c ) {
if ( c.isNotProcessing() ) {
c.setProcessing( true );
ownershipMap.put( task, c );
task.runTaskAsynchronously( Movecraft.getInstance() );
}
}
public void submitCompletedTask( AsyncTask task ) {
finishedAlgorithms.add( task );
}
void processAlgorithmQueue() {
int runLength = 10;
int queueLength = finishedAlgorithms.size();
runLength = Math.min( runLength, queueLength );
for ( int i = 0; i < runLength; i++ ) {
boolean sentMapUpdate=false;
AsyncTask poll = finishedAlgorithms.poll();
Craft c = ownershipMap.get( poll );
if ( poll instanceof DetectionTask ) {
// Process detection task
DetectionTask task = ( DetectionTask ) poll;
DetectionTaskData data = task.getData();
Player p = Movecraft.getInstance().getServer().getPlayer( data.getPlayername() );
Craft pCraft = CraftManager.getInstance().getCraftByPlayer( p );
if ( pCraft != null ) {
//Player is already controlling a craft
p.sendMessage( String.format( I18nSupport.getInternationalisedString( "Detection - Failed - Already commanding a craft" ) ) );
} else {
if ( data.failed() ) {
Movecraft.getInstance().getServer().getPlayer( data.getPlayername() ).sendMessage( data.getFailMessage() );
} else {
Craft[] craftsInWorld = CraftManager.getInstance().getCraftsInWorld( c.getW() );
boolean failed = false;
if ( craftsInWorld != null ) {
for ( Craft craft : craftsInWorld ) {
if ( BlockUtils.arrayContainsOverlap( craft.getBlockList(), data.getBlockList() ) ) {
Movecraft.getInstance().getServer().getPlayer( data.getPlayername() ).sendMessage( String.format( I18nSupport.getInternationalisedString( "Detection - Failed Craft is already being controlled" ) ) );
failed = true;
}
}
}
if ( !failed ) {
c.setBlockList( data.getBlockList() );
c.setHitBox( data.getHitBox() );
c.setMinX( data.getMinX() );
c.setMinZ( data.getMinZ() );
Movecraft.getInstance().getServer().getPlayer( data.getPlayername() ).sendMessage( String.format( I18nSupport.getInternationalisedString( "Detection - Successfully piloted craft" ) ) );
Movecraft.getInstance().getLogger().log( Level.INFO, String.format( I18nSupport.getInternationalisedString( "Detection - Success - Log Output" ), p.getName(), c.getType().getCraftName(), c.getBlockList().length, c.getMinX(), c.getMinZ() ) );
CraftManager.getInstance().addCraft( c, Movecraft.getInstance().getServer().getPlayer( data.getPlayername() ) );
}
}
}
} else if ( poll instanceof TranslationTask ) {
//Process translation task
TranslationTask task = ( TranslationTask ) poll;
Player p = CraftManager.getInstance().getPlayerFromCraft( c );
// Check that the craft hasn't been sneakily unpiloted
if ( p != null ) {
if ( task.getData().failed() ) {
//The craft translation failed
p.sendMessage( task.getData().getFailMessage() );
if(task.getData().collisionExplosion()) {
MapUpdateCommand[] updates = task.getData().getUpdates();
c.setBlockList( task.getData().getBlockList() );
boolean failed = MapUpdateManager.getInstance().addWorldUpdate( c.getW(), updates, null);
if ( failed ) {
Movecraft.getInstance().getLogger().log( Level.SEVERE, String.format( I18nSupport.getInternationalisedString( "Translation - Craft collision" ) ) );
} else {
sentMapUpdate=true;
}
}
} else {
//The craft is clear to move, perform the block updates
MapUpdateCommand[] updates = task.getData().getUpdates();
EntityUpdateCommand[] eUpdates=task.getData().getEntityUpdates();
boolean failed = MapUpdateManager.getInstance().addWorldUpdate( c.getW(), updates, eUpdates);
if ( !failed ) {
sentMapUpdate=true;
c.setBlockList( task.getData().getBlockList() );
c.setMinX( task.getData().getMinX() );
c.setMinZ( task.getData().getMinZ() );
c.setHitBox( task.getData().getHitbox() );
} else {
Movecraft.getInstance().getLogger().log( Level.SEVERE, String.format( I18nSupport.getInternationalisedString( "Translation - Craft collision" ) ) );
}
}
}
} else if ( poll instanceof RotationTask ) {
// Process rotation task
RotationTask task = ( RotationTask ) poll;
Player p = CraftManager.getInstance().getPlayerFromCraft( c );
// Check that the craft hasn't been sneakily unpiloted
if ( p != null ) {
if ( task.isFailed() ) {
//The craft translation failed
p.sendMessage( task.getFailMessage() );
} else {
MapUpdateCommand[] updates = task.getUpdates();
EntityUpdateCommand[] eUpdates=task.getEntityUpdates();
boolean failed = MapUpdateManager.getInstance().addWorldUpdate( c.getW(), updates, eUpdates);
if ( !failed ) {
sentMapUpdate=true;
c.setBlockList( task.getBlockList() );
c.setMinX( task.getMinX() );
c.setMinZ( task.getMinZ() );
c.setHitBox( task.getHitbox() );
} else {
Movecraft.getInstance().getLogger().log( Level.SEVERE, String.format( I18nSupport.getInternationalisedString( "Rotation - Craft Collision" ) ) );
}
}
}
}
ownershipMap.remove( poll );
// only mark the craft as having finished updating if you didn't send any updates to the map updater. Otherwise the map updater will mark the crafts once it is done with them.
if(!sentMapUpdate) {
clear( c );
}
}
}
public void processCruise() {
for( World w : Bukkit.getWorlds()) {
if(w!=null && CraftManager.getInstance().getCraftsInWorld(w)!=null) {
for (Craft pcraft : CraftManager.getInstance().getCraftsInWorld(w)) {
if(pcraft!=null) {
if(pcraft.getCruising()) {
long ticksElapsed = ( System.currentTimeMillis() - pcraft.getLastCruiseUpdate() ) / 50;
if ( Math.abs( ticksElapsed ) >= pcraft.getType().getTickCooldown() ) {
int dx=0;
int dz=0;
// ship faces west
if(pcraft.getCruiseDirection()==0x5) {
dx=0-1-pcraft.getType().getCruiseSkipBlocks();
}
// ship faces east
if(pcraft.getCruiseDirection()==0x4) {
dx=1+pcraft.getType().getCruiseSkipBlocks();
}
// ship faces north
if(pcraft.getCruiseDirection()==0x2) {
dz=1+pcraft.getType().getCruiseSkipBlocks();
}
// ship faces south
if(pcraft.getCruiseDirection()==0x3) {
dz=0-1-pcraft.getType().getCruiseSkipBlocks();
}
pcraft.translate(dx, 0, dz);
pcraft.setLastCruisUpdate(System.currentTimeMillis());
}
} else {
if(pcraft.getLastDX()!=0 || pcraft.getLastDY()!=0 || pcraft.getLastDZ()!=0) {
long rcticksElapsed = ( System.currentTimeMillis() - pcraft.getLastRightClick() ) / 50;
rcticksElapsed=Math.abs(rcticksElapsed);
// if they are holding the button down, keep moving
if (rcticksElapsed <= 10 ) {
long ticksElapsed = ( System.currentTimeMillis() - pcraft.getLastCruiseUpdate() ) / 50;
if ( Math.abs( ticksElapsed ) >= pcraft.getType().getTickCooldown() ) {
pcraft.translate(pcraft.getLastDX(), pcraft.getLastDY(), pcraft.getLastDZ());
pcraft.setLastCruisUpdate(System.currentTimeMillis());
}
}
}
}
}
}
}
}
}
public void processSinking() {
for( World w : Bukkit.getWorlds()) {
if(w!=null && CraftManager.getInstance().getCraftsInWorld(w)!=null) {
// check every 5 seconds for every craft to see if it should be sinking
for (Craft pcraft : CraftManager.getInstance().getCraftsInWorld(w)) {
if(pcraft!=null) {
- if(pcraft.getType().getSinkPercent()!=0.0) {
+ if( pcraft.getType().getSinkPercent()!=0.0 && pcraft.isNotProcessing()) {
long ticksElapsed = ( System.currentTimeMillis() - pcraft.getLastBlockCheck() ) / 50;
if(ticksElapsed>100) {
int totalBlocks=0;
HashMap<Integer, Integer> foundFlyBlocks = new HashMap<Integer, Integer>();
// go through each block in the blocklist, and if its in the FlyBlocks, total up the number of them
for(MovecraftLocation l : pcraft.getBlockList()) {
int blockID=w.getBlockAt(l.getX(), l.getY(), l.getZ()).getTypeId();
if(pcraft.getType().getFlyBlocks().containsKey(blockID) ) {
Integer count=foundFlyBlocks.get(blockID);
if(count==null) {
foundFlyBlocks.put(blockID, 1);
} else {
foundFlyBlocks.put(blockID, count+1);
}
}
if(blockID!=0) { // && blockID!=9 && blockID!=8) {
totalBlocks++;
}
}
// now see if any of the resulting percentages are below the threshold specified in SinkPercent
boolean isSinking=false;
for(int i : pcraft.getType().getFlyBlocks().keySet()) {
int numfound=0;
if(foundFlyBlocks.get(i)!=null) {
numfound=foundFlyBlocks.get(i);
}
double percent=((double)numfound/(double)totalBlocks)*100.0;
double flyPercent=pcraft.getType().getFlyBlocks().get(i).get(0);
double sinkPercent=flyPercent*pcraft.getType().getSinkPercent()/100.0;
if(percent<sinkPercent) {
isSinking=true;
}
}
if(totalBlocks==0) {
isSinking=true;
}
// if the craft is sinking, let the player know and release the craft. Otherwise update the time for the next check
if(isSinking) {
// add the blocks of the craft to the sinking blocks
if(sinkingBlocks.get(w)==null) {
ArrayList<MovecraftLocation> t=new ArrayList<MovecraftLocation>();
sinkingBlocks.put(w, t);
}
sinkingBlocks.get(w).addAll(Arrays.asList(pcraft.getBlockList()));
Player p = CraftManager.getInstance().getPlayerFromCraft( pcraft );
p.sendMessage( String.format( I18nSupport.getInternationalisedString( "Player- Craft is sinking" ) ) );
CraftManager.getInstance().removeCraft( pcraft );
} else {
pcraft.setLastBlockCheck(System.currentTimeMillis());
}
}
}
}
}
}
}
// sink all the sinkingBlocks every second
final int[] fallThroughBlocks = new int[]{ 0, 8, 9, 10, 11, 31, 37, 38, 39, 40, 50, 51, 55, 59, 65, 69, 70, 72, 75, 76, 77, 78, 83, 93, 94, 111, 141, 142, 143, 171};
for( World w : Bukkit.getWorlds()) {
if(w!=null) {
long ticksElapsed = ( System.currentTimeMillis() - lastSinkingUpdate ) / 50;
if(ticksElapsed>=20 && sinkingBlocks.get( w )!=null) {
Iterator<MovecraftLocation> sBlocks=sinkingBlocks.get( w ).iterator();
HashSet<MovecraftLocation> oldBlockSet = new HashSet<MovecraftLocation>();
for(MovecraftLocation l : sinkingBlocks.get( w )) {
MovecraftLocation n=new MovecraftLocation(l.getX(),l.getY(),l.getZ());
oldBlockSet.add(n);
}
ArrayList<MapUpdateCommand> updates=new ArrayList<MapUpdateCommand>();
while(sBlocks.hasNext()) {
MovecraftLocation l=sBlocks.next();
MovecraftLocation oldLoc=new MovecraftLocation(l.getX(), l.getY(), l.getZ());
MovecraftLocation newLoc=new MovecraftLocation(l.getX(), l.getY()-1, l.getZ());
Block oldBlock=w.getBlockAt(l.getX(), l.getY(), l.getZ());
Block newBlock=w.getBlockAt(l.getX(), l.getY()-1, l.getZ());
// If the source is air, remove it from processing
if(oldBlock.getTypeId()!=0) {
// if falling through another falling block, search through all blocks downward to see if they are all on something solid. If so, don't fall
MovecraftLocation testLoc=new MovecraftLocation(newLoc.getX(),newLoc.getY(),newLoc.getZ());
while(oldBlockSet.contains(testLoc)) {
testLoc.setY(testLoc.getY()-1);
}
Block testBlock=w.getBlockAt(testLoc.getX(), testLoc.getY(), testLoc.getZ());
if(Arrays.binarySearch(fallThroughBlocks,testBlock.getTypeId())>=0) {
// remember which blocks used to be water, so we can fill it back in later
if(newBlock.getTypeId()==9) {
if(waterFillBlocks.get( w )==null) {
HashSet<MovecraftLocation> newA=new HashSet<MovecraftLocation>();
waterFillBlocks.put( w ,newA);
}
waterFillBlocks.get(w).add(newLoc);
}
MapUpdateCommand c=new MapUpdateCommand(oldLoc, newLoc, oldBlock.getTypeId(), null);
updates.add(c);
l.setY(l.getY()-1);
} else {
// if the block below is solid, remove the block from the falling list and the waterfill list. Also remove it from oldblocks, so it doesn't get filled in with air/water
waterFillBlocks.remove(l);
oldBlockSet.remove(l);
sBlocks.remove();
}
} else {
// don't process air, waste of time
// oldBlockSet.remove(l);
sBlocks.remove();
}
}
//now add in air or water to where the blocks used to be
// List<MovecraftLocation> fillLocation = ListUtils.subtract( Arrays.asList( oldBlockSet ), Arrays.asList( sinkingBlocks.get(w) ) );
for(MovecraftLocation l : oldBlockSet) {
if(!sinkingBlocks.get(w).contains(l)) {
MapUpdateCommand c;
if(waterFillBlocks.get( w )!=null) {
if(waterFillBlocks.get( w ).contains(l)) {
c=new MapUpdateCommand(l,9,null);
} else {
c=new MapUpdateCommand(l,0,null);
}
} else {
c=new MapUpdateCommand(l,0,null);
}
updates.add(c);
}
}
boolean failed = MapUpdateManager.getInstance().addWorldUpdate( w, updates.toArray(new MapUpdateCommand [0]), null);
lastSinkingUpdate=System.currentTimeMillis();
}
}
}
}
public void run() {
clearAll();
processCruise();
processSinking();
processAlgorithmQueue();
}
private void clear( Craft c ) {
clearanceSet.add( c );
}
private void clearAll() {
for ( Craft c : clearanceSet ) {
c.setProcessing( false );
}
clearanceSet.clear();
}
}
| true | true | public void processSinking() {
for( World w : Bukkit.getWorlds()) {
if(w!=null && CraftManager.getInstance().getCraftsInWorld(w)!=null) {
// check every 5 seconds for every craft to see if it should be sinking
for (Craft pcraft : CraftManager.getInstance().getCraftsInWorld(w)) {
if(pcraft!=null) {
if(pcraft.getType().getSinkPercent()!=0.0) {
long ticksElapsed = ( System.currentTimeMillis() - pcraft.getLastBlockCheck() ) / 50;
if(ticksElapsed>100) {
int totalBlocks=0;
HashMap<Integer, Integer> foundFlyBlocks = new HashMap<Integer, Integer>();
// go through each block in the blocklist, and if its in the FlyBlocks, total up the number of them
for(MovecraftLocation l : pcraft.getBlockList()) {
int blockID=w.getBlockAt(l.getX(), l.getY(), l.getZ()).getTypeId();
if(pcraft.getType().getFlyBlocks().containsKey(blockID) ) {
Integer count=foundFlyBlocks.get(blockID);
if(count==null) {
foundFlyBlocks.put(blockID, 1);
} else {
foundFlyBlocks.put(blockID, count+1);
}
}
if(blockID!=0) { // && blockID!=9 && blockID!=8) {
totalBlocks++;
}
}
// now see if any of the resulting percentages are below the threshold specified in SinkPercent
boolean isSinking=false;
for(int i : pcraft.getType().getFlyBlocks().keySet()) {
int numfound=0;
if(foundFlyBlocks.get(i)!=null) {
numfound=foundFlyBlocks.get(i);
}
double percent=((double)numfound/(double)totalBlocks)*100.0;
double flyPercent=pcraft.getType().getFlyBlocks().get(i).get(0);
double sinkPercent=flyPercent*pcraft.getType().getSinkPercent()/100.0;
if(percent<sinkPercent) {
isSinking=true;
}
}
if(totalBlocks==0) {
isSinking=true;
}
// if the craft is sinking, let the player know and release the craft. Otherwise update the time for the next check
if(isSinking) {
// add the blocks of the craft to the sinking blocks
if(sinkingBlocks.get(w)==null) {
ArrayList<MovecraftLocation> t=new ArrayList<MovecraftLocation>();
sinkingBlocks.put(w, t);
}
sinkingBlocks.get(w).addAll(Arrays.asList(pcraft.getBlockList()));
Player p = CraftManager.getInstance().getPlayerFromCraft( pcraft );
p.sendMessage( String.format( I18nSupport.getInternationalisedString( "Player- Craft is sinking" ) ) );
CraftManager.getInstance().removeCraft( pcraft );
} else {
pcraft.setLastBlockCheck(System.currentTimeMillis());
}
}
}
}
}
}
}
// sink all the sinkingBlocks every second
final int[] fallThroughBlocks = new int[]{ 0, 8, 9, 10, 11, 31, 37, 38, 39, 40, 50, 51, 55, 59, 65, 69, 70, 72, 75, 76, 77, 78, 83, 93, 94, 111, 141, 142, 143, 171};
for( World w : Bukkit.getWorlds()) {
if(w!=null) {
long ticksElapsed = ( System.currentTimeMillis() - lastSinkingUpdate ) / 50;
if(ticksElapsed>=20 && sinkingBlocks.get( w )!=null) {
Iterator<MovecraftLocation> sBlocks=sinkingBlocks.get( w ).iterator();
HashSet<MovecraftLocation> oldBlockSet = new HashSet<MovecraftLocation>();
for(MovecraftLocation l : sinkingBlocks.get( w )) {
MovecraftLocation n=new MovecraftLocation(l.getX(),l.getY(),l.getZ());
oldBlockSet.add(n);
}
ArrayList<MapUpdateCommand> updates=new ArrayList<MapUpdateCommand>();
while(sBlocks.hasNext()) {
MovecraftLocation l=sBlocks.next();
MovecraftLocation oldLoc=new MovecraftLocation(l.getX(), l.getY(), l.getZ());
MovecraftLocation newLoc=new MovecraftLocation(l.getX(), l.getY()-1, l.getZ());
Block oldBlock=w.getBlockAt(l.getX(), l.getY(), l.getZ());
Block newBlock=w.getBlockAt(l.getX(), l.getY()-1, l.getZ());
// If the source is air, remove it from processing
if(oldBlock.getTypeId()!=0) {
// if falling through another falling block, search through all blocks downward to see if they are all on something solid. If so, don't fall
MovecraftLocation testLoc=new MovecraftLocation(newLoc.getX(),newLoc.getY(),newLoc.getZ());
while(oldBlockSet.contains(testLoc)) {
testLoc.setY(testLoc.getY()-1);
}
Block testBlock=w.getBlockAt(testLoc.getX(), testLoc.getY(), testLoc.getZ());
if(Arrays.binarySearch(fallThroughBlocks,testBlock.getTypeId())>=0) {
// remember which blocks used to be water, so we can fill it back in later
if(newBlock.getTypeId()==9) {
if(waterFillBlocks.get( w )==null) {
HashSet<MovecraftLocation> newA=new HashSet<MovecraftLocation>();
waterFillBlocks.put( w ,newA);
}
waterFillBlocks.get(w).add(newLoc);
}
MapUpdateCommand c=new MapUpdateCommand(oldLoc, newLoc, oldBlock.getTypeId(), null);
updates.add(c);
l.setY(l.getY()-1);
} else {
// if the block below is solid, remove the block from the falling list and the waterfill list. Also remove it from oldblocks, so it doesn't get filled in with air/water
waterFillBlocks.remove(l);
oldBlockSet.remove(l);
sBlocks.remove();
}
} else {
// don't process air, waste of time
// oldBlockSet.remove(l);
sBlocks.remove();
}
}
//now add in air or water to where the blocks used to be
// List<MovecraftLocation> fillLocation = ListUtils.subtract( Arrays.asList( oldBlockSet ), Arrays.asList( sinkingBlocks.get(w) ) );
for(MovecraftLocation l : oldBlockSet) {
if(!sinkingBlocks.get(w).contains(l)) {
MapUpdateCommand c;
if(waterFillBlocks.get( w )!=null) {
if(waterFillBlocks.get( w ).contains(l)) {
c=new MapUpdateCommand(l,9,null);
} else {
c=new MapUpdateCommand(l,0,null);
}
} else {
c=new MapUpdateCommand(l,0,null);
}
updates.add(c);
}
}
boolean failed = MapUpdateManager.getInstance().addWorldUpdate( w, updates.toArray(new MapUpdateCommand [0]), null);
lastSinkingUpdate=System.currentTimeMillis();
}
}
}
}
public void run() {
clearAll();
processCruise();
processSinking();
processAlgorithmQueue();
}
private void clear( Craft c ) {
clearanceSet.add( c );
}
private void clearAll() {
for ( Craft c : clearanceSet ) {
c.setProcessing( false );
}
clearanceSet.clear();
}
}
| public void processSinking() {
for( World w : Bukkit.getWorlds()) {
if(w!=null && CraftManager.getInstance().getCraftsInWorld(w)!=null) {
// check every 5 seconds for every craft to see if it should be sinking
for (Craft pcraft : CraftManager.getInstance().getCraftsInWorld(w)) {
if(pcraft!=null) {
if( pcraft.getType().getSinkPercent()!=0.0 && pcraft.isNotProcessing()) {
long ticksElapsed = ( System.currentTimeMillis() - pcraft.getLastBlockCheck() ) / 50;
if(ticksElapsed>100) {
int totalBlocks=0;
HashMap<Integer, Integer> foundFlyBlocks = new HashMap<Integer, Integer>();
// go through each block in the blocklist, and if its in the FlyBlocks, total up the number of them
for(MovecraftLocation l : pcraft.getBlockList()) {
int blockID=w.getBlockAt(l.getX(), l.getY(), l.getZ()).getTypeId();
if(pcraft.getType().getFlyBlocks().containsKey(blockID) ) {
Integer count=foundFlyBlocks.get(blockID);
if(count==null) {
foundFlyBlocks.put(blockID, 1);
} else {
foundFlyBlocks.put(blockID, count+1);
}
}
if(blockID!=0) { // && blockID!=9 && blockID!=8) {
totalBlocks++;
}
}
// now see if any of the resulting percentages are below the threshold specified in SinkPercent
boolean isSinking=false;
for(int i : pcraft.getType().getFlyBlocks().keySet()) {
int numfound=0;
if(foundFlyBlocks.get(i)!=null) {
numfound=foundFlyBlocks.get(i);
}
double percent=((double)numfound/(double)totalBlocks)*100.0;
double flyPercent=pcraft.getType().getFlyBlocks().get(i).get(0);
double sinkPercent=flyPercent*pcraft.getType().getSinkPercent()/100.0;
if(percent<sinkPercent) {
isSinking=true;
}
}
if(totalBlocks==0) {
isSinking=true;
}
// if the craft is sinking, let the player know and release the craft. Otherwise update the time for the next check
if(isSinking) {
// add the blocks of the craft to the sinking blocks
if(sinkingBlocks.get(w)==null) {
ArrayList<MovecraftLocation> t=new ArrayList<MovecraftLocation>();
sinkingBlocks.put(w, t);
}
sinkingBlocks.get(w).addAll(Arrays.asList(pcraft.getBlockList()));
Player p = CraftManager.getInstance().getPlayerFromCraft( pcraft );
p.sendMessage( String.format( I18nSupport.getInternationalisedString( "Player- Craft is sinking" ) ) );
CraftManager.getInstance().removeCraft( pcraft );
} else {
pcraft.setLastBlockCheck(System.currentTimeMillis());
}
}
}
}
}
}
}
// sink all the sinkingBlocks every second
final int[] fallThroughBlocks = new int[]{ 0, 8, 9, 10, 11, 31, 37, 38, 39, 40, 50, 51, 55, 59, 65, 69, 70, 72, 75, 76, 77, 78, 83, 93, 94, 111, 141, 142, 143, 171};
for( World w : Bukkit.getWorlds()) {
if(w!=null) {
long ticksElapsed = ( System.currentTimeMillis() - lastSinkingUpdate ) / 50;
if(ticksElapsed>=20 && sinkingBlocks.get( w )!=null) {
Iterator<MovecraftLocation> sBlocks=sinkingBlocks.get( w ).iterator();
HashSet<MovecraftLocation> oldBlockSet = new HashSet<MovecraftLocation>();
for(MovecraftLocation l : sinkingBlocks.get( w )) {
MovecraftLocation n=new MovecraftLocation(l.getX(),l.getY(),l.getZ());
oldBlockSet.add(n);
}
ArrayList<MapUpdateCommand> updates=new ArrayList<MapUpdateCommand>();
while(sBlocks.hasNext()) {
MovecraftLocation l=sBlocks.next();
MovecraftLocation oldLoc=new MovecraftLocation(l.getX(), l.getY(), l.getZ());
MovecraftLocation newLoc=new MovecraftLocation(l.getX(), l.getY()-1, l.getZ());
Block oldBlock=w.getBlockAt(l.getX(), l.getY(), l.getZ());
Block newBlock=w.getBlockAt(l.getX(), l.getY()-1, l.getZ());
// If the source is air, remove it from processing
if(oldBlock.getTypeId()!=0) {
// if falling through another falling block, search through all blocks downward to see if they are all on something solid. If so, don't fall
MovecraftLocation testLoc=new MovecraftLocation(newLoc.getX(),newLoc.getY(),newLoc.getZ());
while(oldBlockSet.contains(testLoc)) {
testLoc.setY(testLoc.getY()-1);
}
Block testBlock=w.getBlockAt(testLoc.getX(), testLoc.getY(), testLoc.getZ());
if(Arrays.binarySearch(fallThroughBlocks,testBlock.getTypeId())>=0) {
// remember which blocks used to be water, so we can fill it back in later
if(newBlock.getTypeId()==9) {
if(waterFillBlocks.get( w )==null) {
HashSet<MovecraftLocation> newA=new HashSet<MovecraftLocation>();
waterFillBlocks.put( w ,newA);
}
waterFillBlocks.get(w).add(newLoc);
}
MapUpdateCommand c=new MapUpdateCommand(oldLoc, newLoc, oldBlock.getTypeId(), null);
updates.add(c);
l.setY(l.getY()-1);
} else {
// if the block below is solid, remove the block from the falling list and the waterfill list. Also remove it from oldblocks, so it doesn't get filled in with air/water
waterFillBlocks.remove(l);
oldBlockSet.remove(l);
sBlocks.remove();
}
} else {
// don't process air, waste of time
// oldBlockSet.remove(l);
sBlocks.remove();
}
}
//now add in air or water to where the blocks used to be
// List<MovecraftLocation> fillLocation = ListUtils.subtract( Arrays.asList( oldBlockSet ), Arrays.asList( sinkingBlocks.get(w) ) );
for(MovecraftLocation l : oldBlockSet) {
if(!sinkingBlocks.get(w).contains(l)) {
MapUpdateCommand c;
if(waterFillBlocks.get( w )!=null) {
if(waterFillBlocks.get( w ).contains(l)) {
c=new MapUpdateCommand(l,9,null);
} else {
c=new MapUpdateCommand(l,0,null);
}
} else {
c=new MapUpdateCommand(l,0,null);
}
updates.add(c);
}
}
boolean failed = MapUpdateManager.getInstance().addWorldUpdate( w, updates.toArray(new MapUpdateCommand [0]), null);
lastSinkingUpdate=System.currentTimeMillis();
}
}
}
}
public void run() {
clearAll();
processCruise();
processSinking();
processAlgorithmQueue();
}
private void clear( Craft c ) {
clearanceSet.add( c );
}
private void clearAll() {
for ( Craft c : clearanceSet ) {
c.setProcessing( false );
}
clearanceSet.clear();
}
}
|
diff --git a/src/uk/org/ponder/rsf/flow/errors/ActionErrorStrategyManager.java b/src/uk/org/ponder/rsf/flow/errors/ActionErrorStrategyManager.java
index e39d274..c63f6fd 100644
--- a/src/uk/org/ponder/rsf/flow/errors/ActionErrorStrategyManager.java
+++ b/src/uk/org/ponder/rsf/flow/errors/ActionErrorStrategyManager.java
@@ -1,76 +1,76 @@
/*
* Created on Dec 3, 2005
*/
package uk.org.ponder.rsf.flow.errors;
import java.util.ArrayList;
import java.util.List;
import uk.org.ponder.errorutil.CoreMessages;
import uk.org.ponder.errorutil.ThreadErrorState;
import uk.org.ponder.messageutil.TargettedMessage;
import uk.org.ponder.util.UniversalRuntimeException;
/**
* A collection point for ActionErrorStrategies. Tries each strategy in turn,
* and if none match the criteria for the current error, adopts a default
* strategy. This passes through any exception, and queues a general error
* message.
*
* @author Antranig Basman ([email protected])
*
*/
public class ActionErrorStrategyManager implements ActionErrorStrategy {
private List strategies = new ArrayList();
public void setMergeStrategies(ActionErrorStrategyManager strategies) {
this.strategies.addAll(strategies.getStrategies());
}
public void setStrategyList(List newstrategies) {
this.strategies.addAll(newstrategies);
}
public void addStrategy(ActionErrorStrategy toadd) {
strategies.add(toadd);
}
public ActionErrorStrategy strategyAt(int i) {
return (ActionErrorStrategy) strategies.get(i);
}
public List getStrategies() {
return strategies;
}
public Object handleError(String returncode, Exception exception,
String flowstate, String viewID, TargettedMessage message) {
Object code = null;
Throwable tohandlet = exception instanceof UniversalRuntimeException ?
((UniversalRuntimeException) exception).getTargetException()
: exception;
- if (!(tohandlet instanceof Exception)) {
+ if (tohandlet != null && !(tohandlet instanceof Exception)) {
// If it is an Error, throw it out immediately
throw UniversalRuntimeException.accumulate(tohandlet);
}
Exception tohandle = (Exception) tohandlet;
for (int i = 0; i < strategies.size(); ++i) {
code = strategyAt(i).handleError(returncode, tohandle, flowstate, viewID,
message);
if (code != null)
return code;
}
if (exception != null && code == null) {
// Logger.log.warn("Error invoking action", exception);
if (!ThreadErrorState.isError()) {
ThreadErrorState.addMessage(new TargettedMessage(
CoreMessages.GENERAL_ACTION_ERROR));
}
throw UniversalRuntimeException.accumulate(exception,
"Error invoking action");
}
return null;
}
}
| true | true | public Object handleError(String returncode, Exception exception,
String flowstate, String viewID, TargettedMessage message) {
Object code = null;
Throwable tohandlet = exception instanceof UniversalRuntimeException ?
((UniversalRuntimeException) exception).getTargetException()
: exception;
if (!(tohandlet instanceof Exception)) {
// If it is an Error, throw it out immediately
throw UniversalRuntimeException.accumulate(tohandlet);
}
Exception tohandle = (Exception) tohandlet;
for (int i = 0; i < strategies.size(); ++i) {
code = strategyAt(i).handleError(returncode, tohandle, flowstate, viewID,
message);
if (code != null)
return code;
}
if (exception != null && code == null) {
// Logger.log.warn("Error invoking action", exception);
if (!ThreadErrorState.isError()) {
ThreadErrorState.addMessage(new TargettedMessage(
CoreMessages.GENERAL_ACTION_ERROR));
}
throw UniversalRuntimeException.accumulate(exception,
"Error invoking action");
}
return null;
}
| public Object handleError(String returncode, Exception exception,
String flowstate, String viewID, TargettedMessage message) {
Object code = null;
Throwable tohandlet = exception instanceof UniversalRuntimeException ?
((UniversalRuntimeException) exception).getTargetException()
: exception;
if (tohandlet != null && !(tohandlet instanceof Exception)) {
// If it is an Error, throw it out immediately
throw UniversalRuntimeException.accumulate(tohandlet);
}
Exception tohandle = (Exception) tohandlet;
for (int i = 0; i < strategies.size(); ++i) {
code = strategyAt(i).handleError(returncode, tohandle, flowstate, viewID,
message);
if (code != null)
return code;
}
if (exception != null && code == null) {
// Logger.log.warn("Error invoking action", exception);
if (!ThreadErrorState.isError()) {
ThreadErrorState.addMessage(new TargettedMessage(
CoreMessages.GENERAL_ACTION_ERROR));
}
throw UniversalRuntimeException.accumulate(exception,
"Error invoking action");
}
return null;
}
|
diff --git a/src/DVN-web/src/edu/harvard/iq/dvn/api/datadeposit/ServiceDocumentManagerImpl.java b/src/DVN-web/src/edu/harvard/iq/dvn/api/datadeposit/ServiceDocumentManagerImpl.java
index 0247ee599..89ed5c691 100644
--- a/src/DVN-web/src/edu/harvard/iq/dvn/api/datadeposit/ServiceDocumentManagerImpl.java
+++ b/src/DVN-web/src/edu/harvard/iq/dvn/api/datadeposit/ServiceDocumentManagerImpl.java
@@ -1,106 +1,106 @@
/*
Copyright (C) 2005-2012, by the President and Fellows of Harvard College.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Dataverse Network - A web application to share, preserve and analyze research data.
Developed at the Institute for Quantitative Social Science, Harvard University.
Version 3.0.
*/
package edu.harvard.iq.dvn.api.datadeposit;
import edu.harvard.iq.dvn.core.admin.UserServiceLocal;
import edu.harvard.iq.dvn.core.admin.VDCUser;
import edu.harvard.iq.dvn.core.vdc.VDC;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.swordapp.server.AuthCredentials;
import org.swordapp.server.ServiceDocument;
import org.swordapp.server.ServiceDocumentManager;
import org.swordapp.server.SwordAuthException;
import org.swordapp.server.SwordCollection;
import org.swordapp.server.SwordConfiguration;
import org.swordapp.server.SwordError;
import org.swordapp.server.SwordServerException;
import org.swordapp.server.SwordWorkspace;
public class ServiceDocumentManagerImpl implements ServiceDocumentManager {
private static final Logger logger = Logger.getLogger(ServiceDocumentManagerImpl.class.getCanonicalName());
@Override
public ServiceDocument getServiceDocument(String sdUri, AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException, SwordAuthException {
SwordAuth swordAuth = new SwordAuth();
swordAuth.auth(authCredentials);
String username = authCredentials.getUsername();
logger.info("Checking username " + username + " ...");
try {
Context ctx = new InitialContext();
// "vdcUserService" comes from edu.harvard.iq.dvn.core.web.servlet.LoginFilter
UserServiceLocal userService = (UserServiceLocal) ctx.lookup("java:comp/env/vdcUserService");
VDCUser vdcUser = userService.findByUserName(username);
ServiceDocument service = new ServiceDocument();
SwordWorkspace swordWorkspace = new SwordWorkspace();
VDCServiceLocal vdcService = (VDCServiceLocal) ctx.lookup("java:comp/env/vdcService");
List<VDC> vdcList = vdcService.getUserVDCs(vdcUser.getId());
if (vdcList.size() != 1) {
- logger.info("accounts used to look up a Journal Dataverse should find a single dataverse");
- // should throw different exception
- throw new SwordAuthException();
+ String msg = "accounts used to look up a Journal Dataverse should find a single dataverse, not " + vdcList.size();
+ logger.info(msg);
+ throw new SwordError(msg);
}
if (vdcList.get(0) != null) {
VDC journalDataverse = vdcList.get(0);
String dvAlias = journalDataverse.getAlias();
swordWorkspace.setTitle(journalDataverse.getVdcNetwork().getName());
SwordCollection swordCollection = new SwordCollection();
swordCollection.setTitle(journalDataverse.getName());
try {
URI u = new URI(sdUri);
int port = u.getPort();
String hostName = System.getProperty("dvn.inetAddress");
// hard coding https on purpose
swordCollection.setHref("https://" + hostName + ":" + port + "/dvn/api/data-deposit/swordv2/collection/dataverse/" + dvAlias);
swordWorkspace.addCollection(swordCollection);
service.addWorkspace(swordWorkspace);
service.setMaxUploadSize(config.getMaxUploadSize());
return service;
} catch (URISyntaxException ex) {
- logger.info("problem with URL ( " + sdUri + " ): " + ex.getMessage());
- // should throw a different exception
- throw new SwordAuthException();
+ String msg = "problem with URL ( " + sdUri + " ): " + ex.getMessage();
+ logger.info(msg);
+ throw new SwordError(msg);
}
} else {
- logger.info("could not retrieve journal dataverse");
- // should throw a different exception
- throw new SwordAuthException();
+ String msg = "could not retrieve Journal Dataverse";
+ logger.info(msg);
+ throw new SwordError(msg);
}
} catch (NamingException ex) {
- logger.info("exception looking up userService: " + ex.getMessage());
- // would prefer to throw SwordError or SwordServerException here by they don't seem to be caught anywhere
- throw new SwordAuthException();
+ String msg = "exception looking up userService: " + ex.getMessage();
+ logger.info(msg);
+ throw new SwordError(msg);
}
}
}
| false | true | public ServiceDocument getServiceDocument(String sdUri, AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException, SwordAuthException {
SwordAuth swordAuth = new SwordAuth();
swordAuth.auth(authCredentials);
String username = authCredentials.getUsername();
logger.info("Checking username " + username + " ...");
try {
Context ctx = new InitialContext();
// "vdcUserService" comes from edu.harvard.iq.dvn.core.web.servlet.LoginFilter
UserServiceLocal userService = (UserServiceLocal) ctx.lookup("java:comp/env/vdcUserService");
VDCUser vdcUser = userService.findByUserName(username);
ServiceDocument service = new ServiceDocument();
SwordWorkspace swordWorkspace = new SwordWorkspace();
VDCServiceLocal vdcService = (VDCServiceLocal) ctx.lookup("java:comp/env/vdcService");
List<VDC> vdcList = vdcService.getUserVDCs(vdcUser.getId());
if (vdcList.size() != 1) {
logger.info("accounts used to look up a Journal Dataverse should find a single dataverse");
// should throw different exception
throw new SwordAuthException();
}
if (vdcList.get(0) != null) {
VDC journalDataverse = vdcList.get(0);
String dvAlias = journalDataverse.getAlias();
swordWorkspace.setTitle(journalDataverse.getVdcNetwork().getName());
SwordCollection swordCollection = new SwordCollection();
swordCollection.setTitle(journalDataverse.getName());
try {
URI u = new URI(sdUri);
int port = u.getPort();
String hostName = System.getProperty("dvn.inetAddress");
// hard coding https on purpose
swordCollection.setHref("https://" + hostName + ":" + port + "/dvn/api/data-deposit/swordv2/collection/dataverse/" + dvAlias);
swordWorkspace.addCollection(swordCollection);
service.addWorkspace(swordWorkspace);
service.setMaxUploadSize(config.getMaxUploadSize());
return service;
} catch (URISyntaxException ex) {
logger.info("problem with URL ( " + sdUri + " ): " + ex.getMessage());
// should throw a different exception
throw new SwordAuthException();
}
} else {
logger.info("could not retrieve journal dataverse");
// should throw a different exception
throw new SwordAuthException();
}
} catch (NamingException ex) {
logger.info("exception looking up userService: " + ex.getMessage());
// would prefer to throw SwordError or SwordServerException here by they don't seem to be caught anywhere
throw new SwordAuthException();
}
}
| public ServiceDocument getServiceDocument(String sdUri, AuthCredentials authCredentials, SwordConfiguration config)
throws SwordError, SwordServerException, SwordAuthException {
SwordAuth swordAuth = new SwordAuth();
swordAuth.auth(authCredentials);
String username = authCredentials.getUsername();
logger.info("Checking username " + username + " ...");
try {
Context ctx = new InitialContext();
// "vdcUserService" comes from edu.harvard.iq.dvn.core.web.servlet.LoginFilter
UserServiceLocal userService = (UserServiceLocal) ctx.lookup("java:comp/env/vdcUserService");
VDCUser vdcUser = userService.findByUserName(username);
ServiceDocument service = new ServiceDocument();
SwordWorkspace swordWorkspace = new SwordWorkspace();
VDCServiceLocal vdcService = (VDCServiceLocal) ctx.lookup("java:comp/env/vdcService");
List<VDC> vdcList = vdcService.getUserVDCs(vdcUser.getId());
if (vdcList.size() != 1) {
String msg = "accounts used to look up a Journal Dataverse should find a single dataverse, not " + vdcList.size();
logger.info(msg);
throw new SwordError(msg);
}
if (vdcList.get(0) != null) {
VDC journalDataverse = vdcList.get(0);
String dvAlias = journalDataverse.getAlias();
swordWorkspace.setTitle(journalDataverse.getVdcNetwork().getName());
SwordCollection swordCollection = new SwordCollection();
swordCollection.setTitle(journalDataverse.getName());
try {
URI u = new URI(sdUri);
int port = u.getPort();
String hostName = System.getProperty("dvn.inetAddress");
// hard coding https on purpose
swordCollection.setHref("https://" + hostName + ":" + port + "/dvn/api/data-deposit/swordv2/collection/dataverse/" + dvAlias);
swordWorkspace.addCollection(swordCollection);
service.addWorkspace(swordWorkspace);
service.setMaxUploadSize(config.getMaxUploadSize());
return service;
} catch (URISyntaxException ex) {
String msg = "problem with URL ( " + sdUri + " ): " + ex.getMessage();
logger.info(msg);
throw new SwordError(msg);
}
} else {
String msg = "could not retrieve Journal Dataverse";
logger.info(msg);
throw new SwordError(msg);
}
} catch (NamingException ex) {
String msg = "exception looking up userService: " + ex.getMessage();
logger.info(msg);
throw new SwordError(msg);
}
}
|
diff --git a/editor/tools/plugins/com.google.dart.tools.ui/src/com/google/dart/tools/ui/internal/intro/IntroEditor.java b/editor/tools/plugins/com.google.dart.tools.ui/src/com/google/dart/tools/ui/internal/intro/IntroEditor.java
index eba3a769c..2b2f27475 100644
--- a/editor/tools/plugins/com.google.dart.tools.ui/src/com/google/dart/tools/ui/internal/intro/IntroEditor.java
+++ b/editor/tools/plugins/com.google.dart.tools.ui/src/com/google/dart/tools/ui/internal/intro/IntroEditor.java
@@ -1,180 +1,180 @@
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Eclipse Public License v1.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.eclipse.org/legal/epl-v10.html
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.dart.tools.ui.internal.intro;
import com.google.dart.tools.ui.DartToolsPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IPersistableElement;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
import org.eclipse.ui.part.EditorPart;
/**
* A "fake" editor for showing intro content to first time users.
*/
public class IntroEditor extends EditorPart {
/*
* TODO (pquitslund): string content should be externalized.
*/
public static final String ID = "com.google.dart.tools.ui.intro.editor";
public static IEditorInput getInput() {
return new IEditorInput() {
@Override
public boolean exists() {
return false;
}
@Override
public Object getAdapter(@SuppressWarnings("rawtypes") Class adapter) {
return null;
}
@Override
public ImageDescriptor getImageDescriptor() {
return null;
}
@Override
public String getName() {
return "Welcome";
}
@Override
public IPersistableElement getPersistable() {
return null;
}
@Override
public String getToolTipText() {
return "Welcome to Dart!";
}
};
}
private static String bold(String str) {
return "<span font=\"header\">" + str + "</span>";
}
private static String img(String imgName) {
return " <img href=\"" + imgName + "\"/> ";
}
private final FormToolkit toolkit = new FormToolkit(Display.getCurrent());
@Override
public void createPartControl(Composite parent) {
createIntroContent(parent);
}
@Override
public void dispose() {
toolkit.dispose();
super.dispose();
}
@Override
public void doSave(IProgressMonitor monitor) {
//no-op
}
@Override
public void doSaveAs() {
//no-op
}
@Override
public void init(IEditorSite site, IEditorInput input) {
setSite(site);
setInput(input);
setTitleToolTip(input.getToolTipText());
}
@Override
public boolean isDirty() {
return false;
}
@Override
public boolean isSaveAsAllowed() {
return false;
}
@Override
public void setFocus() {
//do nothing on focus gain
}
private Composite createIntroContent(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
TableWrapLayout layout = new TableWrapLayout();
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
layout.bottomMargin = 0;
layout.topMargin = 20;
layout.rightMargin = 0;
layout.leftMargin = 20;
composite.setLayout(layout);
toolkit.adapt(composite);
FormText formText = toolkit.createFormText(composite, true);
formText.setLayoutData(GridDataFactory.fillDefaults().grab(true, true));
StringBuffer buf = new StringBuffer();
buf.append("<form>");
buf.append("<p>");
buf.append("<span color=\"header\" font=\"header\">" + "Getting started is easy!</span>");
buf.append("</p>");
buf.append("<p>" + bold("1. Click ") + img("new_lib_image") + bold("to create an application.")
+ "</p>");
buf.append("<p>" + bold("2. Look around. Click ") + img("run_image") + bold(" to run.")
+ "</p>");
buf.append("<li style=\"text\" bindent=\"20\" indent=\"20\">"
- + "<span color=\"header\">(compiles to Javascript and runs in Chrome).</span></li>");
+ + "<span color=\"header\">(compiles to JavaScript and runs in Chrome)</span></li>");
buf.append("<p>" + bold("3. Have fun. Write awesome code.") + "</p>");
buf.append("</form>");
formText.setWhitespaceNormalized(true);
TableWrapData twd_formText = new TableWrapData(TableWrapData.FILL);
twd_formText.grabHorizontal = true;
formText.setLayoutData(twd_formText);
formText.setImage("new_lib_image",
DartToolsPlugin.getImage("icons/full/dart16/library_new.png"));
formText.setImage("run_image", DartToolsPlugin.getImage("icons/full/etool16/run_exc.gif"));
formText.setColor("header", toolkit.getColors().getColor(IFormColors.TITLE));
formText.setFont("header", JFaceResources.getHeaderFont());
formText.setText(buf.toString(), true, false);
return composite;
}
}
| true | true | private Composite createIntroContent(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
TableWrapLayout layout = new TableWrapLayout();
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
layout.bottomMargin = 0;
layout.topMargin = 20;
layout.rightMargin = 0;
layout.leftMargin = 20;
composite.setLayout(layout);
toolkit.adapt(composite);
FormText formText = toolkit.createFormText(composite, true);
formText.setLayoutData(GridDataFactory.fillDefaults().grab(true, true));
StringBuffer buf = new StringBuffer();
buf.append("<form>");
buf.append("<p>");
buf.append("<span color=\"header\" font=\"header\">" + "Getting started is easy!</span>");
buf.append("</p>");
buf.append("<p>" + bold("1. Click ") + img("new_lib_image") + bold("to create an application.")
+ "</p>");
buf.append("<p>" + bold("2. Look around. Click ") + img("run_image") + bold(" to run.")
+ "</p>");
buf.append("<li style=\"text\" bindent=\"20\" indent=\"20\">"
+ "<span color=\"header\">(compiles to Javascript and runs in Chrome).</span></li>");
buf.append("<p>" + bold("3. Have fun. Write awesome code.") + "</p>");
buf.append("</form>");
formText.setWhitespaceNormalized(true);
TableWrapData twd_formText = new TableWrapData(TableWrapData.FILL);
twd_formText.grabHorizontal = true;
formText.setLayoutData(twd_formText);
formText.setImage("new_lib_image",
DartToolsPlugin.getImage("icons/full/dart16/library_new.png"));
formText.setImage("run_image", DartToolsPlugin.getImage("icons/full/etool16/run_exc.gif"));
formText.setColor("header", toolkit.getColors().getColor(IFormColors.TITLE));
formText.setFont("header", JFaceResources.getHeaderFont());
formText.setText(buf.toString(), true, false);
return composite;
}
| private Composite createIntroContent(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
TableWrapLayout layout = new TableWrapLayout();
layout.verticalSpacing = 0;
layout.horizontalSpacing = 0;
layout.bottomMargin = 0;
layout.topMargin = 20;
layout.rightMargin = 0;
layout.leftMargin = 20;
composite.setLayout(layout);
toolkit.adapt(composite);
FormText formText = toolkit.createFormText(composite, true);
formText.setLayoutData(GridDataFactory.fillDefaults().grab(true, true));
StringBuffer buf = new StringBuffer();
buf.append("<form>");
buf.append("<p>");
buf.append("<span color=\"header\" font=\"header\">" + "Getting started is easy!</span>");
buf.append("</p>");
buf.append("<p>" + bold("1. Click ") + img("new_lib_image") + bold("to create an application.")
+ "</p>");
buf.append("<p>" + bold("2. Look around. Click ") + img("run_image") + bold(" to run.")
+ "</p>");
buf.append("<li style=\"text\" bindent=\"20\" indent=\"20\">"
+ "<span color=\"header\">(compiles to JavaScript and runs in Chrome)</span></li>");
buf.append("<p>" + bold("3. Have fun. Write awesome code.") + "</p>");
buf.append("</form>");
formText.setWhitespaceNormalized(true);
TableWrapData twd_formText = new TableWrapData(TableWrapData.FILL);
twd_formText.grabHorizontal = true;
formText.setLayoutData(twd_formText);
formText.setImage("new_lib_image",
DartToolsPlugin.getImage("icons/full/dart16/library_new.png"));
formText.setImage("run_image", DartToolsPlugin.getImage("icons/full/etool16/run_exc.gif"));
formText.setColor("header", toolkit.getColors().getColor(IFormColors.TITLE));
formText.setFont("header", JFaceResources.getHeaderFont());
formText.setText(buf.toString(), true, false);
return composite;
}
|
diff --git a/src/de/leonhardt/sbm/smsbr/SmsBrIO.java b/src/de/leonhardt/sbm/smsbr/SmsBrIO.java
index 5e3bce4..989ab5b 100644
--- a/src/de/leonhardt/sbm/smsbr/SmsBrIO.java
+++ b/src/de/leonhardt/sbm/smsbr/SmsBrIO.java
@@ -1,221 +1,221 @@
package de.leonhardt.sbm.smsbr;
import java.io.File;
import java.util.Collection;
import java.util.logging.Logger;
import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.PropertyException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.xml.sax.SAXException;
import de.leonhardt.sbm.core.exception.MessageIOException;
import de.leonhardt.sbm.core.service.MessageIOService;
import de.leonhardt.sbm.smsbr.xml.debug.CustomMarshallListener;
import de.leonhardt.sbm.smsbr.xml.debug.CustomUnmarshallListener;
import de.leonhardt.sbm.smsbr.xml.debug.CustomValidationEventHandler;
import de.leonhardt.sbm.smsbr.xml.model.Sms;
import de.leonhardt.sbm.smsbr.xml.model.Smses;
/**
* This class is responsible for reading and writing Backup-XML files.
*
* @author Frederik Leonhardt
*
*/
public class SmsBrIO implements MessageIOService<Sms> {
private final String XML_XSL_HEADER = "\n<?xml-stylesheet type=\"text/xsl\" href=\"sms.xsl\"?>";
private final String XML_SCHEMA = "schema/schema.xsd";
protected boolean DEBUG = false;
protected Logger log = Logger.getLogger("SmsIO");
private JAXBContext jc; // our jaxb context
private Schema schema; // the validation schema, can be null (= no validation)
private Unmarshaller unmarshaller;
private Marshaller marshaller;
/**
* Creates new SmsIO
*
* @param includeXSL, if xsl-stylesheet header should be included in XML
* @throws MessageIOException, if JAXB can not be initialised
*/
public SmsBrIO(boolean includeXSL) throws MessageIOException {
// load schema
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
this.schema = schemaFactory.newSchema(new File(XML_SCHEMA));
} catch (SAXException e) {
log.warning("Schema '" + XML_SCHEMA + "' could not be loaded. No validation will take place.");
}
// initialize JAXB Context with XML classes
try {
this.jc = JAXBContext.newInstance("de.leonhardt.sbm.smsbr.xml");
// create marshaller and unmarshaller
this.unmarshaller = jc.createUnmarshaller();
this.marshaller = jc.createMarshaller();
// in debug mode, add some verbose output
if (DEBUG) {
unmarshaller.setEventHandler(new CustomValidationEventHandler());
unmarshaller.setListener(new CustomUnmarshallListener());
marshaller.setEventHandler(new CustomValidationEventHandler());
marshaller.setListener(new CustomMarshallListener());
}
} catch (JAXBException e) {
throw wrapException(e);
}
// set schema
unmarshaller.setSchema(this.schema);
marshaller.setSchema(this.schema);
// configure marshaller
try {
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (includeXSL) {
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", XML_XSL_HEADER);
}
} catch (PropertyException e) {
throw wrapException(e);
}
// done!
- this.log.info("Initialized MessageIO."
+ this.log.info("Initialized MessageIO (SMS Backup and Restore)."
+ "\n IncludeXSL = " + includeXSL
- + "\n Schema = " + schema.toString());
+ + "\n Schema = " + (schema == null ? "none" : schema.toString()));
}
/**
* Imports SMS from a given file path.
*
* @param filePath
* @return Messages wrapped by Smses object
*
* @throws IllegalArgumentException, if filePath == null
* @throws MessageIOException, if file does not contain any messages or a JAXB error occured
*/
public Collection<Sms> readFrom(String filePath) throws IllegalArgumentException, MessageIOException {
// check file path
if (filePath == null) {
throw new IllegalArgumentException("File path can not be null!");
}
// initialize File
File file = new File(filePath);
return readFrom(file);
}
/**
* Imports SMS from a given file.
*
* @param file
* @return Messages wrapped by Smses object
*
* @throws IllegalArgumentException, if file == null
* @throws MessageIOException, if file does not contain any messages or could not be parsed
*/
public Collection<Sms> readFrom(File file) throws IllegalArgumentException, MessageIOException {
// check file
if (file == null) {
throw new IllegalArgumentException("File can not be null!");
}
Smses smses;
try {
smses = (Smses)unmarshaller.unmarshal(file);
} catch (JAXBException e) {
// rethrow
throw wrapException(e);
}
// check if import was successful
if (smses == null || smses.getCount() == null || smses.getSms() == null) {
// fuck
log.severe("Import unsuccessful.");
throw wrapException(new FaultyInputXMLException("Could not parse XML file. Faulty file?"));
}
// check if number of messages is correct
Integer expectedCount = smses.getCount();
Integer actualCount = smses.getSms().size();
if (!expectedCount.equals(actualCount)) {
log.warning("Expected " + expectedCount + " messages, but found only " + actualCount + " messages.");
}
log.info("Sucessfully read " + actualCount + " messages from '" + file.getPath() + "'.");
return smses.getSms();
}
/**
* Writes a given Smses object to a given file path.
* @param smses
* @param filePath
*
* @throws IllegalArgumentException, if filePath is null
* @throws JAXBException
*/
public void writeTo(Collection<Sms> smses, String filePath) throws IllegalArgumentException, MessageIOException {
// check file path
if (filePath == null) {
throw new IllegalArgumentException("File path can not be null!");
}
// initialize File
File f = new File(filePath);
writeTo(smses, f);
}
/**
* Writes a given Smses object to a given file.
* @param smses
* @param file
*
* @throws IllegalArgumentException, if file is null
* @throws JAXBException
*/
public void writeTo(Collection<Sms> smsCol, File file) throws IllegalArgumentException, MessageIOException {
// check file
if (file == null) {
throw new IllegalArgumentException("File can not be null!");
}
// create xml wrapper object
Smses smses = new Smses(smsCol);
// push it out
try {
marshaller.marshal(smses,file);
} catch (JAXBException e) {
throw wrapException(e);
}
log.info("Sucessfully wrote " + smses.getCount() + " messages to '" + file.getPath() + "'.");
}
/**
* Wraps the given exception into a MEsssageIOException to conform to the
* MessageIOService interface.
*
* @param e
* @return
*/
private static MessageIOException wrapException(Exception e) {
return new MessageIOException(e);
}
}
| false | true | public SmsBrIO(boolean includeXSL) throws MessageIOException {
// load schema
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
this.schema = schemaFactory.newSchema(new File(XML_SCHEMA));
} catch (SAXException e) {
log.warning("Schema '" + XML_SCHEMA + "' could not be loaded. No validation will take place.");
}
// initialize JAXB Context with XML classes
try {
this.jc = JAXBContext.newInstance("de.leonhardt.sbm.smsbr.xml");
// create marshaller and unmarshaller
this.unmarshaller = jc.createUnmarshaller();
this.marshaller = jc.createMarshaller();
// in debug mode, add some verbose output
if (DEBUG) {
unmarshaller.setEventHandler(new CustomValidationEventHandler());
unmarshaller.setListener(new CustomUnmarshallListener());
marshaller.setEventHandler(new CustomValidationEventHandler());
marshaller.setListener(new CustomMarshallListener());
}
} catch (JAXBException e) {
throw wrapException(e);
}
// set schema
unmarshaller.setSchema(this.schema);
marshaller.setSchema(this.schema);
// configure marshaller
try {
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (includeXSL) {
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", XML_XSL_HEADER);
}
} catch (PropertyException e) {
throw wrapException(e);
}
// done!
this.log.info("Initialized MessageIO."
+ "\n IncludeXSL = " + includeXSL
+ "\n Schema = " + schema.toString());
}
| public SmsBrIO(boolean includeXSL) throws MessageIOException {
// load schema
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
try {
this.schema = schemaFactory.newSchema(new File(XML_SCHEMA));
} catch (SAXException e) {
log.warning("Schema '" + XML_SCHEMA + "' could not be loaded. No validation will take place.");
}
// initialize JAXB Context with XML classes
try {
this.jc = JAXBContext.newInstance("de.leonhardt.sbm.smsbr.xml");
// create marshaller and unmarshaller
this.unmarshaller = jc.createUnmarshaller();
this.marshaller = jc.createMarshaller();
// in debug mode, add some verbose output
if (DEBUG) {
unmarshaller.setEventHandler(new CustomValidationEventHandler());
unmarshaller.setListener(new CustomUnmarshallListener());
marshaller.setEventHandler(new CustomValidationEventHandler());
marshaller.setListener(new CustomMarshallListener());
}
} catch (JAXBException e) {
throw wrapException(e);
}
// set schema
unmarshaller.setSchema(this.schema);
marshaller.setSchema(this.schema);
// configure marshaller
try {
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
if (includeXSL) {
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", XML_XSL_HEADER);
}
} catch (PropertyException e) {
throw wrapException(e);
}
// done!
this.log.info("Initialized MessageIO (SMS Backup and Restore)."
+ "\n IncludeXSL = " + includeXSL
+ "\n Schema = " + (schema == null ? "none" : schema.toString()));
}
|
diff --git a/src/com/chess/genesis/view/BoardButton.java b/src/com/chess/genesis/view/BoardButton.java
index 8e1b79f..103008c 100644
--- a/src/com/chess/genesis/view/BoardButton.java
+++ b/src/com/chess/genesis/view/BoardButton.java
@@ -1,110 +1,110 @@
package com.chess.genesis;
import android.content.Context;
import android.view.View;
import android.widget.FrameLayout;
class BoardButton extends FrameLayout
{
private static final int[] pieceImages = {
R.drawable.piece_black_king, R.drawable.piece_black_queen,
R.drawable.piece_black_rook, R.drawable.piece_black_bishop,
R.drawable.piece_black_knight, R.drawable.piece_black_pawn,
R.drawable.square_none,
R.drawable.piece_white_pawn, R.drawable.piece_white_knight,
R.drawable.piece_white_bishop, R.drawable.piece_white_rook,
R.drawable.piece_white_queen, R.drawable.piece_white_king};
private static final int WHITE = 0;
private static final int BLACK = 1;
private final int squareColor;
private final int squareIndex;
private int piece = 0;
private boolean isHighlighted = false;
private boolean isCheck = false;
private boolean isLast = false;
public BoardButton(final Context context, final int index)
{
super(context);
View.inflate(context, R.layout.framelayout_boardbutton, this);
squareIndex = index;
squareColor = ((index / 16) % 2 == 1)?
- ((index % 2 == 1)? WHITE : BLACK) :
- ((index % 2 == 1)? BLACK : WHITE);
+ ((index % 2 == 1)? BLACK : WHITE) :
+ ((index % 2 == 1)? WHITE : BLACK);
setId(squareIndex);
setSquareImage();
}
private void setSquareImage()
{
final int image = (squareColor == WHITE)?
R.drawable.square_light : R.drawable.square_dark;
final MyImageView img = (MyImageView) findViewById(R.id.board_layer);
img.setImageResource(image);
}
private void setHighlightImage()
{
final int image = isHighlighted?
R.drawable.square_ih_green :
(isLast?
R.drawable.square_ih_purple :
(isCheck?
R.drawable.square_ih_red :
R.drawable.square_none));
final MyImageView img = (MyImageView) findViewById(R.id.highlight_layer);
img.setImageResource(image);
}
public void resetSquare()
{
isHighlighted = false;
isCheck = false;
setHighlightImage();
setPiece(0);
}
public void setPiece(final int piece_type)
{
piece = piece_type;
final MyImageView img = (MyImageView) findViewById(R.id.piece_layer);
img.setImageResource(pieceImages[piece + 6]);
}
public int getPiece()
{
return piece;
}
public int getIndex()
{
return squareIndex;
}
public void setHighlight(final boolean mode)
{
isHighlighted = mode;
setHighlightImage();
}
public void setCheck(final boolean mode)
{
isCheck = mode;
setHighlightImage();
}
public void setLast(final boolean mode)
{
isLast = mode;
setHighlightImage();
}
}
| true | true | public BoardButton(final Context context, final int index)
{
super(context);
View.inflate(context, R.layout.framelayout_boardbutton, this);
squareIndex = index;
squareColor = ((index / 16) % 2 == 1)?
((index % 2 == 1)? WHITE : BLACK) :
((index % 2 == 1)? BLACK : WHITE);
setId(squareIndex);
setSquareImage();
}
| public BoardButton(final Context context, final int index)
{
super(context);
View.inflate(context, R.layout.framelayout_boardbutton, this);
squareIndex = index;
squareColor = ((index / 16) % 2 == 1)?
((index % 2 == 1)? BLACK : WHITE) :
((index % 2 == 1)? WHITE : BLACK);
setId(squareIndex);
setSquareImage();
}
|
diff --git a/tizzit-cocoon-block/src/main/java/de/juwimm/cms/cocoon/transformation/NavigationTransformer.java b/tizzit-cocoon-block/src/main/java/de/juwimm/cms/cocoon/transformation/NavigationTransformer.java
index f9862556..c8371e5a 100644
--- a/tizzit-cocoon-block/src/main/java/de/juwimm/cms/cocoon/transformation/NavigationTransformer.java
+++ b/tizzit-cocoon-block/src/main/java/de/juwimm/cms/cocoon/transformation/NavigationTransformer.java
@@ -1,278 +1,278 @@
/**
* @author rhertzfeldt
* @lastChange 4:24:36 PM
*/
package de.juwimm.cms.cocoon.transformation;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.apache.avalon.excalibur.pool.Recyclable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.transformation.AbstractTransformer;
import org.apache.log4j.Logger;
import org.tizzit.util.XercesHelper;
import org.tizzit.util.xml.SAXHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import de.juwimm.cms.beans.WebServiceSpring;
import de.juwimm.cms.cocoon.helper.CocoonSpringHelper;
import de.juwimm.cms.vo.UnitValue;
import de.juwimm.cms.vo.ViewComponentValue;
/**
* @author rhertzfeldt
*
*/
public class NavigationTransformer extends AbstractTransformer implements Recyclable {
private static Logger log = Logger.getLogger(NavigationTransformer.class);
private WebServiceSpring webSpringBean = null;
private Integer viewComponentId = null;
private ViewComponentValue viewComponentValue = null;
private UnitValue unitValue = null;
private boolean iAmTheLiveserver = false;
private boolean disableNavigationAxis = false;
private Serializable uniqueKey;
private Request request = null;
private Map<String, String> safeguardMap = null;
/* (non-Javadoc)
* @see org.apache.cocoon.sitemap.SitemapModelComponent#setup(org.apache.cocoon.environment.SourceResolver, java.util.Map, java.lang.String, org.apache.avalon.framework.parameters.Parameters)
*/
public void setup(SourceResolver resolver, Map objectModel, String src, Parameters par) throws ProcessingException, SAXException, IOException {
if (log.isDebugEnabled()) log.debug("begin setup with src: " + src);
try {
webSpringBean = (WebServiceSpring) CocoonSpringHelper.getBean(objectModel, CocoonSpringHelper.WEB_SERVICE_SPRING);
} catch (Exception exf) {
log.error("could not load webServiceSpringBean ", exf);
}
try {
viewComponentId = new Integer(par.getParameter("viewComponentId"));
request = ObjectModelHelper.getRequest(objectModel);
uniqueKey = viewComponentId + src + "?" + request.getQueryString();
if (log.isDebugEnabled()) {
log.debug("UniqueKey: " + uniqueKey);
}
try {
viewComponentValue = webSpringBean.getViewComponent4Id(viewComponentId);
unitValue = webSpringBean.getUnit4ViewComponent(viewComponentValue.getViewComponentId());
} catch (Exception e) {
if (log.isDebugEnabled()) {
log.debug(e.getMessage());
}
}
HttpSession session = this.request.getSession(true);
try {
this.safeguardMap = (Map<String, String>) session.getAttribute("safeGuardService");
if (this.safeguardMap == null) {
if (log.isDebugEnabled()) log.debug("no SafeguardMap");
this.safeguardMap = new HashMap<String, String>();
if (log.isDebugEnabled()) log.debug("created new SafeguardMap");
session.setAttribute("safeGuardService", this.safeguardMap);
if (log.isDebugEnabled()) log.debug("put SafeguardMap into Session");
} else {
if (log.isDebugEnabled()) log.debug("found SafeguardMap");
}
} catch (Exception cookieex) {
log.warn("SafeGuard-Error: " + cookieex.getMessage());
}
} catch (Exception exe) {
viewComponentId = null;
}
try {
disableNavigationAxis = new Boolean(par.getParameter("disableNavigationAxis")).booleanValue();
} catch (Exception exe) {
}
try {
iAmTheLiveserver = new Boolean(par.getParameter("liveserver")).booleanValue();
} catch (Exception exe) {
}
if (log.isDebugEnabled()) log.debug("end setup");
}
@Override
public void recycle() {
if (log.isDebugEnabled()) log.debug("begin recycle");
super.recycle();
disableNavigationAxis = false;
request = null;
if (log.isDebugEnabled()) log.debug("end recycle");
}
/*
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (localName.equals("navigation")) {
AttributesImpl newAtts = new AttributesImpl();
newAtts.setAttributes(attrs);
if (this.unitValue != null) {
if (log.isDebugEnabled()) log.debug("found a unitValue: " + unitValue.getUnitId());
try {
SAXHelper.setSAXAttr(newAtts, "unitImageId", this.unitValue.getImageId().toString());
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("found a unitValue - but no Image for it ");
}
try {
SAXHelper.setSAXAttr(newAtts, "unitLogoId", this.unitValue.getLogoId().toString());
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("found a unitValue - but no Logo for it ");
}
}
if (log.isDebugEnabled()) log.debug("calling startElement with new attrs");
super.startElement(uri, localName, qName, newAtts);
} else {
super.startElement(uri, localName, qName, attrs);
}
if (localName.equals("navigation")) {
Document doc = XercesHelper.getNewDocument();
if (log.isDebugEnabled()) log.debug("fillNavigation entered.");
String navigationXml = "";
String since = attrs.getValue("since");
int depth = -1;
try {
depth = new Integer(attrs.getValue("depth")).intValue();
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'depth' not found ");
}
try {
viewComponentId = new Integer(attrs.getValue("viewComponentId"));
if (viewComponentId != null) {
viewComponentValue = this.webSpringBean.getViewComponent4Id(viewComponentId);
}
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'viewComponentId' not found ");
}
int ifDistanceToNavigationRoot = -1;
try {
ifDistanceToNavigationRoot = new Integer(attrs.getValue("ifDistanceToNavigationRoot")).intValue();
if (log.isDebugEnabled()) log.debug("GOT ifDistanceToNavigationRoot");
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'ifDistanceToNavigationRoot' not found ");
}
boolean showOnlyAuthorized = false;
try {
showOnlyAuthorized = Boolean.valueOf(attrs.getValue("showOnlyAuthorized")).booleanValue();
if (log.isDebugEnabled()) log.debug("showOnlyAuthorized: " + showOnlyAuthorized);
} catch (Exception e) {
if (log.isDebugEnabled()) log.debug("value for 'showOnlyAuthorized' not found ");
}
try {
if (this.unitValue != null) {
try {
if (log.isDebugEnabled()) log.debug("found that unitValue again: " + unitValue.getUnitId() + " - Try to get it's info...");
Document docUnitInfoXml = XercesHelper.string2Dom(this.webSpringBean.getUnitInfoXml(this.unitValue.getUnitId()));
if (log.isDebugEnabled() && docUnitInfoXml != null) log.debug("got the info for that unit...");
Node page = doc.importNode(docUnitInfoXml.getDocumentElement(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
if (log.isDebugEnabled()) log.debug("attached the unit info to this node...");
} catch (Exception e) {
if (log.isDebugEnabled()) log.debug("Error catched while trying to get unit info from webSpringBean and attache it to the xml", e);
}
}
} catch (Exception exe) {
}
try {
if (ifDistanceToNavigationRoot == -1 || webSpringBean.getNavigationRootDistance4VCId(viewComponentValue.getViewComponentId()) >= ifDistanceToNavigationRoot) {
navigationXml = webSpringBean.getNavigationXml(viewComponentId, since, depth, iAmTheLiveserver);
if (navigationXml != null && !"".equalsIgnoreCase(navigationXml)) {
try {
Document docNavigationXml = XercesHelper.string2Dom(navigationXml);
// add axis
if (!disableNavigationAxis) {
String viewComponentXPath = "//viewcomponent[@id=\"" + viewComponentId + "\"]";
if (log.isDebugEnabled()) log.debug("Resolving Navigation Axis: " + viewComponentXPath);
Node found = XercesHelper.findNode(docNavigationXml, viewComponentXPath);
if (found != null) {
if (log.isDebugEnabled()) log.debug("Found Axis in viewComponentId " + viewComponentId);
this.setAxisToRootAttributes(found);
} else {
ViewComponentValue axisVcl = webSpringBean.getViewComponent4Id(viewComponentValue.getParentId());
while (axisVcl != null) {
found = XercesHelper.findNode(docNavigationXml, "//viewcomponent[@id=\"" + axisVcl.getViewComponentId() + "\"]");
if (found != null) {
if (log.isDebugEnabled()) log.debug("Found Axis in axisVcl " + axisVcl.getViewComponentId());
this.setAxisToRootAttributes(found);
break;
}
axisVcl = axisVcl.getParentId() == null ? null : webSpringBean.getViewComponent4Id(axisVcl.getParentId());
}
}
}
// filter safeGuard
if (showOnlyAuthorized) {
try {
String allNavigationXml = XercesHelper.doc2String(docNavigationXml);
String filteredNavigationXml = this.webSpringBean.filterNavigation(allNavigationXml, safeguardMap);
if (log.isDebugEnabled()) {
log.debug("allNavigationXml\n" + allNavigationXml);
log.debug("filteredNavigationXml\n" + filteredNavigationXml);
}
docNavigationXml = XercesHelper.string2Dom(filteredNavigationXml);
} catch (Exception e) {
log.error("Error filtering navigation with SafeGuard: " + e.getMessage(), e);
}
}
// Insert navigationXml -> sitemap
Node page = doc.importNode(docNavigationXml.getFirstChild(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
} catch (Exception exe) {
log.error("An error occured", exe);
}
}
}
} catch (Exception ex) {
log.warn("Exception in NavigationTransformer accured: " + ex.getMessage(), ex);
}
}
if(localName=="navigationBackward"){
Document doc = XercesHelper.getNewDocument();
if (log.isDebugEnabled()) log.debug("fillNavigationBackward entered.");
String sm = "";
String since = attrs.getValue("since");
int dontShowFirst = 0;
try {
dontShowFirst = new Integer(attrs.getValue("dontShowFirst")).intValue();
} catch (Exception exe) {
}
try {
if (sm.equals("")) {
- sm = "<navigationBackward>" + webSpringBean.getNavigationBackwardXml(viewComponentId, since, dontShowFirst, iAmTheLiveserver) + "</navigationBackward>";
+ sm = "<navigationBackWard>"+webSpringBean.getNavigationBackwardXml(viewComponentId, since, dontShowFirst, iAmTheLiveserver)+"</navigationBackWard>";
}
Document smdoc = XercesHelper.string2Dom(sm);
Node page = doc.importNode(smdoc.getFirstChild(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
} catch (Exception exe) {
log.error("An error occured while trying to create the breadcrumbs navigation", exe);
}
}
}
private void setAxisToRootAttributes(Node found) {
Node changeNode = found;
while (changeNode != null && changeNode instanceof Element && changeNode.getNodeName().equalsIgnoreCase("viewcomponent")) {
((Element) changeNode).setAttribute("onAxisToRoot", "true");
changeNode = changeNode.getParentNode();
}
}
}
| true | true | public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (localName.equals("navigation")) {
AttributesImpl newAtts = new AttributesImpl();
newAtts.setAttributes(attrs);
if (this.unitValue != null) {
if (log.isDebugEnabled()) log.debug("found a unitValue: " + unitValue.getUnitId());
try {
SAXHelper.setSAXAttr(newAtts, "unitImageId", this.unitValue.getImageId().toString());
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("found a unitValue - but no Image for it ");
}
try {
SAXHelper.setSAXAttr(newAtts, "unitLogoId", this.unitValue.getLogoId().toString());
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("found a unitValue - but no Logo for it ");
}
}
if (log.isDebugEnabled()) log.debug("calling startElement with new attrs");
super.startElement(uri, localName, qName, newAtts);
} else {
super.startElement(uri, localName, qName, attrs);
}
if (localName.equals("navigation")) {
Document doc = XercesHelper.getNewDocument();
if (log.isDebugEnabled()) log.debug("fillNavigation entered.");
String navigationXml = "";
String since = attrs.getValue("since");
int depth = -1;
try {
depth = new Integer(attrs.getValue("depth")).intValue();
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'depth' not found ");
}
try {
viewComponentId = new Integer(attrs.getValue("viewComponentId"));
if (viewComponentId != null) {
viewComponentValue = this.webSpringBean.getViewComponent4Id(viewComponentId);
}
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'viewComponentId' not found ");
}
int ifDistanceToNavigationRoot = -1;
try {
ifDistanceToNavigationRoot = new Integer(attrs.getValue("ifDistanceToNavigationRoot")).intValue();
if (log.isDebugEnabled()) log.debug("GOT ifDistanceToNavigationRoot");
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'ifDistanceToNavigationRoot' not found ");
}
boolean showOnlyAuthorized = false;
try {
showOnlyAuthorized = Boolean.valueOf(attrs.getValue("showOnlyAuthorized")).booleanValue();
if (log.isDebugEnabled()) log.debug("showOnlyAuthorized: " + showOnlyAuthorized);
} catch (Exception e) {
if (log.isDebugEnabled()) log.debug("value for 'showOnlyAuthorized' not found ");
}
try {
if (this.unitValue != null) {
try {
if (log.isDebugEnabled()) log.debug("found that unitValue again: " + unitValue.getUnitId() + " - Try to get it's info...");
Document docUnitInfoXml = XercesHelper.string2Dom(this.webSpringBean.getUnitInfoXml(this.unitValue.getUnitId()));
if (log.isDebugEnabled() && docUnitInfoXml != null) log.debug("got the info for that unit...");
Node page = doc.importNode(docUnitInfoXml.getDocumentElement(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
if (log.isDebugEnabled()) log.debug("attached the unit info to this node...");
} catch (Exception e) {
if (log.isDebugEnabled()) log.debug("Error catched while trying to get unit info from webSpringBean and attache it to the xml", e);
}
}
} catch (Exception exe) {
}
try {
if (ifDistanceToNavigationRoot == -1 || webSpringBean.getNavigationRootDistance4VCId(viewComponentValue.getViewComponentId()) >= ifDistanceToNavigationRoot) {
navigationXml = webSpringBean.getNavigationXml(viewComponentId, since, depth, iAmTheLiveserver);
if (navigationXml != null && !"".equalsIgnoreCase(navigationXml)) {
try {
Document docNavigationXml = XercesHelper.string2Dom(navigationXml);
// add axis
if (!disableNavigationAxis) {
String viewComponentXPath = "//viewcomponent[@id=\"" + viewComponentId + "\"]";
if (log.isDebugEnabled()) log.debug("Resolving Navigation Axis: " + viewComponentXPath);
Node found = XercesHelper.findNode(docNavigationXml, viewComponentXPath);
if (found != null) {
if (log.isDebugEnabled()) log.debug("Found Axis in viewComponentId " + viewComponentId);
this.setAxisToRootAttributes(found);
} else {
ViewComponentValue axisVcl = webSpringBean.getViewComponent4Id(viewComponentValue.getParentId());
while (axisVcl != null) {
found = XercesHelper.findNode(docNavigationXml, "//viewcomponent[@id=\"" + axisVcl.getViewComponentId() + "\"]");
if (found != null) {
if (log.isDebugEnabled()) log.debug("Found Axis in axisVcl " + axisVcl.getViewComponentId());
this.setAxisToRootAttributes(found);
break;
}
axisVcl = axisVcl.getParentId() == null ? null : webSpringBean.getViewComponent4Id(axisVcl.getParentId());
}
}
}
// filter safeGuard
if (showOnlyAuthorized) {
try {
String allNavigationXml = XercesHelper.doc2String(docNavigationXml);
String filteredNavigationXml = this.webSpringBean.filterNavigation(allNavigationXml, safeguardMap);
if (log.isDebugEnabled()) {
log.debug("allNavigationXml\n" + allNavigationXml);
log.debug("filteredNavigationXml\n" + filteredNavigationXml);
}
docNavigationXml = XercesHelper.string2Dom(filteredNavigationXml);
} catch (Exception e) {
log.error("Error filtering navigation with SafeGuard: " + e.getMessage(), e);
}
}
// Insert navigationXml -> sitemap
Node page = doc.importNode(docNavigationXml.getFirstChild(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
} catch (Exception exe) {
log.error("An error occured", exe);
}
}
}
} catch (Exception ex) {
log.warn("Exception in NavigationTransformer accured: " + ex.getMessage(), ex);
}
}
if(localName=="navigationBackward"){
Document doc = XercesHelper.getNewDocument();
if (log.isDebugEnabled()) log.debug("fillNavigationBackward entered.");
String sm = "";
String since = attrs.getValue("since");
int dontShowFirst = 0;
try {
dontShowFirst = new Integer(attrs.getValue("dontShowFirst")).intValue();
} catch (Exception exe) {
}
try {
if (sm.equals("")) {
sm = "<navigationBackward>" + webSpringBean.getNavigationBackwardXml(viewComponentId, since, dontShowFirst, iAmTheLiveserver) + "</navigationBackward>";
}
Document smdoc = XercesHelper.string2Dom(sm);
Node page = doc.importNode(smdoc.getFirstChild(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
} catch (Exception exe) {
log.error("An error occured while trying to create the breadcrumbs navigation", exe);
}
}
}
| public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
if (localName.equals("navigation")) {
AttributesImpl newAtts = new AttributesImpl();
newAtts.setAttributes(attrs);
if (this.unitValue != null) {
if (log.isDebugEnabled()) log.debug("found a unitValue: " + unitValue.getUnitId());
try {
SAXHelper.setSAXAttr(newAtts, "unitImageId", this.unitValue.getImageId().toString());
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("found a unitValue - but no Image for it ");
}
try {
SAXHelper.setSAXAttr(newAtts, "unitLogoId", this.unitValue.getLogoId().toString());
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("found a unitValue - but no Logo for it ");
}
}
if (log.isDebugEnabled()) log.debug("calling startElement with new attrs");
super.startElement(uri, localName, qName, newAtts);
} else {
super.startElement(uri, localName, qName, attrs);
}
if (localName.equals("navigation")) {
Document doc = XercesHelper.getNewDocument();
if (log.isDebugEnabled()) log.debug("fillNavigation entered.");
String navigationXml = "";
String since = attrs.getValue("since");
int depth = -1;
try {
depth = new Integer(attrs.getValue("depth")).intValue();
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'depth' not found ");
}
try {
viewComponentId = new Integer(attrs.getValue("viewComponentId"));
if (viewComponentId != null) {
viewComponentValue = this.webSpringBean.getViewComponent4Id(viewComponentId);
}
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'viewComponentId' not found ");
}
int ifDistanceToNavigationRoot = -1;
try {
ifDistanceToNavigationRoot = new Integer(attrs.getValue("ifDistanceToNavigationRoot")).intValue();
if (log.isDebugEnabled()) log.debug("GOT ifDistanceToNavigationRoot");
} catch (Exception exe) {
if (log.isDebugEnabled()) log.debug("value for 'ifDistanceToNavigationRoot' not found ");
}
boolean showOnlyAuthorized = false;
try {
showOnlyAuthorized = Boolean.valueOf(attrs.getValue("showOnlyAuthorized")).booleanValue();
if (log.isDebugEnabled()) log.debug("showOnlyAuthorized: " + showOnlyAuthorized);
} catch (Exception e) {
if (log.isDebugEnabled()) log.debug("value for 'showOnlyAuthorized' not found ");
}
try {
if (this.unitValue != null) {
try {
if (log.isDebugEnabled()) log.debug("found that unitValue again: " + unitValue.getUnitId() + " - Try to get it's info...");
Document docUnitInfoXml = XercesHelper.string2Dom(this.webSpringBean.getUnitInfoXml(this.unitValue.getUnitId()));
if (log.isDebugEnabled() && docUnitInfoXml != null) log.debug("got the info for that unit...");
Node page = doc.importNode(docUnitInfoXml.getDocumentElement(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
if (log.isDebugEnabled()) log.debug("attached the unit info to this node...");
} catch (Exception e) {
if (log.isDebugEnabled()) log.debug("Error catched while trying to get unit info from webSpringBean and attache it to the xml", e);
}
}
} catch (Exception exe) {
}
try {
if (ifDistanceToNavigationRoot == -1 || webSpringBean.getNavigationRootDistance4VCId(viewComponentValue.getViewComponentId()) >= ifDistanceToNavigationRoot) {
navigationXml = webSpringBean.getNavigationXml(viewComponentId, since, depth, iAmTheLiveserver);
if (navigationXml != null && !"".equalsIgnoreCase(navigationXml)) {
try {
Document docNavigationXml = XercesHelper.string2Dom(navigationXml);
// add axis
if (!disableNavigationAxis) {
String viewComponentXPath = "//viewcomponent[@id=\"" + viewComponentId + "\"]";
if (log.isDebugEnabled()) log.debug("Resolving Navigation Axis: " + viewComponentXPath);
Node found = XercesHelper.findNode(docNavigationXml, viewComponentXPath);
if (found != null) {
if (log.isDebugEnabled()) log.debug("Found Axis in viewComponentId " + viewComponentId);
this.setAxisToRootAttributes(found);
} else {
ViewComponentValue axisVcl = webSpringBean.getViewComponent4Id(viewComponentValue.getParentId());
while (axisVcl != null) {
found = XercesHelper.findNode(docNavigationXml, "//viewcomponent[@id=\"" + axisVcl.getViewComponentId() + "\"]");
if (found != null) {
if (log.isDebugEnabled()) log.debug("Found Axis in axisVcl " + axisVcl.getViewComponentId());
this.setAxisToRootAttributes(found);
break;
}
axisVcl = axisVcl.getParentId() == null ? null : webSpringBean.getViewComponent4Id(axisVcl.getParentId());
}
}
}
// filter safeGuard
if (showOnlyAuthorized) {
try {
String allNavigationXml = XercesHelper.doc2String(docNavigationXml);
String filteredNavigationXml = this.webSpringBean.filterNavigation(allNavigationXml, safeguardMap);
if (log.isDebugEnabled()) {
log.debug("allNavigationXml\n" + allNavigationXml);
log.debug("filteredNavigationXml\n" + filteredNavigationXml);
}
docNavigationXml = XercesHelper.string2Dom(filteredNavigationXml);
} catch (Exception e) {
log.error("Error filtering navigation with SafeGuard: " + e.getMessage(), e);
}
}
// Insert navigationXml -> sitemap
Node page = doc.importNode(docNavigationXml.getFirstChild(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
} catch (Exception exe) {
log.error("An error occured", exe);
}
}
}
} catch (Exception ex) {
log.warn("Exception in NavigationTransformer accured: " + ex.getMessage(), ex);
}
}
if(localName=="navigationBackward"){
Document doc = XercesHelper.getNewDocument();
if (log.isDebugEnabled()) log.debug("fillNavigationBackward entered.");
String sm = "";
String since = attrs.getValue("since");
int dontShowFirst = 0;
try {
dontShowFirst = new Integer(attrs.getValue("dontShowFirst")).intValue();
} catch (Exception exe) {
}
try {
if (sm.equals("")) {
sm = "<navigationBackWard>"+webSpringBean.getNavigationBackwardXml(viewComponentId, since, dontShowFirst, iAmTheLiveserver)+"</navigationBackWard>";
}
Document smdoc = XercesHelper.string2Dom(sm);
Node page = doc.importNode(smdoc.getFirstChild(), true);
SAXHelper.string2sax(XercesHelper.node2string(page), this);
} catch (Exception exe) {
log.error("An error occured while trying to create the breadcrumbs navigation", exe);
}
}
}
|
diff --git a/Dart/src/com/jetbrains/lang/dart/ide/formatter/DartSpacingProcessor.java b/Dart/src/com/jetbrains/lang/dart/ide/formatter/DartSpacingProcessor.java
index 54fd0f27bd..ab52c3eae9 100644
--- a/Dart/src/com/jetbrains/lang/dart/ide/formatter/DartSpacingProcessor.java
+++ b/Dart/src/com/jetbrains/lang/dart/ide/formatter/DartSpacingProcessor.java
@@ -1,455 +1,456 @@
package com.jetbrains.lang.dart.ide.formatter;
import com.intellij.formatting.Block;
import com.intellij.formatting.Spacing;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import com.intellij.psi.formatter.common.AbstractBlock;
import com.intellij.psi.impl.source.tree.CompositeElement;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import static com.jetbrains.lang.dart.DartTokenTypes.*;
import static com.jetbrains.lang.dart.DartTokenTypesSets.*;
public class DartSpacingProcessor {
private static final TokenSet TOKENS_WITH_SPACE_AFTER = TokenSet
.create(VAR, FINAL, STATIC, EXTERNAL, ABSTRACT, GET, SET, FACTORY, OPERATOR, PART, EXPORT, DEFERRED, AS, SHOW, HIDE, RETURN_TYPE);
private static final TokenSet KEYWORDS_WITH_SPACE_BEFORE = TokenSet.create(GET, SET, EXTENDS, IMPLEMENTS, DEFERRED, AS);
private static final TokenSet CASCADE_REFERENCE_EXPRESSION_SET = TokenSet.create(CASCADE_REFERENCE_EXPRESSION);
private static final TokenSet REFERENCE_EXPRESSION_SET = TokenSet.create(REFERENCE_EXPRESSION);
private static final TokenSet ID_SET = TokenSet.create(ID);
private final ASTNode myNode;
private final CommonCodeStyleSettings mySettings;
public DartSpacingProcessor(ASTNode node, CommonCodeStyleSettings settings) {
myNode = node;
mySettings = settings;
}
public Spacing getSpacing(final Block child1, final Block child2) {
if (!(child1 instanceof AbstractBlock) || !(child2 instanceof AbstractBlock)) {
return null;
}
final IElementType elementType = myNode.getElementType();
final IElementType parentType = myNode.getTreeParent() == null ? null : myNode.getTreeParent().getElementType();
final ASTNode node1 = ((AbstractBlock)child1).getNode();
final IElementType type1 = node1.getElementType();
final ASTNode node2 = ((AbstractBlock)child2).getNode();
final IElementType type2 = node2.getElementType();
if (SEMICOLON == type2) return Spacing.createSpacing(0, 0, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
if (AT == type1) return Spacing.createSpacing(0, 0, 0, false, 0);
if (METADATA == type1) return Spacing.createSpacing(1, 1, 0, true, 0);
if (FUNCTION_DEFINITION.contains(type2)) {
final int lineFeeds = COMMENTS.contains(type1) ? 1 : 2;
return Spacing.createSpacing(0, 0, lineFeeds, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (DOC_COMMENT_CONTENTS.contains(type2)) {
return Spacing.createSpacing(0, Integer.MAX_VALUE, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (BLOCKS.contains(elementType)) {
boolean topLevel = elementType == DART_FILE || elementType == EMBEDDED_CONTENT;
int lineFeeds = 1;
if (!COMMENTS.contains(type1) && (elementType == CLASS_MEMBERS || topLevel && DECLARATIONS.contains(type2))) {
if (type1 == SEMICOLON && type2 == VAR_DECLARATION_LIST) {
final ASTNode node1TreePrev = node1.getTreePrev();
if (node1TreePrev == null || node1TreePrev.getElementType() != VAR_DECLARATION_LIST) {
lineFeeds = 2;
}
}
else {
lineFeeds = 2;
}
}
return Spacing.createSpacing(0, 0, lineFeeds, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (elementType == STATEMENTS && (parentType == SWITCH_CASE || parentType == DEFAULT_CASE)) {
return Spacing.createSpacing(0, 0, 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (!COMMENTS.contains(type2) && parentType == BLOCK) {
return addLineBreak();
}
if (type1 == STATEMENTS || type2 == STATEMENTS) {
return addLineBreak();
}
if (type1 == CLASS_MEMBERS || type2 == CLASS_MEMBERS) {
return addSingleSpaceIf(false, true);
}
if (type1 == CLASS_MEMBERS) {
return addLineBreak();
}
if (type2 == LPAREN) {
if (elementType == IF_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_IF_PARENTHESES);
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_WHILE_PARENTHESES);
}
else if (elementType == SWITCH_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_SWITCH_PARENTHESES);
}
else if (elementType == TRY_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_TRY_PARENTHESES);
}
else if (elementType == ON_PART || elementType == CATCH_PART) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_CATCH_PARENTHESES);
}
}
if (type2 == FOR_LOOP_PARTS_IN_BRACES) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_FOR_PARENTHESES);
}
if (type2 == FORMAL_PARAMETER_LIST && (FUNCTION_DEFINITION.contains(elementType) || elementType == FUNCTION_EXPRESSION)) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_METHOD_PARENTHESES);
}
if (type2 == ARGUMENTS && elementType == CALL_EXPRESSION) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_METHOD_CALL_PARENTHESES);
}
//
//Spacing before left braces
//
if (type2 == BLOCK) {
if (elementType == IF_STATEMENT && type1 != ELSE) {
return setBraceSpace(mySettings.SPACE_BEFORE_IF_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == IF_STATEMENT && type1 == ELSE) {
return setBraceSpace(mySettings.SPACE_BEFORE_ELSE_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_WHILE_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == FOR_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_FOR_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == TRY_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_TRY_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == ON_PART) {
return setBraceSpace(mySettings.SPACE_BEFORE_CATCH_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
}
if (type2 == LBRACE && elementType == SWITCH_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_SWITCH_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (FUNCTION_DEFINITION.contains(elementType) && type2 == FUNCTION_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_METHOD_LBRACE, mySettings.METHOD_BRACE_STYLE, child1.getTextRange());
}
if (elementType == FUNCTION_EXPRESSION && type2 == FUNCTION_EXPRESSION_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_METHOD_LBRACE, mySettings.METHOD_BRACE_STYLE, child1.getTextRange());
}
if (elementType == CLASS_DEFINITION && type2 == CLASS_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_CLASS_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (elementType == ENUM_DEFINITION && type2 == LBRACE) {
return setBraceSpace(mySettings.SPACE_BEFORE_CLASS_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (type1 == LPAREN || type2 == RPAREN) {
if (elementType == IF_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_IF_PARENTHESES);
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_WHILE_PARENTHESES);
}
else if (elementType == FOR_LOOP_PARTS_IN_BRACES) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_FOR_PARENTHESES);
}
else if (elementType == SWITCH_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_SWITCH_PARENTHESES);
}
else if (elementType == TRY_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_TRY_PARENTHESES);
}
else if (elementType == CATCH_PART) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_CATCH_PARENTHESES);
}
else if (elementType == FORMAL_PARAMETER_LIST) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE : mySettings.METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE;
return addSingleSpaceIf(mySettings.SPACE_WITHIN_METHOD_PARENTHESES, newLineNeeded);
}
else if (elementType == ARGUMENTS) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.CALL_PARAMETERS_LPAREN_ON_NEXT_LINE : mySettings.CALL_PARAMETERS_RPAREN_ON_NEXT_LINE;
return addSingleSpaceIf(mySettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES, newLineNeeded);
}
else if (mySettings.BINARY_OPERATION_WRAP != CommonCodeStyleSettings.DO_NOT_WRAP && elementType == PARENTHESIZED_EXPRESSION) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.PARENTHESES_EXPRESSION_LPAREN_WRAP : mySettings.PARENTHESES_EXPRESSION_RPAREN_WRAP;
return addSingleSpaceIf(false, newLineNeeded);
}
}
if (elementType == TERNARY_EXPRESSION) {
if (type2 == QUEST) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_QUEST);
}
else if (type2 == COLON) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_COLON);
}
else if (type1 == QUEST) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_QUEST);
}
else if (type1 == COLON) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COLON);
}
}
//
// Spacing around assignment operators (=, -=, etc.)
//
if (type1 == ASSIGNMENT_OPERATOR || type2 == ASSIGNMENT_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
if (type1 == EQ && elementType == VAR_INIT) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
if (type2 == VAR_INIT) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
//
// Spacing around logical operators (&&, OR, etc.)
//
if (LOGIC_OPERATORS.contains(type1) || LOGIC_OPERATORS.contains(type2)) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_LOGICAL_OPERATORS);
}
//
// Spacing around equality operators (==, != etc.)
//
if (type1 == EQUALITY_OPERATOR || type2 == EQUALITY_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_EQUALITY_OPERATORS);
}
//
// Spacing around relational operators (<, <= etc.)
//
if (type1 == RELATIONAL_OPERATOR || type2 == RELATIONAL_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_RELATIONAL_OPERATORS);
}
//
// Spacing around additive operators ( &, |, ^, etc.)
//
if (BITWISE_OPERATORS.contains(type1) || BITWISE_OPERATORS.contains(type2)) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_BITWISE_OPERATORS);
}
//
// Spacing around additive operators ( +, -, etc.)
//
if ((type1 == ADDITIVE_OPERATOR || type2 == ADDITIVE_OPERATOR) && elementType != PREFIX_EXPRESSION) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ADDITIVE_OPERATORS);
}
//
// Spacing around multiplicative operators ( *, /, %, etc.)
//
if (type1 == MULTIPLICATIVE_OPERATOR || type2 == MULTIPLICATIVE_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS);
}
//
// Spacing around unary operators ( NOT, ++, etc.)
//
if (type1 == PREFIX_OPERATOR || type2 == PREFIX_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_UNARY_OPERATOR);
}
//
// Spacing around shift operators ( <<, >>, >>>, etc.)
//
if (type1 == SHIFT_OPERATOR || type2 == SHIFT_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_SHIFT_OPERATORS);
}
//
//Spacing before keyword (else, catch, etc)
//
if (type2 == ELSE) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_ELSE_KEYWORD, mySettings.ELSE_ON_NEW_LINE);
}
if (type2 == WHILE) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_WHILE_KEYWORD, mySettings.WHILE_ON_NEW_LINE);
}
if (type2 == ON_PART) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_CATCH_KEYWORD, mySettings.CATCH_ON_NEW_LINE);
}
//
//Other
//
if (type1 == ELSE && type2 == IF_STATEMENT) {
return Spacing.createSpacing(1, 1, mySettings.SPECIAL_ELSE_IF_TREATMENT ? 0 : 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
boolean isBraces = type1 == LBRACE || type2 == RBRACE;
if ((isBraces && elementType != NAMED_FORMAL_PARAMETERS && elementType != MAP_LITERAL_EXPRESSION) ||
BLOCKS.contains(type1) ||
FUNCTION_DEFINITION.contains(type1) ||
COMMENTS.contains(type1)) {
return addLineBreak();
}
if (type1 == COMMA &&
(elementType == FORMAL_PARAMETER_LIST || elementType == ARGUMENT_LIST || elementType == NORMAL_FORMAL_PARAMETER)) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS);
}
if (type1 == COMMA) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COMMA);
}
if (type2 == COMMA) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_COMMA);
}
//todo: customize in settings
if (type1 == EXPRESSION_BODY_DEF || type2 == EXPRESSION_BODY_DEF) {
return addSingleSpaceIf(true);
}
if (type1 == FOR_LOOP_PARTS_IN_BRACES && !BLOCKS.contains(type2)) {
return addLineBreak();
}
if (type1 == IF_STATEMENT ||
type1 == SWITCH_STATEMENT ||
type1 == TRY_STATEMENT ||
type1 == DO_WHILE_STATEMENT ||
type1 == FOR_STATEMENT ||
type1 == SWITCH_CASE ||
type1 == DEFAULT_CASE ||
type1 == WHILE_STATEMENT) {
return addLineBreak();
}
if (COMMENTS.contains(type2)) {
return Spacing.createSpacing(0, 1, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (TOKENS_WITH_SPACE_AFTER.contains(type1) || KEYWORDS_WITH_SPACE_BEFORE.contains(type2)) {
return addSingleSpaceIf(true);
}
if (elementType == VALUE_EXPRESSION && type2 == CASCADE_REFERENCE_EXPRESSION) {
if (type1 == CASCADE_REFERENCE_EXPRESSION) {
if (cascadesAreSameMethod(((AbstractBlock)child1).getNode(), ((AbstractBlock)child2).getNode())) {
- return Spacing.createSpacing(0, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+ return Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
}
else if (type1 == REFERENCE_EXPRESSION) {
CompositeElement elem = (CompositeElement)myNode;
ASTNode[] childs = elem.getChildren(CASCADE_REFERENCE_EXPRESSION_SET);
if (childs.length == 1 || allCascadesAreSameMethod(childs)) {
- return Spacing.createSpacing(0, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+ return Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
}
return addLineBreak();
}
if (type1 == CLOSING_QUOTE && type2 == OPEN_QUOTE && elementType == STRING_LITERAL_EXPRESSION) {
ASTNode sib = node1;
int preserveNewline = 0;
// Adjacent strings on the same line should not be split.
while ((sib = sib.getTreeNext()) != null) {
// Comments are handled elsewhere.
+ // TODO Create a test for this loop after adjacent-string wrapping is implemented.
if (sib.getElementType() == WHITE_SPACE) {
String ws = sib.getText();
- if (ws.contains("\n") || ws.contains("\r")) {
+ if (ws.contains("\n")) {
preserveNewline++;
break;
}
continue;
}
break;
}
// Adjacent strings on separate lines should not include blank lines.
return Spacing.createSpacing(0, 1, preserveNewline, true, 0);
}
return Spacing.createSpacing(0, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
private Spacing addLineBreak() {
return Spacing.createSpacing(0, 0, 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
private Spacing addSingleSpaceIf(boolean condition) {
return addSingleSpaceIf(condition, false);
}
private Spacing addSingleSpaceIf(boolean condition, boolean linesFeed) {
final int spaces = condition ? 1 : 0;
final int lines = linesFeed ? 1 : 0;
return Spacing.createSpacing(spaces, spaces, lines, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
private Spacing setBraceSpace(boolean needSpaceSetting,
@CommonCodeStyleSettings.BraceStyleConstant int braceStyleSetting,
TextRange textRange) {
final int spaces = needSpaceSetting ? 1 : 0;
if (braceStyleSetting == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED && textRange != null) {
return Spacing.createDependentLFSpacing(spaces, spaces, textRange, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
else {
final int lineBreaks =
braceStyleSetting == CommonCodeStyleSettings.END_OF_LINE || braceStyleSetting == CommonCodeStyleSettings.NEXT_LINE_IF_WRAPPED
? 0
: 1;
return Spacing.createSpacing(spaces, spaces, lineBreaks, false, 0);
}
}
private static boolean allCascadesAreSameMethod(ASTNode[] children) {
for (int i = 1; i < children.length; i++) {
if (!cascadesAreSameMethod(children[i - 1], children[i])) {
return false;
}
}
return true;
}
private static boolean cascadesAreSameMethod(ASTNode child1, ASTNode child2) {
ASTNode call1 = child1.getLastChildNode();
if (call1.getElementType() == CALL_EXPRESSION) {
ASTNode call2 = child2.getLastChildNode();
if (call2.getElementType() == CALL_EXPRESSION) {
String name1 = getImmediateCallName(call1);
if (name1 != null) {
String name2 = getImmediateCallName(call2);
if (name1.equals(name2)) {
return true;
}
}
}
}
return false;
}
private static String getImmediateCallName(ASTNode callNode) {
ASTNode[] childs = callNode.getChildren(REFERENCE_EXPRESSION_SET);
if (childs.length != 1) return null;
ASTNode child = childs[0];
childs = child.getChildren(ID_SET);
if (childs.length != 1) return null;
child = childs[0];
return child.getText();
}
}
| false | true | public Spacing getSpacing(final Block child1, final Block child2) {
if (!(child1 instanceof AbstractBlock) || !(child2 instanceof AbstractBlock)) {
return null;
}
final IElementType elementType = myNode.getElementType();
final IElementType parentType = myNode.getTreeParent() == null ? null : myNode.getTreeParent().getElementType();
final ASTNode node1 = ((AbstractBlock)child1).getNode();
final IElementType type1 = node1.getElementType();
final ASTNode node2 = ((AbstractBlock)child2).getNode();
final IElementType type2 = node2.getElementType();
if (SEMICOLON == type2) return Spacing.createSpacing(0, 0, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
if (AT == type1) return Spacing.createSpacing(0, 0, 0, false, 0);
if (METADATA == type1) return Spacing.createSpacing(1, 1, 0, true, 0);
if (FUNCTION_DEFINITION.contains(type2)) {
final int lineFeeds = COMMENTS.contains(type1) ? 1 : 2;
return Spacing.createSpacing(0, 0, lineFeeds, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (DOC_COMMENT_CONTENTS.contains(type2)) {
return Spacing.createSpacing(0, Integer.MAX_VALUE, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (BLOCKS.contains(elementType)) {
boolean topLevel = elementType == DART_FILE || elementType == EMBEDDED_CONTENT;
int lineFeeds = 1;
if (!COMMENTS.contains(type1) && (elementType == CLASS_MEMBERS || topLevel && DECLARATIONS.contains(type2))) {
if (type1 == SEMICOLON && type2 == VAR_DECLARATION_LIST) {
final ASTNode node1TreePrev = node1.getTreePrev();
if (node1TreePrev == null || node1TreePrev.getElementType() != VAR_DECLARATION_LIST) {
lineFeeds = 2;
}
}
else {
lineFeeds = 2;
}
}
return Spacing.createSpacing(0, 0, lineFeeds, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (elementType == STATEMENTS && (parentType == SWITCH_CASE || parentType == DEFAULT_CASE)) {
return Spacing.createSpacing(0, 0, 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (!COMMENTS.contains(type2) && parentType == BLOCK) {
return addLineBreak();
}
if (type1 == STATEMENTS || type2 == STATEMENTS) {
return addLineBreak();
}
if (type1 == CLASS_MEMBERS || type2 == CLASS_MEMBERS) {
return addSingleSpaceIf(false, true);
}
if (type1 == CLASS_MEMBERS) {
return addLineBreak();
}
if (type2 == LPAREN) {
if (elementType == IF_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_IF_PARENTHESES);
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_WHILE_PARENTHESES);
}
else if (elementType == SWITCH_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_SWITCH_PARENTHESES);
}
else if (elementType == TRY_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_TRY_PARENTHESES);
}
else if (elementType == ON_PART || elementType == CATCH_PART) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_CATCH_PARENTHESES);
}
}
if (type2 == FOR_LOOP_PARTS_IN_BRACES) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_FOR_PARENTHESES);
}
if (type2 == FORMAL_PARAMETER_LIST && (FUNCTION_DEFINITION.contains(elementType) || elementType == FUNCTION_EXPRESSION)) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_METHOD_PARENTHESES);
}
if (type2 == ARGUMENTS && elementType == CALL_EXPRESSION) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_METHOD_CALL_PARENTHESES);
}
//
//Spacing before left braces
//
if (type2 == BLOCK) {
if (elementType == IF_STATEMENT && type1 != ELSE) {
return setBraceSpace(mySettings.SPACE_BEFORE_IF_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == IF_STATEMENT && type1 == ELSE) {
return setBraceSpace(mySettings.SPACE_BEFORE_ELSE_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_WHILE_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == FOR_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_FOR_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == TRY_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_TRY_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == ON_PART) {
return setBraceSpace(mySettings.SPACE_BEFORE_CATCH_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
}
if (type2 == LBRACE && elementType == SWITCH_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_SWITCH_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (FUNCTION_DEFINITION.contains(elementType) && type2 == FUNCTION_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_METHOD_LBRACE, mySettings.METHOD_BRACE_STYLE, child1.getTextRange());
}
if (elementType == FUNCTION_EXPRESSION && type2 == FUNCTION_EXPRESSION_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_METHOD_LBRACE, mySettings.METHOD_BRACE_STYLE, child1.getTextRange());
}
if (elementType == CLASS_DEFINITION && type2 == CLASS_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_CLASS_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (elementType == ENUM_DEFINITION && type2 == LBRACE) {
return setBraceSpace(mySettings.SPACE_BEFORE_CLASS_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (type1 == LPAREN || type2 == RPAREN) {
if (elementType == IF_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_IF_PARENTHESES);
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_WHILE_PARENTHESES);
}
else if (elementType == FOR_LOOP_PARTS_IN_BRACES) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_FOR_PARENTHESES);
}
else if (elementType == SWITCH_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_SWITCH_PARENTHESES);
}
else if (elementType == TRY_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_TRY_PARENTHESES);
}
else if (elementType == CATCH_PART) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_CATCH_PARENTHESES);
}
else if (elementType == FORMAL_PARAMETER_LIST) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE : mySettings.METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE;
return addSingleSpaceIf(mySettings.SPACE_WITHIN_METHOD_PARENTHESES, newLineNeeded);
}
else if (elementType == ARGUMENTS) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.CALL_PARAMETERS_LPAREN_ON_NEXT_LINE : mySettings.CALL_PARAMETERS_RPAREN_ON_NEXT_LINE;
return addSingleSpaceIf(mySettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES, newLineNeeded);
}
else if (mySettings.BINARY_OPERATION_WRAP != CommonCodeStyleSettings.DO_NOT_WRAP && elementType == PARENTHESIZED_EXPRESSION) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.PARENTHESES_EXPRESSION_LPAREN_WRAP : mySettings.PARENTHESES_EXPRESSION_RPAREN_WRAP;
return addSingleSpaceIf(false, newLineNeeded);
}
}
if (elementType == TERNARY_EXPRESSION) {
if (type2 == QUEST) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_QUEST);
}
else if (type2 == COLON) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_COLON);
}
else if (type1 == QUEST) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_QUEST);
}
else if (type1 == COLON) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COLON);
}
}
//
// Spacing around assignment operators (=, -=, etc.)
//
if (type1 == ASSIGNMENT_OPERATOR || type2 == ASSIGNMENT_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
if (type1 == EQ && elementType == VAR_INIT) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
if (type2 == VAR_INIT) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
//
// Spacing around logical operators (&&, OR, etc.)
//
if (LOGIC_OPERATORS.contains(type1) || LOGIC_OPERATORS.contains(type2)) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_LOGICAL_OPERATORS);
}
//
// Spacing around equality operators (==, != etc.)
//
if (type1 == EQUALITY_OPERATOR || type2 == EQUALITY_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_EQUALITY_OPERATORS);
}
//
// Spacing around relational operators (<, <= etc.)
//
if (type1 == RELATIONAL_OPERATOR || type2 == RELATIONAL_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_RELATIONAL_OPERATORS);
}
//
// Spacing around additive operators ( &, |, ^, etc.)
//
if (BITWISE_OPERATORS.contains(type1) || BITWISE_OPERATORS.contains(type2)) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_BITWISE_OPERATORS);
}
//
// Spacing around additive operators ( +, -, etc.)
//
if ((type1 == ADDITIVE_OPERATOR || type2 == ADDITIVE_OPERATOR) && elementType != PREFIX_EXPRESSION) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ADDITIVE_OPERATORS);
}
//
// Spacing around multiplicative operators ( *, /, %, etc.)
//
if (type1 == MULTIPLICATIVE_OPERATOR || type2 == MULTIPLICATIVE_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS);
}
//
// Spacing around unary operators ( NOT, ++, etc.)
//
if (type1 == PREFIX_OPERATOR || type2 == PREFIX_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_UNARY_OPERATOR);
}
//
// Spacing around shift operators ( <<, >>, >>>, etc.)
//
if (type1 == SHIFT_OPERATOR || type2 == SHIFT_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_SHIFT_OPERATORS);
}
//
//Spacing before keyword (else, catch, etc)
//
if (type2 == ELSE) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_ELSE_KEYWORD, mySettings.ELSE_ON_NEW_LINE);
}
if (type2 == WHILE) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_WHILE_KEYWORD, mySettings.WHILE_ON_NEW_LINE);
}
if (type2 == ON_PART) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_CATCH_KEYWORD, mySettings.CATCH_ON_NEW_LINE);
}
//
//Other
//
if (type1 == ELSE && type2 == IF_STATEMENT) {
return Spacing.createSpacing(1, 1, mySettings.SPECIAL_ELSE_IF_TREATMENT ? 0 : 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
boolean isBraces = type1 == LBRACE || type2 == RBRACE;
if ((isBraces && elementType != NAMED_FORMAL_PARAMETERS && elementType != MAP_LITERAL_EXPRESSION) ||
BLOCKS.contains(type1) ||
FUNCTION_DEFINITION.contains(type1) ||
COMMENTS.contains(type1)) {
return addLineBreak();
}
if (type1 == COMMA &&
(elementType == FORMAL_PARAMETER_LIST || elementType == ARGUMENT_LIST || elementType == NORMAL_FORMAL_PARAMETER)) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS);
}
if (type1 == COMMA) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COMMA);
}
if (type2 == COMMA) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_COMMA);
}
//todo: customize in settings
if (type1 == EXPRESSION_BODY_DEF || type2 == EXPRESSION_BODY_DEF) {
return addSingleSpaceIf(true);
}
if (type1 == FOR_LOOP_PARTS_IN_BRACES && !BLOCKS.contains(type2)) {
return addLineBreak();
}
if (type1 == IF_STATEMENT ||
type1 == SWITCH_STATEMENT ||
type1 == TRY_STATEMENT ||
type1 == DO_WHILE_STATEMENT ||
type1 == FOR_STATEMENT ||
type1 == SWITCH_CASE ||
type1 == DEFAULT_CASE ||
type1 == WHILE_STATEMENT) {
return addLineBreak();
}
if (COMMENTS.contains(type2)) {
return Spacing.createSpacing(0, 1, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (TOKENS_WITH_SPACE_AFTER.contains(type1) || KEYWORDS_WITH_SPACE_BEFORE.contains(type2)) {
return addSingleSpaceIf(true);
}
if (elementType == VALUE_EXPRESSION && type2 == CASCADE_REFERENCE_EXPRESSION) {
if (type1 == CASCADE_REFERENCE_EXPRESSION) {
if (cascadesAreSameMethod(((AbstractBlock)child1).getNode(), ((AbstractBlock)child2).getNode())) {
return Spacing.createSpacing(0, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
}
else if (type1 == REFERENCE_EXPRESSION) {
CompositeElement elem = (CompositeElement)myNode;
ASTNode[] childs = elem.getChildren(CASCADE_REFERENCE_EXPRESSION_SET);
if (childs.length == 1 || allCascadesAreSameMethod(childs)) {
return Spacing.createSpacing(0, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
}
return addLineBreak();
}
if (type1 == CLOSING_QUOTE && type2 == OPEN_QUOTE && elementType == STRING_LITERAL_EXPRESSION) {
ASTNode sib = node1;
int preserveNewline = 0;
// Adjacent strings on the same line should not be split.
while ((sib = sib.getTreeNext()) != null) {
// Comments are handled elsewhere.
if (sib.getElementType() == WHITE_SPACE) {
String ws = sib.getText();
if (ws.contains("\n") || ws.contains("\r")) {
preserveNewline++;
break;
}
continue;
}
break;
}
// Adjacent strings on separate lines should not include blank lines.
return Spacing.createSpacing(0, 1, preserveNewline, true, 0);
}
return Spacing.createSpacing(0, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
| public Spacing getSpacing(final Block child1, final Block child2) {
if (!(child1 instanceof AbstractBlock) || !(child2 instanceof AbstractBlock)) {
return null;
}
final IElementType elementType = myNode.getElementType();
final IElementType parentType = myNode.getTreeParent() == null ? null : myNode.getTreeParent().getElementType();
final ASTNode node1 = ((AbstractBlock)child1).getNode();
final IElementType type1 = node1.getElementType();
final ASTNode node2 = ((AbstractBlock)child2).getNode();
final IElementType type2 = node2.getElementType();
if (SEMICOLON == type2) return Spacing.createSpacing(0, 0, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
if (AT == type1) return Spacing.createSpacing(0, 0, 0, false, 0);
if (METADATA == type1) return Spacing.createSpacing(1, 1, 0, true, 0);
if (FUNCTION_DEFINITION.contains(type2)) {
final int lineFeeds = COMMENTS.contains(type1) ? 1 : 2;
return Spacing.createSpacing(0, 0, lineFeeds, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (DOC_COMMENT_CONTENTS.contains(type2)) {
return Spacing.createSpacing(0, Integer.MAX_VALUE, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (BLOCKS.contains(elementType)) {
boolean topLevel = elementType == DART_FILE || elementType == EMBEDDED_CONTENT;
int lineFeeds = 1;
if (!COMMENTS.contains(type1) && (elementType == CLASS_MEMBERS || topLevel && DECLARATIONS.contains(type2))) {
if (type1 == SEMICOLON && type2 == VAR_DECLARATION_LIST) {
final ASTNode node1TreePrev = node1.getTreePrev();
if (node1TreePrev == null || node1TreePrev.getElementType() != VAR_DECLARATION_LIST) {
lineFeeds = 2;
}
}
else {
lineFeeds = 2;
}
}
return Spacing.createSpacing(0, 0, lineFeeds, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (elementType == STATEMENTS && (parentType == SWITCH_CASE || parentType == DEFAULT_CASE)) {
return Spacing.createSpacing(0, 0, 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (!COMMENTS.contains(type2) && parentType == BLOCK) {
return addLineBreak();
}
if (type1 == STATEMENTS || type2 == STATEMENTS) {
return addLineBreak();
}
if (type1 == CLASS_MEMBERS || type2 == CLASS_MEMBERS) {
return addSingleSpaceIf(false, true);
}
if (type1 == CLASS_MEMBERS) {
return addLineBreak();
}
if (type2 == LPAREN) {
if (elementType == IF_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_IF_PARENTHESES);
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_WHILE_PARENTHESES);
}
else if (elementType == SWITCH_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_SWITCH_PARENTHESES);
}
else if (elementType == TRY_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_TRY_PARENTHESES);
}
else if (elementType == ON_PART || elementType == CATCH_PART) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_CATCH_PARENTHESES);
}
}
if (type2 == FOR_LOOP_PARTS_IN_BRACES) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_FOR_PARENTHESES);
}
if (type2 == FORMAL_PARAMETER_LIST && (FUNCTION_DEFINITION.contains(elementType) || elementType == FUNCTION_EXPRESSION)) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_METHOD_PARENTHESES);
}
if (type2 == ARGUMENTS && elementType == CALL_EXPRESSION) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_METHOD_CALL_PARENTHESES);
}
//
//Spacing before left braces
//
if (type2 == BLOCK) {
if (elementType == IF_STATEMENT && type1 != ELSE) {
return setBraceSpace(mySettings.SPACE_BEFORE_IF_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == IF_STATEMENT && type1 == ELSE) {
return setBraceSpace(mySettings.SPACE_BEFORE_ELSE_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_WHILE_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == FOR_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_FOR_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == TRY_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_TRY_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
else if (elementType == ON_PART) {
return setBraceSpace(mySettings.SPACE_BEFORE_CATCH_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
}
if (type2 == LBRACE && elementType == SWITCH_STATEMENT) {
return setBraceSpace(mySettings.SPACE_BEFORE_SWITCH_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (FUNCTION_DEFINITION.contains(elementType) && type2 == FUNCTION_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_METHOD_LBRACE, mySettings.METHOD_BRACE_STYLE, child1.getTextRange());
}
if (elementType == FUNCTION_EXPRESSION && type2 == FUNCTION_EXPRESSION_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_METHOD_LBRACE, mySettings.METHOD_BRACE_STYLE, child1.getTextRange());
}
if (elementType == CLASS_DEFINITION && type2 == CLASS_BODY) {
return setBraceSpace(mySettings.SPACE_BEFORE_CLASS_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (elementType == ENUM_DEFINITION && type2 == LBRACE) {
return setBraceSpace(mySettings.SPACE_BEFORE_CLASS_LBRACE, mySettings.BRACE_STYLE, child1.getTextRange());
}
if (type1 == LPAREN || type2 == RPAREN) {
if (elementType == IF_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_IF_PARENTHESES);
}
else if (elementType == WHILE_STATEMENT || elementType == DO_WHILE_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_WHILE_PARENTHESES);
}
else if (elementType == FOR_LOOP_PARTS_IN_BRACES) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_FOR_PARENTHESES);
}
else if (elementType == SWITCH_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_SWITCH_PARENTHESES);
}
else if (elementType == TRY_STATEMENT) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_TRY_PARENTHESES);
}
else if (elementType == CATCH_PART) {
return addSingleSpaceIf(mySettings.SPACE_WITHIN_CATCH_PARENTHESES);
}
else if (elementType == FORMAL_PARAMETER_LIST) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE : mySettings.METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE;
return addSingleSpaceIf(mySettings.SPACE_WITHIN_METHOD_PARENTHESES, newLineNeeded);
}
else if (elementType == ARGUMENTS) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.CALL_PARAMETERS_LPAREN_ON_NEXT_LINE : mySettings.CALL_PARAMETERS_RPAREN_ON_NEXT_LINE;
return addSingleSpaceIf(mySettings.SPACE_WITHIN_METHOD_CALL_PARENTHESES, newLineNeeded);
}
else if (mySettings.BINARY_OPERATION_WRAP != CommonCodeStyleSettings.DO_NOT_WRAP && elementType == PARENTHESIZED_EXPRESSION) {
final boolean newLineNeeded =
type1 == LPAREN ? mySettings.PARENTHESES_EXPRESSION_LPAREN_WRAP : mySettings.PARENTHESES_EXPRESSION_RPAREN_WRAP;
return addSingleSpaceIf(false, newLineNeeded);
}
}
if (elementType == TERNARY_EXPRESSION) {
if (type2 == QUEST) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_QUEST);
}
else if (type2 == COLON) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_COLON);
}
else if (type1 == QUEST) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_QUEST);
}
else if (type1 == COLON) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COLON);
}
}
//
// Spacing around assignment operators (=, -=, etc.)
//
if (type1 == ASSIGNMENT_OPERATOR || type2 == ASSIGNMENT_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
if (type1 == EQ && elementType == VAR_INIT) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
if (type2 == VAR_INIT) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ASSIGNMENT_OPERATORS);
}
//
// Spacing around logical operators (&&, OR, etc.)
//
if (LOGIC_OPERATORS.contains(type1) || LOGIC_OPERATORS.contains(type2)) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_LOGICAL_OPERATORS);
}
//
// Spacing around equality operators (==, != etc.)
//
if (type1 == EQUALITY_OPERATOR || type2 == EQUALITY_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_EQUALITY_OPERATORS);
}
//
// Spacing around relational operators (<, <= etc.)
//
if (type1 == RELATIONAL_OPERATOR || type2 == RELATIONAL_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_RELATIONAL_OPERATORS);
}
//
// Spacing around additive operators ( &, |, ^, etc.)
//
if (BITWISE_OPERATORS.contains(type1) || BITWISE_OPERATORS.contains(type2)) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_BITWISE_OPERATORS);
}
//
// Spacing around additive operators ( +, -, etc.)
//
if ((type1 == ADDITIVE_OPERATOR || type2 == ADDITIVE_OPERATOR) && elementType != PREFIX_EXPRESSION) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_ADDITIVE_OPERATORS);
}
//
// Spacing around multiplicative operators ( *, /, %, etc.)
//
if (type1 == MULTIPLICATIVE_OPERATOR || type2 == MULTIPLICATIVE_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_MULTIPLICATIVE_OPERATORS);
}
//
// Spacing around unary operators ( NOT, ++, etc.)
//
if (type1 == PREFIX_OPERATOR || type2 == PREFIX_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_UNARY_OPERATOR);
}
//
// Spacing around shift operators ( <<, >>, >>>, etc.)
//
if (type1 == SHIFT_OPERATOR || type2 == SHIFT_OPERATOR) {
return addSingleSpaceIf(mySettings.SPACE_AROUND_SHIFT_OPERATORS);
}
//
//Spacing before keyword (else, catch, etc)
//
if (type2 == ELSE) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_ELSE_KEYWORD, mySettings.ELSE_ON_NEW_LINE);
}
if (type2 == WHILE) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_WHILE_KEYWORD, mySettings.WHILE_ON_NEW_LINE);
}
if (type2 == ON_PART) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_CATCH_KEYWORD, mySettings.CATCH_ON_NEW_LINE);
}
//
//Other
//
if (type1 == ELSE && type2 == IF_STATEMENT) {
return Spacing.createSpacing(1, 1, mySettings.SPECIAL_ELSE_IF_TREATMENT ? 0 : 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
boolean isBraces = type1 == LBRACE || type2 == RBRACE;
if ((isBraces && elementType != NAMED_FORMAL_PARAMETERS && elementType != MAP_LITERAL_EXPRESSION) ||
BLOCKS.contains(type1) ||
FUNCTION_DEFINITION.contains(type1) ||
COMMENTS.contains(type1)) {
return addLineBreak();
}
if (type1 == COMMA &&
(elementType == FORMAL_PARAMETER_LIST || elementType == ARGUMENT_LIST || elementType == NORMAL_FORMAL_PARAMETER)) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COMMA_IN_TYPE_ARGUMENTS);
}
if (type1 == COMMA) {
return addSingleSpaceIf(mySettings.SPACE_AFTER_COMMA);
}
if (type2 == COMMA) {
return addSingleSpaceIf(mySettings.SPACE_BEFORE_COMMA);
}
//todo: customize in settings
if (type1 == EXPRESSION_BODY_DEF || type2 == EXPRESSION_BODY_DEF) {
return addSingleSpaceIf(true);
}
if (type1 == FOR_LOOP_PARTS_IN_BRACES && !BLOCKS.contains(type2)) {
return addLineBreak();
}
if (type1 == IF_STATEMENT ||
type1 == SWITCH_STATEMENT ||
type1 == TRY_STATEMENT ||
type1 == DO_WHILE_STATEMENT ||
type1 == FOR_STATEMENT ||
type1 == SWITCH_CASE ||
type1 == DEFAULT_CASE ||
type1 == WHILE_STATEMENT) {
return addLineBreak();
}
if (COMMENTS.contains(type2)) {
return Spacing.createSpacing(0, 1, 0, true, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
if (TOKENS_WITH_SPACE_AFTER.contains(type1) || KEYWORDS_WITH_SPACE_BEFORE.contains(type2)) {
return addSingleSpaceIf(true);
}
if (elementType == VALUE_EXPRESSION && type2 == CASCADE_REFERENCE_EXPRESSION) {
if (type1 == CASCADE_REFERENCE_EXPRESSION) {
if (cascadesAreSameMethod(((AbstractBlock)child1).getNode(), ((AbstractBlock)child2).getNode())) {
return Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
}
else if (type1 == REFERENCE_EXPRESSION) {
CompositeElement elem = (CompositeElement)myNode;
ASTNode[] childs = elem.getChildren(CASCADE_REFERENCE_EXPRESSION_SET);
if (childs.length == 1 || allCascadesAreSameMethod(childs)) {
return Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
}
return addLineBreak();
}
if (type1 == CLOSING_QUOTE && type2 == OPEN_QUOTE && elementType == STRING_LITERAL_EXPRESSION) {
ASTNode sib = node1;
int preserveNewline = 0;
// Adjacent strings on the same line should not be split.
while ((sib = sib.getTreeNext()) != null) {
// Comments are handled elsewhere.
// TODO Create a test for this loop after adjacent-string wrapping is implemented.
if (sib.getElementType() == WHITE_SPACE) {
String ws = sib.getText();
if (ws.contains("\n")) {
preserveNewline++;
break;
}
continue;
}
break;
}
// Adjacent strings on separate lines should not include blank lines.
return Spacing.createSpacing(0, 1, preserveNewline, true, 0);
}
return Spacing.createSpacing(0, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/Element.java b/src/main/java/net/aufdemrand/denizen/objects/Element.java
index f6f7d709e..09e7b3e68 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/Element.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/Element.java
@@ -1,564 +1,564 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.regex.Pattern;
public class Element implements dObject {
public final static Element TRUE = new Element(Boolean.TRUE);
public final static Element FALSE = new Element(Boolean.FALSE);
/**
*
* @param string the string or dScript argument String
* @return a dScript dList
*
*/
@ObjectFetcher("el")
public static Element valueOf(String string) {
if (string == null) return null;
return new Element(string);
}
public static boolean matches(String string) {
return string != null;
}
private String element;
public Element(String string) {
this.prefix = "element";
this.element = string;
}
public Element(Integer integer) {
this.prefix = "integer";
this.element = String.valueOf(integer);
}
public Element(Double dbl) {
this.prefix = "double";
this.element = String.valueOf(dbl);
}
public Element(Boolean bool) {
this.prefix = "boolean";
this.element = String.valueOf(bool);
}
public Element(String prefix, String string) {
if (prefix == null) this.prefix = "element";
else this.prefix = prefix;
this.element = string;
}
public double asDouble() {
return Double.valueOf(element.replace("%", ""));
}
public float asFloat() {
return Float.valueOf(element.replace("%", ""));
}
public int asInt() {
return Integer.valueOf(element.replace("%", ""));
}
public boolean asBoolean() {
return Boolean.valueOf(element);
}
public String asString() {
return element;
}
private String prefix;
@Override
public String getType() {
return "Element";
}
@Override
public String getPrefix() {
return prefix;
}
@Override
public dObject setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return (prefix + "='<A>" + identify() + "<G>' ");
}
@Override
public String identify() {
return element;
}
@Override
public String toString() {
return identify();
}
@Override
public boolean isUnique() {
return false;
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <element.as_int>
// @returns Element(Number)
// @description
// Returns the element as a number without a decimal. Rounds up double values.
// -->
if (attribute.startsWith("asint")
|| attribute.startsWith("as_int"))
try {
// Round the Double instead of just getting its
// value as an Integer (which would incorrectly
// turn 2.9 into 2)
return new Element(String.valueOf
(Math.round(Double.valueOf(element))))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Integer.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.as_double>
// @returns Element(Number)
// @description
// Returns the element as a number with a decimal.
// -->
if (attribute.startsWith("asdouble")
|| attribute.startsWith("as_double"))
try { return new Element(String.valueOf(Double.valueOf(element)))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Double.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.as_money>
// @returns Element(Number)
// @description
// Returns the element as a number with two decimal places.
// -->
if (attribute.startsWith("asmoney")
|| attribute.startsWith("as_money")) {
try {
DecimalFormat d = new DecimalFormat("0.00");
return new Element(String.valueOf(d.format(Double.valueOf(element))))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Money format.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <element.as_boolean>
// @returns Element(Boolean)
// @description
// Returns the element as true/false.
// -->
if (attribute.startsWith("asboolean")
|| attribute.startsWith("as_boolean"))
return new Element(Boolean.valueOf(element).toString())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_list>
// @returns dList
// @description
// Returns the element as a list. Lists are sometimes prefixed with li@ and are
// always separated by the pipe character (|)
// -->
if (attribute.startsWith("aslist")
|| attribute.startsWith("as_list"))
return dList.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.asentity>
// @returns dEntity
// @description
// Returns the element as an entity. Note: the value must be a valid entity.
// -->
- if (attribute.startsWith("as_entity")
+ if (attribute.startsWith("asentity")
|| attribute.startsWith("as_entity"))
return dEntity.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.aslocation>
// @returns dLocation
// @description
// Returns the element as a location. Note: the value must be a valid location.
// -->
- if (attribute.startsWith("as_location")
+ if (attribute.startsWith("aslocation")
|| attribute.startsWith("as_location"))
return dLocation.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_player>
// @returns dPlayer
// @description
// Returns the element as a player. Note: the value must be a valid player. Can be online or offline.
// -->
if (attribute.startsWith("asplayer")
|| attribute.startsWith("as_player"))
return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_npc>
// @returns dNPC
// @description
// Returns the element as an NPC. Note: the value must be a valid NPC.
// -->
if (attribute.startsWith("asnpc")
|| attribute.startsWith("as_npc"))
return dNPC.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_item>
// @returns dItem
// @description
// Returns the element as an item. Additional attributes can be accessed by dItem.
// Note: the value must be a valid item.
// -->
if (attribute.startsWith("asitem")
|| attribute.startsWith("as_item"))
return dItem.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_script>
// @returns dScript
// @description
// Returns the element as a script. Note: the value must be a valid script.
// -->
if (attribute.startsWith("asscript")
|| attribute.startsWith("as_script"))
return dScript.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_duration>
// @returns Duration
// @description
// Returns the element as a duration.
// -->
if (attribute.startsWith("asduration")
|| attribute.startsWith("as_duration"))
return Duration.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.contains[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element contains a specified string, case in-sensitive. Can use
// regular expression by prefixing the string with regex:
// -->
if (attribute.startsWith("contains")) {
String contains = attribute.getContext(1);
if (contains.toLowerCase().startsWith("regex:")) {
if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches())
return new Element("true").getAttribute(attribute.fulfill(1));
else return new Element("false").getAttribute(attribute.fulfill(1));
}
else if (element.toLowerCase().contains(contains.toLowerCase()))
return new Element("true").getAttribute(attribute.fulfill(1));
else return new Element("false").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.after[<string>]>
// @returns Element
// @description
// Returns the portion of an element after a specified string. ie. <el@hello world.after[hello ]> returns 'world'.
// -->
// Get the substring after a certain text
if (attribute.startsWith("after")) {
String delimiter = attribute.getContext(1);
return new Element(String.valueOf(element.substring
(element.indexOf(delimiter) + delimiter.length())))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.before[<string>]>
// @returns Element
// @description
// Returns the portion of an element before a specified string.
// -->
// Get the substring before a certain text
if (attribute.startsWith("before")) {
String delimiter = attribute.getContext(1);
return new Element(String.valueOf(element.substring
(0, element.indexOf(delimiter))))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.substring[<#>(,<#>)]>
// @returns Element
// @description
// Returns the portion of an element between two string indices.
// If no second index is specified, it will return the portion of an
// element after the specified index.
// -->
if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8]
int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1;
int ending_index;
if (attribute.getContext(1).split(",").length > 1)
ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1;
else
ending_index = element.length();
return new Element(String.valueOf(element.substring(beginning_index, ending_index)))
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("last_color"))
return new Element(String.valueOf(ChatColor.getLastColors(element))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.strip_color>
// @returns Element
// @description
// Returns the element with all color encoding stripped.
// -->
if (attribute.startsWith("strip_color"))
return new Element(String.valueOf(ChatColor.stripColor(element))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.startswith[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element starts with a specified string.
// -->
if (attribute.startsWith("starts_with") || attribute.startsWith("startswith"))
return new Element(String.valueOf(element.startsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.endswith[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element ends with a specified string.
// -->
if (attribute.startsWith("ends_with") || attribute.startsWith("endswith"))
return new Element(String.valueOf(element.endsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.split[<string>].limit[<#>]>
// @returns dList
// @description
// Returns a list of portions of this element, split by the specified string,
// and capped at the specified number of max list items.
// -->
if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) {
String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " ");
Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1);
if (split_string.toLowerCase().startsWith("regex:"))
return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit)))
.getAttribute(attribute.fulfill(1));
else
return new dList(Arrays.asList(StringUtils.split(element, split_string, limit)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.split[<string>]>
// @returns dList
// @description
// Returns a list of portions of this element, split by the specified string.
// -->
if (attribute.startsWith("split")) {
String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " ");
if (split_string.toLowerCase().startsWith("regex:"))
return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1])))
.getAttribute(attribute.fulfill(1));
else
return new dList(Arrays.asList(StringUtils.split(element, split_string)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.sqrt>
// @returns Element(Number)
// @description
// Returns the square root of the element.
// -->
if (attribute.startsWith("sqrt")) {
return new Element(Math.sqrt(asDouble()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.abs>
// @returns Element(Number)
// @description
// Returns the absolute value of the element.
// -->
if (attribute.startsWith("abs")) {
return new Element(Math.abs(asDouble()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.mul[<#>]>
// @returns Element(Number)
// @description
// Returns the element multiplied by a number.
// -->
if (attribute.startsWith("mul")
&& attribute.hasContext(1)) {
return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.sub[<#>]>
// @returns Element(Number)
// @description
// Returns the element minus a number.
// -->
if (attribute.startsWith("sub")
&& attribute.hasContext(1)) {
return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.add[<#>]>
// @returns Element(Number)
// @description
// Returns the element plus a number.
// -->
if (attribute.startsWith("add")
&& attribute.hasContext(1)) {
return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.div[<#>]>
// @returns Element(Number)
// @description
// Returns the element divided by a number.
// -->
if (attribute.startsWith("div")
&& attribute.hasContext(1)) {
return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.mod[<#>]>
// @returns Element(Number)
// @description
// Returns the remainder of the element divided by a number.
// -->
if (attribute.startsWith("mod")
&& attribute.hasContext(1)) {
return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.replace[<string>]>
// @returns Element
// @description
// Returns the element with all instances of a string removed.
// -->
// <--[tag]
// @attribute <element.replace[<string>].with[<string>]>
// @returns Element
// @description
// Returns the element with all instances of a string replaced with another.
// -->
if (attribute.startsWith("replace")
&& attribute.hasContext(1)) {
String replace = attribute.getContext(1);
String replacement = "";
if (attribute.startsWith("with", 2)) {
if (attribute.hasContext(2)) replacement = attribute.getContext(2);
attribute.fulfill(1);
}
return new Element(element.replace(replace, replacement))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.length>
// @returns Element(Number)
// @description
// Returns the length of the element.
// -->
if (attribute.startsWith("length")) {
return new Element(element.length())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.prefix>
// @returns Element
// @description
// Returns the prefix of the element.
// -->
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
// Unfilled attributes past this point probably means the tag is spelled
// incorrectly. So instead of just passing through what's been resolved
// so far, 'null' shall be returned with an error message.
if (attribute.attributes.size() > 0) {
dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" +
"for tag <" + attribute.getOrigin() + ">!");
return "null";
} else {
dB.log("Filled tag <" + attribute.getOrigin() + "> with '" + element + "'.");
return element;
}
}
}
| false | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <element.as_int>
// @returns Element(Number)
// @description
// Returns the element as a number without a decimal. Rounds up double values.
// -->
if (attribute.startsWith("asint")
|| attribute.startsWith("as_int"))
try {
// Round the Double instead of just getting its
// value as an Integer (which would incorrectly
// turn 2.9 into 2)
return new Element(String.valueOf
(Math.round(Double.valueOf(element))))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Integer.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.as_double>
// @returns Element(Number)
// @description
// Returns the element as a number with a decimal.
// -->
if (attribute.startsWith("asdouble")
|| attribute.startsWith("as_double"))
try { return new Element(String.valueOf(Double.valueOf(element)))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Double.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.as_money>
// @returns Element(Number)
// @description
// Returns the element as a number with two decimal places.
// -->
if (attribute.startsWith("asmoney")
|| attribute.startsWith("as_money")) {
try {
DecimalFormat d = new DecimalFormat("0.00");
return new Element(String.valueOf(d.format(Double.valueOf(element))))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Money format.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <element.as_boolean>
// @returns Element(Boolean)
// @description
// Returns the element as true/false.
// -->
if (attribute.startsWith("asboolean")
|| attribute.startsWith("as_boolean"))
return new Element(Boolean.valueOf(element).toString())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_list>
// @returns dList
// @description
// Returns the element as a list. Lists are sometimes prefixed with li@ and are
// always separated by the pipe character (|)
// -->
if (attribute.startsWith("aslist")
|| attribute.startsWith("as_list"))
return dList.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.asentity>
// @returns dEntity
// @description
// Returns the element as an entity. Note: the value must be a valid entity.
// -->
if (attribute.startsWith("as_entity")
|| attribute.startsWith("as_entity"))
return dEntity.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.aslocation>
// @returns dLocation
// @description
// Returns the element as a location. Note: the value must be a valid location.
// -->
if (attribute.startsWith("as_location")
|| attribute.startsWith("as_location"))
return dLocation.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_player>
// @returns dPlayer
// @description
// Returns the element as a player. Note: the value must be a valid player. Can be online or offline.
// -->
if (attribute.startsWith("asplayer")
|| attribute.startsWith("as_player"))
return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_npc>
// @returns dNPC
// @description
// Returns the element as an NPC. Note: the value must be a valid NPC.
// -->
if (attribute.startsWith("asnpc")
|| attribute.startsWith("as_npc"))
return dNPC.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_item>
// @returns dItem
// @description
// Returns the element as an item. Additional attributes can be accessed by dItem.
// Note: the value must be a valid item.
// -->
if (attribute.startsWith("asitem")
|| attribute.startsWith("as_item"))
return dItem.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_script>
// @returns dScript
// @description
// Returns the element as a script. Note: the value must be a valid script.
// -->
if (attribute.startsWith("asscript")
|| attribute.startsWith("as_script"))
return dScript.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_duration>
// @returns Duration
// @description
// Returns the element as a duration.
// -->
if (attribute.startsWith("asduration")
|| attribute.startsWith("as_duration"))
return Duration.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.contains[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element contains a specified string, case in-sensitive. Can use
// regular expression by prefixing the string with regex:
// -->
if (attribute.startsWith("contains")) {
String contains = attribute.getContext(1);
if (contains.toLowerCase().startsWith("regex:")) {
if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches())
return new Element("true").getAttribute(attribute.fulfill(1));
else return new Element("false").getAttribute(attribute.fulfill(1));
}
else if (element.toLowerCase().contains(contains.toLowerCase()))
return new Element("true").getAttribute(attribute.fulfill(1));
else return new Element("false").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.after[<string>]>
// @returns Element
// @description
// Returns the portion of an element after a specified string. ie. <el@hello world.after[hello ]> returns 'world'.
// -->
// Get the substring after a certain text
if (attribute.startsWith("after")) {
String delimiter = attribute.getContext(1);
return new Element(String.valueOf(element.substring
(element.indexOf(delimiter) + delimiter.length())))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.before[<string>]>
// @returns Element
// @description
// Returns the portion of an element before a specified string.
// -->
// Get the substring before a certain text
if (attribute.startsWith("before")) {
String delimiter = attribute.getContext(1);
return new Element(String.valueOf(element.substring
(0, element.indexOf(delimiter))))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.substring[<#>(,<#>)]>
// @returns Element
// @description
// Returns the portion of an element between two string indices.
// If no second index is specified, it will return the portion of an
// element after the specified index.
// -->
if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8]
int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1;
int ending_index;
if (attribute.getContext(1).split(",").length > 1)
ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1;
else
ending_index = element.length();
return new Element(String.valueOf(element.substring(beginning_index, ending_index)))
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("last_color"))
return new Element(String.valueOf(ChatColor.getLastColors(element))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.strip_color>
// @returns Element
// @description
// Returns the element with all color encoding stripped.
// -->
if (attribute.startsWith("strip_color"))
return new Element(String.valueOf(ChatColor.stripColor(element))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.startswith[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element starts with a specified string.
// -->
if (attribute.startsWith("starts_with") || attribute.startsWith("startswith"))
return new Element(String.valueOf(element.startsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.endswith[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element ends with a specified string.
// -->
if (attribute.startsWith("ends_with") || attribute.startsWith("endswith"))
return new Element(String.valueOf(element.endsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.split[<string>].limit[<#>]>
// @returns dList
// @description
// Returns a list of portions of this element, split by the specified string,
// and capped at the specified number of max list items.
// -->
if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) {
String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " ");
Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1);
if (split_string.toLowerCase().startsWith("regex:"))
return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit)))
.getAttribute(attribute.fulfill(1));
else
return new dList(Arrays.asList(StringUtils.split(element, split_string, limit)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.split[<string>]>
// @returns dList
// @description
// Returns a list of portions of this element, split by the specified string.
// -->
if (attribute.startsWith("split")) {
String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " ");
if (split_string.toLowerCase().startsWith("regex:"))
return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1])))
.getAttribute(attribute.fulfill(1));
else
return new dList(Arrays.asList(StringUtils.split(element, split_string)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.sqrt>
// @returns Element(Number)
// @description
// Returns the square root of the element.
// -->
if (attribute.startsWith("sqrt")) {
return new Element(Math.sqrt(asDouble()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.abs>
// @returns Element(Number)
// @description
// Returns the absolute value of the element.
// -->
if (attribute.startsWith("abs")) {
return new Element(Math.abs(asDouble()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.mul[<#>]>
// @returns Element(Number)
// @description
// Returns the element multiplied by a number.
// -->
if (attribute.startsWith("mul")
&& attribute.hasContext(1)) {
return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.sub[<#>]>
// @returns Element(Number)
// @description
// Returns the element minus a number.
// -->
if (attribute.startsWith("sub")
&& attribute.hasContext(1)) {
return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.add[<#>]>
// @returns Element(Number)
// @description
// Returns the element plus a number.
// -->
if (attribute.startsWith("add")
&& attribute.hasContext(1)) {
return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.div[<#>]>
// @returns Element(Number)
// @description
// Returns the element divided by a number.
// -->
if (attribute.startsWith("div")
&& attribute.hasContext(1)) {
return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.mod[<#>]>
// @returns Element(Number)
// @description
// Returns the remainder of the element divided by a number.
// -->
if (attribute.startsWith("mod")
&& attribute.hasContext(1)) {
return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.replace[<string>]>
// @returns Element
// @description
// Returns the element with all instances of a string removed.
// -->
// <--[tag]
// @attribute <element.replace[<string>].with[<string>]>
// @returns Element
// @description
// Returns the element with all instances of a string replaced with another.
// -->
if (attribute.startsWith("replace")
&& attribute.hasContext(1)) {
String replace = attribute.getContext(1);
String replacement = "";
if (attribute.startsWith("with", 2)) {
if (attribute.hasContext(2)) replacement = attribute.getContext(2);
attribute.fulfill(1);
}
return new Element(element.replace(replace, replacement))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.length>
// @returns Element(Number)
// @description
// Returns the length of the element.
// -->
if (attribute.startsWith("length")) {
return new Element(element.length())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.prefix>
// @returns Element
// @description
// Returns the prefix of the element.
// -->
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
// Unfilled attributes past this point probably means the tag is spelled
// incorrectly. So instead of just passing through what's been resolved
// so far, 'null' shall be returned with an error message.
if (attribute.attributes.size() > 0) {
dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" +
"for tag <" + attribute.getOrigin() + ">!");
return "null";
} else {
dB.log("Filled tag <" + attribute.getOrigin() + "> with '" + element + "'.");
return element;
}
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--[tag]
// @attribute <element.as_int>
// @returns Element(Number)
// @description
// Returns the element as a number without a decimal. Rounds up double values.
// -->
if (attribute.startsWith("asint")
|| attribute.startsWith("as_int"))
try {
// Round the Double instead of just getting its
// value as an Integer (which would incorrectly
// turn 2.9 into 2)
return new Element(String.valueOf
(Math.round(Double.valueOf(element))))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Integer.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.as_double>
// @returns Element(Number)
// @description
// Returns the element as a number with a decimal.
// -->
if (attribute.startsWith("asdouble")
|| attribute.startsWith("as_double"))
try { return new Element(String.valueOf(Double.valueOf(element)))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Double.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.as_money>
// @returns Element(Number)
// @description
// Returns the element as a number with two decimal places.
// -->
if (attribute.startsWith("asmoney")
|| attribute.startsWith("as_money")) {
try {
DecimalFormat d = new DecimalFormat("0.00");
return new Element(String.valueOf(d.format(Double.valueOf(element))))
.getAttribute(attribute.fulfill(1)); }
catch (NumberFormatException e) {
dB.echoError("'" + element + "' is not a valid Money format.");
return new Element("null").getAttribute(attribute.fulfill(1));
}
}
// <--[tag]
// @attribute <element.as_boolean>
// @returns Element(Boolean)
// @description
// Returns the element as true/false.
// -->
if (attribute.startsWith("asboolean")
|| attribute.startsWith("as_boolean"))
return new Element(Boolean.valueOf(element).toString())
.getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_list>
// @returns dList
// @description
// Returns the element as a list. Lists are sometimes prefixed with li@ and are
// always separated by the pipe character (|)
// -->
if (attribute.startsWith("aslist")
|| attribute.startsWith("as_list"))
return dList.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.asentity>
// @returns dEntity
// @description
// Returns the element as an entity. Note: the value must be a valid entity.
// -->
if (attribute.startsWith("asentity")
|| attribute.startsWith("as_entity"))
return dEntity.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.aslocation>
// @returns dLocation
// @description
// Returns the element as a location. Note: the value must be a valid location.
// -->
if (attribute.startsWith("aslocation")
|| attribute.startsWith("as_location"))
return dLocation.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_player>
// @returns dPlayer
// @description
// Returns the element as a player. Note: the value must be a valid player. Can be online or offline.
// -->
if (attribute.startsWith("asplayer")
|| attribute.startsWith("as_player"))
return dPlayer.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_npc>
// @returns dNPC
// @description
// Returns the element as an NPC. Note: the value must be a valid NPC.
// -->
if (attribute.startsWith("asnpc")
|| attribute.startsWith("as_npc"))
return dNPC.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_item>
// @returns dItem
// @description
// Returns the element as an item. Additional attributes can be accessed by dItem.
// Note: the value must be a valid item.
// -->
if (attribute.startsWith("asitem")
|| attribute.startsWith("as_item"))
return dItem.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_script>
// @returns dScript
// @description
// Returns the element as a script. Note: the value must be a valid script.
// -->
if (attribute.startsWith("asscript")
|| attribute.startsWith("as_script"))
return dScript.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.as_duration>
// @returns Duration
// @description
// Returns the element as a duration.
// -->
if (attribute.startsWith("asduration")
|| attribute.startsWith("as_duration"))
return Duration.valueOf(element).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.contains[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element contains a specified string, case in-sensitive. Can use
// regular expression by prefixing the string with regex:
// -->
if (attribute.startsWith("contains")) {
String contains = attribute.getContext(1);
if (contains.toLowerCase().startsWith("regex:")) {
if (Pattern.compile(contains.substring(("regex:").length()), Pattern.CASE_INSENSITIVE).matcher(element).matches())
return new Element("true").getAttribute(attribute.fulfill(1));
else return new Element("false").getAttribute(attribute.fulfill(1));
}
else if (element.toLowerCase().contains(contains.toLowerCase()))
return new Element("true").getAttribute(attribute.fulfill(1));
else return new Element("false").getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.after[<string>]>
// @returns Element
// @description
// Returns the portion of an element after a specified string. ie. <el@hello world.after[hello ]> returns 'world'.
// -->
// Get the substring after a certain text
if (attribute.startsWith("after")) {
String delimiter = attribute.getContext(1);
return new Element(String.valueOf(element.substring
(element.indexOf(delimiter) + delimiter.length())))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.before[<string>]>
// @returns Element
// @description
// Returns the portion of an element before a specified string.
// -->
// Get the substring before a certain text
if (attribute.startsWith("before")) {
String delimiter = attribute.getContext(1);
return new Element(String.valueOf(element.substring
(0, element.indexOf(delimiter))))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.substring[<#>(,<#>)]>
// @returns Element
// @description
// Returns the portion of an element between two string indices.
// If no second index is specified, it will return the portion of an
// element after the specified index.
// -->
if (attribute.startsWith("substring")||attribute.startsWith("substr")) { // substring[2,8]
int beginning_index = Integer.valueOf(attribute.getContext(1).split(",")[0]) - 1;
int ending_index;
if (attribute.getContext(1).split(",").length > 1)
ending_index = Integer.valueOf(attribute.getContext(1).split(",")[1]) - 1;
else
ending_index = element.length();
return new Element(String.valueOf(element.substring(beginning_index, ending_index)))
.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("last_color"))
return new Element(String.valueOf(ChatColor.getLastColors(element))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.strip_color>
// @returns Element
// @description
// Returns the element with all color encoding stripped.
// -->
if (attribute.startsWith("strip_color"))
return new Element(String.valueOf(ChatColor.stripColor(element))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.startswith[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element starts with a specified string.
// -->
if (attribute.startsWith("starts_with") || attribute.startsWith("startswith"))
return new Element(String.valueOf(element.startsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.endswith[<string>]>
// @returns Element(Boolean)
// @description
// Returns whether the element ends with a specified string.
// -->
if (attribute.startsWith("ends_with") || attribute.startsWith("endswith"))
return new Element(String.valueOf(element.endsWith(attribute.getContext(1)))).getAttribute(attribute.fulfill(1));
// <--[tag]
// @attribute <element.split[<string>].limit[<#>]>
// @returns dList
// @description
// Returns a list of portions of this element, split by the specified string,
// and capped at the specified number of max list items.
// -->
if (attribute.startsWith("split") && attribute.startsWith("limit", 2)) {
String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " ");
Integer limit = (attribute.hasContext(2) ? attribute.getIntContext(2) : 1);
if (split_string.toLowerCase().startsWith("regex:"))
return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1], limit)))
.getAttribute(attribute.fulfill(1));
else
return new dList(Arrays.asList(StringUtils.split(element, split_string, limit)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.split[<string>]>
// @returns dList
// @description
// Returns a list of portions of this element, split by the specified string.
// -->
if (attribute.startsWith("split")) {
String split_string = (attribute.hasContext(1) ? attribute.getContext(1) : " ");
if (split_string.toLowerCase().startsWith("regex:"))
return new dList(Arrays.asList(element.split(split_string.split(":", 2)[1])))
.getAttribute(attribute.fulfill(1));
else
return new dList(Arrays.asList(StringUtils.split(element, split_string)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.sqrt>
// @returns Element(Number)
// @description
// Returns the square root of the element.
// -->
if (attribute.startsWith("sqrt")) {
return new Element(Math.sqrt(asDouble()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.abs>
// @returns Element(Number)
// @description
// Returns the absolute value of the element.
// -->
if (attribute.startsWith("abs")) {
return new Element(Math.abs(asDouble()))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.mul[<#>]>
// @returns Element(Number)
// @description
// Returns the element multiplied by a number.
// -->
if (attribute.startsWith("mul")
&& attribute.hasContext(1)) {
return new Element(asDouble() * aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.sub[<#>]>
// @returns Element(Number)
// @description
// Returns the element minus a number.
// -->
if (attribute.startsWith("sub")
&& attribute.hasContext(1)) {
return new Element(asDouble() - aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.add[<#>]>
// @returns Element(Number)
// @description
// Returns the element plus a number.
// -->
if (attribute.startsWith("add")
&& attribute.hasContext(1)) {
return new Element(asDouble() + aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.div[<#>]>
// @returns Element(Number)
// @description
// Returns the element divided by a number.
// -->
if (attribute.startsWith("div")
&& attribute.hasContext(1)) {
return new Element(asDouble() / aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.mod[<#>]>
// @returns Element(Number)
// @description
// Returns the remainder of the element divided by a number.
// -->
if (attribute.startsWith("mod")
&& attribute.hasContext(1)) {
return new Element(asDouble() % aH.getDoubleFrom(attribute.getContext(1)))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.replace[<string>]>
// @returns Element
// @description
// Returns the element with all instances of a string removed.
// -->
// <--[tag]
// @attribute <element.replace[<string>].with[<string>]>
// @returns Element
// @description
// Returns the element with all instances of a string replaced with another.
// -->
if (attribute.startsWith("replace")
&& attribute.hasContext(1)) {
String replace = attribute.getContext(1);
String replacement = "";
if (attribute.startsWith("with", 2)) {
if (attribute.hasContext(2)) replacement = attribute.getContext(2);
attribute.fulfill(1);
}
return new Element(element.replace(replace, replacement))
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.length>
// @returns Element(Number)
// @description
// Returns the length of the element.
// -->
if (attribute.startsWith("length")) {
return new Element(element.length())
.getAttribute(attribute.fulfill(1));
}
// <--[tag]
// @attribute <element.prefix>
// @returns Element
// @description
// Returns the prefix of the element.
// -->
if (attribute.startsWith("prefix"))
return new Element(prefix)
.getAttribute(attribute.fulfill(1));
if (attribute.startsWith("debug.log")) {
dB.log(debug());
return new Element(Boolean.TRUE.toString())
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug.no_color")) {
return new Element(ChatColor.stripColor(debug()))
.getAttribute(attribute.fulfill(2));
}
if (attribute.startsWith("debug")) {
return new Element(debug())
.getAttribute(attribute.fulfill(1));
}
// Unfilled attributes past this point probably means the tag is spelled
// incorrectly. So instead of just passing through what's been resolved
// so far, 'null' shall be returned with an error message.
if (attribute.attributes.size() > 0) {
dB.echoError("Unfilled attributes '" + attribute.attributes.toString() + "'" +
"for tag <" + attribute.getOrigin() + ">!");
return "null";
} else {
dB.log("Filled tag <" + attribute.getOrigin() + "> with '" + element + "'.");
return element;
}
}
|
diff --git a/CoVoiturage-Spring-WS/CoVoiturage-WS/src/test/java/iaws/covoiturage/ws/contractfirst/TestIntegrationCoVoiturageEndPoint.java b/CoVoiturage-Spring-WS/CoVoiturage-WS/src/test/java/iaws/covoiturage/ws/contractfirst/TestIntegrationCoVoiturageEndPoint.java
index 13761ff..c8f7c7a 100644
--- a/CoVoiturage-Spring-WS/CoVoiturage-WS/src/test/java/iaws/covoiturage/ws/contractfirst/TestIntegrationCoVoiturageEndPoint.java
+++ b/CoVoiturage-Spring-WS/CoVoiturage-WS/src/test/java/iaws/covoiturage/ws/contractfirst/TestIntegrationCoVoiturageEndPoint.java
@@ -1,42 +1,42 @@
package iaws.covoiturage.ws.contractfirst;
import static org.springframework.ws.test.server.RequestCreators.withPayload;
import static org.springframework.ws.test.server.ResponseMatchers.payload;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ws.test.server.MockWebServiceClient;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("application-context.xml")
public class TestIntegrationCoVoiturageEndPoint {
@Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
@Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
}
@Test
public void releveNotesEndpoint() throws Exception {
- Source requestPayload = new StreamSource(new ClassPathResource("ReleveNotesRequest.xml").getInputStream() );
- Source responsePayload = new StreamSource(new ClassPathResource("ReleveNotes.xml").getInputStream());
+ Source requestPayload = new StreamSource(new ClassPathResource("CoVoiturageRequest.xml").getInputStream() );
+ Source responsePayload = new StreamSource(new ClassPathResource("Covoiturage.xml").getInputStream());
mockClient.sendRequest(withPayload(requestPayload)).
andExpect(payload(responsePayload));
}
}
| true | true | public void releveNotesEndpoint() throws Exception {
Source requestPayload = new StreamSource(new ClassPathResource("ReleveNotesRequest.xml").getInputStream() );
Source responsePayload = new StreamSource(new ClassPathResource("ReleveNotes.xml").getInputStream());
mockClient.sendRequest(withPayload(requestPayload)).
andExpect(payload(responsePayload));
}
| public void releveNotesEndpoint() throws Exception {
Source requestPayload = new StreamSource(new ClassPathResource("CoVoiturageRequest.xml").getInputStream() );
Source responsePayload = new StreamSource(new ClassPathResource("Covoiturage.xml").getInputStream());
mockClient.sendRequest(withPayload(requestPayload)).
andExpect(payload(responsePayload));
}
|
diff --git a/server/src/test/java/com/sinnerschrader/smaller/ServerTest.java b/server/src/test/java/com/sinnerschrader/smaller/ServerTest.java
index eff92bf..b762a9d 100644
--- a/server/src/test/java/com/sinnerschrader/smaller/ServerTest.java
+++ b/server/src/test/java/com/sinnerschrader/smaller/ServerTest.java
@@ -1,195 +1,204 @@
package com.sinnerschrader.smaller;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
/**
* @author marwol
*/
public class ServerTest extends AbstractBaseTest {
/**
* @throws Exception
*/
@Test
public void testCoffeeScript() throws Exception {
runToolChain("coffeeScript", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "script.js"));
assertThat(basicMin, is("(function() {\n var square;\n\n square = function(x) {\n return x * x;\n };\n\n}).call(this);\n"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testClosure() throws Exception {
runToolChain("closure", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})();"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testUglifyJs() throws Exception {
runToolChain("uglify", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){var aLongVariableName=\"Test 2\";alert(aLongVariableName)})()"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testClosureUglify() throws Exception {
runToolChain("closure-uglify", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})()"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testLessJs() throws Exception {
runToolChain("lessjs", new ToolChainCallback() {
public void test(File directory) throws Exception {
String css = FileUtils.readFileToString(new File(directory, "style.css"));
assertThat(css, is("#header {\n color: #4d926f;\n}\nh2 {\n color: #4d926f;\n}\n.background {\n background: url('some/where.png');\n}\n"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testLessJsIncludes() throws Exception {
runToolChain("lessjs-includes", new ToolChainCallback() {
public void test(File directory) throws Exception {
String css = FileUtils.readFileToString(new File(directory, "style.css"));
assertThat(css, is("#header {\n color: #4d926f;\n}\nh2 {\n color: #4d926f;\n}\n.background {\n background: url('../some/where.png');\n}\n"));
}
});
}
/**
* @throws Exception
*/
@Test
@Ignore("Currently sass does not work as expected")
public void testSass() throws Exception {
runToolChain("sass.zip", new ToolChainCallback() {
public void test(File directory) throws Exception {
String css = FileUtils.readFileToString(new File(directory, "style.css"));
assertThat(css, is(""));
}
});
}
/**
* @throws Exception
*/
@Test
public void testAny() throws Exception {
runToolChain("any", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})()"));
String css = FileUtils.readFileToString(new File(directory, "style.css"));
- assertThat(css, is("#header{color:#4d926f}h2{color:#4d926f;background-image:url(data:image/gif;base64,R0lGODlhZABkAP"
- + "AAAERERP///ywAAAAAZABkAEAI/wABCBxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIMYBHjxxDPvwI0iHJkyhLJkx5EiLLlAZfs"
- + "lxJ0uTHkTULtrS402XOhT1FHkSJMKhPmUVlvhyqFKbCpkKjSp1KtarVq1izat3KtavXr2DDihVrdGzEsgzRJv3J9GZbt0DXqsQJ92l"
- + "TqHKXAmVrs65dvlTRqjVLuLDhw4gTK17MuLHjx5AjS55M" + "ubLlwY8x57UsUDPBu4A7g/arc7Rf0wFokt6cNrTnvathz1WN"
- + "WjDRia9Lx9Y9O6RS2qnPhn4bHKvt3X9751Wuu23r4bmXIwcAWjbevrc5a9/Ovbv37+DDi7wfT768+fPo06tfz769+/fw48ufT19r9MT3RU9vnJ/6c"
- + "Mj99feZUxIhZR1d1UmnV3IJDoRaTKYR1xuBEKrF14OsNeTZccwhWJyH2H3IYIUd"
- + "hljgfwPu5yBg2eGGYoYM1qbcbyAKp6KMLZJoIIwmPldiRxSm+CNxGgpYUY76Daljj8a59iKRIYr41FA18iZlkTRauRqS/jk5"
- + "2F0+Bilkg1peF6ORNgY4U31stunmm3DGKeecdNZp55145plVQAA7)}"));
+ assertThat(
+ css,
+ is("#header{color:#4d926f}h2{color:#4d926f;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIcAAACbCAYAAABI84jqAAAABmJLR0QA9gD2APbboEbJAABMi0lEQVR4XuzSQQ0AIRAEsOFy/lVusLEY4AXh12ro6O7swJd3kAM5kAPkQA7kQA7kQA7kQA7kQA74c6lq5tRi7zvgq6qyftctuamFNBIgdAIECL2KgCJSLChib1jxU8cpFuxjG2uZGRV0bDhjF7tgRQRRsYD0EmpoCYEkhBTSbnvr/2fvdy6BkUHf7yXfe98Jh3PLuefss/faa/1X3W63S6qqqkUkLPEJCeL3+/VlWN+JRPuiZcOGDb1btsxY2apVaynYurX1hk0bS/bv3+/3eDwiLvm3W8AfkES9Xqf27cXr9cq+ffukaFeRdOjQUdq2bSuhUEhvE+Z3e0pKZM+ePeJv8KM9/Ky0rFRiY+OkRYsWUl9XJy6X6DUqpb6hXlJSUiUQ8EswEOD76OhYvV5Yf98gdfW1EhsTK4FgkPcI6rG+vl5at24jycktZMfObSmVFVXdo6N943y+6JzExKTf68XLwuGQuF3oiypx67P5fD79LdrIdgo2HHG9Th07aruSpUHvd6Rt8KABv5E4mtnm0k5yu90DS0tLn9KOHVpbW/dpbW3Nxurq6mtqamoWtczIGKvEUY+OO8xmOtMlCfHxzvv/S1soDIII6MD5eV8Ji1sHNFRXV4vn6llf3/BtZmZmi2QlOr+/QfT9ieFQeLK45JvmyzmafsPMIeeI8nrTAg3+xXvL90pWq1ainGPC/urqCRs3bQTljBw0YICeElUfCAQORxpKWB4BZ9mxY7vo75QDxB6JGDHLOcM9HrwOclZGR8ccibDwPX+LtjToYEtI8nzRMeMSEpOHR0V5u3k83qSqqso1SgjjROTq2Ji4FlXVVQLeGBcXj0mQEQyHFuplrhOXTP8f4jj8xk5OTUnN3rx50ydgq927dxdfVBRZacG2bbKzqEgmT5p0eatWWdVyhK20pFSqKyvFo7+PGEgSTXR0tGXJQvZNInOdk5mZNV4HNEMHLBgW1xYRuU9FzF6Ii0ZEYsUF2gziOiYmNma0iqAJMTExx6i4IIGGw0GKm4SEhDa7dxfPqKgovyUmNj7eH/BfXFZW5ob48Xo8OAfXf0pvMVSPT+i+WUT2/g9xcOPsk1atW18578sv//rj998nXH3ttbJ/f41U6QBXqhxesWqVtG/XrrRXbu5MnAsOc7hZrIMj5eXlsnr1anAgciOzEUvU1tRIYWGRpKamiO8AkbhcbvcLnTt1uiw2Lg6DDoKkrK+o2PdhwO9fAEKyBKUiThITA22ioqJGKEeaEB8XPyo5Obl9AzgeCFnb1lDfgPbhqSR8gHiAU65RwsxWLLJNzwu1yspyJyUlSZ2em+zzyu7de4CzLtD2XxAIBir1Ge8Rkb8enlv9/0EcBG4JiYkXaeffmL9uXe+vvvxSrpw6Var375evFy5Udh2UmtoasF8ZO+aEyS63SwFiPTu80UbCqK2tlbVr1pIovBxkpycxo6uqq7GTeAq2blFckpDZf8CAyxQHAFASBDaEhWB027Zt/RXj/JSYmOBTkJibmpo6Mis6eowSw3FKQF4QFwCkzxdFEFmjxCwuAWGBIxFTBJR7YEO7U1JTJ4JoQBQ7tu+Q+V99KUF/UFoooZ44foJyIr8+W60Sd1lSIBB6XJ+5pT7/LSBI/D5sQLTLRVH4/zZxUIykpkzNX5f/7P6a/fLdt9/KyaecIq2z28pL//qn7KuskC6dOn8anxD/1XEjR6zOysxcaIngcJvfH5Dly5ZzhsfFxTUWBXgPIiMXqNRrF+8qlvz8tcVLly7defkVV2Tn5uZKnRJXIECClZycro8rYd6mHMjnjfIl4pperwdcAdoQjhRTlaptJSclgiBIHN4or9TVKYeJSVBtpgG4h2ImqNeN8kbJvvJyJeDVMm/uXOnRs5dqZOv1s33i8Xp198jE0ybJtq0FUlNXe3PL9"
+ + "PTF7fu2fbfBaFJ1nBhuIxabP3Gww45uc1kRcPH27duffeftWcpWd8vYceNkxMgR8tPiJZKRniEjhh8LlTJ1y9aCx3bs2CG7oW6iUyJmjSJ9nZEpsnTJElm2bJlMOn0SZDzEw78jSHKXtLR0Ofvsc2TXrqIuChBLMzLSs6l66h4d45P4+AQMpL4PpuF2IATs9XUBCRlV20V124drgtOR6ECPVZVVVHFjVMVNTErAeVTXPR43wXHBls2ycuUKuera38nM556TKZdeJp/M+UiUSAHAySFGjzlR6nftAnC9ze1yvwuigPh16Z8vxmsIv/kTh5X/R0L1mFlA9WDFsGGM8yQl/gsd2r5DB2nTpo2cOnGilJaWSVZmlvTonssOXvzzkiGK+KfvLd/3u7pG4gTXTEhMkLK9e+Xuu++WEceOUM2mJcRB43uTIFQVBuF4tB25MTGxJ6i4mJCbO3ocbBkVFZUUX4oh1G6zQzlLpeT17kNR5HKFqZruLi4G54HIIogNud0gDBA5+wDtowYVdoGT6Hu/VKhtJDk5EeAVIosaTW6PnnLvXX+WzKwsufm22+WOW26WabfdJqrliIJVJagknh8fHydlZXv7l5SUnt2pY4dZwCd79Vm7d8uxE6z5E8eWLVv+A2OXm7MrXllzeno6OunW8AEQKps3beKgxsfHYwAhEihjN23eJMXgKGPGbOjbO49gMHLAQVgguKeefFISzG/xvlevXmqwquA9raEtKyurQ0Vl5YsKSrtBe8C9IBLAYdDhGFy0LTOzJdXM3592GkVcz7ze8sZrr8qEk05SzjZen0FFSIsUHfR9IDheOxSiFoQdoJRsHyQcF+fRNtUAUINjAOvwPunKFadcdpn85S/3yaQzzpSLplwizz49Q8674CJ5V7lo334DaCsJBUO8nrb5LX3WfAW9KwGyyTn/u3COMrUmHmnTmSpr1qyhdXL48OH91CI5WB8a1kcMkJGhYXYsPgd3yV+/QTWDxFC3nC6vuj1uAj9sxrLJff78+bJ02VLpoFbDZcuXybPPPSt33XUXziEgFHHx+olJieGOnTqO3qccImy0Hb2nAXgugsStW7fKou++kxYpKdJvwABaVRMT4jF7ZdZbs+RSHdCVK1fJnTrTz1SRlNuzJ89xu6GVCEQSBpOEWaGYJk45Sk1tHcVcbCw5DttTUrJHzjv/Qvnph+9l8mmnyoo1+ZwgL/9zppw++SwpV2JNSk7CBMH1yI2Wr1z1jeKcTBV/dRBl4FJouza+WRMHB/TIG4EkuMJIZcUf6R6Ljk3Qzv/TDdeDfWMQMNthiIKpXG0b2+X4kSNeUALZqx2E78z9aOIGxyLBpehgqkmdomnmSzOlW7ducuqpp6iIKsFvaLWsravZplxlnYqDXFzLEJntfALGtLRUufDc82TEqJHy5Izp/CzK61EssEx+/PFHjsMmNcStW7dW2qpZnr+jFqH3cOu13B6Kpv011aIiiyqtmsn1GeP42mNsGiBMtPfe+x/S+50tY44bSdyR3jJDRh43Sqqr9uv31cAX4GLEKslKvfosr6qa7iovryhLSWkxFUSPZ2jWxJGXl/dLYEPCRqy0yc6+Xgf6cdghrEbh8xH8QXZzNsTGRgu+X7N2nbLftMCQwYOmRVoyLdcoUX/I4sWLMePZ6Xag1S4ts2bNkpNOOllaK7HAVsLfUQ2UNdqOXNxLjyQGQecr8NyrhNleB/yGaTfJs888AxFFjNAyI121miLiIGyzP/xQr5st7dq1U3V0O68t+GeAeXVJtaSlptGPUlOzn8NbW0e8oZwA4iYkXvGoKCuT9IwM+ccLM+Weu+6U4uJdcvU118rOwp2qMT"
+ + "UYIxrOFamtD0CLAlFNBidTiyve/zMuPm4ROa64mi9xpCmG+KXNcwC4ZaWlpT2ug2hYsZsDiw0iBLMwFMIAe+gI27W7WFR9/Yuy0ApgAjPTIbt5/jfffIOBIXHZ2UNDmqL9lStXyvOqBdykAw1gZ6+fkJS4HdwLr5U9y/r8fCWwJdK1a470HzgQoFQxwBls29YtW6WbWmj37CmRjRs2yO/+8EeZN2++nK7fz/38C3n91VfknPPOU4NaIf3arhDtGwCR4CZGbPmNqHRh9uP5KFpC5HxRUqLaV0JCojw5/RngMVyLv3N7MAlcbGdNbS0dkPGqkUX5fLzWNuWo9Q3+99WtkAmCBOE1V+KgTv9vNoPuVSoHg7OAG4ADMIggDIAuDDzEEs6LiYmmjWFLwTaIiprBAwc+iNmWqmIDm5Wv36o9pKKiQmC4wrGRZkLx8sabb1CcnDbxNIBMakFlpaWLFPNcr0YsWbZ0GTSSpd1zu5++bu06j3qEZ6s46lVevk+xxaUgCoqDmS++IO0Vzxw/+nhZpXjjhBOOB2ejTeasc85VwvdA3dVnJHFKog72vgoQv4eDWt9QxwHl7gYFm9cuWmyVgOqlpLQO6i98OuyDYIjeV/QbgDrVdU4iJaBqJfQwJ0KgpRLh00rkcEaSe7iaIXEcXu4RLFEMdN5XUT5XuUdHUD4eGrMXM8kYkfg+KsoH7YM4Qu0ayjVGPq3vG7YUFJjOdOs56l7fvZsiBQOMwThMWyiusD3//POy8OuFMmHCBOnSpQsA7Weqjm5TAkxUwnhducx1cO5ltMzI27x5856MjAw422DKJkfauHETRdWNN02D2R1iSkHrdjnu+OMFBjO0BW3DIIaUdbjCHHiow9RMoCJ7Q1F07/MZ0D4DSvH8Xi/ESzm+B2BGyAAnWpQv2k4GaHCcAHvUVxQbE4M+MtglpKr1nqu1nc/o866CeGmGxEGx8W+5hlL1GzrwHePiYvFAeDh0FGdHNC2dYLcBsFA+tKqb6LiQDuSMd9/7QNauyxe1kGLUeU5aaqrigBQlMocgje1jsBJeDz2nUAlkLgiuo8748opymaXqYfv27TSWo8P+jh06ddDvRoUklLzo+0UvaZsmKSdIBhEMGzZMcIQowobjRFVpU9PSqLraNoADwjYDVRZWT3AoaBYuPksQzwi3ADgTtA4+H+jYFQ6jr+C70e+qVMXV7xOTlIsmCNiKvx7EUaz3rYP5nsc9SqgqPnBfi5/Qr/geWo+2q+K1rjldegPg6nM3P+JwH0ocGGh07kna+YMAOEXCluIx+OzoyopKslFqOzTqwJyeKt1yuta7RB5MSkxIVvP6fTorvg8bIgD6x/2MxgEucaYebtZzBioewXvMvjOVK72r54PNY/bBtJ67Y2fh6PJ9FSMqKyqG6qxuD1CphEGCOOeccwAi8R73IWFkZ2fzO+U2EBVoshURAKy0Q6g3Fp5VEoN+DC5C7ojJQK2kej80MthocC3gH3AC/q5ddrYeY8k9Kiqr6ChEX4GocA3gEvXegrOCiEBQvAYHLcpD0bxp8+Y8Fa9n9uzR/R3YU/5PC5ffXLxFLXiHIxh04Ba1bnakL0TC1qRNDPDcs8/J5598Ki/88yUjexsMUblBLGChHJC5875Cp3RSA1UBzNawPOopwCbonPs1Uuy2BQsWgCjwHgMH0"
+ + "fS2Ypkb9Lr9dR+jnx+rtoa+1mM7ePBgufjii0kM2EBwuKfaXvB7236+LikthS0GA0xA6HZ5ADjxLATW/kCAGlIDsVQYWhE4CV5DC4JX2RjKQhhoiCttZyIHe7+KKqrvnCwEoHx+en/VAYcNBAMRCiswcAy4GMQZiBMbCE2frbBfn97ZGjh0iKgdOXJ4c3K8sWMx8yZqB3bUAUCHQHUDyASaJ6vcvHGj9OnXFzOM7DkSqniI1mkQI+LPyel8Wp+8vL9rKIT8sGgRwCK1jYKCgqs///xzAlNj8cTMxPXG6z3PVIJx6efoPDvjMFBqA5kIi6m1ohqzN/EPiViE3AExIRgsiCMcwdbhOcW5/F2yigzMVt0M9tBjlNdek8YsjWDjAMfqc2cquAQRB8OKF/QZQkGKIBJTMBACkYBA6LhLjEqiGuyjk7ASfUEwukiB8EAlblwHogRYpay0rM3a/PxzO3bs8CaIqll7ZV0uqnIP4wHi4mPl9Vdel7ETxpKqF323SGfvXvo/Hn7sUXANcAF0PkCp0dlD+ByDTHCY271bHMDi+vXr5euvv6Y9QiQd5+Qpwa3SQU1Bp1pDmYqLRBPUg3NAaNgNGI6FlmRVXxtLSqLRgwGLHmhRZP2tW7dSlbMUmMKqpFQz41QcVOhgKWfUAaQ3lgRRva9Sj3Sxc1IkJ7UkPihXLgPOA5UV6inAdVDbyngPuvR1D7rg+kf7dGcsCBx2vG+Wuhneev01mT79SZky5VK55PIrYFWFaMN9MBkfVBfCm3ExxHbNyULqakwYI/TYvaWKj5kvvCgvv/SSeiI3KQglpqA8P33SJAwyRJLxH3gAwMg6QVRgucuWrxAQxaBBg975+OOP5SW9TufOnfVczs60fv36TVAx4f7uu++gvho57bUufRvgGxmgCwLi/R3N2BWpXFlCAmHR8aesGrMTbQNugSGLszhsfl9dVQ1igLoJMEqXe0pqC9pjfFHRIBiAbLQFBMfA4NhQjARAoEZzwcFlj2HiFtpOMMRRviiIKPbrrqIiGhy3qfV4zapVqmVBld9HrllcvKfD2rX547KyMj+vranFtZsd58DgQA7ehodB8MumDRvV79EJcpTsvXOXLmSnkyafAZmN8yHzadhZsy4fXlZ/Rnq6YsbKtKJduwMt01Pve+zRhzd89NHsFj179myj6udQETlBOc+pykUSYDgCARkfCY7/zktsgSYtjA5B2O/se8aQsq3hqrC69HdhoPU9xZZys3oQAAgCBEQrqzrEoIEYfw9VV8Z4V"
+ + "FRUW+0CBAtCMbEfyeKvrhLek/8ZqnCxIeZoAHhUNNvcoHunLp3ZljZt26nNZYVMnHQG4lKMO4Gm+9uVUD5HXAgeprkRBy2hehivR4KmW++4nbIZ2zMznpaP1Px8rloW0XSwTjwsDFQ/L10uhUVF5du3FbymlsNuyoLHaGeHtmzeNEwHaL3OmGwd+DgFoBh8YAsSglpdbSiAHGmzxAOCMu/NZxZngGuI5X5w+oEAwH1AJAj1AwHoe7+E3QCQQYhC7Dy/lk7E/byWm2IlCmzfRqTr9eJVrNTALQ+Vluo828E/52htJ3WBOjwnLNDEbCedfKrcf+/d8tOPP8hxo08AULYaIIKVAdxHAOelp6UV4Ltmk9TkzLrQRY6892DQiMhhxeuhXswTx46V0SeMRuQTZhsfLF+5yz5F3Vs2bYhZvXL5hVVVFSfW7K9yNdTX+pRTjFcvblcFnXEYJFwHGyyHAJVWrf0PN7YLgUM2uNghEnaFxT4gWn5uzP14zd8yHUJo9cUA4z0tpNbeExMdAzxh8Qv+gUiQy8IBdBn7CYAmmUQEl7BHI+0ogperx3mdOhc1+Jnc97Irr0KIIYEpxSiBNu9BblZUtOsKAfc0GKwZWUgZ23BBkCjch9dKIHx6HdRaGXXcKOPiL6dW4I2OJlFofgpBakN9XWyvvN6xwCA2UryS8pocxvpRsP9a0AX5jA6EWgmug3aZazI1QbFOA2YkOhfiz6rXVL/x1sRwUhRYe04sLJougaNQsdVWGMyoftY3BNAPwFU0eNHUHgzRqOVwKyHAxeZclq947KkY43l1BGa2aqUYrYMgCPqBRx6R115+Gc/A+9SRuOmphsp7rmKl26363PSA1GHPHdS72AfyGS54NA6DC3QeEx1tbQdmxriB6Gl32K8DtL+amV6WE1gCwHuwbHz2mx4WBIvrYHbl5+cjpBDEquKi2IoTbDZ4l3YWECnAMVRRuOL9/iCIARZNaClQbanRaGA0bQ8L1RkYVNB6zvnnkcuIy6Nq924OYmpaKkArsIfVxCLxjtMvYXsU2kjyNNhouEa43XLj9Sqi/8w4E82Sg+Zj0yKwW4Mg2tmppKRsYIvkpCXqnGt64nBM5bWTcEQj0WDo4RgQBZiQuRxgh5W7QQDQShhxTU3FdQi1WzzB3brmj7DZnBKIILBitAX4gSAzO7uNKLDFdTm40dFRBJGRqq+bXmRco8FqNoheAxEDZAN/IDgZmEqNec9Kjx495IILL5QX1BOc06279O7dm0HDbpcXbYDpnqmZtXXUeAAucQ/YNiyH4D9nJ7XQ7lFUVChnK0ZDjMhNf/q95CIgOX+ddMnppip7exV55eIxFlr0N/xOGampQ1QrWgInZ3MQK1ZtHKuBu2YQGS8JNs6BiPKqWbu+Hp8bwEacQtETxG8DQaiJjTPQcG3LcX6JMMERwIVARCAEyGsQAXGJ4haoujDCYSdHKNhSQDtC69atjRhB+/0cPBGKLs7OVL0WZrnm09C0vXbtWvnD734n99x3n/zx+j/JU088IV27ddO9q0w8/XRoJFBvCS0pXmN8ZqLUApvwnjR2+fFdNO/DwJ4wQ3sc+uAf+4GxHpdcdoUa4zrJ0zOeVG4VJ2efe54Fo3TYVanWkhAfpziulfiDwdEazjgD/d8cxAoGJVbZ8yi8hlwF28XDAZmTWEQcvwoJioOKmYo3kYYqa4uI5BgYULBkAwrDkaozItfJrUaMGCFdVN3r1KkzrKYkhEYbLa5Kj1ABqXImJSVTFdXNhA7g2gSfdGz9c+ZMef7ZZxit/tHHn5AIFsyfr5rXDDlb/TFn6d5WfTQijDpnTGxdfR2uQWDqdhGUEzOF6kNUXcPBMMWRDqASiR8xHcYcbhCqlSs4uNm3DHoeoo7Bbrk9"
+ + "QEyYAIx0s1bfNnpfTC6EHGgw9hk6KZK1vyqaQ2oCxEYfZc+xJmjXGpcAwszAM2ueD+t2W92fbBziCEBKcUclBgvcBmCRYsD4ZRiIU1xcDO5gBx3XpWGpT58+cuGFF0FkNCYEtMvgCbbB2kOQl0Lg6HIf1t5hRGC0jBs3jmbwxx5+WJYbnPKyBvqcqTaGDu3aysuvva7+ixFwnFnAi8h0XIcD7PV4ibkIUOsaRAxHwqyG1gH8EBcfr3ucaPY9+4Y/dXZoRlCHgV+gSSEUAOIKfQiHHiYC71FQsBVcGgQH8TdCraVzmkGwTwNY7zBYFONi48l+6ZTyN8BAxQHSuEcMjzAoxnAJj5EtA/r3Y6kAX5RHxUEaHh5EwtlmOQ0dV2oPefudt2XJkiUgGgwyHU+TJ08GYZjcVccYhs0Shj1iQ7vACfaWlcEzbGM7DTClpgDxwntkqsi4+957pFS5yJjjj5PV+eulm3KPd95/T0YcM1wee+ghOU8xQVJiIjQcDjIjsw5wU1pLdxYWIuBYz0k2vhOPbF6xie/bKoEhNDAlJRnqKL9vBEBIZPhDHg0m3vbt2wBuEQgNP4zxTYWNh9uF/oV9JE8NinOa2s5hAle8nTUIVo+IySgHa+UAW5UtLi4G8hYdCHGDGYU4DXooBw3sL6O1449VVA5wBxxg4j84+/1+OroQlKMhfd3QgZYD0N7x1FNPITTQpAVYIuAxkiNY1RHXxX1hqgcnoghptNnzEFnPzp+u6uToE8bICGXtNkXib4o3lq1aKZdePEUCJlQP7B4DyNuZWZ+uBF9auhdAFp5fxS3rEFTEvBWUZoA2VFdbj8lgCEsid5vzQ/FXpqIkBYFOwQAy5/AbOP/YP+RawaC1BA8Jh5telSXFakPy0NnQ62mPSAhBC8DAGuKIU9aawtmJDe2GTIZnFCIDD2nObZQL6tLvYsgVPlDr6hfqhTXqIDqNwPPTTz/FaxAJOomvrRbgmNXFUVl5D6ZFQmNhO0WIEyyXsRsICJZHOuxmf/KJ9FROMkENeQu+Wcg2vfH6G3LbLbfI+BPHQGMBpwQ45rUs5opVQm+VmQknIn0qySpKUlLS4LsB7sGgQkyQw3q8BJlsiaFztJN9VFmxT4F1axVLyjXdHmoyxhKqvyeRgbj0SA7UDRHvTc050MHROsP7aoPY6WtWr6EnU8PnTcieE46v56IjyFka/AFgEqurH0oYznuy5id1psK6aUIEqaZu2rSJ2shpGrHliJHIa4ixVzAQiPLdF00OY0LzGiw8Opy/xRq6MOPJ9r9WJx/iR6+47HIAYXUFnCtvv/uufLVgvvz4w4/aliwQZKR/hO2Ev6NtW0ajIT/Y5MyE0F+4vk3ThH3FclvsmAgEmdUqlrQSAGwnvC/zat1M3sZktA3GtRCXCrDbVq8d1xzM521EwsirgIOKNouHHnhA3nn7bcwu5nAw8trtGMwiZ6ad5REfO+8josqHDz8Werwi952wqoKFMnDnH//4h4wZMwYEaH4TyXViEUqnBLuaOS75a2GwKtFZVyRbCwqQqkhx5xBGOFIMmdckEMx8uvAXqLHrRc2P+Uw5CbYBAweojeMFyenahSUVsEWopEY1D5NT1FFtDkYSpPUmR7ogwAFB1BRFfu3DLjm8NrELg5MMIWCjm9/J67HiOF7vldPUxIGGphsRT1Px2HFj5VhVK++562654/bbTT5ptDPgPDoD4fRU5IAc5Ell/MQjjzwsTz/9jFx11V"
+ + "Uybdo0uU9tDTfffDNiRQ0OidQ4KO7AaVBugaLDakslivqRc9JOQwaydTaDm1mMcvgaGC6rMvL5hh87XO6/7y/SoVNHzvKiomI594LzZcoll0oRnXqO6DIc0blSoz0yuYqDHGIANvusUCdBQnyserI7M60SlQhs1h/7NDaW0XKlJSUIooK5PzJNFH3SrhkYwSQNKB+xB9AEHnvkUXgSVc17TZ7TWY1ZiuhveF+NBZIs1ZkljZvgco6OkYudNmzY0MgTrW0kcrabzmZKpWzSCPL+A/pTFJnNnG9jQRsH5hJ3WAKLJBrLAfgcN91yMwNxiotL8CxUi7GZqj4QG0hqIlfyxcQaTSpgb+HYMfiabeHHviifEm8hYk/JpZK03YgasxFiIQJfakL0s6S0oOqPFoKzoI/gsrAJ7ilNThw//vh9FjQNdDI6p7faHd6e9ZZ8q+wXxHLLtJvlz3ffpRbLHiojaxENRflPs2+AVtRGA2xkrrNZ2c0Z0fhzC04dLyRZLllyamoLEAYBmxPMY49hByCHfyk/2QJV3g9thcHLWHjpb0G7kI4AdRtpDDhbTAUiGgQzMlqSyFnMBfd3rq0EwSGgzUYDWZSggjTmgQx2MbOf3mJej22JcD6m63XBFWFFnT9vLisDxCUk2PyW5KYWK8jhaGEsmwSbuaqOnnHGZPmvq69Rg9GrMuyYYwCcqJbuLCqkNRBF0zRXBKwUct+IBdehosVJnMYAkAu99OJM+dvjj8utKlJuuWkako0waGDNnNmNE7idmiDC3dFmDksMh21D5Gu3G4QaALGCnaPtzIorVmIEFwHQhdaSrUnjnTt3oVGquLgIEydSwCA/BTMdsRrgcBhQ1hrpqBbemro6OOzwTIe6DpxJxD7dtm0r2sD0Sq09hmsClILY4pucOLKyWicw5jFMczbkLqO2l2kswjcLv5EbbrxBhqo4QLQXEHaHDu1hD2BsZUulfPzWIYRD40RsdcDXXnlVLle5jlNHjBzJ5KJ16uvo06e3PD19utUsnIEPheGQslfCbn01IDS01RLf0YpRm5oJgMxErPjERFQQIP7JUNsLraAsN8lyT1RZLaejKg6AW1xMoqirqYVtB6Z3RKxDq4PmAjF9KMHappo2gBBRJehtzfCLi41jLVerusfDuNSkxEF2WBplXAJ8cKv6XXv11fKIWhDhjMKOQYHpGyzerX8a74jPbMDv4WazjahSzecdufKKK+VBNWNfcvllMnDQIBk3frx8+PEcufD8C+Ta666DdhRZZQiBv8QqjnMwDJsDZjdEDmYsQCuIFCz6aIgD3lz8HiZ95tR2YNY90jv3KZfcb4K"
+ + "XYSqH+Ry5K0nAQWgPzObggPRCZ6nq2zmnKwYZxjUGQYVMLItDCNwpWsSx/pITbVyfT4vy8BEjZfWqlbY2CEAp1HZPMyCO8rABmDQjr9cGwyDz8iuvyMWXTJElixdT7obFyRMNhYPoKMpsS+kikeyeu42sllsVAF485WItbNLXynLu2B569BFJTkjQ+hb/snYNfAdPLGYl1F6wf6rZZTrTly9fzkEo2VOCtiHQCKGMBuxJY0Jt3Ca2n7ijqgoeWTwrRUA4TKyD57GxG3Te7S7ezVm/fds2ZMfDZ0RjltYLwUwnkVVXV8HYh/7ADq5kCdaKFQQMwaJq8RL9LDbXJiurFfxFdEn4IaJNY5uaOGDCrsMsMcYfIG2qiueperdyxUpY/SJZt9FUhEDq8OUDQgeFHq7SSOtNyrqhdWBD7GbERpY8+vjRSHcAKLSgkYSV3a4tHWble8tR/wuBPsQBffr2kV55eSgLIStWrICsRuf+EgexfhfuPI+R4tKYuPnnmO9dOrNTwNEgXkCwcJSBEJl/U1dbQ/HmctN7S8IOmrgXPce4/kNIcmL1ouw2rYDRIC5BKMq1crWPl6thbqGq5h3onPO66cWG38nfxMTBQa42g06bwaXK9jfrYKJjYM1DDqrfD1UuiLgNlHcE+4NzjsfGLDuSl9o65i5TqsFukVoHtuSUFHCiyLxdsGmmP3TJyUHBFSXYnajeh5A/mMShaiJghl7d/Pz1ANNUF53NajCNBj9M0z8i5ZFLwxltrbaOKuKCaRv2GajxTMJiJcF9lbB44lyDeYyY4LMQQAOwQ+OBEw+fkdAzW2ZovyVqHzBfFpF1EM+0+J4y8XTm7haqW5+aG9vMONKGZmDnCJWFKRPBXktxpCdzgNa8uOCCCzBomBWgfNbeUGmM2QG/CryfGCwbsdXIJyLcemiBtY46K374/gcjNrwAe+QwluUuW7qUnIXmeod4AOwQewkLq7XOgsgMUTKugzO5eNduAsu83nkMzzuUAO3ODe2FXwcTgxgiKwv5LUkI9LHcj3iJM1zvx+IxmIletwXLEjZg+VDA7IUPhs7J8n3lajbvyL7YUrCdRBUXy7gWzBZoQngGAHOkgJgQRObR4Jnzm5pzAFCW6SBDqwArA7dgtPQdd96hZQta62csnsKEHlb/K92rwDAe4XMAawCrVtXEFnkkYSUpGyXgfO9dFRErOMCRM/yF55+ndHpFjW7YEO0OAtXTDIHUgDWbIKIGgmDnPozSUvd3CyGOMXGXjsiOtORKpLqNQaDrv7USHgAuCIWDHj6YlNyUPTyiX8A5gTHQjsOGODLy3dhq2rfLBubS6+8GMEfEviVcBgnNm/uFvPvWW8yhbZ3dBmGDIET0M9TZcBMTBwHgBu3AGgyy1+uDcwlaAFRX6Nqc6Tb4Jj0tVTSnU+UiWSo6FL4YG4MRCQB5tIHF12vdsN9r3c6LFMd8PHuOuAxYXTB/gXyvKZaz53xsNSQ1l6+yZmYnyIfJzRYvHMQVTEQYwJwLtgZ2ieOAg4oeKWYcMAgtZ/u2rfCOUo0lYbnJ/Sx1ATdAfQeXIWdZvXKlAueXAJLJ5Q4Fv/y9BEjM8JEEiJdCxrsc4nNwJ9F3V656oar3MLIhKAnlKo3rH6KzvqnFCoJ7ClWtUgJvwNNCdgOp0/JJnBEMctY4NUsDwtnvjkY/wK1tMtel0UCIKdiyh7PsielPySJNpL7vnnvgg0DtDGSvQe6rl/QyWmRr1Pgzdux44384SMtopH1wjzSy4YaoOIwOZrstnnGcb15TnjIEQsQsJYF2zukCtRKDCN8N2kbTNk3ZFZU0+P28YAmJ+pM5s+X6G29Uu88xsnPHDkOkLD/htNGsIAGRiGt5rT8lGFYswkh+0BA4CmwjEGXs1zhfHH5nQgv90MDWNzlxVFTQU9gAsQGRokRibAdMCDZZ81RhI2akU8ObIokPZKOxwMxsVJabYO9mre+14UDpSVnw1XzppcASxIHgIIQUQqW8eMoUVADGZxRHzuAecrQxrNY5ZjUn2BLI9fx+agkgbAyQiXar0SOBNYQgsBICdmBKR1QZOAHZe6z+frWGLXymhDxg0CAQHp18PXv1lDdnvakD2oafhRwD3UFEizfkFPDMMrt/P1RgtsVjcoFL91J06ud1CDuA4c0Y2GIBhBG0Xaoa0rYmJg6KlQZ1Qi3"
+ + "XBx6XmZmhHUtucVDMJjbHZ+LMFkRi075gw/lIRCFzpChCGiFF1afqIj9Ny1c/8dST0q9/fxAhVdEPdTZGbiYzzt7XEAIGPkqP+J41SoH2IdL0Pdk0wB1AMrUoW4TN+PKsd5XGr4SEVFTsoRgpUfe/mJhUJDp/+MEHVJeLCotYkdnih+HHHktOge1nDXMcN2ECBz8csv0UafmM9CdBA3NRLJGLeL2M/LKLAzAA28vieyBcEzhUi4vs0GcINX3ZpwPJSJs0WmncgfC7oO1c+x0JoTH3IOFQqgPJ288tgTizCd7Pq6+9juzY2Zx64iASa57mb5xit7aQPc7FzLcYxtybLBhtxLnoYHBA4gl+bjgL2s+cWMz2MINyaETDxsgtM5pQQffrjsj0oepPOvPss4lHEJG1bs1aJj8dM2SIfK3FZi5ULof7mZxfy9XYE3xvnXpuNw2L1fRNNcCLjOcx1YQCBkOFDZfD+yi0ERN2JZ69OSQ1oXN/0hl7LajXZLRxh6ptiuBzRjucxA6+8GG4OUE/ZlDwmjsAJsSPU7nQCaLR3W+vxwGMivaBDSMoGBqFMUcz4srGOpgCdb7IIBuog8hMg5scA2o5CtrN+9aGHYulrRNKQtMdhj8sHoRI9A2a+/uBBiCvUONUdnZbaDQofUlV82ItRnvdNVeDaCCS6F538BCJ1go/iB22G30KrGGYrnE5OJgIBA+iJCci0XNSLsE5zSXLfpFNz3Nc4VxSCywesw0mbATWYtCtIQkyFOwSg2bAa8ionfUgBjPLsTPdj6ZnZ/ZHek6pvRD/lG0txSwCjgD2AavFjvuhU23KgikRDVc+MQ7SBXjt2po6Hi1YdfAROj8St3DHK4hHaAesi963Xz95YeYLsnb1aoYvbNOUga1qQ5kw4SRZl78OLabTjVbQ0MHXEksowkBjm7fD1zzHOddqgPjenEvPuK2dthhqdRMTh01W8mzShm3XRrfTo2KBNkDOiJxCdjlAFSyDJmeFouagROkdO7ZZe4e1MtpCKbgOOgthdrAPMH3B4+HssfYRXAseUgTdMGEoJSUTOSHoRKB6YgswHcf7a1+7IzlRIyttJEcThzA4OI0G1AwcrK65PXJVc4gmJ0pQR9/8+fNYx6O7AmXUVweRA1yD69nHde7lqFdOm9jHtg1WjMECaiYaUykwARgCEWpoKFcN8keIpOaQDmkdTgv09cUIoH37rVksGT31v64iQCI6ZwnrWuM0a9Adct1iA58OJss24L3djaEIBEWtBk4q7MhdbRzaBycXzOUAb7AaMjOscbCyHWDnyJ3YgTRJ7sfRPsQoZ939eBty2HokkUC8UFx07NyJwHPHziIliG0yatRxCGWA1ZL1TNfnrwdng0GMKnFkW6xocZEbMHsQ76ythvexIo+aS0kJ8o2hqQFMw67yrds44JpDgLFJPg59BsCEbYmWjV6o9bumP/UUWDjc56bISAJUT3gR6eaOio5G0AuCYyAyIHZswjRYpp31wA7W02oK0O21EWCROSzwkRjDW7TtbGv0MgvtHRoNJoJwft4T2CIyYTvy+mgfnsVWKTIVARytTP8Q54n4Fhk4YCBtIU/PmM4kr4GDBiMYCPXKaOOY/9U8lMgG9oAIcESVOP4ZAOZqk4yuHlv0h8mnCXJyxWg/UCtzexBYBJwFmwdWevgUfYOJ1xyIwxagnaPUHYQ6eOLYE+UN1enbaaNf0VoSXgMIYfuwg15bX0egRY2DVXECxmVtBw3Hg7gTtQ4bIeUMNkUHgB8caUwLBJF6PJZ47HUOfW2PLpPVjkx6DFZEPXUQIwAxk6i3bClg0PKmjRttwBABddgGFwVYmwSlEpCZxmi3s885F1oJcdXWbQUMFejVO49cVBliY+7DawXNcqScCOXlCCVEGwCUQcAwhJEzmOW96PBUbRHnoKDLB+iPZsA5+GC2E6t"
+ + "UPfsMXGDF8uVquLoZtb+UpY5iLktGRhrOc2auMW84qQGHil1nMEkciMgGK2UNURvPYZOpsEGksSZX5T6KKEdNxD2c143EC7gByjqhABtfW3uJXZXh55+Xwq5BD2uOenmrlPgKFGQCZFNzCDlYACpzjmbm7ddBbJvdFtdFuADuxtyWEzX/9tXX35TzNQmqRWoqwbrjj6HJ3VQMYp9ChKHgDHJaAJqRg8PvQAAmM89wME7QRQq8d5mswGZTTdDmW8xU8HnyyOOOk4cffFAunXKJsrxslEOiTLRJwE7tTtoprBrWKEaykcobCiIc39bpMgVd/ah3gdoX+pqZ+YjvwIBwZmI7NGf2kNcgNHhnUS+M1s3Bao+orWFcCjADraGdu+TAlkH1vFv3blKkhIr3+hRGpQ1bHIDEZsh+qrPvvTMLJa84oMccMxw5rgww2qt70GgXITMb6LjDkQQSBqHifHIr7Sq6/sGZ7Zq2Xk8UQhLhSQZRwUL6kpuJYqFmVRjfArYPVOZXaGckY/0QGJMAluaryft8Xd3oLw8+oAHHw0xMQxDqJWaDcx0HvjeORgdBAK+gY+EFNWc6QUawRiIM0aY5ihx0vcMRRqRqihkMWwXEByPEjJ8IeSMs61jJiPOgeU4P2DcGD2AauAjXgDud3GGlBhD97e9PIPga1lSo1LgWdiWKMohEEDI1OarSIS4sSALiznaR2PAbEAW0NkwkiBa0Adckl3rnzbeQCqKifLxfOejrEfaNZiFWsFtcEFKZOPNAtHk9ZiPSAGl/GKkrEuX17s1O1s3EeMRZV7oVJca6ymjyyGsb1hkGtoC/BS5rFGfBykxIsEbEFTgJZi5iMu3aa404x+EJAy8hjoA7UPQF10BJyH79+lN1rmKbQ9ahZzCB41QMUcWEuu1n209Vv88FWhaiY6dOuDaIGbMbrB9gFqmiwFhIKcA9cY5j02GuLCPcJWDAqMvloVuC3zvr/SsR/6Rm+e3gzGjzm+rSr2m2xBEM0iP5d8wkeAxBFHNmz4bVESFtNpHJnsu4A93QSXCbA1DpkfYJpB+auAxih0ikzvPSM9JY0+vO2+9AFDdAGghKvbPfAg/gHBARZ5j19UQasA4VLy7MShArCBqz0SQ4B+lTEQER2Gh4AFFWPibnw0WMhgXxSQ6iZTKRcolrIH4Vz2VCBqPgksd73AtYxrrhrVhhWKDLxYBoTBZjAQXJ0OtLDejbhV/Lj98v0rKTY2TQkKGYjA8HjIptrte81luh6zg2druWePpIVx2YiAX1TjrlFM7EW6ZNY+eccurJGHjjWPIzA31nYRGSolkKySVMzkYHgtUjVgKsF4R"
+ + "h7RWmBmgUc2AfeOB+TUWcAuMX9ztuvVUSlSjeeOtNmXrF5Roo9Hvp27ePEuBuzrZDxWHj11RpAWjBeZBzws9IEMQVBINYrAcTgaF/bieOlO2kCEEFnqQEekrxFdRMqKb6AAgZhP0H6iYMVwZcU2yAo5C4GLVWXcPJYMuGkcgN5yos3Kl4qAChj1jV+ltXOLwG3zfnJTVsWP00rbU5EXIZMQ2wXgLcwd+B800JKKuuMSpsj34HcYTvUI4R+GL9+o2yXdlmxw4ddMCCJvKbKF6wzftynnwx90v54ou58rqWQ/jjn/4kPiXEBx96iJ7LL+fORUAxxA8xiVm89xfxR5iOK+IJbfM2xGlCO7L2Dw6e38/FDDnALss96XuhWo1ZzHviEzjprGvBKRQjUsmlNZjjCk7Bvoih7ycOk4be11CQvzO/YbwJI9YX//A923jsyOOwbo3+zneDKbnQrJbUgJp1uBWn0UEfKuudWF5WBh8Dqf2vjz5KTtKBg13n/MIsUmMNNw1+slrK23XqAk9NSYWhDAMGpxk76jG9FsTGTdNulH59+8rtt9+pa78t5ADcpYsQ/9fUqTTPT1EP6DHqMgcrxsBFYJDDiRnrqIeNgkCwVas2qF8OrYi4wmPM/yg/aQYPz2ZVctb6ytTIrColdNg3ALrxLGY3MS5uWnptKADdCbAOe7y00ew3IQe4PryvdukPcimPG+IECxEi/RKuim81mWoEnq3Rppzz0qbFHHxoZ6dMFBcH/FokBiPQBdZCBMH07NULhd1J7ZFEGTLplOhkzA5cx1g1KYpsfEbkDNXFeqjzX6zAb4pW1znzrMmSl9eLkdvvv/cerJFQnaFGYiYasWR/H7KvbTvs/cCVoNIylyWrVWsEMJEwaNQ269VC3OGtCd2zmAvPzHP3lJYwaMiWcrLfW+Dp5yKEmYgDAQdCf5BoyvaiKhITwExQMnGMCUCidZYc54QTx/E5i4sLEeg0FfdojgsAYkAPRzCwYexUWfq4PvQNYMWoj4GgFzwgQuqcmSrgGrBVgIgI1Kxjjiwei/UYB5OxhvI47ZabsUQHxBXTCwb27SfvffghTPAgQP2sL3w8XJT4HLVS4nfgVrh2owo+kR5R"
+ + "s2xoEICUEV52ZUfr9OKpYt9bEBnidyHghXgmKkFE0kZhjWw83ww40i1M+SjjZ2J0mRG5BM+ojQ5VFfVNCIKrqrhKJgiKsavfKCA9ZeJpryveWYf2NkfiAOv7JTwyTdnhFXv2VCTDowouEMG+bSwFxchuJQysBIlcj7ABt2CvAKfQdgw3MYlCyRo087XcqiAXEd29euXJNQo8URsM6vMnc+bQMtt/wABqK59paag+KnqgRmKgnO0gPwvAITASB48sPrCfA+YQAo4OYfBo/Tb8npFxOqDJao9RB6E3Xb+zhEOuyiPVHuFnONhlz2kUg8bhN9wTVlGIMRi+MAlxHr776IP31c+UHdIKx9fAqnuErUkjwX6RdtR+cJ5Wy/tEO8+sdUZvK3enlmgJjFcAcSjiZmuOgkBsTi1Zua0uyEKzBQWwI2DlImKLs845m2x8546dzC4DGIYV8uWX/qWJVpfg2iAMcA874IfdfVi+cx/LYWPgGnEI3c1g871T3huzH9yJ/REXC2diDjACNCsQsFHD/fgNOWcNlk01K2abJdSpIXH9WOIwxt6iPjy/03dQg7EeLtXlMyafOVVDBCpMkbhmyjmOULVOv/7Up84g9UOcriAVkdomiIVGKrOeKj2McHljJlMLwGYCdDBbzIDyilBLGVB8/OjRkMGMPJ/54ouyWe0dd959F2qOQYVEOSg4ybQjJ8u7mozdpWsOZhwJhKIhJOZoiYP+FPhw4AqHrYarLOnwO0nuBIocaBiprNuAhBkXmwzACNUbCwBAHDDV8rVX/iUZmVlY21aKi4pklKZv9ujVCxPBgE6GBKL6EDglOKkNdjL4mO57bfd+BhSN7tLla73niwf8K813RWpQ/ZGcL5j15yrL3h3rjUpmKoKxcXi9UA3djCpnxbyqChPtRcAYsdryQZVVDOdxweMLVsw2JCv4nHbrzcAvNCzNnPmi9FIwuvinH+XRhx9RL+l2zEqs9oT2kI0bVGmsnLRiA+hRs9mBskuJrC4MEQMitj4Q3p+VE6Pgx6CtAi3kNSsrq8EheU52dqb845kZ8vLL/4p0DBDsDh42lB7mIDUYuhKg0iIwCtczJTyp7pNQgiFyJmhwDdpHpx8BhDYXO4fnSOQjHp+vXh9ugg7aIrBLfXrMV7O+G3BEDLQEyFbjca1z0iOd4iuRG4lp5MhRsKyicC2sovCa8rxTTz1VlmqK5IhRI+W0SZMwAFCFCTBLSstohHJ7wtAsrBOL97NiEkuQQQxCXGGpDJzDIBtj4rZpDSFTt105nQk7DBn3P79jHm0rjV3pltONWfUpOuu/mveleH0+VjR21Nsgdgw8svkMSA1wEgXNOSYbD8FMp6ko3uekkDpbs7NzbN5ccBSaTfBGvd+jqsmwA8WAOZNYDB+EDkwm8moNu3axg8R1iGcVMwqONswymJfB5u3n0DQA5mhIYmyD05HwmPJ9GPdUVdsGMnPAeT9oSl4QBrLWkQfDOmBh6xgzajeO1ixiNREOJKO0gvY1sBM4FdRVtveaq66UbuqQm3Lp5bKrsIgcweb/eA1+qzfttYavALASwwpaPKDFgG8H4Rx5o52jaYljXf4RE6tsJ9oBeksf+2wMBAdEmKEFkAkDEOQt4jIwU5wAXw4YQWxE8S5ez0a34/fWHmJd/hBLtlQkrm38Mj4QFIgAv7EJz9avYrPdEB6AdALeN693X3iDTa6ty2ot1qiFI37HYySRWBXTg5TQsIAo1Rd0q1ZbHMk12nbv2oVzTRwIRYptHwYGNg8QPUQwLLxfaL+Ms1pb8ycOco4tRxX7ETpgq/heQd1QVW1RBwvAzJQsiENBWnSQWUmpxrrkMZg2S65RUBA714gK5pFACEXmsDAlUe+HoGNc2xa5"
+ + "Rcdb9biREzFkV4HE2ikIIwSQZQJ4VRWvdTC34B42R0dl5WvYQCgy4gh077/vXl0i43JkwxH0OqtY2kQmWmKtQw4EA+Jfo/3RKyLY+CiIowkxx9GvCMRBHakGopUa+9B948YNcvLJpzAOsnxvKcAatBE44bhyM2UrOQwHz2oO3JxKOwEUcKV9gZtELuZXD6wBPMICsVwvPyInRpy4kIPtGEGqlhoS0J1VeTZu3ASOxsJsNdRSHIIIRxCJDXUkPnG4CbgeuY+wllcSfD/2O0toIFYQEhrO2FB/HZc536nBS8fYojQRW7MHpL+mwegov/bHEJWxS7SuVs7naqRCQvJxquLBugifBrQLBBQj4wvslYNpyyA4m10WyxIRCcWKnZDJj0HYPhbpBSiFKIkM7Qv/u93ksoQbwky7zAqFsBgfQWNcfCIwgjWHO3vYHIORnwFshpGjg5RItA/R84xUcwApfSh8zfbBN8WIOSlOT88YpKKt8tcSRtOHCR79hpIBlb379h3YOjv7BzV3537+2WcMOB6ttglssHQiRK+TonyAy4PROY72JY1UUFM5UylmTEqlmMFDgFBNTZ0U797NIOSGen8kx7Diyby2ycwO0EQ2P4rAosAbPKkQLdby6XANZ3c+s+mKQarcuiyqhiAOo8OwxBEpTgyozwf8Q/e+0vn29JYthyogLz4CYTRfbWXV6rVHSyA8n1bBYBBYQUVq9HzN8xj63jtvawG4x6Ch0FBFjUE7sVPHjuA27HDDPyLuaUooiJP1RRuGyf+wy5EzWhxGNX9Qau2acmGHgACQcbTeV5rEjRGKebIG+KLYCzgVzicR8DwHiNrXDlfA53C+cVE/ihS/NXLZQaekpDcaebEQe/nqNBymXGTfEQijeWOO3NweGgC7HQMJreDoiESA4OvrVE4PU+/i7P79+5/y8ezZCCdkLS8Mb5W6wLeqzIeXVc+zKUqWyqyKaddbMSopsYmtC2IHmANCjQY5JxhIEgGJC3kfAMoMMWR6AAaPE4dma2tbMeLLY0RTBBAl8DTvDQgNcGBBnDwfeAW11/E5wxz9JuwvaFRjGM+ifVELVZWfoH1Zg+v+qgxEtwfqfJOLFSbunHTyydKnt7rjt+9E1tXREgk6HLPy1F59+jy2ds3aGz768AMZPHiI5KmzLC01TWoNF4F7m7PciT42EVJhqKJWtUWdDBAJzfEuAz4DJq+EflFnoT9cB2mWqOpjlj4Xa8fA0XAjJioDv0B8GZc9fx9BDJGYg4NufUGIarNLqUILYhSZxT3+ADMA9XsW839en3GqwXJH3Y+Mfjf2lO8XfSdnnH5K08Zz/OEP18mJY0bLQw89jLcgEgLAozHvukykd8eOnW7UtIDzO3Xu0vDG66+ry/0tOp7i9IHpUbULAxoZjj3Ao10WPAgPLhfpe0jDB19Rs/WH6sHEIj7fqf9l06aNEgqEGJtJddGkBmCZDd2AJ2DSRltMARgWu6XBrrqqEoCSM99HbGBEBtuiu5MIDk7GvNkAYzC45poxfcfpjM6ANZVE53ZyfgF0r9ZnnPorF1W2izMzs/8V9eU8/NADzSLjjQnCt956i4wcMVweePAhNrJ791wQydE8KGYWor3f0JUQc8efdNKCDevzOaMLi7gEFrmADU5mrgsTisG+QSQ8YqBMtb80qserVqyE7wa+F2gYKKKL1AHMeLQPrBw4AMV2dd9Ldu+liHJzqaxtBQXIUQEIhXiBtRSEYtaWqWdbuOP+ZoFko3IDW5j1VDwkqHXr1iAOAyIO2grWjgGHW6bt6K199g9TWuHXEAa5qsbtyozpT6iTcVaTayuNN6qft992q0ZivStPPDkdhcwQ6o9yzpiRkO1HAqoYBHg4t+iaLcdrBZ8/6UA/qg/vAeHoaxAe2DuKrrHDbQ1QW36geHcxk5IGDRkML60ehxC/JCXxPKrKuwoLdZAWqu0jhwvdlJeHGSy8efMmzG7jQg+A5dOLnJTcAhZTXJ/H4qJC5viK0Lpq4Q9D/dw2osyUlQCR4f3qVStgL+ESXmVIaiorhaHvASXc263Wgu1XEgYTtJ984u/y0YfvN2FqwpE3OsKGHzNUxc3xco+60DGoffvkQTQcqRPsEuWY5Tj3b9qxXUXkHchRriTN8Lg9IAawbMw+mwBtZy09qYU7dsL"
+ + "aCO6B+6NGKgYbiUTwbSCuFQnN2tbFIDg6/NIzMoUD7fEwsLh16zaot4U2wVtLbYMlpLxelHsAeAXBGM2Hwc+4l119Cbm9WCQA68LCFK+E2FXy9L56+mdaH7VvZlar2/Gshrv+WlHCdj75979awmjWxGE3lpy+T83FEDePPvY4BhCLAh+NgQ0dCfv8WSrDJyoWWBWvgwtCgdiARxaDoIY0AmH6XkzSNQZjhxLIli2b2Y6uKuaW/vyzemt/pkm6j4YVdlar6f333qsDSMyBmAoQCSyztrA+wWoDzewhU6pbaEbHFjY13OvrbeGXWuvTgejS+y2RD959m4lHgwYPRQ7tZhWKF7VMz5igomQFCO7XbRZ8xmLRY1UKnpLZH33YBEaw375RrEy76UaNbXhaZuhSXOPHjVVZXy+F6njap3L+yHYSF/bZOnNna4zoZUoE1+ug9BQJIzgHrB+cBoMOfEE80qdff3AVJjGvWL5M5s+bx+SpEerm//Tjj+U1LYGQv3YtiBWaDrkS/RrWJxO5cLLYpC1nOVP1kMLmQY2jpqEGnAW4hiD0888+YRBSHy1sx/LWLbM2q3f274ozZoTU/El7iIlc/w0cA1xRMcaTKsbfaWIL6W/fWEJ6wvhxcsIJJ2pS8TCZoonWvXv3xszGqtQOIRwej9gKvjOVo8zUmXw27DwKRE9QTgH5jVnO6yDqHQ49JHE3mDwSlGU89/wLUXlH5f9qiVdC6d9/gOR06waVFxZbaisSkWYQNioqbCLUjkzcBwralwT84BRWHQbotFoXlhWnyT0xIeF7JdwXtF2aYF79m4jBPCMnQpSPNc0UY/xN3n+XhPHfnzjsNm/eXO7/1Gq+V145VSZNmgzgSpBZWFhEuX64zeB4Y52UWarCztIz+/tDwQtFZLKCyXZg+QDGuAbUWoQG9tUZzDKNlRUoooIkKt3bQ2OAK58gmDVETEpAlDr9avRzhBuCg9hqO04EuYscgnmsDO8jOGWsSGx87O68Vr3fVy/zq0pQ39UECGx/DWFYhx09wmjBou++VbV7N7nl2rVrZO4XnzdT38pv31ha4M9/vpMLBp951lkyWZf/6q1YYOOG9f+RSscOD4eXaicuVWvmDYoNxikRnKJY5EQdqK4uDnYYRIdOtiZzAEUYnqiK2vXzCxSbILc1J6cr7Q/RMbEQUeQEju2B8aPC+BOkTogHEdRSEwgWqJo7Vy8/R1XauVWVFXXM83VqJHJw/9PNhhGQKFi7dLF88vFshDw2geOtaTfW83rm6Rla5P45mT7jGbnooou4Dsp/GEBrPbZhjfn4TPHAZ5p1jk97qiVzlIgMUO1lgIqEPi2UELhUBa2aBJbQLqB2wo5Cz23RzkIWcWmvNdqHDDsGEVwgCGMCJyiF1rVa7SNLQ37/Mk30XhAKBZYzz8bJgfm1G4AtxAeIlkQxZ85HzKZvis0rzWcj0Ltq6hUq/8vkmmt/h5qeEAUYmKNx6lnD0xrlFmt0tGCCRzxnO8UjXTWZuZ36YdpjV1DbUm0RiRoSENd/wEDfoMFDXMo9wggDUU2gRoFqldopSsUlW5Xwtiv3QMXEDSp6CpyVoN2KR/zy2zdqZ0gVJZB+4m9/lZ9++uF/tXO1R4rjQJS7uv+jjeB0EYw2gvFGgDcCmwiACDARABFgIjBEAESwngjWGZw3gjtN1Zvqri6NDq0/4Lb0"
+ + "qrqYoa3utvTcaiQBKR9pVzYi4veHjCoikiMikiMikiMikiMikiMi4o8b1g3ODsXVSmHFWNkI3cFKaSW3ksn30d5l88ukL0RoK9+sfPqPldjOmeOrlcZKAjlZKaCrraytGOgaIgBeqU0pbLbUxvroExErK8pKPui0gkFc4vUNjdBfrOygM5LBIM/WYfMVtmaw3QMiBCmmw5KDCFJ6HG5xjbGSsIyhoHMhA3F6RASIUWI8UitqjIL0wJxrB3mO0M9ZattBJwDioE1/iED/71jfpmNsvNUQA4IUQr/G+yn0xlNLzBm731A5GN6+t4evF0c8S39RjHYCmMoaqXfYP2HaBBCnB4ipZgMz91x7hR/XQ+LvEzcSEXtOfR0IVKxeEchxROH7xI0KeitEHgENvXbZhiycN056SYYN8yntGit/Q793kNCImKnad8eS0vVki7WR962YrUpcXyC2M8Ud1CcSe+6f3bf+ibEPXuc4gr36g3S1E4WqC3PYaYSiFDWMxIXZPDmIMwM5GmfGo4zSOvQXHrP4BLXhJOBPubDVIHs+yQzI4n0V1xf4CJ+AICqoT9yFaOmINR265pC1ReZMxYTMcwO7SX/YwG856RGCZCbg4XkN8kKxayurjoVozeNmpMyGJofMDukHU0PjKVxT6C89VuYJ5vkh0dyW0mUGDC/2Oxei7kxvIIOSQ6bpuSPANQbfdbOrHrPGAgOCBbXeYaC4eMiRQFJIKOQUrIIHkeLQIMhZyDuysfZWdpzp4u/yXY9gFV/3gL4rNhAUdt0hbCkQr6Ws5CXHFG06I9gODfwRsa65sPjTUc6QIpCNKIKQNSyo4NTQbyntdQdbsf2GTwCf4a8rpuho2gvyZ6WCE+vOK6JfPdP1CvEZK/WgmUMWpu6sQNkDgaXQd4Vc51AgSGcg5i+QbeB0tezw5FOb8Hosp/FwQy5QDkkOOfgJsshB6Ev2sfeM/5tJv9iiMw2mgXuiZlOeCa8ZMIihkItc/oI3HYkcVJiCAFtPdtEIsH9QQZpD7gmFAahDBxiK9U8WoqcbiNtQfIOTgxjp2UNZy4WmG+fv3FP8vWEqSDhjT23uaZdB4dUHxJkIYmwcxNDM7jOfQkCkim011AF9kgQU5ZqNzwr+On9vxf+NM1oa/uyZnyuQSKZM/z4Cbef791YI54C9FWQbv94Tpw8nZFH/3grd4xV90wb0CZu6/AemPNde7dgXncnxSyIi/CRYRMT9yRERyRERyaEmj4AIdY+fYFh4HP9pRctKuYPdpueV1PSDar0YabA21D+Dnhvdw8eFLalvx8ocBUT+f+i4wjnFDRWQ50m/OFp54jGPmO1a9M/QKEEKTsqXsaaV47AdSBioM384OvPXBU6yjUWO5sal3AqixNRR0C6uFwYKjesX4lxkymyZQB8y1pb5ydH+LFYiDdnFsjNdmzNbBV4VdBAnUofNBPeZsDhSbxxkawPRMqtLn/ChRi5IERixNWdBNni9giAuZIJADXt/iZSZIFUWWJavgnxQ2z3FS36QTWasvWLEXLKNvSOub9ku6jNeK7EyaxyknDKbcysp2hrotsyfproFbbD9zvpjCWnF6vELI9ac98+ovwkmjv69MnZmLMAnzxL7Ae2NmApOaHNhg1OQzyAfV9Y2536ga0QtkooNrU9sGtxhII+wtXQQ7otj/yUT0+aOHdRp2f3WIFkKf/K+lbTFySGJAtIriB6PHH7owHMRtc8WOvPYxQdQol3j9edv/x0ZDHaIBAE2W0+a/8EGtHZMUzr0zAfkYRbBavGUqo62Mm6ro49VqD/HcYQ9y5g1CKJFG2lzKvTXiRvP8FE7vtaoyB/Z8hDjCQ9QMxg54GgKydmhVoMbMExv8GSt2Jwpn64F2syFLmF2EkrBKNxYQXiDjxR2XlihVnE/0Gn2xaGCpfqK+ePYoc2FEWbLri9E/+SINaFT86gxCBn0C9irZRwQmpLIlwLhE+HzDYb505xU996VVQiugXRFQh03iA8J45zyqJNL+T6Rxn/yS1xzRg3RMGLIOJRjPcPAjkI7AdGW+qnF2A9AjogFHYXsBWdklsv/d8s+QqEYbSF9wLBMpB/9Z58i/Cu6fw1gd+ZQ/PI/bx0Rz3NERHJERHJERPwLZ401JHjcCs0AAAAASUVORK5CYII=)}"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testCssEmbed() throws Exception {
runToolChain("cssembed", new ToolChainCallback() {
public void test(File directory) throws Exception {
String css = FileUtils.readFileToString(new File(directory, "css/style-base64.css"));
assertThat(css, is(".background {\n background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAA"
+ "ABaElEQVR42u3aQRKCMAwAQB7n/7+EVx1HbZsEStlcldAsUJrq9hDNsSGABQsWLFiwEMCCBQsWLFgIYMGCBQsWLASwYMGCBQsWAliwYMGCBQtB"
+ "CGt/j1UrHygTFixYsGDBgnUE1v4lKnK2Zw5h7f0RLGmMLDjCSJlVWOnuYyP8zDwdVkpVKTlnx4o8Dr1YLV8uwUqZ4IP3S1ba1wPnfRsWvZUqVj"
+ "MnYw1ffFiZBy6OlTvu1bBKZ7rc1f90WJGILx3ujpXSD94Iq/0ssLpPtOYEX7RR03WTro8V2TW7NVbvImOuOWtyr6u2O6fsr8O6LNY8T+JxWEd6"
+ "/SisGqvlFFvpZsvAenrg0+HBl2DFO97g5S1qthP24NsTVbQ+uQlTurT/WLnNxIS/rQ2UuUVyJXbX6Y16YpvZgXVK41Z3/SLhD7iwYMGCBUvAgg"
+ "ULFixYAhYsWLBgwRKwYMGCBQuWgAULFixYsAQsWDXxBFVy4xyOC7MdAAAAAElFTkSuQmCC);\n}\n"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testOutputOnly() throws Exception {
runToolChain("out-only", new ToolChainCallback() {
public void test(File directory) throws Exception {
assertThat(directory.list().length, is(2));
assertThat(new File(directory, "basic-min.js").exists(), is(true));
assertThat(new File(directory, "style.css").exists(), is(true));
}
});
}
/**
* @throws Exception
*/
@Test
@Ignore
public void testClosureError() throws Exception {
runToolChain("closure-error", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})();"));
}
});
}
/**
* @throws Exception
*/
@Test
public void testUnicodeEscape() throws Exception {
runToolChain("unicode-escape", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
System.out.println(basicMin);
System.out
.println("var stringEscapes={\"\\\\\":\"\\\\\",\"'\":\"'\",\"\\n\":\"n\",\"\\r\":\"r\",\"\t\":\"t\",\"\\u2028\":\"u2028\",\"\\u2029\":\"u2029\"}");
assertThat(basicMin,
is("var stringEscapes={\"\\\\\":\"\\\\\",\"'\":\"'\",\"\\n\":\"n\",\"\\r\":\"r\",\"\t\":\"t\",\"\\u2028\":\"u2028\",\"\\u2029\":\"u2029\"}"));
}
});
}
}
| true | true | public void testAny() throws Exception {
runToolChain("any", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})()"));
String css = FileUtils.readFileToString(new File(directory, "style.css"));
assertThat(css, is("#header{color:#4d926f}h2{color:#4d926f;background-image:url(data:image/gif;base64,R0lGODlhZABkAP"
+ "AAAERERP///ywAAAAAZABkAEAI/wABCBxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIMYBHjxxDPvwI0iHJkyhLJkx5EiLLlAZfs"
+ "lxJ0uTHkTULtrS402XOhT1FHkSJMKhPmUVlvhyqFKbCpkKjSp1KtarVq1izat3KtavXr2DDihVrdGzEsgzRJv3J9GZbt0DXqsQJ92l"
+ "TqHKXAmVrs65dvlTRqjVLuLDhw4gTK17MuLHjx5AjS55M" + "ubLlwY8x57UsUDPBu4A7g/arc7Rf0wFokt6cNrTnvathz1WN"
+ "WjDRia9Lx9Y9O6RS2qnPhn4bHKvt3X9751Wuu23r4bmXIwcAWjbevrc5a9/Ovbv37+DDi7wfT768+fPo06tfz769+/fw48ufT19r9MT3RU9vnJ/6c"
+ "Mj99feZUxIhZR1d1UmnV3IJDoRaTKYR1xuBEKrF14OsNeTZccwhWJyH2H3IYIUd"
+ "hljgfwPu5yBg2eGGYoYM1qbcbyAKp6KMLZJoIIwmPldiRxSm+CNxGgpYUY76Daljj8a59iKRIYr41FA18iZlkTRauRqS/jk5"
+ "2F0+Bilkg1peF6ORNgY4U31stunmm3DGKeecdNZp55145plVQAA7)}"));
}
});
}
| public void testAny() throws Exception {
runToolChain("any", new ToolChainCallback() {
public void test(File directory) throws Exception {
String basicMin = FileUtils.readFileToString(new File(directory, "basic-min.js"));
assertThat(basicMin, is("(function(){alert(\"Test1\")})()(function(){alert(\"Test 2\")})()"));
String css = FileUtils.readFileToString(new File(directory, "style.css"));
assertThat(
css,
is("#header{color:#4d926f}h2{color:#4d926f;background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIcAAACbCAYAAABI84jqAAAABmJLR0QA9gD2APbboEbJAABMi0lEQVR4XuzSQQ0AIRAEsOFy/lVusLEY4AXh12ro6O7swJd3kAM5kAPkQA7kQA7kQA7kQA7kQA74c6lq5tRi7zvgq6qyftctuamFNBIgdAIECL2KgCJSLChib1jxU8cpFuxjG2uZGRV0bDhjF7tgRQRRsYD0EmpoCYEkhBTSbnvr/2fvdy6BkUHf7yXfe98Jh3PLuefss/faa/1X3W63S6qqqkUkLPEJCeL3+/VlWN+JRPuiZcOGDb1btsxY2apVaynYurX1hk0bS/bv3+/3eDwiLvm3W8AfkES9Xqf27cXr9cq+ffukaFeRdOjQUdq2bSuhUEhvE+Z3e0pKZM+ePeJv8KM9/Ky0rFRiY+OkRYsWUl9XJy6X6DUqpb6hXlJSUiUQ8EswEOD76OhYvV5Yf98gdfW1EhsTK4FgkPcI6rG+vl5at24jycktZMfObSmVFVXdo6N943y+6JzExKTf68XLwuGQuF3oiypx67P5fD79LdrIdgo2HHG9Th07aruSpUHvd6Rt8KABv5E4mtnm0k5yu90DS0tLn9KOHVpbW/dpbW3Nxurq6mtqamoWtczIGKvEUY+OO8xmOtMlCfHxzvv/S1soDIII6MD5eV8Ji1sHNFRXV4vn6llf3/BtZmZmi2QlOr+/QfT9ieFQeLK45JvmyzmafsPMIeeI8nrTAg3+xXvL90pWq1ainGPC/urqCRs3bQTljBw0YICeElUfCAQORxpKWB4BZ9mxY7vo75QDxB6JGDHLOcM9HrwOclZGR8ccibDwPX+LtjToYEtI8nzRMeMSEpOHR0V5u3k83qSqqso1SgjjROTq2Ji4FlXVVQLeGBcXj0mQEQyHFuplrhOXTP8f4jj8xk5OTUnN3rx50ydgq927dxdfVBRZacG2bbKzqEgmT5p0eatWWdVyhK20pFSqKyvFo7+PGEgSTXR0tGXJQvZNInOdk5mZNV4HNEMHLBgW1xYRuU9FzF6Ii0ZEYsUF2gziOiYmNma0iqAJMTExx6i4IIGGw0GKm4SEhDa7dxfPqKgovyUmNj7eH/BfXFZW5ob48Xo8OAfXf0pvMVSPT+i+WUT2/g9xcOPsk1atW18578sv//rj998nXH3ttbJ/f41U6QBXqhxesWqVtG/XrrRXbu5MnAsOc7hZrIMj5eXlsnr1anAgciOzEUvU1tRIYWGRpKamiO8AkbhcbvcLnTt1uiw2Lg6DDoKkrK+o2PdhwO9fAEKyBKUiThITA22ioqJGKEeaEB8XPyo5Obl9AzgeCFnb1lDfgPbhqSR8gHiAU65RwsxWLLJNzwu1yspyJyUlSZ2em+zzyu7de4CzLtD2XxAIBir1Ge8Rkb8enlv9/0EcBG4JiYkXaeffmL9uXe+vvvxSrpw6Var375evFy5Udh2UmtoasF8ZO+aEyS63SwFiPTu80UbCqK2tlbVr1pIovBxkpycxo6uqq7GTeAq2blFckpDZf8CAyxQHAFASBDaEhWB027Zt/RXj/JSYmOBTkJibmpo6Mis6eowSw3FKQF4QFwCkzxdFEFmjxCwuAWGBIxFTBJR7YEO7U1JTJ4JoQBQ7tu+Q+V99KUF/UFoooZ44foJyIr8+W60Sd1lSIBB6XJ+5pT7/LSBI/D5sQLTLRVH4/zZxUIykpkzNX5f/7P6a/fLdt9/KyaecIq2z28pL//qn7KuskC6dOn8anxD/1XEjR6zOysxcaIngcJvfH5Dly5ZzhsfFxTUWBXgPIiMXqNRrF+8qlvz8tcVLly7defkVV2Tn5uZKnRJXIECClZycro8rYd6mHMjnjfIl4pperwdcAdoQjhRTlaptJSclgiBIHN4or9TVKYeJSVBtpgG4h2ImqNeN8kbJvvJyJeDVMm/uXOnRs5dqZOv1s33i8Xp198jE0ybJtq0FUlNXe3PL9"
+ "PTF7fu2fbfBaFJ1nBhuIxabP3Gww45uc1kRcPH27duffeftWcpWd8vYceNkxMgR8tPiJZKRniEjhh8LlTJ1y9aCx3bs2CG7oW6iUyJmjSJ9nZEpsnTJElm2bJlMOn0SZDzEw78jSHKXtLR0Ofvsc2TXrqIuChBLMzLSs6l66h4d45P4+AQMpL4PpuF2IATs9XUBCRlV20V124drgtOR6ECPVZVVVHFjVMVNTErAeVTXPR43wXHBls2ycuUKuera38nM556TKZdeJp/M+UiUSAHAySFGjzlR6nftAnC9ze1yvwuigPh16Z8vxmsIv/kTh5X/R0L1mFlA9WDFsGGM8yQl/gsd2r5DB2nTpo2cOnGilJaWSVZmlvTonssOXvzzkiGK+KfvLd/3u7pG4gTXTEhMkLK9e+Xuu++WEceOUM2mJcRB43uTIFQVBuF4tB25MTGxJ6i4mJCbO3ocbBkVFZUUX4oh1G6zQzlLpeT17kNR5HKFqZruLi4G54HIIogNud0gDBA5+wDtowYVdoGT6Hu/VKhtJDk5EeAVIosaTW6PnnLvXX+WzKwsufm22+WOW26WabfdJqrliIJVJagknh8fHydlZXv7l5SUnt2pY4dZwCd79Vm7d8uxE6z5E8eWLVv+A2OXm7MrXllzeno6OunW8AEQKps3beKgxsfHYwAhEihjN23eJMXgKGPGbOjbO49gMHLAQVgguKeefFISzG/xvlevXmqwquA9raEtKyurQ0Vl5YsKSrtBe8C9IBLAYdDhGFy0LTOzJdXM3592GkVcz7ze8sZrr8qEk05SzjZen0FFSIsUHfR9IDheOxSiFoQdoJRsHyQcF+fRNtUAUINjAOvwPunKFadcdpn85S/3yaQzzpSLplwizz49Q8674CJ5V7lo334DaCsJBUO8nrb5LX3WfAW9KwGyyTn/u3COMrUmHmnTmSpr1qyhdXL48OH91CI5WB8a1kcMkJGhYXYsPgd3yV+/QTWDxFC3nC6vuj1uAj9sxrLJff78+bJ02VLpoFbDZcuXybPPPSt33XUXziEgFHHx+olJieGOnTqO3qccImy0Hb2nAXgugsStW7fKou++kxYpKdJvwABaVRMT4jF7ZdZbs+RSHdCVK1fJnTrTz1SRlNuzJ89xu6GVCEQSBpOEWaGYJk45Sk1tHcVcbCw5DttTUrJHzjv/Qvnph+9l8mmnyoo1+ZwgL/9zppw++SwpV2JNSk7CBMH1yI2Wr1z1jeKcTBV/dRBl4FJouza+WRMHB/TIG4EkuMJIZcUf6R6Ljk3Qzv/TDdeDfWMQMNthiIKpXG0b2+X4kSNeUALZqx2E78z9aOIGxyLBpehgqkmdomnmSzOlW7ducuqpp6iIKsFvaLWsravZplxlnYqDXFzLEJntfALGtLRUufDc82TEqJHy5Izp/CzK61EssEx+/PFHjsMmNcStW7dW2qpZnr+jFqH3cOu13B6Kpv011aIiiyqtmsn1GeP42mNsGiBMtPfe+x/S+50tY44bSdyR3jJDRh43Sqqr9uv31cAX4GLEKslKvfosr6qa7iovryhLSWkxFUSPZ2jWxJGXl/dLYEPCRqy0yc6+Xgf6cdghrEbh8xH8QXZzNsTGRgu+X7N2nbLftMCQwYOmRVoyLdcoUX/I4sWLMePZ6Xag1S4ts2bNkpNOOllaK7HAVsLfUQ2UNdqOXNxLjyQGQecr8NyrhNleB/yGaTfJs888AxFFjNAyI121miLiIGyzP/xQr5st7dq1U3V0O68t+GeAeXVJtaSlptGPUlOzn8NbW0e8oZwA4iYkXvGoKCuT9IwM+ccLM+Weu+6U4uJdcvU118rOwp2qMT"
+ "UYIxrOFamtD0CLAlFNBidTiyve/zMuPm4ROa64mi9xpCmG+KXNcwC4ZaWlpT2ug2hYsZsDiw0iBLMwFMIAe+gI27W7WFR9/Yuy0ApgAjPTIbt5/jfffIOBIXHZ2UNDmqL9lStXyvOqBdykAw1gZ6+fkJS4HdwLr5U9y/r8fCWwJdK1a470HzgQoFQxwBls29YtW6WbWmj37CmRjRs2yO/+8EeZN2++nK7fz/38C3n91VfknPPOU4NaIf3arhDtGwCR4CZGbPmNqHRh9uP5KFpC5HxRUqLaV0JCojw5/RngMVyLv3N7MAlcbGdNbS0dkPGqkUX5fLzWNuWo9Q3+99WtkAmCBOE1V+KgTv9vNoPuVSoHg7OAG4ADMIggDIAuDDzEEs6LiYmmjWFLwTaIiprBAwc+iNmWqmIDm5Wv36o9pKKiQmC4wrGRZkLx8sabb1CcnDbxNIBMakFlpaWLFPNcr0YsWbZ0GTSSpd1zu5++bu06j3qEZ6s46lVevk+xxaUgCoqDmS++IO0Vzxw/+nhZpXjjhBOOB2ejTeasc85VwvdA3dVnJHFKog72vgoQv4eDWt9QxwHl7gYFm9cuWmyVgOqlpLQO6i98OuyDYIjeV/QbgDrVdU4iJaBqJfQwJ0KgpRLh00rkcEaSe7iaIXEcXu4RLFEMdN5XUT5XuUdHUD4eGrMXM8kYkfg+KsoH7YM4Qu0ayjVGPq3vG7YUFJjOdOs56l7fvZsiBQOMwThMWyiusD3//POy8OuFMmHCBOnSpQsA7Weqjm5TAkxUwnhducx1cO5ltMzI27x5856MjAw422DKJkfauHETRdWNN02D2R1iSkHrdjnu+OMFBjO0BW3DIIaUdbjCHHiow9RMoCJ7Q1F07/MZ0D4DSvH8Xi/ESzm+B2BGyAAnWpQv2k4GaHCcAHvUVxQbE4M+MtglpKr1nqu1nc/o866CeGmGxEGx8W+5hlL1GzrwHePiYvFAeDh0FGdHNC2dYLcBsFA+tKqb6LiQDuSMd9/7QNauyxe1kGLUeU5aaqrigBQlMocgje1jsBJeDz2nUAlkLgiuo8748opymaXqYfv27TSWo8P+jh06ddDvRoUklLzo+0UvaZsmKSdIBhEMGzZMcIQowobjRFVpU9PSqLraNoADwjYDVRZWT3AoaBYuPksQzwi3ADgTtA4+H+jYFQ6jr+C70e+qVMXV7xOTlIsmCNiKvx7EUaz3rYP5nsc9SqgqPnBfi5/Qr/geWo+2q+K1rjldegPg6nM3P+JwH0ocGGh07kna+YMAOEXCluIx+OzoyopKslFqOzTqwJyeKt1yuta7RB5MSkxIVvP6fTorvg8bIgD6x/2MxgEucaYebtZzBioewXvMvjOVK72r54PNY/bBtJ67Y2fh6PJ9FSMqKyqG6qxuD1CphEGCOOeccwAi8R73IWFkZ2fzO+U2EBVoshURAKy0Q6g3Fp5VEoN+DC5C7ojJQK2kej80MthocC3gH3AC/q5ddrYeY8k9Kiqr6ChEX4GocA3gEvXegrOCiEBQvAYHLcpD0bxp8+Y8Fa9n9uzR/R3YU/5PC5ffXLxFLXiHIxh04Ba1bnakL0TC1qRNDPDcs8/J5598Ki/88yUjexsMUblBLGChHJC5875Cp3RSA1UBzNawPOopwCbonPs1Uuy2BQsWgCjwHgMH0"
+ "fS2Ypkb9Lr9dR+jnx+rtoa+1mM7ePBgufjii0kM2EBwuKfaXvB7236+LikthS0GA0xA6HZ5ADjxLATW/kCAGlIDsVQYWhE4CV5DC4JX2RjKQhhoiCttZyIHe7+KKqrvnCwEoHx+en/VAYcNBAMRCiswcAy4GMQZiBMbCE2frbBfn97ZGjh0iKgdOXJ4c3K8sWMx8yZqB3bUAUCHQHUDyASaJ6vcvHGj9OnXFzOM7DkSqniI1mkQI+LPyel8Wp+8vL9rKIT8sGgRwCK1jYKCgqs///xzAlNj8cTMxPXG6z3PVIJx6efoPDvjMFBqA5kIi6m1ohqzN/EPiViE3AExIRgsiCMcwdbhOcW5/F2yigzMVt0M9tBjlNdek8YsjWDjAMfqc2cquAQRB8OKF/QZQkGKIBJTMBACkYBA6LhLjEqiGuyjk7ASfUEwukiB8EAlblwHogRYpay0rM3a/PxzO3bs8CaIqll7ZV0uqnIP4wHi4mPl9Vdel7ETxpKqF323SGfvXvo/Hn7sUXANcAF0PkCp0dlD+ByDTHCY271bHMDi+vXr5euvv6Y9QiQd5+Qpwa3SQU1Bp1pDmYqLRBPUg3NAaNgNGI6FlmRVXxtLSqLRgwGLHmhRZP2tW7dSlbMUmMKqpFQz41QcVOhgKWfUAaQ3lgRRva9Sj3Sxc1IkJ7UkPihXLgPOA5UV6inAdVDbyngPuvR1D7rg+kf7dGcsCBx2vG+Wuhneev01mT79SZky5VK55PIrYFWFaMN9MBkfVBfCm3ExxHbNyULqakwYI/TYvaWKj5kvvCgvv/SSeiI3KQglpqA8P33SJAwyRJLxH3gAwMg6QVRgucuWrxAQxaBBg975+OOP5SW9TufOnfVczs60fv36TVAx4f7uu++gvho57bUufRvgGxmgCwLi/R3N2BWpXFlCAmHR8aesGrMTbQNugSGLszhsfl9dVQ1igLoJMEqXe0pqC9pjfFHRIBiAbLQFBMfA4NhQjARAoEZzwcFlj2HiFtpOMMRRviiIKPbrrqIiGhy3qfV4zapVqmVBld9HrllcvKfD2rX547KyMj+vranFtZsd58DgQA7ehodB8MumDRvV79EJcpTsvXOXLmSnkyafAZmN8yHzadhZsy4fXlZ/Rnq6YsbKtKJduwMt01Pve+zRhzd89NHsFj179myj6udQETlBOc+pykUSYDgCARkfCY7/zktsgSYtjA5B2O/se8aQsq3hqrC69HdhoPU9xZZys3oQAAgCBEQrqzrEoIEYfw9VV8Z4V"
+ "FRUW+0CBAtCMbEfyeKvrhLek/8ZqnCxIeZoAHhUNNvcoHunLp3ZljZt26nNZYVMnHQG4lKMO4Gm+9uVUD5HXAgeprkRBy2hehivR4KmW++4nbIZ2zMznpaP1Px8rloW0XSwTjwsDFQ/L10uhUVF5du3FbymlsNuyoLHaGeHtmzeNEwHaL3OmGwd+DgFoBh8YAsSglpdbSiAHGmzxAOCMu/NZxZngGuI5X5w+oEAwH1AJAj1AwHoe7+E3QCQQYhC7Dy/lk7E/byWm2IlCmzfRqTr9eJVrNTALQ+Vluo828E/52htJ3WBOjwnLNDEbCedfKrcf+/d8tOPP8hxo08AULYaIIKVAdxHAOelp6UV4Ltmk9TkzLrQRY6892DQiMhhxeuhXswTx46V0SeMRuQTZhsfLF+5yz5F3Vs2bYhZvXL5hVVVFSfW7K9yNdTX+pRTjFcvblcFnXEYJFwHGyyHAJVWrf0PN7YLgUM2uNghEnaFxT4gWn5uzP14zd8yHUJo9cUA4z0tpNbeExMdAzxh8Qv+gUiQy8IBdBn7CYAmmUQEl7BHI+0ogperx3mdOhc1+Jnc97Irr0KIIYEpxSiBNu9BblZUtOsKAfc0GKwZWUgZ23BBkCjch9dKIHx6HdRaGXXcKOPiL6dW4I2OJlFofgpBakN9XWyvvN6xwCA2UryS8pocxvpRsP9a0AX5jA6EWgmug3aZazI1QbFOA2YkOhfiz6rXVL/x1sRwUhRYe04sLJougaNQsdVWGMyoftY3BNAPwFU0eNHUHgzRqOVwKyHAxeZclq947KkY43l1BGa2aqUYrYMgCPqBRx6R115+Gc/A+9SRuOmphsp7rmKl26363PSA1GHPHdS72AfyGS54NA6DC3QeEx1tbQdmxriB6Gl32K8DtL+amV6WE1gCwHuwbHz2mx4WBIvrYHbl5+cjpBDEquKi2IoTbDZ4l3YWECnAMVRRuOL9/iCIARZNaClQbanRaGA0bQ8L1RkYVNB6zvnnkcuIy6Nq924OYmpaKkArsIfVxCLxjtMvYXsU2kjyNNhouEa43XLj9Sqi/8w4E82Sg+Zj0yKwW4Mg2tmppKRsYIvkpCXqnGt64nBM5bWTcEQj0WDo4RgQBZiQuRxgh5W7QQDQShhxTU3FdQi1WzzB3brmj7DZnBKIILBitAX4gSAzO7uNKLDFdTm40dFRBJGRqq+bXmRco8FqNoheAxEDZAN/IDgZmEqNec9Kjx495IILL5QX1BOc06279O7dm0HDbpcXbYDpnqmZtXXUeAAucQ/YNiyH4D9nJ7XQ7lFUVChnK0ZDjMhNf/q95CIgOX+ddMnppip7exV55eIxFlr0N/xOGampQ1QrWgInZ3MQK1ZtHKuBu2YQGS8JNs6BiPKqWbu+Hp8bwEacQtETxG8DQaiJjTPQcG3LcX6JMMERwIVARCAEyGsQAXGJ4haoujDCYSdHKNhSQDtC69atjRhB+/0cPBGKLs7OVL0WZrnm09C0vXbtWvnD734n99x3n/zx+j/JU088IV27ddO9q0w8/XRoJFBvCS0pXmN8ZqLUApvwnjR2+fFdNO/DwJ4wQ3sc+uAf+4GxHpdcdoUa4zrJ0zOeVG4VJ2efe54Fo3TYVanWkhAfpziulfiDwdEazjgD/d8cxAoGJVbZ8yi8hlwF28XDAZmTWEQcvwoJioOKmYo3kYYqa4uI5BgYULBkAwrDkaozItfJrUaMGCFdVN3r1KkzrKYkhEYbLa5Kj1ABqXImJSVTFdXNhA7g2gSfdGz9c+ZMef7ZZxit/tHHn5AIFsyfr5rXDDlb/TFn6d5WfTQijDpnTGxdfR2uQWDqdhGUEzOF6kNUXcPBMMWRDqASiR8xHcYcbhCqlSs4uNm3DHoeoo7Bbrk9"
+ "QEyYAIx0s1bfNnpfTC6EHGgw9hk6KZK1vyqaQ2oCxEYfZc+xJmjXGpcAwszAM2ueD+t2W92fbBziCEBKcUclBgvcBmCRYsD4ZRiIU1xcDO5gBx3XpWGpT58+cuGFF0FkNCYEtMvgCbbB2kOQl0Lg6HIf1t5hRGC0jBs3jmbwxx5+WJYbnPKyBvqcqTaGDu3aysuvva7+ixFwnFnAi8h0XIcD7PV4ibkIUOsaRAxHwqyG1gH8EBcfr3ucaPY9+4Y/dXZoRlCHgV+gSSEUAOIKfQiHHiYC71FQsBVcGgQH8TdCraVzmkGwTwNY7zBYFONi48l+6ZTyN8BAxQHSuEcMjzAoxnAJj5EtA/r3Y6kAX5RHxUEaHh5EwtlmOQ0dV2oPefudt2XJkiUgGgwyHU+TJ08GYZjcVccYhs0Shj1iQ7vACfaWlcEzbGM7DTClpgDxwntkqsi4+957pFS5yJjjj5PV+eulm3KPd95/T0YcM1wee+ghOU8xQVJiIjQcDjIjsw5wU1pLdxYWIuBYz0k2vhOPbF6xie/bKoEhNDAlJRnqKL9vBEBIZPhDHg0m3vbt2wBuEQgNP4zxTYWNh9uF/oV9JE8NinOa2s5hAle8nTUIVo+IySgHa+UAW5UtLi4G8hYdCHGDGYU4DXooBw3sL6O1449VVA5wBxxg4j84+/1+OroQlKMhfd3QgZYD0N7x1FNPITTQpAVYIuAxkiNY1RHXxX1hqgcnoghptNnzEFnPzp+u6uToE8bICGXtNkXib4o3lq1aKZdePEUCJlQP7B4DyNuZWZ+uBF9auhdAFp5fxS3rEFTEvBWUZoA2VFdbj8lgCEsid5vzQ/FXpqIkBYFOwQAy5/AbOP/YP+RawaC1BA8Jh5telSXFakPy0NnQ62mPSAhBC8DAGuKIU9aawtmJDe2GTIZnFCIDD2nObZQL6tLvYsgVPlDr6hfqhTXqIDqNwPPTTz/FaxAJOomvrRbgmNXFUVl5D6ZFQmNhO0WIEyyXsRsICJZHOuxmf/KJ9FROMkENeQu+Wcg2vfH6G3LbLbfI+BPHQGMBpwQ45rUs5opVQm+VmQknIn0qySpKUlLS4LsB7sGgQkyQw3q8BJlsiaFztJN9VFmxT4F1axVLyjXdHmoyxhKqvyeRgbj0SA7UDRHvTc050MHROsP7aoPY6WtWr6EnU8PnTcieE46v56IjyFka/AFgEqurH0oYznuy5id1psK6aUIEqaZu2rSJ2shpGrHliJHIa4ixVzAQiPLdF00OY0LzGiw8Opy/xRq6MOPJ9r9WJx/iR6+47HIAYXUFnCtvv/uufLVgvvz4w4/aliwQZKR/hO2Ev6NtW0ajIT/Y5MyE0F+4vk3ThH3FclvsmAgEmdUqlrQSAGwnvC/zat1M3sZktA3GtRCXCrDbVq8d1xzM521EwsirgIOKNouHHnhA3nn7bcwu5nAw8trtGMwiZ6ad5REfO+8josqHDz8Werwi952wqoKFMnDnH//4h4wZMwYEaH4TyXViEUqnBLuaOS75a2GwKtFZVyRbCwqQqkhx5xBGOFIMmdckEMx8uvAXqLHrRc2P+Uw5CbYBAweojeMFyenahSUVsEWopEY1D5NT1FFtDkYSpPUmR7ogwAFB1BRFfu3DLjm8NrELg5MMIWCjm9/J67HiOF7vldPUxIGGphsRT1Px2HFj5VhVK++562654/bbTT5ptDPgPDoD4fRU5IAc5Ell/MQjjzwsTz/9jFx11V"
+ "Uybdo0uU9tDTfffDNiRQ0OidQ4KO7AaVBugaLDakslivqRc9JOQwaydTaDm1mMcvgaGC6rMvL5hh87XO6/7y/SoVNHzvKiomI594LzZcoll0oRnXqO6DIc0blSoz0yuYqDHGIANvusUCdBQnyserI7M60SlQhs1h/7NDaW0XKlJSUIooK5PzJNFH3SrhkYwSQNKB+xB9AEHnvkUXgSVc17TZ7TWY1ZiuhveF+NBZIs1ZkljZvgco6OkYudNmzY0MgTrW0kcrabzmZKpWzSCPL+A/pTFJnNnG9jQRsH5hJ3WAKLJBrLAfgcN91yMwNxiotL8CxUi7GZqj4QG0hqIlfyxcQaTSpgb+HYMfiabeHHviifEm8hYk/JpZK03YgasxFiIQJfakL0s6S0oOqPFoKzoI/gsrAJ7ilNThw//vh9FjQNdDI6p7faHd6e9ZZ8q+wXxHLLtJvlz3ffpRbLHiojaxENRflPs2+AVtRGA2xkrrNZ2c0Z0fhzC04dLyRZLllyamoLEAYBmxPMY49hByCHfyk/2QJV3g9thcHLWHjpb0G7kI4AdRtpDDhbTAUiGgQzMlqSyFnMBfd3rq0EwSGgzUYDWZSggjTmgQx2MbOf3mJej22JcD6m63XBFWFFnT9vLisDxCUk2PyW5KYWK8jhaGEsmwSbuaqOnnHGZPmvq69Rg9GrMuyYYwCcqJbuLCqkNRBF0zRXBKwUct+IBdehosVJnMYAkAu99OJM+dvjj8utKlJuuWkako0waGDNnNmNE7idmiDC3dFmDksMh21D5Gu3G4QaALGCnaPtzIorVmIEFwHQhdaSrUnjnTt3oVGquLgIEydSwCA/BTMdsRrgcBhQ1hrpqBbemro6OOzwTIe6DpxJxD7dtm0r2sD0Sq09hmsClILY4pucOLKyWicw5jFMczbkLqO2l2kswjcLv5EbbrxBhqo4QLQXEHaHDu1hD2BsZUulfPzWIYRD40RsdcDXXnlVLle5jlNHjBzJ5KJ16uvo06e3PD19utUsnIEPheGQslfCbn01IDS01RLf0YpRm5oJgMxErPjERFQQIP7JUNsLraAsN8lyT1RZLaejKg6AW1xMoqirqYVtB6Z3RKxDq4PmAjF9KMHappo2gBBRJehtzfCLi41jLVerusfDuNSkxEF2WBplXAJ8cKv6XXv11fKIWhDhjMKOQYHpGyzerX8a74jPbMDv4WazjahSzecdufKKK+VBNWNfcvllMnDQIBk3frx8+PEcufD8C+Ta666DdhRZZQiBv8QqjnMwDJsDZjdEDmYsQCuIFCz6aIgD3lz8HiZ95tR2YNY90jv3KZfcb4K"
+ "XYSqH+Ry5K0nAQWgPzObggPRCZ6nq2zmnKwYZxjUGQYVMLItDCNwpWsSx/pITbVyfT4vy8BEjZfWqlbY2CEAp1HZPMyCO8rABmDQjr9cGwyDz8iuvyMWXTJElixdT7obFyRMNhYPoKMpsS+kikeyeu42sllsVAF485WItbNLXynLu2B569BFJTkjQ+hb/snYNfAdPLGYl1F6wf6rZZTrTly9fzkEo2VOCtiHQCKGMBuxJY0Jt3Ca2n7ijqgoeWTwrRUA4TKyD57GxG3Te7S7ezVm/fds2ZMfDZ0RjltYLwUwnkVVXV8HYh/7ADq5kCdaKFQQMwaJq8RL9LDbXJiurFfxFdEn4IaJNY5uaOGDCrsMsMcYfIG2qiueperdyxUpY/SJZt9FUhEDq8OUDQgeFHq7SSOtNyrqhdWBD7GbERpY8+vjRSHcAKLSgkYSV3a4tHWble8tR/wuBPsQBffr2kV55eSgLIStWrICsRuf+EgexfhfuPI+R4tKYuPnnmO9dOrNTwNEgXkCwcJSBEJl/U1dbQ/HmctN7S8IOmrgXPce4/kNIcmL1ouw2rYDRIC5BKMq1crWPl6thbqGq5h3onPO66cWG38nfxMTBQa42g06bwaXK9jfrYKJjYM1DDqrfD1UuiLgNlHcE+4NzjsfGLDuSl9o65i5TqsFukVoHtuSUFHCiyLxdsGmmP3TJyUHBFSXYnajeh5A/mMShaiJghl7d/Pz1ANNUF53NajCNBj9M0z8i5ZFLwxltrbaOKuKCaRv2GajxTMJiJcF9lbB44lyDeYyY4LMQQAOwQ+OBEw+fkdAzW2ZovyVqHzBfFpF1EM+0+J4y8XTm7haqW5+aG9vMONKGZmDnCJWFKRPBXktxpCdzgNa8uOCCCzBomBWgfNbeUGmM2QG/CryfGCwbsdXIJyLcemiBtY46K374/gcjNrwAe+QwluUuW7qUnIXmeod4AOwQewkLq7XOgsgMUTKugzO5eNduAsu83nkMzzuUAO3ODe2FXwcTgxgiKwv5LUkI9LHcj3iJM1zvx+IxmIletwXLEjZg+VDA7IUPhs7J8n3lajbvyL7YUrCdRBUXy7gWzBZoQngGAHOkgJgQRObR4Jnzm5pzAFCW6SBDqwArA7dgtPQdd96hZQta62csnsKEHlb/K92rwDAe4XMAawCrVtXEFnkkYSUpGyXgfO9dFRErOMCRM/yF55+ndHpFjW7YEO0OAtXTDIHUgDWbIKIGgmDnPozSUvd3CyGOMXGXjsiOtORKpLqNQaDrv7USHgAuCIWDHj6YlNyUPTyiX8A5gTHQjsOGODLy3dhq2rfLBubS6+8GMEfEviVcBgnNm/uFvPvWW8yhbZ3dBmGDIET0M9TZcBMTBwHgBu3AGgyy1+uDcwlaAFRX6Nqc6Tb4Jj0tVTSnU+UiWSo6FL4YG4MRCQB5tIHF12vdsN9r3c6LFMd8PHuOuAxYXTB/gXyvKZaz53xsNSQ1l6+yZmYnyIfJzRYvHMQVTEQYwJwLtgZ2ieOAg4oeKWYcMAgtZ/u2rfCOUo0lYbnJ/Sx1ATdAfQeXIWdZvXKlAueXAJLJ5Q4Fv/y9BEjM8JEEiJdCxrsc4nNwJ9F3V656oar3MLIhKAnlKo3rH6KzvqnFCoJ7ClWtUgJvwNNCdgOp0/JJnBEMctY4NUsDwtnvjkY/wK1tMtel0UCIKdiyh7PsielPySJNpL7vnnvgg0DtDGSvQe6rl/QyWmRr1Pgzdux44384SMtopH1wjzSy4YaoOIwOZrstnnGcb15TnjIEQsQsJYF2zukCtRKDCN8N2kbTNk3ZFZU0+P28YAmJ+pM5s+X6G29Uu88xsnPHDkOkLD/htNGsIAGRiGt5rT8lGFYswkh+0BA4CmwjEGXs1zhfHH5nQgv90MDWNzlxVFTQU9gAsQGRokRibAdMCDZZ81RhI2akU8ObIokPZKOxwMxsVJabYO9mre+14UDpSVnw1XzppcASxIHgIIQUQqW8eMoUVADGZxRHzuAecrQxrNY5ZjUn2BLI9fx+agkgbAyQiXar0SOBNYQgsBICdmBKR1QZOAHZe6z+frWGLXymhDxg0CAQHp18PXv1lDdnvakD2oafhRwD3UFEizfkFPDMMrt/P1RgtsVjcoFL91J06ud1CDuA4c0Y2GIBhBG0Xaoa0rYmJg6KlQZ1Qi3"
+ "XBx6XmZmhHUtucVDMJjbHZ+LMFkRi075gw/lIRCFzpChCGiFF1afqIj9Ny1c/8dST0q9/fxAhVdEPdTZGbiYzzt7XEAIGPkqP+J41SoH2IdL0Pdk0wB1AMrUoW4TN+PKsd5XGr4SEVFTsoRgpUfe/mJhUJDp/+MEHVJeLCotYkdnih+HHHktOge1nDXMcN2ECBz8csv0UafmM9CdBA3NRLJGLeL2M/LKLAzAA28vieyBcEzhUi4vs0GcINX3ZpwPJSJs0WmncgfC7oO1c+x0JoTH3IOFQqgPJ288tgTizCd7Pq6+9juzY2Zx64iASa57mb5xit7aQPc7FzLcYxtybLBhtxLnoYHBA4gl+bjgL2s+cWMz2MINyaETDxsgtM5pQQffrjsj0oepPOvPss4lHEJG1bs1aJj8dM2SIfK3FZi5ULof7mZxfy9XYE3xvnXpuNw2L1fRNNcCLjOcx1YQCBkOFDZfD+yi0ERN2JZ69OSQ1oXN/0hl7LajXZLRxh6ptiuBzRjucxA6+8GG4OUE/ZlDwmjsAJsSPU7nQCaLR3W+vxwGMivaBDSMoGBqFMUcz4srGOpgCdb7IIBuog8hMg5scA2o5CtrN+9aGHYulrRNKQtMdhj8sHoRI9A2a+/uBBiCvUONUdnZbaDQofUlV82ItRnvdNVeDaCCS6F538BCJ1go/iB22G30KrGGYrnE5OJgIBA+iJCci0XNSLsE5zSXLfpFNz3Nc4VxSCywesw0mbATWYtCtIQkyFOwSg2bAa8ionfUgBjPLsTPdj6ZnZ/ZHek6pvRD/lG0txSwCjgD2AavFjvuhU23KgikRDVc+MQ7SBXjt2po6Hi1YdfAROj8St3DHK4hHaAesi963Xz95YeYLsnb1aoYvbNOUga1qQ5kw4SRZl78OLabTjVbQ0MHXEksowkBjm7fD1zzHOddqgPjenEvPuK2dthhqdRMTh01W8mzShm3XRrfTo2KBNkDOiJxCdjlAFSyDJmeFouagROkdO7ZZe4e1MtpCKbgOOgthdrAPMH3B4+HssfYRXAseUgTdMGEoJSUTOSHoRKB6YgswHcf7a1+7IzlRIyttJEcThzA4OI0G1AwcrK65PXJVc4gmJ0pQR9/8+fNYx6O7AmXUVweRA1yD69nHde7lqFdOm9jHtg1WjMECaiYaUykwARgCEWpoKFcN8keIpOaQDmkdTgv09cUIoH37rVksGT31v64iQCI6ZwnrWuM0a9Adct1iA58OJss24L3djaEIBEWtBk4q7MhdbRzaBycXzOUAb7AaMjOscbCyHWDnyJ3YgTRJ7sfRPsQoZ939eBty2HokkUC8UFx07NyJwHPHziIliG0yatRxCGWA1ZL1TNfnrwdng0GMKnFkW6xocZEbMHsQ76ythvexIo+aS0kJ8o2hqQFMw67yrds44JpDgLFJPg59BsCEbYmWjV6o9bumP/UUWDjc56bISAJUT3gR6eaOio5G0AuCYyAyIHZswjRYpp31wA7W02oK0O21EWCROSzwkRjDW7TtbGv0MgvtHRoNJoJwft4T2CIyYTvy+mgfnsVWKTIVARytTP8Q54n4Fhk4YCBtIU/PmM4kr4GDBiMYCPXKaOOY/9U8lMgG9oAIcESVOP4ZAOZqk4yuHlv0h8mnCXJyxWg/UCtzexBYBJwFmwdWevgUfYOJ1xyIwxagnaPUHYQ6eOLYE+UN1enbaaNf0VoSXgMIYfuwg15bX0egRY2DVXECxmVtBw3Hg7gTtQ4bIeUMNkUHgB8caUwLBJF6PJZ47HUOfW2PLpPVjkx6DFZEPXUQIwAxk6i3bClg0PKmjRttwBABddgGFwVYmwSlEpCZxmi3s885F1oJcdXWbQUMFejVO49cVBliY+7DawXNcqScCOXlCCVEGwCUQcAwhJEzmOW96PBUbRHnoKDLB+iPZsA5+GC2E6t"
+ "UPfsMXGDF8uVquLoZtb+UpY5iLktGRhrOc2auMW84qQGHil1nMEkciMgGK2UNURvPYZOpsEGksSZX5T6KKEdNxD2c143EC7gByjqhABtfW3uJXZXh55+Xwq5BD2uOenmrlPgKFGQCZFNzCDlYACpzjmbm7ddBbJvdFtdFuADuxtyWEzX/9tXX35TzNQmqRWoqwbrjj6HJ3VQMYp9ChKHgDHJaAJqRg8PvQAAmM89wME7QRQq8d5mswGZTTdDmW8xU8HnyyOOOk4cffFAunXKJsrxslEOiTLRJwE7tTtoprBrWKEaykcobCiIc39bpMgVd/ah3gdoX+pqZ+YjvwIBwZmI7NGf2kNcgNHhnUS+M1s3Bao+orWFcCjADraGdu+TAlkH1vFv3blKkhIr3+hRGpQ1bHIDEZsh+qrPvvTMLJa84oMccMxw5rgww2qt70GgXITMb6LjDkQQSBqHifHIr7Sq6/sGZ7Zq2Xk8UQhLhSQZRwUL6kpuJYqFmVRjfArYPVOZXaGckY/0QGJMAluaryft8Xd3oLw8+oAHHw0xMQxDqJWaDcx0HvjeORgdBAK+gY+EFNWc6QUawRiIM0aY5ihx0vcMRRqRqihkMWwXEByPEjJ8IeSMs61jJiPOgeU4P2DcGD2AauAjXgDud3GGlBhD97e9PIPga1lSo1LgWdiWKMohEEDI1OarSIS4sSALiznaR2PAbEAW0NkwkiBa0Adckl3rnzbeQCqKifLxfOejrEfaNZiFWsFtcEFKZOPNAtHk9ZiPSAGl/GKkrEuX17s1O1s3EeMRZV7oVJca6ymjyyGsb1hkGtoC/BS5rFGfBykxIsEbEFTgJZi5iMu3aa404x+EJAy8hjoA7UPQF10BJyH79+lN1rmKbQ9ahZzCB41QMUcWEuu1n209Vv88FWhaiY6dOuDaIGbMbrB9gFqmiwFhIKcA9cY5j02GuLCPcJWDAqMvloVuC3zvr/SsR/6Rm+e3gzGjzm+rSr2m2xBEM0iP5d8wkeAxBFHNmz4bVESFtNpHJnsu4A93QSXCbA1DpkfYJpB+auAxih0ikzvPSM9JY0+vO2+9AFDdAGghKvbPfAg/gHBARZ5j19UQasA4VLy7MShArCBqz0SQ4B+lTEQER2Gh4AFFWPibnw0WMhgXxSQ6iZTKRcolrIH4Vz2VCBqPgksd73AtYxrrhrVhhWKDLxYBoTBZjAQXJ0OtLDejbhV/Lj98v0rKTY2TQkKGYjA8HjIptrte81luh6zg2druWePpIVx2YiAX1TjrlFM7EW6ZNY+eccurJGHjjWPIzA31nYRGSolkKySVMzkYHgtUjVgKsF4R"
+ "h7RWmBmgUc2AfeOB+TUWcAuMX9ztuvVUSlSjeeOtNmXrF5Roo9Hvp27ePEuBuzrZDxWHj11RpAWjBeZBzws9IEMQVBINYrAcTgaF/bieOlO2kCEEFnqQEekrxFdRMqKb6AAgZhP0H6iYMVwZcU2yAo5C4GLVWXcPJYMuGkcgN5yos3Kl4qAChj1jV+ltXOLwG3zfnJTVsWP00rbU5EXIZMQ2wXgLcwd+B800JKKuuMSpsj34HcYTvUI4R+GL9+o2yXdlmxw4ddMCCJvKbKF6wzftynnwx90v54ou58rqWQ/jjn/4kPiXEBx96iJ7LL+fORUAxxA8xiVm89xfxR5iOK+IJbfM2xGlCO7L2Dw6e38/FDDnALss96XuhWo1ZzHviEzjprGvBKRQjUsmlNZjjCk7Bvoih7ycOk4be11CQvzO/YbwJI9YX//A923jsyOOwbo3+zneDKbnQrJbUgJp1uBWn0UEfKuudWF5WBh8Dqf2vjz5KTtKBg13n/MIsUmMNNw1+slrK23XqAk9NSYWhDAMGpxk76jG9FsTGTdNulH59+8rtt9+pa78t5ADcpYsQ/9fUqTTPT1EP6DHqMgcrxsBFYJDDiRnrqIeNgkCwVas2qF8OrYi4wmPM/yg/aQYPz2ZVctb6ytTIrColdNg3ALrxLGY3MS5uWnptKADdCbAOe7y00ew3IQe4PryvdukPcimPG+IECxEi/RKuim81mWoEnq3Rppzz0qbFHHxoZ6dMFBcH/FokBiPQBdZCBMH07NULhd1J7ZFEGTLplOhkzA5cx1g1KYpsfEbkDNXFeqjzX6zAb4pW1znzrMmSl9eLkdvvv/cerJFQnaFGYiYasWR/H7KvbTvs/cCVoNIylyWrVWsEMJEwaNQ269VC3OGtCd2zmAvPzHP3lJYwaMiWcrLfW+Dp5yKEmYgDAQdCf5BoyvaiKhITwExQMnGMCUCidZYc54QTx/E5i4sLEeg0FfdojgsAYkAPRzCwYexUWfq4PvQNYMWoj4GgFzwgQuqcmSrgGrBVgIgI1Kxjjiwei/UYB5OxhvI47ZabsUQHxBXTCwb27SfvffghTPAgQP2sL3w8XJT4HLVS4nfgVrh2owo+kR5R"
+ "s2xoEICUEV52ZUfr9OKpYt9bEBnidyHghXgmKkFE0kZhjWw83ww40i1M+SjjZ2J0mRG5BM+ojQ5VFfVNCIKrqrhKJgiKsavfKCA9ZeJpryveWYf2NkfiAOv7JTwyTdnhFXv2VCTDowouEMG+bSwFxchuJQysBIlcj7ABt2CvAKfQdgw3MYlCyRo087XcqiAXEd29euXJNQo8URsM6vMnc+bQMtt/wABqK59paag+KnqgRmKgnO0gPwvAITASB48sPrCfA+YQAo4OYfBo/Tb8npFxOqDJao9RB6E3Xb+zhEOuyiPVHuFnONhlz2kUg8bhN9wTVlGIMRi+MAlxHr776IP31c+UHdIKx9fAqnuErUkjwX6RdtR+cJ5Wy/tEO8+sdUZvK3enlmgJjFcAcSjiZmuOgkBsTi1Zua0uyEKzBQWwI2DlImKLs845m2x8546dzC4DGIYV8uWX/qWJVpfg2iAMcA874IfdfVi+cx/LYWPgGnEI3c1g871T3huzH9yJ/REXC2diDjACNCsQsFHD/fgNOWcNlk01K2abJdSpIXH9WOIwxt6iPjy/03dQg7EeLtXlMyafOVVDBCpMkbhmyjmOULVOv/7Up84g9UOcriAVkdomiIVGKrOeKj2McHljJlMLwGYCdDBbzIDyilBLGVB8/OjRkMGMPJ/54ouyWe0dd959F2qOQYVEOSg4ybQjJ8u7mozdpWsOZhwJhKIhJOZoiYP+FPhw4AqHrYarLOnwO0nuBIocaBiprNuAhBkXmwzACNUbCwBAHDDV8rVX/iUZmVlY21aKi4pklKZv9ujVCxPBgE6GBKL6EDglOKkNdjL4mO57bfd+BhSN7tLla73niwf8K813RWpQ/ZGcL5j15yrL3h3rjUpmKoKxcXi9UA3djCpnxbyqChPtRcAYsdryQZVVDOdxweMLVsw2JCv4nHbrzcAvNCzNnPmi9FIwuvinH+XRhx9RL+l2zEqs9oT2kI0bVGmsnLRiA+hRs9mBskuJrC4MEQMitj4Q3p+VE6Pgx6CtAi3kNSsrq8EheU52dqb845kZ8vLL/4p0DBDsDh42lB7mIDUYuhKg0iIwCtczJTyp7pNQgiFyJmhwDdpHpx8BhDYXO4fnSOQjHp+vXh9ugg7aIrBLfXrMV7O+G3BEDLQEyFbjca1z0iOd4iuRG4lp5MhRsKyicC2sovCa8rxTTz1VlmqK5IhRI+W0SZMwAFCFCTBLSstohHJ7wtAsrBOL97NiEkuQQQxCXGGpDJzDIBtj4rZpDSFTt105nQk7DBn3P79jHm0rjV3pltONWfUpOuu/mveleH0+VjR21Nsgdgw8svkMSA1wEgXNOSYbD8FMp6ko3uekkDpbs7NzbN5ccBSaTfBGvd+jqsmwA8WAOZNYDB+EDkwm8moNu3axg8R1iGcVMwqONswymJfB5u3n0DQA5mhIYmyD05HwmPJ9GPdUVdsGMnPAeT9oSl4QBrLWkQfDOmBh6xgzajeO1ixiNREOJKO0gvY1sBM4FdRVtveaq66UbuqQm3Lp5bKrsIgcweb/eA1+qzfttYavALASwwpaPKDFgG8H4Rx5o52jaYljXf4RE6tsJ9oBeksf+2wMBAdEmKEFkAkDEOQt4jIwU5wAXw4YQWxE8S5ez0a34/fWHmJd/hBLtlQkrm38Mj4QFIgAv7EJz9avYrPdEB6AdALeN693X3iDTa6ty2ot1qiFI37HYySRWBXTg5TQsIAo1Rd0q1ZbHMk12nbv2oVzTRwIRYptHwYGNg8QPUQwLLxfaL+Ms1pb8ycOco4tRxX7ETpgq/heQd1QVW1RBwvAzJQsiENBWnSQWUmpxrrkMZg2S65RUBA714gK5pFACEXmsDAlUe+HoGNc2xa5"
+ "Rcdb9biREzFkV4HE2ikIIwSQZQJ4VRWvdTC34B42R0dl5WvYQCgy4gh077/vXl0i43JkwxH0OqtY2kQmWmKtQw4EA+Jfo/3RKyLY+CiIowkxx9GvCMRBHakGopUa+9B948YNcvLJpzAOsnxvKcAatBE44bhyM2UrOQwHz2oO3JxKOwEUcKV9gZtELuZXD6wBPMICsVwvPyInRpy4kIPtGEGqlhoS0J1VeTZu3ASOxsJsNdRSHIIIRxCJDXUkPnG4CbgeuY+wllcSfD/2O0toIFYQEhrO2FB/HZc536nBS8fYojQRW7MHpL+mwegov/bHEJWxS7SuVs7naqRCQvJxquLBugifBrQLBBQj4wvslYNpyyA4m10WyxIRCcWKnZDJj0HYPhbpBSiFKIkM7Qv/u93ksoQbwky7zAqFsBgfQWNcfCIwgjWHO3vYHIORnwFshpGjg5RItA/R84xUcwApfSh8zfbBN8WIOSlOT88YpKKt8tcSRtOHCR79hpIBlb379h3YOjv7BzV3537+2WcMOB6ttglssHQiRK+TonyAy4PROY72JY1UUFM5UylmTEqlmMFDgFBNTZ0U797NIOSGen8kx7Diyby2ycwO0EQ2P4rAosAbPKkQLdby6XANZ3c+s+mKQarcuiyqhiAOo8OwxBEpTgyozwf8Q/e+0vn29JYthyogLz4CYTRfbWXV6rVHSyA8n1bBYBBYQUVq9HzN8xj63jtvawG4x6Ch0FBFjUE7sVPHjuA27HDDPyLuaUooiJP1RRuGyf+wy5EzWhxGNX9Qau2acmGHgACQcbTeV5rEjRGKebIG+KLYCzgVzicR8DwHiNrXDlfA53C+cVE/ihS/NXLZQaekpDcaebEQe/nqNBymXGTfEQijeWOO3NweGgC7HQMJreDoiESA4OvrVE4PU+/i7P79+5/y8ezZCCdkLS8Mb5W6wLeqzIeXVc+zKUqWyqyKaddbMSopsYmtC2IHmANCjQY5JxhIEgGJC3kfAMoMMWR6AAaPE4dma2tbMeLLY0RTBBAl8DTvDQgNcGBBnDwfeAW11/E5wxz9JuwvaFRjGM+ifVELVZWfoH1Zg+v+qgxEtwfqfJOLFSbunHTyydKnt7rjt+9E1tXREgk6HLPy1F59+jy2ds3aGz768AMZPHiI5KmzLC01TWoNF4F7m7PciT42EVJhqKJWtUWdDBAJzfEuAz4DJq+EflFnoT9cB2mWqOpjlj4Xa8fA0XAjJioDv0B8GZc9fx9BDJGYg4NufUGIarNLqUILYhSZxT3+ADMA9XsW839en3GqwXJH3Y+Mfjf2lO8XfSdnnH5K08Zz/OEP18mJY0bLQw89jLcgEgLAozHvukykd8eOnW7UtIDzO3Xu0vDG66+ry/0tOp7i9IHpUbULAxoZjj3Ao10WPAgPLhfpe0jDB19Rs/WH6sHEIj7fqf9l06aNEgqEGJtJddGkBmCZDd2AJ2DSRltMARgWu6XBrrqqEoCSM99HbGBEBtuiu5MIDk7GvNkAYzC45poxfcfpjM6ANZVE53ZyfgF0r9ZnnPorF1W2izMzs/8V9eU8/NADzSLjjQnCt956i4wcMVweePAhNrJ791wQydE8KGYWor3f0JUQc8efdNKCDevzOaMLi7gEFrmADU5mrgsTisG+QSQ8YqBMtb80qserVqyE7wa+F2gYKKKL1AHMeLQPrBw4AMV2dd9Ldu+liHJzqaxtBQXIUQEIhXiBtRSEYtaWqWdbuOP+ZoFko3IDW5j1VDwkqHXr1iAOAyIO2grWjgGHW6bt6K199g9TWuHXEAa5qsbtyozpT6iTcVaTayuNN6qft992q0ZivStPPDkdhcwQ6o9yzpiRkO1HAqoYBHg4t+iaLcdrBZ8/6UA/qg/vAeHoaxAe2DuKrrHDbQ1QW36geHcxk5IGDRkML60ehxC/JCXxPKrKuwoLdZAWqu0jhwvdlJeHGSy8efMmzG7jQg+A5dOLnJTcAhZTXJ/H4qJC5viK0Lpq4Q9D/dw2osyUlQCR4f3qVStgL+ESXmVIaiorhaHvASXc263Wgu1XEgYTtJ984u/y0YfvN2FqwpE3OsKGHzNUxc3xco+60DGoffvkQTQcqRPsEuWY5Tj3b9qxXUXkHchRriTN8Lg9IAawbMw+mwBtZy09qYU7dsL"
+ "aCO6B+6NGKgYbiUTwbSCuFQnN2tbFIDg6/NIzMoUD7fEwsLh16zaot4U2wVtLbYMlpLxelHsAeAXBGM2Hwc+4l119Cbm9WCQA68LCFK+E2FXy9L56+mdaH7VvZlar2/Gshrv+WlHCdj75979awmjWxGE3lpy+T83FEDePPvY4BhCLAh+NgQ0dCfv8WSrDJyoWWBWvgwtCgdiARxaDoIY0AmH6XkzSNQZjhxLIli2b2Y6uKuaW/vyzemt/pkm6j4YVdlar6f333qsDSMyBmAoQCSyztrA+wWoDzewhU6pbaEbHFjY13OvrbeGXWuvTgejS+y2RD959m4lHgwYPRQ7tZhWKF7VMz5igomQFCO7XbRZ8xmLRY1UKnpLZH33YBEaw375RrEy76UaNbXhaZuhSXOPHjVVZXy+F6njap3L+yHYSF/bZOnNna4zoZUoE1+ug9BQJIzgHrB+cBoMOfEE80qdff3AVJjGvWL5M5s+bx+SpEerm//Tjj+U1LYGQv3YtiBWaDrkS/RrWJxO5cLLYpC1nOVP1kMLmQY2jpqEGnAW4hiD0888+YRBSHy1sx/LWLbM2q3f274ozZoTU/El7iIlc/w0cA1xRMcaTKsbfaWIL6W/fWEJ6wvhxcsIJJ2pS8TCZoonWvXv3xszGqtQOIRwej9gKvjOVo8zUmXw27DwKRE9QTgH5jVnO6yDqHQ49JHE3mDwSlGU89/wLUXlH5f9qiVdC6d9/gOR06waVFxZbaisSkWYQNioqbCLUjkzcBwralwT84BRWHQbotFoXlhWnyT0xIeF7JdwXtF2aYF79m4jBPCMnQpSPNc0UY/xN3n+XhPHfnzjsNm/eXO7/1Gq+V145VSZNmgzgSpBZWFhEuX64zeB4Y52UWarCztIz+/tDwQtFZLKCyXZg+QDGuAbUWoQG9tUZzDKNlRUoooIkKt3bQ2OAK58gmDVETEpAlDr9avRzhBuCg9hqO04EuYscgnmsDO8jOGWsSGx87O68Vr3fVy/zq0pQ39UECGx/DWFYhx09wmjBou++VbV7N7nl2rVrZO4XnzdT38pv31ha4M9/vpMLBp951lkyWZf/6q1YYOOG9f+RSscOD4eXaicuVWvmDYoNxikRnKJY5EQdqK4uDnYYRIdOtiZzAEUYnqiK2vXzCxSbILc1J6cr7Q/RMbEQUeQEju2B8aPC+BOkTogHEdRSEwgWqJo7Vy8/R1XauVWVFXXM83VqJHJw/9PNhhGQKFi7dLF88vFshDw2geOtaTfW83rm6Rla5P45mT7jGbnooou4Dsp/GEBrPbZhjfn4TPHAZ5p1jk97qiVzlIgMUO1lgIqEPi2UELhUBa2aBJbQLqB2wo5Cz23RzkIWcWmvNdqHDDsGEVwgCGMCJyiF1rVa7SNLQ37/Mk30XhAKBZYzz8bJgfm1G4AtxAeIlkQxZ85HzKZvis0rzWcj0Ltq6hUq/8vkmmt/h5qeEAUYmKNx6lnD0xrlFmt0tGCCRzxnO8UjXTWZuZ36YdpjV1DbUm0RiRoSENd/wEDfoMFDXMo9wggDUU2gRoFqldopSsUlW5Xwtiv3QMXEDSp6CpyVoN2KR/zy2zdqZ0gVJZB+4m9/lZ9++uF/tXO1R4rjQJS7uv+jjeB0EYw2gvFGgDcCmwiACDARABFgIjBEAESwngjWGZw3gjtN1Zvqri6NDq0/4Lb0"
+ "qrqYoa3utvTcaiQBKR9pVzYi4veHjCoikiMikiMikiMikiMikiMi4o8b1g3ODsXVSmHFWNkI3cFKaSW3ksn30d5l88ukL0RoK9+sfPqPldjOmeOrlcZKAjlZKaCrraytGOgaIgBeqU0pbLbUxvroExErK8pKPui0gkFc4vUNjdBfrOygM5LBIM/WYfMVtmaw3QMiBCmmw5KDCFJ6HG5xjbGSsIyhoHMhA3F6RASIUWI8UitqjIL0wJxrB3mO0M9ZattBJwDioE1/iED/71jfpmNsvNUQA4IUQr/G+yn0xlNLzBm731A5GN6+t4evF0c8S39RjHYCmMoaqXfYP2HaBBCnB4ipZgMz91x7hR/XQ+LvEzcSEXtOfR0IVKxeEchxROH7xI0KeitEHgENvXbZhiycN056SYYN8yntGit/Q793kNCImKnad8eS0vVki7WR962YrUpcXyC2M8Ud1CcSe+6f3bf+ibEPXuc4gr36g3S1E4WqC3PYaYSiFDWMxIXZPDmIMwM5GmfGo4zSOvQXHrP4BLXhJOBPubDVIHs+yQzI4n0V1xf4CJ+AICqoT9yFaOmINR265pC1ReZMxYTMcwO7SX/YwG856RGCZCbg4XkN8kKxayurjoVozeNmpMyGJofMDukHU0PjKVxT6C89VuYJ5vkh0dyW0mUGDC/2Oxei7kxvIIOSQ6bpuSPANQbfdbOrHrPGAgOCBbXeYaC4eMiRQFJIKOQUrIIHkeLQIMhZyDuysfZWdpzp4u/yXY9gFV/3gL4rNhAUdt0hbCkQr6Ws5CXHFG06I9gODfwRsa65sPjTUc6QIpCNKIKQNSyo4NTQbyntdQdbsf2GTwCf4a8rpuho2gvyZ6WCE+vOK6JfPdP1CvEZK/WgmUMWpu6sQNkDgaXQd4Vc51AgSGcg5i+QbeB0tezw5FOb8Hosp/FwQy5QDkkOOfgJsshB6Ev2sfeM/5tJv9iiMw2mgXuiZlOeCa8ZMIihkItc/oI3HYkcVJiCAFtPdtEIsH9QQZpD7gmFAahDBxiK9U8WoqcbiNtQfIOTgxjp2UNZy4WmG+fv3FP8vWEqSDhjT23uaZdB4dUHxJkIYmwcxNDM7jOfQkCkim011AF9kgQU5ZqNzwr+On9vxf+NM1oa/uyZnyuQSKZM/z4Cbef791YI54C9FWQbv94Tpw8nZFH/3grd4xV90wb0CZu6/AemPNde7dgXncnxSyIi/CRYRMT9yRERyRERyaEmj4AIdY+fYFh4HP9pRctKuYPdpueV1PSDar0YabA21D+Dnhvdw8eFLalvx8ocBUT+f+i4wjnFDRWQ50m/OFp54jGPmO1a9M/QKEEKTsqXsaaV47AdSBioM384OvPXBU6yjUWO5sal3AqixNRR0C6uFwYKjesX4lxkymyZQB8y1pb5ydH+LFYiDdnFsjNdmzNbBV4VdBAnUofNBPeZsDhSbxxkawPRMqtLn/ChRi5IERixNWdBNni9giAuZIJADXt/iZSZIFUWWJavgnxQ2z3FS36QTWasvWLEXLKNvSOub9ku6jNeK7EyaxyknDKbcysp2hrotsyfproFbbD9zvpjCWnF6vELI9ac98+ovwkmjv69MnZmLMAnzxL7Ae2NmApOaHNhg1OQzyAfV9Y2536ga0QtkooNrU9sGtxhII+wtXQQ7otj/yUT0+aOHdRp2f3WIFkKf/K+lbTFySGJAtIriB6PHH7owHMRtc8WOvPYxQdQol3j9edv/x0ZDHaIBAE2W0+a/8EGtHZMUzr0zAfkYRbBavGUqo62Mm6ro49VqD/HcYQ9y5g1CKJFG2lzKvTXiRvP8FE7vtaoyB/Z8hDjCQ9QMxg54GgKydmhVoMbMExv8GSt2Jwpn64F2syFLmF2EkrBKNxYQXiDjxR2XlihVnE/0Gn2xaGCpfqK+ePYoc2FEWbLri9E/+SINaFT86gxCBn0C9irZRwQmpLIlwLhE+HzDYb505xU996VVQiugXRFQh03iA8J45zyqJNL+T6Rxn/yS1xzRg3RMGLIOJRjPcPAjkI7AdGW+qnF2A9AjogFHYXsBWdklsv/d8s+QqEYbSF9wLBMpB/9Z58i/Cu6fw1gd+ZQ/PI/bx0Rz3NERHJERHJERPwLZ401JHjcCs0AAAAASUVORK5CYII=)}"));
}
});
}
|
diff --git a/src/main/java/com/ning/http/client/providers/jdk/JDKAsyncHttpProvider.java b/src/main/java/com/ning/http/client/providers/jdk/JDKAsyncHttpProvider.java
index 5b155b2ec..928663e6c 100644
--- a/src/main/java/com/ning/http/client/providers/jdk/JDKAsyncHttpProvider.java
+++ b/src/main/java/com/ning/http/client/providers/jdk/JDKAsyncHttpProvider.java
@@ -1,724 +1,727 @@
/*
* Copyright (c) 2010-2011 Sonatype, Inc. All rights reserved.
*
* This program is licensed to you under the Apache License Version 2.0,
* and you may not use this file except in compliance with the Apache License Version 2.0.
* You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the Apache License Version 2.0 is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Apache License Version 2.0 for the specific language governing permissions and limitations there under.
*/
package com.ning.http.client.providers.jdk;
import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpProvider;
import com.ning.http.client.AsyncHttpProviderConfig;
import com.ning.http.client.Body;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.FutureImpl;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import com.ning.http.client.MaxRedirectException;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProgressAsyncHandler;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.Realm;
import com.ning.http.client.Request;
import com.ning.http.client.RequestBuilder;
import com.ning.http.client.Response;
import com.ning.http.client.filter.FilterContext;
import com.ning.http.client.filter.FilterException;
import com.ning.http.client.filter.IOExceptionFilter;
import com.ning.http.client.filter.ResponseFilter;
import com.ning.http.multipart.MultipartRequestEntity;
import com.ning.http.util.AsyncHttpProviderUtils;
import com.ning.http.util.AuthenticatorUtils;
import com.ning.http.util.SslUtils;
import com.ning.http.util.UTF8UrlEncoder;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.naming.AuthenticationException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLSession;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.Authenticator;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.PasswordAuthentication;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.GZIPInputStream;
public class JDKAsyncHttpProvider implements AsyncHttpProvider<HttpURLConnection> {
private final static Logger logger = LoggerFactory.getLogger(JDKAsyncHttpProvider.class);
private final static String NTLM_DOMAIN = "http.auth.ntlm.domain";
private final AsyncHttpClientConfig config;
private final AtomicBoolean isClose = new AtomicBoolean(false);
private final static int MAX_BUFFERED_BYTES = 8192;
private final AtomicInteger maxConnections = new AtomicInteger();
private String jdkNtlmDomain;
private Authenticator jdkAuthenticator;
public JDKAsyncHttpProvider(AsyncHttpClientConfig config) {
this.config = config;
AsyncHttpProviderConfig<?, ?> providerConfig = config.getAsyncHttpProviderConfig();
if (providerConfig != null && JDKAsyncHttpProviderConfig.class.isAssignableFrom(providerConfig.getClass())) {
configure(JDKAsyncHttpProviderConfig.class.cast(providerConfig));
}
}
private void configure(JDKAsyncHttpProviderConfig config) {
for(Map.Entry<String,String> e: config.propertiesSet()) {
System.setProperty(e.getKey(), e.getValue());
}
}
public <T> Future<T> execute(Request request, AsyncHandler<T> handler) throws IOException {
return execute(request, handler, null);
}
public <T> Future<T> execute(Request request, AsyncHandler<T> handler, FutureImpl<?> future) throws IOException {
if (isClose.get()) {
throw new IOException("Closed");
}
if (config.getMaxTotalConnections() > -1 && (maxConnections.get() + 1) > config.getMaxTotalConnections()) {
throw new IOException(String.format("Too many connections %s", config.getMaxTotalConnections()));
}
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
Proxy proxy = null;
if (proxyServer != null || realm != null) {
try {
proxy = configureProxyAndAuth(proxyServer, realm);
} catch (AuthenticationException e) {
throw new IOException(e.getMessage());
}
}
JDKDelegateFuture delegate = null;
if (future != null) {
delegate = new JDKDelegateFuture(handler, config.getRequestTimeoutInMs(), future);
}
HttpURLConnection urlConnection = createUrlConnection(request);
JDKFuture f = delegate == null ? new JDKFuture<T>(handler, config.getRequestTimeoutInMs()) : delegate;
f.touch();
f.setInnerFuture(config.executorService().submit(new AsyncHttpUrlConnection(urlConnection, request, handler, f)));
maxConnections.incrementAndGet();
return f;
}
private HttpURLConnection createUrlConnection(Request request) throws IOException {
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
Proxy proxy = null;
if (proxyServer != null || realm != null) {
try {
proxy = configureProxyAndAuth(proxyServer, realm);
} catch (AuthenticationException e) {
throw new IOException(e.getMessage());
}
}
HttpURLConnection urlConnection = null;
if (proxy == null) {
urlConnection = (HttpURLConnection) AsyncHttpProviderUtils.createUri(request.getUrl()).toURL().openConnection();
} else {
urlConnection = (HttpURLConnection) AsyncHttpProviderUtils.createUri(request.getUrl()).toURL().openConnection(proxy);
}
if (request.getUrl().startsWith("https")) {
HttpsURLConnection secure = (HttpsURLConnection) urlConnection;
SSLContext sslContext = config.getSSLContext();
if (sslContext == null) {
try {
sslContext = SslUtils.getSSLContext();
} catch (NoSuchAlgorithmException e) {
throw new IOException(e.getMessage());
} catch (GeneralSecurityException e) {
throw new IOException(e.getMessage());
}
}
secure.setSSLSocketFactory(sslContext.getSocketFactory());
secure.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
}
return urlConnection;
}
public void close() {
isClose.set(true);
}
public Response prepareResponse(HttpResponseStatus status, HttpResponseHeaders headers, Collection<HttpResponseBodyPart> bodyParts) {
return new JDKResponse(status, headers, bodyParts);
}
private final class AsyncHttpUrlConnection<T> implements Callable<T> {
private HttpURLConnection urlConnection;
private Request request;
private final AsyncHandler<T> asyncHandler;
private final FutureImpl<T> future;
private int currentRedirectCount;
private AtomicBoolean isAuth = new AtomicBoolean(false);
private byte[] cachedBytes;
private int cachedBytesLenght;
private boolean terminate = true;
public AsyncHttpUrlConnection(HttpURLConnection urlConnection, Request request, AsyncHandler<T> asyncHandler, FutureImpl<T> future) {
this.urlConnection = urlConnection;
this.request = request;
this.asyncHandler = asyncHandler;
this.future = future;
this.request = request;
}
public T call() throws Exception {
AsyncHandler.STATE state = AsyncHandler.STATE.ABORT;
try {
URI uri = null;
// Encoding with URLConnection is a bit bogus so we need to try both way before setting it
try {
uri = AsyncHttpProviderUtils.createUri(request.getRawUrl());
} catch (IllegalArgumentException u) {
uri = AsyncHttpProviderUtils.createUri(request.getUrl());
}
configure(uri, urlConnection, request);
urlConnection.connect();
int statusCode = urlConnection.getResponseCode();
logger.debug("\n\nRequest {}\n\nResponse {}\n", request, statusCode);
ResponseStatus status = new ResponseStatus(uri, urlConnection, JDKAsyncHttpProvider.this);
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(asyncHandler).request(request).responseStatus(status).build();
for (ResponseFilter asyncFilter : config.getResponseFilters()) {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
}
// The request has changed
if (fc.replayRequest()) {
request = fc.getRequest();
urlConnection = createUrlConnection(request);
terminate = false;
return call();
}
boolean redirectEnabled = (request.isRedirectEnabled() || config.isRedirectEnabled());
if (redirectEnabled && (statusCode == 302 || statusCode == 301)) {
if (currentRedirectCount++ < config.getMaxRedirects()) {
String location = urlConnection.getHeaderField("Location");
URI redirUri = AsyncHttpProviderUtils.getRedirectUri(uri, location);
String newUrl = redirUri.toString();
if (!newUrl.equals(uri.toString())) {
RequestBuilder builder = new RequestBuilder(request);
logger.debug("Redirecting to {}", newUrl);
request = builder.setUrl(newUrl).build();
urlConnection = createUrlConnection(request);
terminate = false;
return call();
}
} else {
throw new MaxRedirectException("Maximum redirect reached: " + config.getMaxRedirects());
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (statusCode == 401 && !isAuth.getAndSet(true) && realm != null ) {
String wwwAuth = urlConnection.getHeaderField("WWW-Authenticate");
logger.debug("Sending authentication to {}", request.getUrl());
Realm nr = new Realm.RealmBuilder().clone(realm)
.parseWWWAuthenticateHeader(wwwAuth)
.setUri(URI.create(request.getUrl()).getPath())
.setMethodName(request.getMethod())
.setScheme(realm.getAuthScheme())
.setUsePreemptiveAuth(true)
.build();
RequestBuilder builder = new RequestBuilder(request);
request = builder.setRealm(nr).build();
urlConnection = createUrlConnection(request);
terminate = false;
return call();
}
state = asyncHandler.onStatusReceived(status);
if (state == AsyncHandler.STATE.CONTINUE) {
state = asyncHandler.onHeadersReceived(new ResponseHeaders(uri, urlConnection, JDKAsyncHttpProvider.this));
}
if (state == AsyncHandler.STATE.CONTINUE) {
InputStream is = getInputStream(urlConnection);
String contentEncoding = urlConnection.getHeaderField("Content-Encoding");
boolean isGZipped = contentEncoding == null ? false : "gzip".equalsIgnoreCase(contentEncoding);
if (isGZipped) {
is = new GZIPInputStream(is);
}
int byteToRead = urlConnection.getContentLength();
InputStream stream = is;
if (byteToRead <= 0) {
int[] lengthWrapper = new int[1];
byte[] bytes = AsyncHttpProviderUtils.readFully(is, lengthWrapper);
stream = new ByteArrayInputStream(bytes, 0, lengthWrapper[0]);
byteToRead = lengthWrapper[0];
}
if (byteToRead > 0) {
int minBytes = Math.min(8192, byteToRead);
byte[] bytes = new byte[minBytes];
int leftBytes = minBytes < 8192 ? 0 : byteToRead;
int read = 0;
while (leftBytes > -1) {
read = stream.read(bytes);
if (read == -1) {
break;
}
future.touch();
byte[] b = new byte[read];
System.arraycopy(bytes, 0, b, 0, read);
asyncHandler.onBodyPartReceived(new ResponseBodyPart(uri, b, JDKAsyncHttpProvider.this));
leftBytes -= read;
}
}
}
if (ProgressAsyncHandler.class.isAssignableFrom(asyncHandler.getClass())) {
ProgressAsyncHandler.class.cast(asyncHandler).onHeaderWriteCompleted();
ProgressAsyncHandler.class.cast(asyncHandler).onContentWriteCompleted();
}
try {
T t = asyncHandler.onCompleted();
future.content(t);
future.done(null);
return t;
} catch (Throwable t) {
RuntimeException ex = new RuntimeException();
ex.initCause(t);
throw ex;
}
} catch (Throwable t) {
logger.debug(t.getMessage(), t);
if (IOException.class.isAssignableFrom(t.getClass()) && config.getIOExceptionFilters().size() > 0) {
FilterContext fc = new FilterContext.FilterContextBuilder().asyncHandler(asyncHandler)
.request(request).ioException(IOException.class.cast(t)).build();
try {
fc = handleIoException(fc);
} catch (FilterException e) {
if (config.getMaxTotalConnections() != -1) {
maxConnections.decrementAndGet();
}
future.done(null);
}
if (fc.replayRequest()) {
request = fc.getRequest();
urlConnection = createUrlConnection(request);
return call();
}
}
try {
future.abort(filterException(t));
} catch (Throwable t2) {
logger.error(t2.getMessage(), t2);
}
} finally {
if (terminate) {
if (config.getMaxTotalConnections() != -1) {
maxConnections.decrementAndGet();
}
urlConnection.disconnect();
if (jdkNtlmDomain != null) {
System.setProperty(NTLM_DOMAIN, jdkNtlmDomain);
}
Authenticator.setDefault(jdkAuthenticator);
}
}
return null;
}
private FilterContext handleIoException(FilterContext fc) throws FilterException {
for (IOExceptionFilter asyncFilter : config.getIOExceptionFilters()) {
fc = asyncFilter.filter(fc);
if (fc == null) {
throw new NullPointerException("FilterContext is null");
}
}
return fc;
}
private Throwable filterException(Throwable t) {
if (UnknownHostException.class.isAssignableFrom(t.getClass())) {
t = new ConnectException(t.getMessage());
}
if (SocketTimeoutException.class.isAssignableFrom(t.getClass())) {
int responseTimeoutInMs = config.getRequestTimeoutInMs();
if (request.getPerRequestConfig() != null && request.getPerRequestConfig().getRequestTimeoutInMs() != -1) {
responseTimeoutInMs = request.getPerRequestConfig().getRequestTimeoutInMs();
}
t = new TimeoutException(String.format("No response received after %s", responseTimeoutInMs));
}
if (SSLHandshakeException.class.isAssignableFrom(t.getClass())) {
Throwable t2 = new ConnectException();
t2.initCause(t);
t = t2;
}
return t;
}
private void configure(URI uri, HttpURLConnection urlConnection, Request request) throws IOException, AuthenticationException {
PerRequestConfig conf = request.getPerRequestConfig();
int requestTimeout = (conf != null && conf.getRequestTimeoutInMs() != 0) ?
conf.getRequestTimeoutInMs() : config.getRequestTimeoutInMs();
urlConnection.setConnectTimeout(config.getConnectionTimeoutInMs());
if (requestTimeout != -1)
urlConnection.setReadTimeout(requestTimeout);
urlConnection.setInstanceFollowRedirects(false);
String host = uri.getHost();
String method = request.getMethod();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
if (uri.getPort() == -1) {
urlConnection.setRequestProperty("Host", host);
} else {
urlConnection.setRequestProperty("Host", host + ":" + uri.getPort());
}
if (config.isCompressionEnabled()) {
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
}
boolean contentTypeSet = false;
if (!method.equalsIgnoreCase("CONNECT")) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
urlConnection.setRequestProperty(name, value);
if (name.equalsIgnoreCase("Expect")) {
throw new IllegalStateException("Expect: 100-Continue not supported");
}
}
}
}
}
}
String ka = config.getAllowPoolingConnection() ? "keep-alive" : "close";
urlConnection.setRequestProperty("Connection", ka);
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
if (proxyServer != null) {
urlConnection.setRequestProperty("Proxy-Connection", ka);
if (proxyServer.getPrincipal() != null) {
urlConnection.setRequestProperty("Proxy-Authorization", AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth() ) {
switch (realm.getAuthScheme()) {
case BASIC:
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
jdkNtlmDomain = System.getProperty(NTLM_DOMAIN);
System.setProperty(NTLM_DOMAIN, realm.getDomain());
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
urlConnection.setRequestProperty("Accept", "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
urlConnection.setRequestProperty("User-Agent", config.getUserAgent());
} else {
urlConnection.setRequestProperty("User-Agent", AsyncHttpProviderUtils.constructUserAgent(JDKAsyncHttpProvider.class));
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
urlConnection.setRequestProperty("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
}
String reqType = request.getMethod();
urlConnection.setRequestMethod(reqType);
if ("POST".equals(reqType) || "PUT".equals(reqType)) {
urlConnection.setRequestProperty("Content-Length", "0");
urlConnection.setDoOutput(true);
//urlConnection.setChunkedStreamingMode(0);
if (cachedBytes != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getByteData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getByteData().length));
urlConnection.setFixedLengthStreamingMode(request.getByteData().length);
urlConnection.getOutputStream().write(request.getByteData());
} else if (request.getStringData() != null) {
+ if (!request.getHeaders().containsKey("Content-Type")) {
+ urlConnection.setRequestProperty("Content-Type", "text/html;charset=ISO-8859-1");
+ }
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getStringData().length()));
- byte[] b = request.getStringData().getBytes("UTF-8");
- urlConnection.setFixedLengthStreamingMode(b.length);
+ byte[] b = request.getStringData().getBytes("ISO-8859-1");
+ //urlConnection.setFixedLengthStreamingMode(b.length);
urlConnection.getOutputStream().write(b);
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
cachedBytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
cachedBytesLenght = lengthWrapper[0];
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(sb.length()));
urlConnection.setFixedLengthStreamingMode(sb.length());
if (!request.getHeaders().containsKey("Content-Type")) {
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
urlConnection.getOutputStream().write(sb.toString().getBytes("ISO-8859-1"));
} else if (request.getParts() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
urlConnection.setRequestProperty("Content-Type", mre.getContentType());
urlConnection.setRequestProperty("Content-Length", String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(urlConnection.getOutputStream());
} else if (request.getEntityWriter() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
request.getEntityWriter().writeEntity(urlConnection.getOutputStream());
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format(Thread.currentThread()
+ "File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(file.length()));
urlConnection.setFixedLengthStreamingMode((int) file.length());
FileInputStream fis = new FileInputStream(file);
try {
OutputStream os = urlConnection.getOutputStream();
for (final byte[] buffer = new byte[1024 * 16];;) {
int read = fis.read(buffer);
if (read < 0) {
break;
}
os.write(buffer, 0, read);
}
} finally {
fis.close();
}
} else if (request.getBodyGenerator() != null) {
Body body = request.getBodyGenerator().createBody();
try {
int length = (int) body.getContentLength();
if (length < 0) {
length = (int) request.getLength();
}
if (length >= 0) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(length));
urlConnection.setFixedLengthStreamingMode(length);
}
OutputStream os = urlConnection.getOutputStream();
for (ByteBuffer buffer = ByteBuffer.allocate( 1024 * 8 );;) {
buffer.clear();
if (body.read(buffer) < 0) {
break;
}
os.write( buffer.array(), buffer.arrayOffset(), buffer.position() );
}
} finally {
try {
body.close();
} catch (IOException e) {
logger.warn("Failed to close request body: {}", e.getMessage(), e);
}
}
}
}
}
}
private Proxy configureProxyAndAuth(final ProxyServer proxyServer, final Realm realm) throws AuthenticationException {
Proxy proxy = null;
if (proxyServer != null) {
String proxyHost = proxyServer.getHost().startsWith("http://")
? proxyServer.getHost().substring("http://".length()) : proxyServer.getHost();
SocketAddress addr = new InetSocketAddress(proxyHost, proxyServer.getPort());
proxy = new Proxy(Proxy.Type.HTTP, addr);
}
final boolean hasProxy = (proxyServer != null && proxyServer.getPrincipal() != null);
final boolean hasAuthentication = (realm != null && realm.getPrincipal() != null);
if (hasProxy || hasAuthentication) {
Field f = null;
try {
f = Authenticator.class.getDeclaredField("theAuthenticator");
f.setAccessible(true);
jdkAuthenticator = (Authenticator) f.get(Authenticator.class);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
if (hasProxy && getRequestingHost().equals(proxyServer.getHost())
&& getRequestingPort() == proxyServer.getPort()) {
String password = "";
if (proxyServer.getPassword() != null) {
password = proxyServer.getPassword();
}
return new PasswordAuthentication(proxyServer.getPrincipal(), password.toCharArray());
}
if (hasAuthentication) {
return new PasswordAuthentication(realm.getPrincipal(), realm.getPassword().toCharArray());
}
return super.getPasswordAuthentication();
}
});
} else {
Authenticator.setDefault(null);
}
return proxy;
}
private InputStream getInputStream(HttpURLConnection urlConnection) throws IOException {
if (urlConnection.getResponseCode() < 400) {
return urlConnection.getInputStream();
} else {
InputStream ein = urlConnection.getErrorStream();
return (ein != null)
? ein : new ByteArrayInputStream(new byte[0]);
}
}
}
| false | true | private void configure(URI uri, HttpURLConnection urlConnection, Request request) throws IOException, AuthenticationException {
PerRequestConfig conf = request.getPerRequestConfig();
int requestTimeout = (conf != null && conf.getRequestTimeoutInMs() != 0) ?
conf.getRequestTimeoutInMs() : config.getRequestTimeoutInMs();
urlConnection.setConnectTimeout(config.getConnectionTimeoutInMs());
if (requestTimeout != -1)
urlConnection.setReadTimeout(requestTimeout);
urlConnection.setInstanceFollowRedirects(false);
String host = uri.getHost();
String method = request.getMethod();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
if (uri.getPort() == -1) {
urlConnection.setRequestProperty("Host", host);
} else {
urlConnection.setRequestProperty("Host", host + ":" + uri.getPort());
}
if (config.isCompressionEnabled()) {
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
}
boolean contentTypeSet = false;
if (!method.equalsIgnoreCase("CONNECT")) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
urlConnection.setRequestProperty(name, value);
if (name.equalsIgnoreCase("Expect")) {
throw new IllegalStateException("Expect: 100-Continue not supported");
}
}
}
}
}
}
String ka = config.getAllowPoolingConnection() ? "keep-alive" : "close";
urlConnection.setRequestProperty("Connection", ka);
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
if (proxyServer != null) {
urlConnection.setRequestProperty("Proxy-Connection", ka);
if (proxyServer.getPrincipal() != null) {
urlConnection.setRequestProperty("Proxy-Authorization", AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth() ) {
switch (realm.getAuthScheme()) {
case BASIC:
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
jdkNtlmDomain = System.getProperty(NTLM_DOMAIN);
System.setProperty(NTLM_DOMAIN, realm.getDomain());
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
urlConnection.setRequestProperty("Accept", "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
urlConnection.setRequestProperty("User-Agent", config.getUserAgent());
} else {
urlConnection.setRequestProperty("User-Agent", AsyncHttpProviderUtils.constructUserAgent(JDKAsyncHttpProvider.class));
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
urlConnection.setRequestProperty("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
}
String reqType = request.getMethod();
urlConnection.setRequestMethod(reqType);
if ("POST".equals(reqType) || "PUT".equals(reqType)) {
urlConnection.setRequestProperty("Content-Length", "0");
urlConnection.setDoOutput(true);
//urlConnection.setChunkedStreamingMode(0);
if (cachedBytes != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getByteData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getByteData().length));
urlConnection.setFixedLengthStreamingMode(request.getByteData().length);
urlConnection.getOutputStream().write(request.getByteData());
} else if (request.getStringData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getStringData().length()));
byte[] b = request.getStringData().getBytes("UTF-8");
urlConnection.setFixedLengthStreamingMode(b.length);
urlConnection.getOutputStream().write(b);
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
cachedBytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
cachedBytesLenght = lengthWrapper[0];
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(sb.length()));
urlConnection.setFixedLengthStreamingMode(sb.length());
if (!request.getHeaders().containsKey("Content-Type")) {
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
urlConnection.getOutputStream().write(sb.toString().getBytes("ISO-8859-1"));
} else if (request.getParts() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
urlConnection.setRequestProperty("Content-Type", mre.getContentType());
urlConnection.setRequestProperty("Content-Length", String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(urlConnection.getOutputStream());
} else if (request.getEntityWriter() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
request.getEntityWriter().writeEntity(urlConnection.getOutputStream());
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format(Thread.currentThread()
+ "File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(file.length()));
urlConnection.setFixedLengthStreamingMode((int) file.length());
FileInputStream fis = new FileInputStream(file);
try {
OutputStream os = urlConnection.getOutputStream();
for (final byte[] buffer = new byte[1024 * 16];;) {
int read = fis.read(buffer);
if (read < 0) {
break;
}
os.write(buffer, 0, read);
}
} finally {
fis.close();
}
} else if (request.getBodyGenerator() != null) {
Body body = request.getBodyGenerator().createBody();
try {
int length = (int) body.getContentLength();
if (length < 0) {
length = (int) request.getLength();
}
if (length >= 0) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(length));
urlConnection.setFixedLengthStreamingMode(length);
}
OutputStream os = urlConnection.getOutputStream();
for (ByteBuffer buffer = ByteBuffer.allocate( 1024 * 8 );;) {
buffer.clear();
if (body.read(buffer) < 0) {
break;
}
os.write( buffer.array(), buffer.arrayOffset(), buffer.position() );
}
} finally {
try {
body.close();
} catch (IOException e) {
logger.warn("Failed to close request body: {}", e.getMessage(), e);
}
}
}
}
}
| private void configure(URI uri, HttpURLConnection urlConnection, Request request) throws IOException, AuthenticationException {
PerRequestConfig conf = request.getPerRequestConfig();
int requestTimeout = (conf != null && conf.getRequestTimeoutInMs() != 0) ?
conf.getRequestTimeoutInMs() : config.getRequestTimeoutInMs();
urlConnection.setConnectTimeout(config.getConnectionTimeoutInMs());
if (requestTimeout != -1)
urlConnection.setReadTimeout(requestTimeout);
urlConnection.setInstanceFollowRedirects(false);
String host = uri.getHost();
String method = request.getMethod();
if (request.getVirtualHost() != null) {
host = request.getVirtualHost();
}
if (uri.getPort() == -1) {
urlConnection.setRequestProperty("Host", host);
} else {
urlConnection.setRequestProperty("Host", host + ":" + uri.getPort());
}
if (config.isCompressionEnabled()) {
urlConnection.setRequestProperty("Accept-Encoding", "gzip");
}
boolean contentTypeSet = false;
if (!method.equalsIgnoreCase("CONNECT")) {
FluentCaseInsensitiveStringsMap h = request.getHeaders();
if (h != null) {
for (String name : h.keySet()) {
if (!"host".equalsIgnoreCase(name)) {
for (String value : h.get(name)) {
urlConnection.setRequestProperty(name, value);
if (name.equalsIgnoreCase("Expect")) {
throw new IllegalStateException("Expect: 100-Continue not supported");
}
}
}
}
}
}
String ka = config.getAllowPoolingConnection() ? "keep-alive" : "close";
urlConnection.setRequestProperty("Connection", ka);
ProxyServer proxyServer = request.getProxyServer() != null ? request.getProxyServer() : config.getProxyServer();
if (proxyServer != null) {
urlConnection.setRequestProperty("Proxy-Connection", ka);
if (proxyServer.getPrincipal() != null) {
urlConnection.setRequestProperty("Proxy-Authorization", AuthenticatorUtils.computeBasicAuthentication(proxyServer));
}
}
Realm realm = request.getRealm() != null ? request.getRealm() : config.getRealm();
if (realm != null && realm.getUsePreemptiveAuth() ) {
switch (realm.getAuthScheme()) {
case BASIC:
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeBasicAuthentication(realm));
break;
case DIGEST:
if (realm.getNonce() != null && !realm.getNonce().equals("")) {
try {
urlConnection.setRequestProperty("Authorization",
AuthenticatorUtils.computeDigestAuthentication(realm));
} catch (NoSuchAlgorithmException e) {
throw new SecurityException(e);
}
}
break;
case NTLM:
jdkNtlmDomain = System.getProperty(NTLM_DOMAIN);
System.setProperty(NTLM_DOMAIN, realm.getDomain());
break;
default:
throw new IllegalStateException(String.format("Invalid Authentication %s", realm.toString()));
}
}
// Add default accept headers.
if (request.getHeaders().getFirstValue("Accept") == null) {
urlConnection.setRequestProperty("Accept", "*/*");
}
if (request.getHeaders().getFirstValue("User-Agent") == null && config.getUserAgent() != null) {
urlConnection.setRequestProperty("User-Agent", config.getUserAgent());
} else {
urlConnection.setRequestProperty("User-Agent", AsyncHttpProviderUtils.constructUserAgent(JDKAsyncHttpProvider.class));
}
if (request.getCookies() != null && !request.getCookies().isEmpty()) {
urlConnection.setRequestProperty("Cookie", AsyncHttpProviderUtils.encodeCookies(request.getCookies()));
}
String reqType = request.getMethod();
urlConnection.setRequestMethod(reqType);
if ("POST".equals(reqType) || "PUT".equals(reqType)) {
urlConnection.setRequestProperty("Content-Length", "0");
urlConnection.setDoOutput(true);
//urlConnection.setChunkedStreamingMode(0);
if (cachedBytes != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getByteData() != null) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getByteData().length));
urlConnection.setFixedLengthStreamingMode(request.getByteData().length);
urlConnection.getOutputStream().write(request.getByteData());
} else if (request.getStringData() != null) {
if (!request.getHeaders().containsKey("Content-Type")) {
urlConnection.setRequestProperty("Content-Type", "text/html;charset=ISO-8859-1");
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(request.getStringData().length()));
byte[] b = request.getStringData().getBytes("ISO-8859-1");
//urlConnection.setFixedLengthStreamingMode(b.length);
urlConnection.getOutputStream().write(b);
} else if (request.getStreamData() != null) {
int[] lengthWrapper = new int[1];
cachedBytes = AsyncHttpProviderUtils.readFully(request.getStreamData(), lengthWrapper);
cachedBytesLenght = lengthWrapper[0];
urlConnection.setRequestProperty("Content-Length", String.valueOf(cachedBytesLenght));
urlConnection.setFixedLengthStreamingMode(cachedBytesLenght);
urlConnection.getOutputStream().write(cachedBytes, 0, cachedBytesLenght);
} else if (request.getParams() != null) {
StringBuilder sb = new StringBuilder();
for (final Map.Entry<String, List<String>> paramEntry : request.getParams()) {
final String key = paramEntry.getKey();
for (final String value : paramEntry.getValue()) {
if (sb.length() > 0) {
sb.append("&");
}
UTF8UrlEncoder.appendEncoded(sb, key);
sb.append("=");
UTF8UrlEncoder.appendEncoded(sb, value);
}
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(sb.length()));
urlConnection.setFixedLengthStreamingMode(sb.length());
if (!request.getHeaders().containsKey("Content-Type")) {
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
}
urlConnection.getOutputStream().write(sb.toString().getBytes("ISO-8859-1"));
} else if (request.getParts() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
if (lenght == -1) {
lenght = MAX_BUFFERED_BYTES;
}
MultipartRequestEntity mre = AsyncHttpProviderUtils.createMultipartRequestEntity(request.getParts(), request.getParams());
urlConnection.setRequestProperty("Content-Type", mre.getContentType());
urlConnection.setRequestProperty("Content-Length", String.valueOf(mre.getContentLength()));
ChannelBuffer b = ChannelBuffers.dynamicBuffer(lenght);
mre.writeRequest(urlConnection.getOutputStream());
} else if (request.getEntityWriter() != null) {
int lenght = (int) request.getLength();
if (lenght != -1) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(lenght));
urlConnection.setFixedLengthStreamingMode(lenght);
}
request.getEntityWriter().writeEntity(urlConnection.getOutputStream());
} else if (request.getFile() != null) {
File file = request.getFile();
if (!file.isFile()) {
throw new IOException(String.format(Thread.currentThread()
+ "File %s is not a file or doesn't exist", file.getAbsolutePath()));
}
urlConnection.setRequestProperty("Content-Length", String.valueOf(file.length()));
urlConnection.setFixedLengthStreamingMode((int) file.length());
FileInputStream fis = new FileInputStream(file);
try {
OutputStream os = urlConnection.getOutputStream();
for (final byte[] buffer = new byte[1024 * 16];;) {
int read = fis.read(buffer);
if (read < 0) {
break;
}
os.write(buffer, 0, read);
}
} finally {
fis.close();
}
} else if (request.getBodyGenerator() != null) {
Body body = request.getBodyGenerator().createBody();
try {
int length = (int) body.getContentLength();
if (length < 0) {
length = (int) request.getLength();
}
if (length >= 0) {
urlConnection.setRequestProperty("Content-Length", String.valueOf(length));
urlConnection.setFixedLengthStreamingMode(length);
}
OutputStream os = urlConnection.getOutputStream();
for (ByteBuffer buffer = ByteBuffer.allocate( 1024 * 8 );;) {
buffer.clear();
if (body.read(buffer) < 0) {
break;
}
os.write( buffer.array(), buffer.arrayOffset(), buffer.position() );
}
} finally {
try {
body.close();
} catch (IOException e) {
logger.warn("Failed to close request body: {}", e.getMessage(), e);
}
}
}
}
}
|
diff --git a/beans/src/main/java/org/sola/clients/beans/administrative/LeaseReportBean.java b/beans/src/main/java/org/sola/clients/beans/administrative/LeaseReportBean.java
index 49789807..d72d4ce7 100644
--- a/beans/src/main/java/org/sola/clients/beans/administrative/LeaseReportBean.java
+++ b/beans/src/main/java/org/sola/clients/beans/administrative/LeaseReportBean.java
@@ -1,508 +1,508 @@
/**
* ******************************************************************************************
* Copyright (c) 2013 Food and Agriculture Organization of the United Nations (FAO)
* and the Lesotho Land Administration Authority (LAA). All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,this list
* of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,this list
* of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* 3. Neither the names of FAO, the LAA nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,STRICT LIABILITY,OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *********************************************************************************************
*/
package org.sola.clients.beans.administrative;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.sola.clients.beans.AbstractBindingBean;
import org.sola.clients.beans.application.ApplicationBean;
import org.sola.clients.beans.application.ApplicationServiceBean;
import org.sola.clients.beans.cadastre.CadastreObjectBean;
import org.sola.clients.beans.party.PartyBean;
import org.sola.common.DateUtility;
import org.sola.common.NumberToWords;
import org.sola.common.StringUtility;
/**
* Provides data to be used for generating reports.
*/
public class LeaseReportBean extends AbstractBindingBean {
private ApplicationBean application;
private ApplicationServiceBean service;
private RrrBean lease;
private String freeText;
private CadastreObjectBean cadastreObject;
/**
* Default constructor.
*/
public LeaseReportBean() {
super();
}
/**
* Class constructor with initial values for BaUnit, RRR, Application and
* ApplicationService object.
*/
public LeaseReportBean(RrrBean lease, CadastreObjectBean cadastreObject, ApplicationBean application, ApplicationServiceBean service) {
super();
this.lease = lease;
this.cadastreObject = cadastreObject;
this.application = application;
this.service = service;
}
public String getFreeText() {
if (freeText == null) {
freeText = "";
}
return freeText;
}
public void setFreeText(String freeText) {
if (freeText == null) {
freeText = "";
}
this.freeText = freeText;
}
public RrrBean getLease() {
if (lease == null) {
lease = new RrrBean();
}
return lease;
}
public void setLease(RrrBean lease) {
if (lease == null) {
lease = new RrrBean();
}
this.lease = lease;
}
public CadastreObjectBean getCadastreObject() {
if (cadastreObject == null) {
cadastreObject = new CadastreObjectBean();
}
return cadastreObject;
}
public void setCadastreObject(CadastreObjectBean cadastreObject) {
this.cadastreObject = cadastreObject;
}
public ApplicationBean getApplication() {
if (application == null) {
application = new ApplicationBean();
}
return application;
}
public void setApplication(ApplicationBean application) {
if (application == null) {
application = new ApplicationBean();
}
this.application = application;
}
public ApplicationServiceBean getService() {
if (service == null) {
service = new ApplicationServiceBean();
}
return service;
}
public void setService(ApplicationServiceBean service) {
if (service == null) {
service = new ApplicationServiceBean();
}
this.service = service;
}
/**
* Shortcut for application number.
*/
public String getApplicationNumber() {
return StringUtility.empty(getApplication().getApplicationNumberFormatted());
}
/**
* Shortcut for application date, converted to string.
*/
public String getApplicationDate() {
return DateUtility.getShortDateString(getApplication().getLodgingDatetime(), true);
}
/**
* Shortcut for applicant's full name.
*/
public String getApplicantName() {
if (getApplication().getContactPerson() != null && getApplication().getContactPerson().getFullName() != null) {
return getApplication().getContactPerson().getFullName();
}
return "";
}
/**
* Returns total payment for the lease including service fee, stamp duty,
* remaining ground rent and registration fee.
*/
public String getTotalLeaseFee(){
BigDecimal serviceFee = BigDecimal.ZERO;
BigDecimal regFee = BigDecimal.ZERO;
BigDecimal stampDuty = BigDecimal.ZERO;
BigDecimal remGroundRent = BigDecimal.valueOf(getLease().getGroundRentRemaining());
- if(getService()!=null && getService().getServiceFee()!=null){
- serviceFee = getService().getServiceFee();
+ if(getService()!=null && getLease().getServiceFee()!=null){
+ serviceFee = getLease().getServiceFee();
}
if(getLease()!=null && getLease().getRegistrationFee()!=null){
regFee = getLease().getRegistrationFee();
}
if(getLease()!=null && getLease().getStampDuty()!=null){
stampDuty = getLease().getStampDuty();
}
BigDecimal totalFee = serviceFee.add(regFee).add(stampDuty).add(remGroundRent);
if(totalFee.compareTo(BigDecimal.ZERO)!=0){
return "M " + totalFee.setScale(2, RoundingMode.HALF_UP).toPlainString();
} else {
return "NIL";
}
}
/** Shortcut to the service fee. */
public String getServiceFee(){
if(getService()!=null && getLease().getServiceFee()!=null){
return "M " + getLease().getServiceFee().setScale(2, RoundingMode.HALF_UP).toPlainString();
}
return "NIL";
}
/** Shortcut to the registration fee. */
public String getRegistrationFee(){
if(getLease()!=null && getLease().getRegistrationFee()!=null){
return "M " + getLease().getRegistrationFee().setScale(2, RoundingMode.HALF_UP).toPlainString();
}
return "NIL";
}
/** Shortcut to stamp duty. */
public String getStampDuty(){
if(getLease()!=null && getLease().getStampDuty()!=null){
return "M " + getLease().getStampDuty().setScale(2, RoundingMode.HALF_UP).toPlainString();
}
return "NIL";
}
/**
* Shortcut for the ground rent.
*/
public String getGroundRent() {
if (getLease().getGroundRent() != null && getLease().getGroundRent().compareTo(BigDecimal.ZERO) > 0) {
return "M " + getLease().getGroundRent().setScale(2, RoundingMode.HALF_UP).toPlainString();
} else {
return "NIL";
}
}
/**
* Calculated remaining ground rent.
*/
public String getGroundRentRemaining() {
if (getLease().getGroundRentRemaining() > 0) {
return "M " + String.valueOf(getLease().getGroundRentRemaining());
} else {
return "NIL";
}
}
/**
* Shortcut for service name.
*/
public String getServiceName() {
if (getService() != null && getService().getRequestType() != null
&& getService().getRequestType().getDisplayValue() != null) {
return getService().getRequestType().getDisplayValue();
}
return "";
}
/**
* Shortcut for the parcel first/last name parts.
*/
public String getParcelCode() {
if (getCadastreObject() != null) {
return getCadastreObject().toString();
}
return "";
}
/**
* Shortcut for the parcel type.
*/
public String getParcelType() {
if (getCadastreObject() != null) {
if (getCadastreObject().getCadastreObjectType() != null) {
return getCadastreObject().getCadastreObjectType().toString();
}
}
return "";
}
/**
* Shortcut for the parcel official area.
*/
public String getParcelOfficialArea() {
if (getCadastreObject() != null) {
if (getCadastreObject().getOfficialAreaSize() != null) {
return getCadastreObject().getOfficialAreaSize().toPlainString();
}
}
return "";
}
/**
* Shortcut for the parcel land use.
*/
public String getParcelLandUse() {
if (getLease().getLandUseType() != null) {
return getLease().getLandUseType().getDisplayValue().toUpperCase();
}
return "";
}
/**
* Shortcut for the parcel address.
*/
public String getParcelAddress() {
if (getCadastreObject() != null) {
return getCadastreObject().getAddressString().toUpperCase();
}
return "";
}
/**
* Shortcut for the first parcel map reference number.
*/
public String getParcelMapRef() {
if (getCadastreObject() != null && getCadastreObject().getSourceReference() != null) {
return getCadastreObject().getSourceReference();
}
return "";
}
/**
* Shortcut for the lease registration number.
*/
public String getLeaseRegistrationNumber() {
if (getLease().getLeaseNumber() != null) {
return getLease().getLeaseNumber();
}
return "";
}
/**
* Shortcut for the lease execution date in MEDIUM format without time.
*/
public String getLeaseExecutionDate() {
return DateUtility.getMediumDateString(getLease().getExecutionDate(), false);
}
/**
* Shortcut for the lease execution day.
*/
public String getLeaseExecutionDay() {
if (getLease().getExecutionDate() == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(getLease().getExecutionDate());
return String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
}
/**
* Shortcut for the lease execution year and month.
*/
public String getLeaseExecutionMonthAndYear() {
if (getLease().getExecutionDate() == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(getLease().getExecutionDate());
return new SimpleDateFormat("MMMMM").format(cal.getTime()) + " " + String.valueOf(cal.get(Calendar.YEAR));
}
/**
* Shortcut for the lease expiration date in MEDIUM format without time.
*/
public String getLeaseExpirationDate() {
return DateUtility.getMediumDateString(getLease().getExpirationDate(), false);
}
/**
* Shortcut for the lease expiration day.
*/
public String getLeaseExpirationDay() {
if (getLease().getExpirationDate() == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(getLease().getExpirationDate());
return String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
}
/**
* Shortcut for the lease expiration year and month.
*/
public String getLeaseExpirationMonthAndYear() {
if (getLease().getExpirationDate() == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(getLease().getExpirationDate());
return new SimpleDateFormat("MMMMM").format(cal.getTime()) + " " + String.valueOf(cal.get(Calendar.YEAR));
}
/**
* Shortcut for the lease start date in MEDIUM format without time.
*/
public String getLeaseStartDate() {
return DateUtility.getMediumDateString(getLease().getStartDate(), false);
}
/**
* Shortcut for the lease start day.
*/
public String getLeaseStartDay() {
if (getLease().getStartDate() == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(getLease().getStartDate());
return String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
}
/**
* Shortcut for the lease start year and month.
*/
public String getLeaseStartMonthAndYear() {
if (getLease().getStartDate() == null) {
return "";
}
Calendar cal = Calendar.getInstance();
cal.setTime(getLease().getStartDate());
return new SimpleDateFormat("MMMMM").format(cal.getTime()) + " " + String.valueOf(cal.get(Calendar.YEAR));
}
/**
* Shortcut to lessee address.
*/
public String getLesseeAddress() {
String address = "";
if (getLease().getRightHolderList().size() > 0) {
for (PartyBean party : getLease().getFilteredRightHolderList()) {
if (party.getAddress() != null && !StringUtility.empty(party.getAddress().getDescription()).equals("")) {
address = party.getAddress().getDescription();
break;
}
}
}
return address.toUpperCase();
}
/**
* Shortcut to lessees marital status.
*/
public String getLesseeMaritalStatus() {
String legalStatus = "";
if (getLease().getRightHolderList().size() > 0) {
for (PartyBean party : getLease().getFilteredRightHolderList()) {
if (!StringUtility.empty(party.getLegalType()).equals("")) {
legalStatus = party.getLegalType();
break;
}
}
}
return legalStatus.toUpperCase();
}
/**
* Shortcut to lessees names.
*/
public String getLessees() {
String lessess = "";
if (getLease().getFilteredRightHolderList() != null && getLease().getFilteredRightHolderList().size() > 0) {
for (PartyBean party : getLease().getFilteredRightHolderList()) {
if (lessess.equals("")) {
lessess = party.getFullName();
} else {
lessess = lessess + " AND " + party.getFullName();
}
}
}
return lessess.toUpperCase();
}
/**
* Returns true is lessee is private, otherwise false
*/
public boolean isLesseePrivate() {
boolean result = true;
if (getLease().getRightHolderList() != null && getLease().getRightHolderList().size() > 0) {
result = getLease().getRightHolderList().get(0).getTypeCode().equalsIgnoreCase("naturalPerson");
}
return result;
}
/**
* Shortcut to lessees and marital status.
*/
public String getLesseesAndMaritalStatus() {
String result = getLessees();
if (!result.equals("") && !getLesseeMaritalStatus().equals("")) {
result = result + " - " + getLesseeMaritalStatus();
}
return result;
}
/**
* Calculates and returns lease term in years.
*/
public String getLeaseTerm() {
return String.valueOf(getLease().getLeaseTerm());
}
/**
* Calculates and returns lease term in years transformed into words.
*/
public String getLeaseTermWord() {
NumberToWords.DefaultProcessor processor = new NumberToWords.DefaultProcessor();
return processor.getName(getLeaseTerm());
}
}
| true | true | public String getTotalLeaseFee(){
BigDecimal serviceFee = BigDecimal.ZERO;
BigDecimal regFee = BigDecimal.ZERO;
BigDecimal stampDuty = BigDecimal.ZERO;
BigDecimal remGroundRent = BigDecimal.valueOf(getLease().getGroundRentRemaining());
if(getService()!=null && getService().getServiceFee()!=null){
serviceFee = getService().getServiceFee();
}
if(getLease()!=null && getLease().getRegistrationFee()!=null){
regFee = getLease().getRegistrationFee();
}
if(getLease()!=null && getLease().getStampDuty()!=null){
stampDuty = getLease().getStampDuty();
}
BigDecimal totalFee = serviceFee.add(regFee).add(stampDuty).add(remGroundRent);
if(totalFee.compareTo(BigDecimal.ZERO)!=0){
return "M " + totalFee.setScale(2, RoundingMode.HALF_UP).toPlainString();
} else {
return "NIL";
}
}
| public String getTotalLeaseFee(){
BigDecimal serviceFee = BigDecimal.ZERO;
BigDecimal regFee = BigDecimal.ZERO;
BigDecimal stampDuty = BigDecimal.ZERO;
BigDecimal remGroundRent = BigDecimal.valueOf(getLease().getGroundRentRemaining());
if(getService()!=null && getLease().getServiceFee()!=null){
serviceFee = getLease().getServiceFee();
}
if(getLease()!=null && getLease().getRegistrationFee()!=null){
regFee = getLease().getRegistrationFee();
}
if(getLease()!=null && getLease().getStampDuty()!=null){
stampDuty = getLease().getStampDuty();
}
BigDecimal totalFee = serviceFee.add(regFee).add(stampDuty).add(remGroundRent);
if(totalFee.compareTo(BigDecimal.ZERO)!=0){
return "M " + totalFee.setScale(2, RoundingMode.HALF_UP).toPlainString();
} else {
return "NIL";
}
}
|
diff --git a/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/shortcut/Mwe2LaunchDelegate.java b/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/shortcut/Mwe2LaunchDelegate.java
index be35986e..4863a761 100644
--- a/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/shortcut/Mwe2LaunchDelegate.java
+++ b/plugins/org.eclipse.emf.mwe2.launch/src/org/eclipse/emf/mwe2/launch/shortcut/Mwe2LaunchDelegate.java
@@ -1,57 +1,62 @@
package org.eclipse.emf.mwe2.launch.shortcut;
import org.apache.log4j.Logger;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.debug.core.DebugEvent;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.IDebugEventSetListener;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jdt.launching.JavaLaunchDelegate;
public class Mwe2LaunchDelegate extends JavaLaunchDelegate {
private static final Logger logger = Logger.getLogger(Mwe2LaunchDelegate.class);
//Use RefreshUtil after switching to debug >= 3.6
private static final String ATTR_REFRESH_SCOPE = DebugPlugin.getUniqueIdentifier() + ".ATTR_REFRESH_SCOPE";
@Override
public void launch(final ILaunchConfiguration configuration, String mode,
ILaunch launch, IProgressMonitor monitor) throws CoreException {
if (configuration.getAttribute(ATTR_REFRESH_SCOPE, (String) null) != null) {
DebugPlugin.getDefault().addDebugEventListener(new IDebugEventSetListener() {
public void handleDebugEvents(DebugEvent[] events) {
for (int i = 0; i < events.length; i++) {
DebugEvent event = events[i];
if (event.getSource() instanceof IProcess && event.getKind() == DebugEvent.TERMINATE) {
IProcess process = (IProcess) event.getSource();
if (configuration == process.getLaunch().getLaunchConfiguration()) {
DebugPlugin.getDefault().removeDebugEventListener(this);
Job job = new Job(Messages.Mwe2LaunchDelegate_0) {
public IStatus run(IProgressMonitor monitor) {
try {
org.eclipse.debug.ui.RefreshTab.refreshResources(configuration, monitor);
} catch (CoreException e) {
logger.error(e.getMessage(), e);
- return e.getStatus();
+ return Status.OK_STATUS;
+ } catch (Throwable t){
+ // In eclipse headless mode there are normally any ui bundles,
+ // just ignore auto refresh
+ logger.error(t.getMessage(), t);
+ return Status.OK_STATUS;
}
return Status.OK_STATUS;
}
};
job.schedule();
return;
}
}
}
}
});
}
super.launch(configuration, mode, launch, monitor);
}
}
| true | true | public void launch(final ILaunchConfiguration configuration, String mode,
ILaunch launch, IProgressMonitor monitor) throws CoreException {
if (configuration.getAttribute(ATTR_REFRESH_SCOPE, (String) null) != null) {
DebugPlugin.getDefault().addDebugEventListener(new IDebugEventSetListener() {
public void handleDebugEvents(DebugEvent[] events) {
for (int i = 0; i < events.length; i++) {
DebugEvent event = events[i];
if (event.getSource() instanceof IProcess && event.getKind() == DebugEvent.TERMINATE) {
IProcess process = (IProcess) event.getSource();
if (configuration == process.getLaunch().getLaunchConfiguration()) {
DebugPlugin.getDefault().removeDebugEventListener(this);
Job job = new Job(Messages.Mwe2LaunchDelegate_0) {
public IStatus run(IProgressMonitor monitor) {
try {
org.eclipse.debug.ui.RefreshTab.refreshResources(configuration, monitor);
} catch (CoreException e) {
logger.error(e.getMessage(), e);
return e.getStatus();
}
return Status.OK_STATUS;
}
};
job.schedule();
return;
}
}
}
}
});
}
super.launch(configuration, mode, launch, monitor);
}
| public void launch(final ILaunchConfiguration configuration, String mode,
ILaunch launch, IProgressMonitor monitor) throws CoreException {
if (configuration.getAttribute(ATTR_REFRESH_SCOPE, (String) null) != null) {
DebugPlugin.getDefault().addDebugEventListener(new IDebugEventSetListener() {
public void handleDebugEvents(DebugEvent[] events) {
for (int i = 0; i < events.length; i++) {
DebugEvent event = events[i];
if (event.getSource() instanceof IProcess && event.getKind() == DebugEvent.TERMINATE) {
IProcess process = (IProcess) event.getSource();
if (configuration == process.getLaunch().getLaunchConfiguration()) {
DebugPlugin.getDefault().removeDebugEventListener(this);
Job job = new Job(Messages.Mwe2LaunchDelegate_0) {
public IStatus run(IProgressMonitor monitor) {
try {
org.eclipse.debug.ui.RefreshTab.refreshResources(configuration, monitor);
} catch (CoreException e) {
logger.error(e.getMessage(), e);
return Status.OK_STATUS;
} catch (Throwable t){
// In eclipse headless mode there are normally any ui bundles,
// just ignore auto refresh
logger.error(t.getMessage(), t);
return Status.OK_STATUS;
}
return Status.OK_STATUS;
}
};
job.schedule();
return;
}
}
}
}
});
}
super.launch(configuration, mode, launch, monitor);
}
|
diff --git a/src/org/odk/collect/android/activities/FormHierarchyActivity.java b/src/org/odk/collect/android/activities/FormHierarchyActivity.java
index 568917b..e4ee6d4 100644
--- a/src/org/odk/collect/android/activities/FormHierarchyActivity.java
+++ b/src/org/odk/collect/android/activities/FormHierarchyActivity.java
@@ -1,503 +1,503 @@
package org.odk.collect.android.activities;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import org.javarosa.core.model.FormDef;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.GroupDef;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.formmanager.view.FormElementBinding;
import org.odk.collect.android.R;
import org.odk.collect.android.adapters.HierarchyListAdapter;
import org.odk.collect.android.logic.FormHandler;
import org.odk.collect.android.logic.HierarchyElement;
import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
/**
*
* TODO: WARNING, this file is by no means complete, or correct for that matter.
* It is hacky attempt #1 to make a hierarchy viewer by stealing a bunch of
* things from formHandler. JavaRosa should give us better methods to accomplish
* this (and will in the future...fingers crossed) But until then, we're
* trying...
*
*/
public class FormHierarchyActivity extends ListActivity {
private static final String t = "FormHierarchyActivity";
FormDef mForm;
int state;
private static final int CHILD = 1;
private static final int EXPANDED = 2;
private static final int COLLAPSED = 3;
private static final int QUESTION = 4;
private final String mIndent = " -- ";
private Button mBackButton;
private FormIndex mCurrentIndex;
List<HierarchyElement> formList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hierarchy_layout);
// We'll use formhandler to set the CurrentIndex before returning to
// FormEntryActivity
FormHandler mFormHandler = FormEntryActivity.mFormHandler;
mForm = mFormHandler.getForm();
mCurrentIndex = mFormHandler.getIndex();
if (mCurrentIndex.isBeginningOfFormIndex()) {
// we always have to start on a valid formIndex
mCurrentIndex = mForm.incrementIndex(mCurrentIndex);
}
mBackButton = (Button) findViewById(R.id.backbutton);
mBackButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.e("carl", "clicked back");
mCurrentIndex = stepIndexOut(mCurrentIndex);
/*
* Log.e("carl", "mCurrentIndex = " + mCurrentIndex);
* Log.e("Carl", "local index = " +
* mCurrentIndex.getLocalIndex()); Log.e("carl",
* "instance index = " + mCurrentIndex.getInstanceIndex());
*/
if (mCurrentIndex == null || indexIsBeginning(mCurrentIndex)) {
mCurrentIndex = FormIndex.createBeginningOfFormIndex();
mCurrentIndex = mForm.incrementIndex(mCurrentIndex);
} else {
FormIndex levelTest = mCurrentIndex;
int level = 0;
while (levelTest.getNextLevel() != null) {
level++;
levelTest = levelTest.getNextLevel();
}
FormIndex tempIndex;
boolean done = false;
while (!done) {
Log.e("carl", "stepping in loop");
tempIndex = mCurrentIndex;
int i = 0;
while (tempIndex.getNextLevel() != null && i < level) {
Log.e("carl", "stepping in next level");
tempIndex = tempIndex.getNextLevel();
i++;
}
if (tempIndex.getLocalIndex() == 0) {
done = true;
} else {
mCurrentIndex = prevIndex(mCurrentIndex);
}
// Log.e("carl", "temp instance = " +
// tempIndex.getInstanceIndex());
}
Log.e("carl", "now showing : " + mCurrentIndex);
Log.e("Carl", "now shoing instance index = "
+ mCurrentIndex.getInstanceIndex());
}
refreshView();
// we've already stepped back...
// now we just have to refresh, I think
}
});
Button startButton = (Button) findViewById(R.id.startbutton);
startButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCurrentIndex = FormIndex.createBeginningOfFormIndex();
FormEntryActivity.mFormHandler.setFormIndex(mCurrentIndex);
finish();
}
});
Button endButton = (Button) findViewById(R.id.endbutton);
endButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCurrentIndex = FormIndex.createEndOfFormIndex();
FormEntryActivity.mFormHandler.setFormIndex(mCurrentIndex);
finish();
}
});
refreshView();
}
private boolean indexIsBeginning(FormIndex fi) {
String startTest = fi.toString();
int firstComma = startTest.indexOf(",");
Log.e("carl", "firstcomma found at " + firstComma);
int secondComma = startTest.indexOf(",", firstComma + 1);
Log.e("carl", "secondcomma found at " + secondComma);
boolean beginning = (secondComma == -1);
return beginning;
}
public void refreshView() {
formList = new ArrayList<HierarchyElement>();
FormIndex currentIndex = mCurrentIndex;
// would like to use this, but it's broken and changes the currentIndex
// TODO: fix in javarosa.
/*
* FormIndex startTest = stepIndexOut(currentIndex); Log.e("carl",
* "starttest = " + startTest); boolean beginning = (startTest == null);
*/
// begin hack around:
boolean beginning = indexIsBeginning(currentIndex);
// end hack around
String displayGroup = "";
int level = 0;
String repeatGroup = "-1";
Log.e("Carl", "just checking at beginnig " + currentIndex);
if (!beginning) {
FormIndex levelTest = currentIndex;
while (levelTest.getNextLevel() != null) {
level++;
levelTest = levelTest.getNextLevel();
}
Log.e("Carl", "level is: " + level);
boolean found = false;
while (!found) {
FormIndex localTest = currentIndex;
for (int i = 0; i < level; i++) {
localTest = localTest.getNextLevel();
- }
+ }
Log.e("carl", "localtest local = " + localTest.getLocalIndex()
+ " and instance = " + localTest.getInstanceIndex());
if (localTest.getLocalIndex() == 0)
found = true;
else
currentIndex = prevIndex(currentIndex);
}
// we're displaying only things only within a given group
FormIndex prevIndex = prevIndex(currentIndex);
Log.e("Carl", "local = " + prevIndex.getLocalIndex()
+ " and instance = " + prevIndex.getInstanceIndex());
displayGroup = mForm.getChildInstanceRef(prevIndex).toString(false);
Log.e("carl", "display group is: " + displayGroup);
mBackButton.setEnabled(true);
} else {
Log.e("carl", "at beginning");
currentIndex = FormIndex.createBeginningOfFormIndex();
currentIndex = nextRelevantIndex(currentIndex);
Log.e("carl", "index is now "
+ mForm.getChildInstanceRef(currentIndex).toString(false));
Log.e("carl", "index # is " + currentIndex);
mBackButton.setEnabled(false);
}
int repeatIndex = -1;
int groupCount = 1;
String repeatedGroupName = "";
while (!isEnd(currentIndex)) {
FormIndex normalizedLevel = currentIndex;
for (int i = 0; i < level; i++) {
normalizedLevel = normalizedLevel.getNextLevel();
Log.e("carl", "incrementing normalized level");
}
Log.e("carl", "index # is: " + currentIndex + " for: "
+ mForm.getChildInstanceRef(currentIndex).toString(false));
IFormElement e = mForm.getChild(currentIndex);
String currentGroupName = mForm.getChildInstanceRef(currentIndex)
.toString(false);
// we're displaying only a particular group, and we've reached the
// end of that group
if (displayGroup.equalsIgnoreCase(currentGroupName)) {
break;
}
// Here we're adding new child elements to a group, or skipping over
// elements in the index
// that are just members of the current group.
if (currentGroupName.startsWith(repeatGroup)) {
Log.e("carl", "testing: " + repeatIndex + " against: "
+ normalizedLevel.getInstanceIndex());
// the last repeated group doesn't exist, so make sure the next
// item is still in the group.
FormIndex nextIndex = nextRelevantIndex(currentIndex);
if (nextIndex.isEndOfFormIndex())
break;
String nextIndexName = mForm.getChildInstanceRef(nextIndex)
.toString(false);
if (repeatIndex != normalizedLevel.getInstanceIndex()
&& nextIndexName.startsWith(repeatGroup)) {
repeatIndex = normalizedLevel.getInstanceIndex();
Log.e("Carl", "adding new group: " + currentGroupName
+ " in repeat");
HierarchyElement h = formList.get(formList.size() - 1);
h
.AddChild(new HierarchyElement(mIndent
+ repeatedGroupName + " " + groupCount++,
"", null, CHILD, currentIndex));
}
// if it's not a new repeat, we skip it because it's in the
// group anyway
currentIndex = nextRelevantIndex(currentIndex);
continue;
}
if (e instanceof GroupDef) {
GroupDef g = (GroupDef) e;
// h += "\t" + g.getLongText() + "\t" + g.getRepeat();
if (g.getRepeat() && !currentGroupName.startsWith(repeatGroup)) {
// we have a new repeated group that we haven't seen
// before
repeatGroup = currentGroupName;
repeatIndex = normalizedLevel.getInstanceIndex();
Log.e("carl", "found new repeat: " + repeatGroup
+ " with instance index: " + repeatIndex);
FormIndex nextIndex = nextRelevantIndex(currentIndex);
if (nextIndex.isEndOfFormIndex())
break;
String nextIndexName = mForm.getChildInstanceRef(nextIndex)
.toString(false);
// Make sure the next element is in this group, else no
// reason to add it
if (nextIndexName.startsWith(repeatGroup)) {
groupCount = 0;
// add the group, but this index is also the first
// instance of a
// repeat, so add it as a child of the group
repeatedGroupName = g.getLongText();
HierarchyElement group = new HierarchyElement(
repeatedGroupName, "Repeated Group",
getResources().getDrawable(
R.drawable.arrow_right_float),
COLLAPSED, currentIndex);
group.AddChild(new HierarchyElement(mIndent
+ repeatedGroupName + " " + groupCount++, "",
null, CHILD, currentIndex));
formList.add(group);
} else {
Log.e("Carl", "no children, so skipping");
}
currentIndex = nextRelevantIndex(currentIndex);
continue;
}
} else if (e instanceof QuestionDef) {
QuestionDef q = (QuestionDef) e;
// h += "\t" + q.getLongText();
// Log.e("FHV", h);
String answer = "";
FormElementBinding feb = new FormElementBinding(null,
currentIndex, mForm);
IAnswerData a = feb.getValue();
if (a != null)
answer = a.getDisplayText();
formList.add(new HierarchyElement(q.getLongText(), answer,
null, QUESTION, currentIndex));
} else {
Log.e(t, "we shouldn't get here");
}
currentIndex = nextRelevantIndex(currentIndex);
}
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
}
// used to go 'back', the only problem is this changes whatever it's
// referencing
public FormIndex stepIndexOut(FormIndex index) {
if (index.isTerminal()) {
return null;
} else {
index.setNextLevel(stepIndexOut(index.getNextLevel()));
return index;
}
}
private FormIndex prevIndex(FormIndex index) {
do {
index = mForm.decrementIndex(index);
} while (index.isInForm() && !isRelevant(index));
return index;
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
HierarchyElement h = (HierarchyElement) l.getItemAtPosition(position);
Log.e("carl", "item is " + h.getPrimaryText());
switch (h.getType()) {
case EXPANDED:
Log.e("carl", "is expanded group, collapsing");
h.setType(COLLAPSED);
ArrayList<HierarchyElement> children = h.getChildren();
for (int i = 0; i < children.size(); i++) {
formList.remove(position + 1);
}
h.setIcon(getResources().getDrawable(R.drawable.arrow_right_float));
break;
case COLLAPSED:
Log.e("carl", "is collapsed group, expanding");
h.setType(EXPANDED);
ArrayList<HierarchyElement> children1 = h.getChildren();
for (int i = 0; i < children1.size(); i++) {
Log.e("Carl", "adding child: "
+ children1.get(i).getFormIndex());
formList.add(position + 1 + i, children1.get(i));
}
h.setIcon(getResources().getDrawable(
android.R.drawable.arrow_down_float));
break;
case QUESTION:
// Toast.makeText(this, "Question", Toast.LENGTH_SHORT).show();
FormEntryActivity.mFormHandler.setFormIndex(h.getFormIndex());
finish();
return;
case CHILD:
// Toast.makeText(this, "CHILD", Toast.LENGTH_SHORT).show();
mCurrentIndex = h.getFormIndex();
mCurrentIndex = nextRelevantIndex(mCurrentIndex);
Log.e("carl", "clicked index was " + mCurrentIndex);
refreshView();
return;
}
// Should only get here if we've expanded or collapsed a group
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
this.getListView().setSelection(position);
}
private FormIndex nextRelevantIndex(FormIndex index) {
do {
index = mForm.incrementIndex(index);
} while (index.isInForm() && !isRelevant(index));
return index;
}
private boolean isRelevant(FormIndex questionIndex) {
TreeReference ref = mForm.getChildInstanceRef(questionIndex);
boolean isAskNewRepeat = false;
Vector<IFormElement> defs = getIndexVector(questionIndex);
IFormElement last = (defs.size() == 0 ? null : (IFormElement) defs
.lastElement());
if (last instanceof GroupDef
&& ((GroupDef) last).getRepeat()
&& mForm.getDataModel().resolveReference(
mForm.getChildInstanceRef(questionIndex)) == null) {
isAskNewRepeat = true;
}
boolean relevant;
if (isAskNewRepeat) {
relevant = mForm.canCreateRepeat(ref);
} else {
TreeElement node = mForm.getDataModel().resolveReference(ref);
relevant = node.isRelevant(); // check instance flag first
}
if (relevant) {
/*
* if instance flag/condition says relevant, we still have check the
* <group>/<repeat> hierarchy
*/
FormIndex ancestorIndex = null;
FormIndex cur = null;
FormIndex qcur = questionIndex;
for (int i = 0; i < defs.size() - 1; i++) {
FormIndex next = new FormIndex(qcur.getLocalIndex(), qcur
.getInstanceIndex());
if (ancestorIndex == null) {
ancestorIndex = next;
cur = next;
} else {
cur.setNextLevel(next);
cur = next;
}
qcur = qcur.getNextLevel();
TreeElement ancestorNode = mForm.getDataModel()
.resolveReference(
mForm.getChildInstanceRef(ancestorIndex));
if (!ancestorNode.isRelevant()) {
relevant = false;
break;
}
}
}
return relevant;
}
@SuppressWarnings("unchecked")
public Vector<IFormElement> getIndexVector(FormIndex index) {
return mForm.explodeIndex(index);
}
public boolean isEnd(FormIndex mCurrentIndex) {
if (mCurrentIndex.isEndOfFormIndex())
return true;
else
return false;
}
// private boolean indexIsGroup(FormIndex index) {
// Vector<IFormElement> defs = getIndexVector(index);
// IFormElement last = (defs.size() == 0 ? null : (IFormElement)
// defs.lastElement());
// if (last instanceof GroupDef) {
// return true;
// } else {
// return false;
// }
// }
//
//
// private TreeElement resolveReferenceForCurrentIndex(FormIndex i) {
// return
// mForm.getDataModel().resolveReference(mForm.getChildInstanceRef(i));
// }
}
| true | true | public void refreshView() {
formList = new ArrayList<HierarchyElement>();
FormIndex currentIndex = mCurrentIndex;
// would like to use this, but it's broken and changes the currentIndex
// TODO: fix in javarosa.
/*
* FormIndex startTest = stepIndexOut(currentIndex); Log.e("carl",
* "starttest = " + startTest); boolean beginning = (startTest == null);
*/
// begin hack around:
boolean beginning = indexIsBeginning(currentIndex);
// end hack around
String displayGroup = "";
int level = 0;
String repeatGroup = "-1";
Log.e("Carl", "just checking at beginnig " + currentIndex);
if (!beginning) {
FormIndex levelTest = currentIndex;
while (levelTest.getNextLevel() != null) {
level++;
levelTest = levelTest.getNextLevel();
}
Log.e("Carl", "level is: " + level);
boolean found = false;
while (!found) {
FormIndex localTest = currentIndex;
for (int i = 0; i < level; i++) {
localTest = localTest.getNextLevel();
}
Log.e("carl", "localtest local = " + localTest.getLocalIndex()
+ " and instance = " + localTest.getInstanceIndex());
if (localTest.getLocalIndex() == 0)
found = true;
else
currentIndex = prevIndex(currentIndex);
}
// we're displaying only things only within a given group
FormIndex prevIndex = prevIndex(currentIndex);
Log.e("Carl", "local = " + prevIndex.getLocalIndex()
+ " and instance = " + prevIndex.getInstanceIndex());
displayGroup = mForm.getChildInstanceRef(prevIndex).toString(false);
Log.e("carl", "display group is: " + displayGroup);
mBackButton.setEnabled(true);
} else {
Log.e("carl", "at beginning");
currentIndex = FormIndex.createBeginningOfFormIndex();
currentIndex = nextRelevantIndex(currentIndex);
Log.e("carl", "index is now "
+ mForm.getChildInstanceRef(currentIndex).toString(false));
Log.e("carl", "index # is " + currentIndex);
mBackButton.setEnabled(false);
}
int repeatIndex = -1;
int groupCount = 1;
String repeatedGroupName = "";
while (!isEnd(currentIndex)) {
FormIndex normalizedLevel = currentIndex;
for (int i = 0; i < level; i++) {
normalizedLevel = normalizedLevel.getNextLevel();
Log.e("carl", "incrementing normalized level");
}
Log.e("carl", "index # is: " + currentIndex + " for: "
+ mForm.getChildInstanceRef(currentIndex).toString(false));
IFormElement e = mForm.getChild(currentIndex);
String currentGroupName = mForm.getChildInstanceRef(currentIndex)
.toString(false);
// we're displaying only a particular group, and we've reached the
// end of that group
if (displayGroup.equalsIgnoreCase(currentGroupName)) {
break;
}
// Here we're adding new child elements to a group, or skipping over
// elements in the index
// that are just members of the current group.
if (currentGroupName.startsWith(repeatGroup)) {
Log.e("carl", "testing: " + repeatIndex + " against: "
+ normalizedLevel.getInstanceIndex());
// the last repeated group doesn't exist, so make sure the next
// item is still in the group.
FormIndex nextIndex = nextRelevantIndex(currentIndex);
if (nextIndex.isEndOfFormIndex())
break;
String nextIndexName = mForm.getChildInstanceRef(nextIndex)
.toString(false);
if (repeatIndex != normalizedLevel.getInstanceIndex()
&& nextIndexName.startsWith(repeatGroup)) {
repeatIndex = normalizedLevel.getInstanceIndex();
Log.e("Carl", "adding new group: " + currentGroupName
+ " in repeat");
HierarchyElement h = formList.get(formList.size() - 1);
h
.AddChild(new HierarchyElement(mIndent
+ repeatedGroupName + " " + groupCount++,
"", null, CHILD, currentIndex));
}
// if it's not a new repeat, we skip it because it's in the
// group anyway
currentIndex = nextRelevantIndex(currentIndex);
continue;
}
if (e instanceof GroupDef) {
GroupDef g = (GroupDef) e;
// h += "\t" + g.getLongText() + "\t" + g.getRepeat();
if (g.getRepeat() && !currentGroupName.startsWith(repeatGroup)) {
// we have a new repeated group that we haven't seen
// before
repeatGroup = currentGroupName;
repeatIndex = normalizedLevel.getInstanceIndex();
Log.e("carl", "found new repeat: " + repeatGroup
+ " with instance index: " + repeatIndex);
FormIndex nextIndex = nextRelevantIndex(currentIndex);
if (nextIndex.isEndOfFormIndex())
break;
String nextIndexName = mForm.getChildInstanceRef(nextIndex)
.toString(false);
// Make sure the next element is in this group, else no
// reason to add it
if (nextIndexName.startsWith(repeatGroup)) {
groupCount = 0;
// add the group, but this index is also the first
// instance of a
// repeat, so add it as a child of the group
repeatedGroupName = g.getLongText();
HierarchyElement group = new HierarchyElement(
repeatedGroupName, "Repeated Group",
getResources().getDrawable(
R.drawable.arrow_right_float),
COLLAPSED, currentIndex);
group.AddChild(new HierarchyElement(mIndent
+ repeatedGroupName + " " + groupCount++, "",
null, CHILD, currentIndex));
formList.add(group);
} else {
Log.e("Carl", "no children, so skipping");
}
currentIndex = nextRelevantIndex(currentIndex);
continue;
}
} else if (e instanceof QuestionDef) {
QuestionDef q = (QuestionDef) e;
// h += "\t" + q.getLongText();
// Log.e("FHV", h);
String answer = "";
FormElementBinding feb = new FormElementBinding(null,
currentIndex, mForm);
IAnswerData a = feb.getValue();
if (a != null)
answer = a.getDisplayText();
formList.add(new HierarchyElement(q.getLongText(), answer,
null, QUESTION, currentIndex));
} else {
Log.e(t, "we shouldn't get here");
}
currentIndex = nextRelevantIndex(currentIndex);
}
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
}
| public void refreshView() {
formList = new ArrayList<HierarchyElement>();
FormIndex currentIndex = mCurrentIndex;
// would like to use this, but it's broken and changes the currentIndex
// TODO: fix in javarosa.
/*
* FormIndex startTest = stepIndexOut(currentIndex); Log.e("carl",
* "starttest = " + startTest); boolean beginning = (startTest == null);
*/
// begin hack around:
boolean beginning = indexIsBeginning(currentIndex);
// end hack around
String displayGroup = "";
int level = 0;
String repeatGroup = "-1";
Log.e("Carl", "just checking at beginnig " + currentIndex);
if (!beginning) {
FormIndex levelTest = currentIndex;
while (levelTest.getNextLevel() != null) {
level++;
levelTest = levelTest.getNextLevel();
}
Log.e("Carl", "level is: " + level);
boolean found = false;
while (!found) {
FormIndex localTest = currentIndex;
for (int i = 0; i < level; i++) {
localTest = localTest.getNextLevel();
}
Log.e("carl", "localtest local = " + localTest.getLocalIndex()
+ " and instance = " + localTest.getInstanceIndex());
if (localTest.getLocalIndex() == 0)
found = true;
else
currentIndex = prevIndex(currentIndex);
}
// we're displaying only things only within a given group
FormIndex prevIndex = prevIndex(currentIndex);
Log.e("Carl", "local = " + prevIndex.getLocalIndex()
+ " and instance = " + prevIndex.getInstanceIndex());
displayGroup = mForm.getChildInstanceRef(prevIndex).toString(false);
Log.e("carl", "display group is: " + displayGroup);
mBackButton.setEnabled(true);
} else {
Log.e("carl", "at beginning");
currentIndex = FormIndex.createBeginningOfFormIndex();
currentIndex = nextRelevantIndex(currentIndex);
Log.e("carl", "index is now "
+ mForm.getChildInstanceRef(currentIndex).toString(false));
Log.e("carl", "index # is " + currentIndex);
mBackButton.setEnabled(false);
}
int repeatIndex = -1;
int groupCount = 1;
String repeatedGroupName = "";
while (!isEnd(currentIndex)) {
FormIndex normalizedLevel = currentIndex;
for (int i = 0; i < level; i++) {
normalizedLevel = normalizedLevel.getNextLevel();
Log.e("carl", "incrementing normalized level");
}
Log.e("carl", "index # is: " + currentIndex + " for: "
+ mForm.getChildInstanceRef(currentIndex).toString(false));
IFormElement e = mForm.getChild(currentIndex);
String currentGroupName = mForm.getChildInstanceRef(currentIndex)
.toString(false);
// we're displaying only a particular group, and we've reached the
// end of that group
if (displayGroup.equalsIgnoreCase(currentGroupName)) {
break;
}
// Here we're adding new child elements to a group, or skipping over
// elements in the index
// that are just members of the current group.
if (currentGroupName.startsWith(repeatGroup)) {
Log.e("carl", "testing: " + repeatIndex + " against: "
+ normalizedLevel.getInstanceIndex());
// the last repeated group doesn't exist, so make sure the next
// item is still in the group.
FormIndex nextIndex = nextRelevantIndex(currentIndex);
if (nextIndex.isEndOfFormIndex())
break;
String nextIndexName = mForm.getChildInstanceRef(nextIndex)
.toString(false);
if (repeatIndex != normalizedLevel.getInstanceIndex()
&& nextIndexName.startsWith(repeatGroup)) {
repeatIndex = normalizedLevel.getInstanceIndex();
Log.e("Carl", "adding new group: " + currentGroupName
+ " in repeat");
HierarchyElement h = formList.get(formList.size() - 1);
h
.AddChild(new HierarchyElement(mIndent
+ repeatedGroupName + " " + groupCount++,
"", null, CHILD, currentIndex));
}
// if it's not a new repeat, we skip it because it's in the
// group anyway
currentIndex = nextRelevantIndex(currentIndex);
continue;
}
if (e instanceof GroupDef) {
GroupDef g = (GroupDef) e;
// h += "\t" + g.getLongText() + "\t" + g.getRepeat();
if (g.getRepeat() && !currentGroupName.startsWith(repeatGroup)) {
// we have a new repeated group that we haven't seen
// before
repeatGroup = currentGroupName;
repeatIndex = normalizedLevel.getInstanceIndex();
Log.e("carl", "found new repeat: " + repeatGroup
+ " with instance index: " + repeatIndex);
FormIndex nextIndex = nextRelevantIndex(currentIndex);
if (nextIndex.isEndOfFormIndex())
break;
String nextIndexName = mForm.getChildInstanceRef(nextIndex)
.toString(false);
// Make sure the next element is in this group, else no
// reason to add it
if (nextIndexName.startsWith(repeatGroup)) {
groupCount = 0;
// add the group, but this index is also the first
// instance of a
// repeat, so add it as a child of the group
repeatedGroupName = g.getLongText();
HierarchyElement group = new HierarchyElement(
repeatedGroupName, "Repeated Group",
getResources().getDrawable(
R.drawable.arrow_right_float),
COLLAPSED, currentIndex);
group.AddChild(new HierarchyElement(mIndent
+ repeatedGroupName + " " + groupCount++, "",
null, CHILD, currentIndex));
formList.add(group);
} else {
Log.e("Carl", "no children, so skipping");
}
currentIndex = nextRelevantIndex(currentIndex);
continue;
}
} else if (e instanceof QuestionDef) {
QuestionDef q = (QuestionDef) e;
// h += "\t" + q.getLongText();
// Log.e("FHV", h);
String answer = "";
FormElementBinding feb = new FormElementBinding(null,
currentIndex, mForm);
IAnswerData a = feb.getValue();
if (a != null)
answer = a.getDisplayText();
formList.add(new HierarchyElement(q.getLongText(), answer,
null, QUESTION, currentIndex));
} else {
Log.e(t, "we shouldn't get here");
}
currentIndex = nextRelevantIndex(currentIndex);
}
HierarchyListAdapter itla = new HierarchyListAdapter(this);
itla.setListItems(formList);
setListAdapter(itla);
}
|
diff --git a/src/Level2.java b/src/Level2.java
index edd1b92..5a8cb48 100644
--- a/src/Level2.java
+++ b/src/Level2.java
@@ -1,304 +1,300 @@
import java.awt.Font;
import java.util.ArrayList;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.gui.TextField;
public class Level2 extends Level {
CommandBox commandbox_1;
CommandBox commandbox_2;
CommandBox commandbox_3;
CommandBox commandbox_4;
CommandBox commandbox_5;
CommandBox commandbox_6;
CommandBox commandbox_7;
CommandBox commandbox_8;
CommandBox commandbox_9;
CommandBox commandbox_10;
CommandBox commandbox_11;
CommandBox commandbox_12;
CommandBox commandbox_13;
CommandBox commandbox_14;
CommandBox commandbox_15;
CommandBox commandbox_16;
CommandBox commandbox_17;
Model model;
TextField tf1;
TextField tf2;
TextField tf3;
TextField tf4;
TextField tf5;
ArrayList<TextField> tf_list;
Font font1;
TrueTypeFont font2;
ArrayList<CommandBox> boxes;
Level prev_level;
Level next_level;
Stack stack = new Stack(600, 40, 24);
public Level2(Model m, GameContainer gc) {
this.model = m;
commandbox_1 = new CommandBox(40, 180, "IF at fridge");
commandbox_2 = new CommandBox(40, 240, "IF at drawer");
commandbox_3 = new CommandBox(210, 180, "IF at cabinet");
commandbox_4 = new CommandBox(210, 240, "open fridge");
commandbox_5 = new CommandBox(40, 300, "open cabinet");
commandbox_6 = new CommandBox(40, 360, "open drawer");
commandbox_7 = new CommandBox(40, 420, "close fridge");
commandbox_8 = new CommandBox(210, 300, "close drawer");
commandbox_9 = new CommandBox(210, 360, "close cabinet");
commandbox_10 = new CommandBox(210, 420, "get bread");
commandbox_11 = new CommandBox(40, 480, "get knife");
commandbox_12 = new CommandBox(210, 480, "get spoon");
commandbox_13 = new CommandBox(40, 540, "get fork");
commandbox_14 = new CommandBox(210, 540, "get bowl");
commandbox_15 = new CommandBox(40, 600, "get peanut butter");
commandbox_16 = new CommandBox(210, 600, "get jelly");
commandbox_17 = new CommandBox(40, 660, "get plate");
boxes = new ArrayList<CommandBox>();
boxes.add( commandbox_1);
boxes.add( commandbox_2);
boxes.add( commandbox_3);
boxes.add(commandbox_4);
boxes.add( commandbox_5);
boxes.add(commandbox_6);
boxes.add( commandbox_7);
boxes.add( commandbox_8);
boxes.add(commandbox_9);
boxes.add(commandbox_10);
boxes.add( commandbox_11);
boxes.add(commandbox_12);
boxes.add(commandbox_13);
boxes.add(commandbox_14);
boxes.add(commandbox_15);
boxes.add(commandbox_16);
boxes.add(commandbox_17);
tf_list = new ArrayList<TextField>();
font1 = new Font("Times New Roman", Font.PLAIN, 15);
font2 = new TrueTypeFont(font1, false);
tf1 = new TextField(gc,font2, 100, 40, 400, 20);
tf2 = new TextField(gc,font2, 100, 60, 400, 20);
tf3 = new TextField(gc,font2, 100, 80, 400, 20);
tf4 = new TextField(gc,font2, 100, 100, 400, 20);
tf5 = new TextField(gc, font2, 100, 120, 400, 20);
tf1.setText("Now that the kitchen is cleaned, it's time for the ");
tf2.setText("robot to gather all of the materials it needs. The");
tf3.setText("robot is moving around the kitchen and will stop at ");
tf4.setText("different locations in the kitchen. Make sure he gathers" );
tf5.setText("everything it needs to make sandwiches!");
tf_list = new ArrayList<TextField>();
tf_list.add(tf1);
tf_list.add(tf2);
tf_list.add(tf3);
tf_list.add(tf4);
tf_list.add(tf5);
}
public void run() {
boolean at_fridge = false;
boolean at_drawer = false;
boolean at_cabinet = false;
boolean open_fridge = false;
boolean open_drawer = false;
boolean open_cabinet = false;
boolean close_fridge = false;
boolean close_drawer = false;
boolean close_cabinet = false;
boolean bread = false;
boolean knife = false;
boolean pb = false;
boolean j = false;
boolean plate = false;
boolean too_much = false;
boolean fBlock = false;
boolean dBlock = false;
boolean cBlock = false;
boolean food_place = true;
boolean wrong = false;
for(int i = 0; i<stack.num_boxes; i++) {
CommandBox temp = stack.box_stack[i];
if (temp == null) {
continue;
}
if (temp.str.equals(commandbox_1.str) && !dBlock && !cBlock) {
at_fridge = true;
fBlock = true;
}
else if (temp.str.equals(commandbox_2.str) && !fBlock && !cBlock) {
at_drawer = true;
dBlock = true;
}
else if (temp.str.equals(commandbox_3.str) && !fBlock && !dBlock) {
at_cabinet = true;
cBlock = true;
}
else if (temp.str.equals(commandbox_4.str) && at_fridge) {
open_fridge = true;
}
else if (temp.str.equals(commandbox_5.str) && at_cabinet) {
open_cabinet = true;
}
else if (temp.str.equals(commandbox_6.str) && at_drawer) {
open_drawer = true;
}
else if (temp.str.equals(commandbox_7.str) && open_fridge) {
close_fridge = true;
fBlock = false;
}
else if (temp.str.equals(commandbox_8.str) && open_drawer) {
close_drawer = true;
dBlock = false;
}
else if (temp.str.equals(commandbox_9.str) && open_cabinet) {
close_cabinet = true;
cBlock = false;
}
else if (temp.str.equals(commandbox_10.str)) {
bread = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_11.str) && open_drawer) {
knife = true;
}
else if (temp.str.equals(commandbox_12.str) ||
temp.str.equals(commandbox_13.str) ||
temp.str.equals(commandbox_14.str)) {
too_much = true;
}
else if (temp.str.equals(commandbox_15.str)){
pb = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_16.str)){
j = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_17.str) && open_cabinet){
plate = true;
}
else{
wrong = true;
}
}
if (!(at_fridge && at_drawer && at_cabinet)){
- model.cur_error = "You're passing a crucial location!";
- model.cur_prog = Model.Progress.ERROR;
- }
- else if (fBlock || cBlock || dBlock){
- model.cur_error = "You can't be at 2 places at once!";
+ model.cur_error = "You're not going to a crucial location!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!(close_fridge && close_cabinet && close_drawer)){
model.cur_error = "You left something open!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!(bread && knife && pb && j && plate)){
model.cur_error = "You forgot to get something!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!food_place){
model.cur_error = "There's no food in the cabinet or drawer!";
model.cur_prog = Model.Progress.ERROR;
}
else if (too_much) {
model.cur_error = "You're carrying too many things!";
model.cur_prog = Model.Progress.ERROR;
}
else if (wrong) {
model.cur_error = "Wrong";
model.cur_prog = Model.Progress.ERROR;
}
else {
model.cur_error = "Done!";
model.cur_prog = Model.Progress.SUCCESS;
}
}
@Override
void render() {
// TODO Auto-generated method stub
}
@Override
ArrayList<CommandBox> getBoxes() {
// TODO Auto-generated method stub
return boxes;
}
@Override
Stack getStack() {
// TODO Auto-generated method stub
return stack;
}
@Override
ArrayList<TextField> getTF() {
// TODO Auto-generated method stub
return tf_list;
}
@Override
void setPrevLevel(Level level) {
// TODO Auto-generated method stub
prev_level = level;
}
@Override
Level getPrevLevel() {
// TODO Auto-generated method stub
return prev_level;
}
@Override
void setNextLevel(Level level) {
// TODO Auto-generated method stub
next_level = level;
}
@Override
Level getNextLevel() {
// TODO Auto-generated method stub
return next_level;
}
}
| true | true | public void run() {
boolean at_fridge = false;
boolean at_drawer = false;
boolean at_cabinet = false;
boolean open_fridge = false;
boolean open_drawer = false;
boolean open_cabinet = false;
boolean close_fridge = false;
boolean close_drawer = false;
boolean close_cabinet = false;
boolean bread = false;
boolean knife = false;
boolean pb = false;
boolean j = false;
boolean plate = false;
boolean too_much = false;
boolean fBlock = false;
boolean dBlock = false;
boolean cBlock = false;
boolean food_place = true;
boolean wrong = false;
for(int i = 0; i<stack.num_boxes; i++) {
CommandBox temp = stack.box_stack[i];
if (temp == null) {
continue;
}
if (temp.str.equals(commandbox_1.str) && !dBlock && !cBlock) {
at_fridge = true;
fBlock = true;
}
else if (temp.str.equals(commandbox_2.str) && !fBlock && !cBlock) {
at_drawer = true;
dBlock = true;
}
else if (temp.str.equals(commandbox_3.str) && !fBlock && !dBlock) {
at_cabinet = true;
cBlock = true;
}
else if (temp.str.equals(commandbox_4.str) && at_fridge) {
open_fridge = true;
}
else if (temp.str.equals(commandbox_5.str) && at_cabinet) {
open_cabinet = true;
}
else if (temp.str.equals(commandbox_6.str) && at_drawer) {
open_drawer = true;
}
else if (temp.str.equals(commandbox_7.str) && open_fridge) {
close_fridge = true;
fBlock = false;
}
else if (temp.str.equals(commandbox_8.str) && open_drawer) {
close_drawer = true;
dBlock = false;
}
else if (temp.str.equals(commandbox_9.str) && open_cabinet) {
close_cabinet = true;
cBlock = false;
}
else if (temp.str.equals(commandbox_10.str)) {
bread = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_11.str) && open_drawer) {
knife = true;
}
else if (temp.str.equals(commandbox_12.str) ||
temp.str.equals(commandbox_13.str) ||
temp.str.equals(commandbox_14.str)) {
too_much = true;
}
else if (temp.str.equals(commandbox_15.str)){
pb = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_16.str)){
j = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_17.str) && open_cabinet){
plate = true;
}
else{
wrong = true;
}
}
if (!(at_fridge && at_drawer && at_cabinet)){
model.cur_error = "You're passing a crucial location!";
model.cur_prog = Model.Progress.ERROR;
}
else if (fBlock || cBlock || dBlock){
model.cur_error = "You can't be at 2 places at once!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!(close_fridge && close_cabinet && close_drawer)){
model.cur_error = "You left something open!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!(bread && knife && pb && j && plate)){
model.cur_error = "You forgot to get something!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!food_place){
model.cur_error = "There's no food in the cabinet or drawer!";
model.cur_prog = Model.Progress.ERROR;
}
else if (too_much) {
model.cur_error = "You're carrying too many things!";
model.cur_prog = Model.Progress.ERROR;
}
else if (wrong) {
model.cur_error = "Wrong";
model.cur_prog = Model.Progress.ERROR;
}
else {
model.cur_error = "Done!";
model.cur_prog = Model.Progress.SUCCESS;
}
}
| public void run() {
boolean at_fridge = false;
boolean at_drawer = false;
boolean at_cabinet = false;
boolean open_fridge = false;
boolean open_drawer = false;
boolean open_cabinet = false;
boolean close_fridge = false;
boolean close_drawer = false;
boolean close_cabinet = false;
boolean bread = false;
boolean knife = false;
boolean pb = false;
boolean j = false;
boolean plate = false;
boolean too_much = false;
boolean fBlock = false;
boolean dBlock = false;
boolean cBlock = false;
boolean food_place = true;
boolean wrong = false;
for(int i = 0; i<stack.num_boxes; i++) {
CommandBox temp = stack.box_stack[i];
if (temp == null) {
continue;
}
if (temp.str.equals(commandbox_1.str) && !dBlock && !cBlock) {
at_fridge = true;
fBlock = true;
}
else if (temp.str.equals(commandbox_2.str) && !fBlock && !cBlock) {
at_drawer = true;
dBlock = true;
}
else if (temp.str.equals(commandbox_3.str) && !fBlock && !dBlock) {
at_cabinet = true;
cBlock = true;
}
else if (temp.str.equals(commandbox_4.str) && at_fridge) {
open_fridge = true;
}
else if (temp.str.equals(commandbox_5.str) && at_cabinet) {
open_cabinet = true;
}
else if (temp.str.equals(commandbox_6.str) && at_drawer) {
open_drawer = true;
}
else if (temp.str.equals(commandbox_7.str) && open_fridge) {
close_fridge = true;
fBlock = false;
}
else if (temp.str.equals(commandbox_8.str) && open_drawer) {
close_drawer = true;
dBlock = false;
}
else if (temp.str.equals(commandbox_9.str) && open_cabinet) {
close_cabinet = true;
cBlock = false;
}
else if (temp.str.equals(commandbox_10.str)) {
bread = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_11.str) && open_drawer) {
knife = true;
}
else if (temp.str.equals(commandbox_12.str) ||
temp.str.equals(commandbox_13.str) ||
temp.str.equals(commandbox_14.str)) {
too_much = true;
}
else if (temp.str.equals(commandbox_15.str)){
pb = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_16.str)){
j = true;
if (!fBlock){
food_place = false;
}
}
else if (temp.str.equals(commandbox_17.str) && open_cabinet){
plate = true;
}
else{
wrong = true;
}
}
if (!(at_fridge && at_drawer && at_cabinet)){
model.cur_error = "You're not going to a crucial location!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!(close_fridge && close_cabinet && close_drawer)){
model.cur_error = "You left something open!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!(bread && knife && pb && j && plate)){
model.cur_error = "You forgot to get something!";
model.cur_prog = Model.Progress.ERROR;
}
else if (!food_place){
model.cur_error = "There's no food in the cabinet or drawer!";
model.cur_prog = Model.Progress.ERROR;
}
else if (too_much) {
model.cur_error = "You're carrying too many things!";
model.cur_prog = Model.Progress.ERROR;
}
else if (wrong) {
model.cur_error = "Wrong";
model.cur_prog = Model.Progress.ERROR;
}
else {
model.cur_error = "Done!";
model.cur_prog = Model.Progress.SUCCESS;
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java
index dfb26a62b..69a495de3 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/TasksUiPlugin.java
@@ -1,1281 +1,1283 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.eclipse.core.net.proxy.IProxyChangeEvent;
import org.eclipse.core.net.proxy.IProxyChangeListener;
import org.eclipse.core.net.proxy.IProxyService;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.ISaveContext;
import org.eclipse.core.resources.ISaveParticipant;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.ISafeRunnable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.SafeRunner;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.SafeRunnable;
import org.eclipse.mylyn.commons.core.CoreUtil;
import org.eclipse.mylyn.commons.core.StatusHandler;
import org.eclipse.mylyn.commons.net.AuthenticationType;
import org.eclipse.mylyn.commons.net.WebUtil;
import org.eclipse.mylyn.context.core.ContextCore;
import org.eclipse.mylyn.internal.context.core.ContextCorePlugin;
import org.eclipse.mylyn.internal.provisional.commons.ui.AbstractNotification;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonColors;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonFonts;
import org.eclipse.mylyn.internal.tasks.core.AbstractSearchHandler;
import org.eclipse.mylyn.internal.tasks.core.AbstractTask;
import org.eclipse.mylyn.internal.tasks.core.IRepositoryModelListener;
import org.eclipse.mylyn.internal.tasks.core.ITasksCoreConstants;
import org.eclipse.mylyn.internal.tasks.core.LocalRepositoryConnector;
import org.eclipse.mylyn.internal.tasks.core.RepositoryExternalizationParticipant;
import org.eclipse.mylyn.internal.tasks.core.RepositoryModel;
import org.eclipse.mylyn.internal.tasks.core.RepositoryTemplateManager;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityManager;
import org.eclipse.mylyn.internal.tasks.core.TaskActivityUtil;
import org.eclipse.mylyn.internal.tasks.core.TaskList;
import org.eclipse.mylyn.internal.tasks.core.TaskRepositoryManager;
import org.eclipse.mylyn.internal.tasks.core.data.TaskDataManager;
import org.eclipse.mylyn.internal.tasks.core.data.TaskDataStore;
import org.eclipse.mylyn.internal.tasks.core.externalization.ExternalizationManager;
import org.eclipse.mylyn.internal.tasks.core.externalization.IExternalizationParticipant;
import org.eclipse.mylyn.internal.tasks.core.externalization.TaskListExternalizationParticipant;
import org.eclipse.mylyn.internal.tasks.core.externalization.TaskListExternalizer;
import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotificationReminder;
import org.eclipse.mylyn.internal.tasks.ui.notifications.TaskListNotifier;
import org.eclipse.mylyn.internal.tasks.ui.util.TaskListElementImporter;
import org.eclipse.mylyn.internal.tasks.ui.util.TasksUiExtensionReader;
import org.eclipse.mylyn.internal.tasks.ui.views.TaskRepositoriesView;
import org.eclipse.mylyn.tasks.core.AbstractDuplicateDetector;
import org.eclipse.mylyn.tasks.core.AbstractRepositoryConnector;
import org.eclipse.mylyn.tasks.core.IRepositoryQuery;
import org.eclipse.mylyn.tasks.core.ITask;
import org.eclipse.mylyn.tasks.core.ITaskActivationListener;
import org.eclipse.mylyn.tasks.core.ITaskContainer;
import org.eclipse.mylyn.tasks.core.RepositoryTemplate;
import org.eclipse.mylyn.tasks.core.TaskActivationAdapter;
import org.eclipse.mylyn.tasks.core.TaskRepository;
import org.eclipse.mylyn.tasks.core.ITask.PriorityLevel;
import org.eclipse.mylyn.tasks.ui.AbstractRepositoryConnectorUi;
import org.eclipse.mylyn.tasks.ui.AbstractTaskRepositoryLinkProvider;
import org.eclipse.mylyn.tasks.ui.TasksUi;
import org.eclipse.mylyn.tasks.ui.editors.AbstractTaskEditorPageFactory;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.forms.FormColors;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.progress.IProgressService;
import org.eclipse.ui.progress.UIJob;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
/**
* Main entry point for the Tasks UI.
*
* @author Mik Kersten
* @since 3.0
*/
public class TasksUiPlugin extends AbstractUIPlugin {
private static final int DELAY_QUERY_REFRESH_ON_STARTUP = 20 * 1000;
private static final int DEFAULT_LINK_PROVIDER_TIMEOUT = 5 * 1000;
public static final String ID_PLUGIN = "org.eclipse.mylyn.tasks.ui"; //$NON-NLS-1$
private static final String DIRECTORY_METADATA = ".metadata"; //$NON-NLS-1$
private static final String NAME_DATA_DIR = ".mylyn"; //$NON-NLS-1$
private static final char DEFAULT_PATH_SEPARATOR = '/';
private static final int NOTIFICATION_DELAY = 5000;
private static TasksUiPlugin INSTANCE;
private static ExternalizationManager externalizationManager;
private static TaskActivityManager taskActivityManager;
private static TaskRepositoryManager repositoryManager;
private static TaskListSynchronizationScheduler synchronizationScheduler;
private static TaskDataManager taskDataManager;
private static Map<String, AbstractRepositoryConnectorUi> repositoryConnectorUiMap = new HashMap<String, AbstractRepositoryConnectorUi>();
//private TaskListSaveManager taskListSaveManager;
private TaskListNotificationManager taskListNotificationManager;
private TaskListBackupManager taskListBackupManager;
private RepositoryTemplateManager repositoryTemplateManager;
private final Set<AbstractTaskEditorPageFactory> taskEditorPageFactories = new HashSet<AbstractTaskEditorPageFactory>();
private final TreeSet<AbstractTaskRepositoryLinkProvider> repositoryLinkProviders = new TreeSet<AbstractTaskRepositoryLinkProvider>(
new OrderComparator());
private TaskListExternalizer taskListExternalizer;
private ITaskHighlighter highlighter;
private final Map<String, Image> brandingIcons = new HashMap<String, Image>();
private final Map<String, ImageDescriptor> overlayIcons = new HashMap<String, ImageDescriptor>();
private final Set<AbstractDuplicateDetector> duplicateDetectors = new HashSet<AbstractDuplicateDetector>();
private ISaveParticipant saveParticipant;
private TaskEditorBloatMonitor taskEditorBloatManager;
private TaskJobFactory taskJobFactory;
// shared colors for all forms
private FormColors formColors;
private final List<AbstractSearchHandler> searchHandlers = new ArrayList<AbstractSearchHandler>();
private static final boolean DEBUG_HTTPCLIENT = "true".equalsIgnoreCase(Platform.getDebugOption("org.eclipse.mylyn.tasks.ui/debug/httpclient")); //$NON-NLS-1$ //$NON-NLS-2$
// XXX reconsider if this is necessary
public static class TasksUiStartup implements IStartup {
public void earlyStartup() {
// ignore
}
}
private static final class OrderComparator implements Comparator<AbstractTaskRepositoryLinkProvider> {
public int compare(AbstractTaskRepositoryLinkProvider p1, AbstractTaskRepositoryLinkProvider p2) {
return p1.getOrder() - p2.getOrder();
}
}
public enum TaskListSaveMode {
ONE_HOUR, THREE_HOURS, DAY;
@Override
public String toString() {
switch (this) {
case ONE_HOUR:
return "1 hour"; //$NON-NLS-1$
case THREE_HOURS:
return "3 hours"; //$NON-NLS-1$
case DAY:
return "1 day"; //$NON-NLS-1$
default:
return "3 hours"; //$NON-NLS-1$
}
}
public static TaskListSaveMode fromString(String string) {
if (string == null) {
return null;
}
if (string.equals("1 hour")) { //$NON-NLS-1$
return ONE_HOUR;
}
if (string.equals("3 hours")) { //$NON-NLS-1$
return THREE_HOURS;
}
if (string.equals("1 day")) { //$NON-NLS-1$
return DAY;
}
return null;
}
public static long fromStringToLong(String string) {
long hour = 3600 * 1000;
switch (fromString(string)) {
case ONE_HOUR:
return hour;
case THREE_HOURS:
return hour * 3;
case DAY:
return hour * 24;
default:
return hour * 3;
}
}
}
public enum ReportOpenMode {
EDITOR, INTERNAL_BROWSER, EXTERNAL_BROWSER;
}
private static ITaskActivationListener CONTEXT_TASK_ACTIVATION_LISTENER = new TaskActivationAdapter() {
@Override
public void taskActivated(final ITask task) {
ContextCore.getContextManager().activateContext(task.getHandleIdentifier());
}
@Override
public void taskDeactivated(final ITask task) {
ContextCore.getContextManager().deactivateContext(task.getHandleIdentifier());
}
};
private static ITaskListNotificationProvider REMINDER_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() {
public Set<AbstractNotification> getNotifications() {
Collection<AbstractTask> allTasks = TasksUiPlugin.getTaskList().getAllTasks();
Set<AbstractNotification> reminders = new HashSet<AbstractNotification>();
for (AbstractTask task : allTasks) {
if (TasksUiPlugin.getTaskActivityManager().isPastReminder(task) && !task.isReminded()) {
reminders.add(new TaskListNotificationReminder(task));
task.setReminded(true);
}
}
return reminders;
}
};
// private static ITaskListNotificationProvider INCOMING_NOTIFICATION_PROVIDER = new ITaskListNotificationProvider() {
//
// @SuppressWarnings( { "deprecation", "restriction" })
// public Set<AbstractNotification> getNotifications() {
// Set<AbstractNotification> notifications = new HashSet<AbstractNotification>();
// // Incoming Changes
// for (TaskRepository repository : getRepositoryManager().getAllRepositories()) {
// AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector(
// repository.getConnectorKind());
// if (connector instanceof AbstractLegacyRepositoryConnector) {
// AbstractRepositoryConnectorUi connectorUi = getConnectorUi(repository.getConnectorKind());
// if (connectorUi != null && !connectorUi.hasCustomNotifications()) {
// for (ITask itask : TasksUiPlugin.getTaskList().getTasks(repository.getRepositoryUrl())) {
// if (itask instanceof AbstractTask) {
// AbstractTask task = (AbstractTask) itask;
// if ((task.getLastReadTimeStamp() == null || task.getSynchronizationState() == SynchronizationState.INCOMING)
// && task.isNotified() == false) {
// TaskListNotification notification = LegacyChangeManager.getIncommingNotification(
// connector, task);
// notifications.add(notification);
// task.setNotified(true);
// }
// }
// }
// }
// }
// }
// // New query hits
// for (RepositoryQuery query : TasksUiPlugin.getTaskList().getQueries()) {
// TaskRepository repository = getRepositoryManager().getRepository(query.getRepositoryUrl());
// if (repository != null) {
// AbstractRepositoryConnector connector = getRepositoryManager().getRepositoryConnector(
// repository.getConnectorKind());
// if (connector instanceof AbstractLegacyRepositoryConnector) {
// AbstractRepositoryConnectorUi connectorUi = getConnectorUi(repository.getConnectorKind());
// if (!connectorUi.hasCustomNotifications()) {
// for (ITask hit : query.getChildren()) {
// if (((AbstractTask) hit).isNotified() == false) {
// notifications.add(new TaskListNotificationQueryIncoming(hit));
// ((AbstractTask) hit).setNotified(true);
// }
// }
// }
// }
// }
// }
// return notifications;
// }
// };
// private final IPropertyChangeListener PREFERENCE_LISTENER = new IPropertyChangeListener() {
//
// public void propertyChange(PropertyChangeEvent event) {
// // TODO: do we ever get here?
//// if (event.getProperty().equals(ContextPreferenceContstants.PREF_DATA_DIR)) {
//// if (event.getOldValue() instanceof String) {
//// reloadDataDirectory();
//// }
//// }
// }
// };
private final org.eclipse.jface.util.IPropertyChangeListener PROPERTY_LISTENER = new org.eclipse.jface.util.IPropertyChangeListener() {
public void propertyChange(org.eclipse.jface.util.PropertyChangeEvent event) {
if (event.getProperty().equals(ITasksUiPreferenceConstants.PREF_DATA_DIR)) {
if (event.getOldValue() instanceof String) {
try {
setDataDirectory((String) event.getNewValue(), new NullProgressMonitor(), false);
} catch (CoreException e) {
StatusHandler.log(new Status(IStatus.ERROR, ID_PLUGIN, "Unable to load from task data folder", //$NON-NLS-1$
e));
}
}
}
if (event.getProperty().equals(ITasksUiPreferenceConstants.PLANNING_ENDHOUR)
|| event.getProperty().equals(ITasksUiPreferenceConstants.WEEK_START_DAY)) {
updateTaskActivityManager();
}
if (event.getProperty().equals(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED)
|| event.getProperty().equals(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS)) {
updateSynchronizationScheduler(false);
}
}
};
private TaskActivityMonitor taskActivityMonitor;
private ServiceReference proxyServiceReference;
private IProxyChangeListener proxyChangeListener;
private static TaskListExternalizationParticipant taskListExternalizationParticipant;
private final Set<IRepositoryModelListener> listeners = new HashSet<IRepositoryModelListener>();
private boolean settingDataDirectory = false;
private static TaskListElementImporter taskListImporter;
private static TaskList taskList;
private static RepositoryModel repositoryModel;
private static TasksUiFactory uiFactory;
@Deprecated
public static String LABEL_VIEW_REPOSITORIES = Messages.TasksUiPlugin_Task_Repositories;
private class TasksUiInitializationJob extends UIJob {
public TasksUiInitializationJob() {
super(Messages.TasksUiPlugin_Initializing_Task_List);
setSystem(true);
}
@Override
public IStatus runInUIThread(IProgressMonitor monitor) {
// NOTE: failure in one part of the initialization should
// not prevent others
monitor.beginTask("Initializing Task List", 5); //$NON-NLS-1$
try {
// Needs to run after workbench is loaded because it
// relies on images.
TasksUiExtensionReader.initWorkbenchUiExtensions();
if (externalizationManager.getLoadStatus() != null) {
// XXX: recovery from task list load failure (Rendered in task list)
}
boolean activateTask = Boolean.parseBoolean(System.getProperty(
ITasksCoreConstants.PROPERTY_ACTIVATE_TASK, Boolean.TRUE.toString()));
// Needs to happen asynchronously to avoid bug 159706
for (AbstractTask task : taskList.getAllTasks()) {
if (task.isActive()) {
// the externalizer might set multiple tasks active
task.setActive(false);
if (activateTask) {
// make sure only one task is activated
taskActivityManager.activateTask(task);
activateTask = false;
}
}
}
//taskActivityMonitor.reloadActivityTime();
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not initialize task activity", t)); //$NON-NLS-1$
}
monitor.worked(1);
try {
taskListNotificationManager = new TaskListNotificationManager();
taskListNotificationManager.addNotificationProvider(REMINDER_NOTIFICATION_PROVIDER);
// taskListNotificationManager.addNotificationProvider(INCOMING_NOTIFICATION_PROVIDER);
taskListNotificationManager.addNotificationProvider(new TaskListNotifier(getRepositoryModel(),
getTaskDataManager()));
taskListNotificationManager.startNotification(NOTIFICATION_DELAY);
getPreferenceStore().addPropertyChangeListener(taskListNotificationManager);
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not initialize notifications", t)); //$NON-NLS-1$
}
monitor.worked(1);
try {
taskListBackupManager = new TaskListBackupManager(getBackupFolderPath());
getPreferenceStore().addPropertyChangeListener(taskListBackupManager);
synchronizationScheduler = new TaskListSynchronizationScheduler(taskJobFactory);
updateSynchronizationScheduler(true);
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not initialize task list backup and synchronization", t)); //$NON-NLS-1$
}
monitor.worked(1);
try {
getPreferenceStore().addPropertyChangeListener(PROPERTY_LISTENER);
// TODO: get rid of this, hack to make decorators show
// up on startup
TaskRepositoriesView repositoriesView = TaskRepositoriesView.getFromActivePerspective();
if (repositoriesView != null) {
repositoriesView.getViewer().refresh();
}
taskEditorBloatManager = new TaskEditorBloatMonitor();
taskEditorBloatManager.install(PlatformUI.getWorkbench());
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not finish Tasks UI initialization", t)); //$NON-NLS-1$
} finally {
monitor.done();
}
return new Status(IStatus.OK, TasksUiPlugin.ID_PLUGIN, IStatus.OK, "", null); //$NON-NLS-1$
}
}
public TasksUiPlugin() {
super();
INSTANCE = this;
}
private void updateSynchronizationScheduler(boolean initial) {
boolean enabled = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED);
if (enabled) {
long interval = TasksUiPlugin.getDefault().getPreferenceStore().getLong(
ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS);
if (initial) {
synchronizationScheduler.setInterval(DELAY_QUERY_REFRESH_ON_STARTUP, interval);
} else {
synchronizationScheduler.setInterval(interval);
}
} else {
synchronizationScheduler.setInterval(0);
}
}
@SuppressWarnings( { "deprecation", "restriction" })
@Override
public void start(BundleContext context) throws Exception {
super.start(context);
// NOTE: startup order is very sensitive
try {
// initialize framework and settings
- WebUtil.init();
if (DEBUG_HTTPCLIENT) {
+ // do this before anything else, once commons logging is initialized and an instance
+ // of Log has been created it's too late
initHttpLogging();
}
+ WebUtil.init();
initializePreferences(getPreferenceStore());
// initialize CommonFonts from UI thread: bug 240076
if (CommonFonts.BOLD == null) {
// ignore
}
File dataDir = new File(getDataDirectory());
dataDir.mkdirs();
// create data model
externalizationManager = new ExternalizationManager(getDataDirectory());
repositoryManager = new TaskRepositoryManager();
IExternalizationParticipant repositoryParticipant = new RepositoryExternalizationParticipant(
externalizationManager, repositoryManager);
externalizationManager.addParticipant(repositoryParticipant);
taskList = new TaskList();
repositoryModel = new RepositoryModel(taskList, repositoryManager);
taskListExternalizer = new TaskListExternalizer(repositoryModel, repositoryManager);
taskListImporter = new TaskListElementImporter(repositoryManager, repositoryModel);
taskListExternalizationParticipant = new TaskListExternalizationParticipant(repositoryModel, taskList,
taskListExternalizer, externalizationManager, repositoryManager);
//externalizationManager.load(taskListSaveParticipant);
externalizationManager.addParticipant(taskListExternalizationParticipant);
taskList.addChangeListener(taskListExternalizationParticipant);
taskActivityManager = new TaskActivityManager(repositoryManager, taskList);
taskActivityManager.addActivationListener(taskListExternalizationParticipant);
// initialize
updateTaskActivityManager();
proxyServiceReference = context.getServiceReference(IProxyService.class.getName());
if (proxyServiceReference != null) {
IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference);
if (proxyService != null) {
proxyChangeListener = new IProxyChangeListener() {
public void proxyInfoChanged(IProxyChangeEvent event) {
List<TaskRepository> repos = repositoryManager.getAllRepositories();
for (TaskRepository repo : repos) {
if (repo.isDefaultProxyEnabled()) {
repositoryManager.notifyRepositorySettingsChanged(repo);
}
}
}
};
proxyService.addProxyChangeListener(proxyChangeListener);
}
}
repositoryTemplateManager = new RepositoryTemplateManager();
// NOTE: initializing extensions in start(..) has caused race
// conditions previously
TasksUiExtensionReader.initStartupExtensions(taskListExternalizer, taskListImporter);
// instantiate taskDataManager
TaskDataStore taskDataStore = new TaskDataStore(repositoryManager);
taskDataManager = new TaskDataManager(taskDataStore, repositoryManager, taskList, taskActivityManager);
taskDataManager.setDataPath(getDataDirectory());
taskJobFactory = new TaskJobFactory(taskList, taskDataManager, repositoryManager, repositoryModel);
taskActivityManager.addActivationListener(CONTEXT_TASK_ACTIVATION_LISTENER);
taskActivityMonitor = new TaskActivityMonitor(taskActivityManager, ContextCorePlugin.getContextManager());
taskActivityMonitor.start();
saveParticipant = new ISaveParticipant() {
public void doneSaving(ISaveContext context) {
}
public void prepareToSave(ISaveContext context) throws CoreException {
}
public void rollback(ISaveContext context) {
}
public void saving(ISaveContext context) throws CoreException {
if (context.getKind() == ISaveContext.FULL_SAVE) {
externalizationManager.stop();
}
}
};
ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant);
ActivityExternalizationParticipant ACTIVITY_EXTERNALIZTAION_PARTICIPANT = new ActivityExternalizationParticipant(
externalizationManager);
externalizationManager.addParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
taskActivityManager.addActivityListener(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
taskActivityMonitor.setExternalizationParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
loadDataSources();
new TasksUiInitializationJob().schedule();
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Task list initialization failed", e)); //$NON-NLS-1$
}
}
private void initHttpLogging() {
System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire.header", "debug"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug"); //$NON-NLS-1$ //$NON-NLS-2$
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient.HttpConnection", //$NON-NLS-1$
"trace"); //$NON-NLS-1$
System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.axis.message", "debug"); //$NON-NLS-1$ //$NON-NLS-2$
}
private void updateTaskActivityManager() {
int endHour = getPreferenceStore().getInt(ITasksUiPreferenceConstants.PLANNING_ENDHOUR);
// if (taskActivityManager.getEndHour() != endHour) {
// taskActivityManager.setEndHour(endHour);
TaskActivityUtil.setEndHour(endHour);
// }
int newWeekStartDay = getPreferenceStore().getInt(ITasksUiPreferenceConstants.WEEK_START_DAY);
int oldWeekStartDay = taskActivityManager.getWeekStartDay();
if (oldWeekStartDay != newWeekStartDay) {
taskActivityManager.setWeekStartDay(newWeekStartDay);
// taskActivityManager.setStartTime(new Date());
}
// event.getProperty().equals(TaskListPreferenceConstants.PLANNING_STARTDAY)
// scheduledStartHour =
// TasksUiPlugin.getDefault().getPreferenceStore().getInt(
// TaskListPreferenceConstants.PLANNING_STARTHOUR);
}
private void loadTemplateRepositories() {
// Add standard local task repository
TaskRepository localRepository = getLocalTaskRepository();
// FIXME what does this line do?
localRepository.setRepositoryLabel(LocalRepositoryConnector.REPOSITORY_LABEL);
// Add the automatically created templates
for (AbstractRepositoryConnector connector : repositoryManager.getRepositoryConnectors()) {
for (RepositoryTemplate template : repositoryTemplateManager.getTemplates(connector.getConnectorKind())) {
if (template.addAutomatically && !TaskRepositoryUtil.isAddAutomaticallyDisabled(template.repositoryUrl)) {
try {
TaskRepository taskRepository = repositoryManager.getRepository(connector.getConnectorKind(),
template.repositoryUrl);
if (taskRepository == null) {
taskRepository = new TaskRepository(connector.getConnectorKind(), template.repositoryUrl);
taskRepository.setVersion(template.version);
taskRepository.setRepositoryLabel(template.label);
taskRepository.setCharacterEncoding(template.characterEncoding);
if (template.anonymous) {
taskRepository.setCredentials(AuthenticationType.REPOSITORY, null, true);
}
repositoryManager.addRepository(taskRepository);
}
} catch (Throwable t) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Could not load repository template", t)); //$NON-NLS-1$
}
}
}
}
}
/**
* Returns the local task repository. If the repository does not exist it is created and added to the task
* repository manager.
*
* @return the local task repository; never <code>null</code>
* @since 3.0
*/
public TaskRepository getLocalTaskRepository() {
TaskRepository localRepository = repositoryManager.getRepository(LocalRepositoryConnector.CONNECTOR_KIND,
LocalRepositoryConnector.REPOSITORY_URL);
if (localRepository == null) {
localRepository = new TaskRepository(LocalRepositoryConnector.CONNECTOR_KIND,
LocalRepositoryConnector.REPOSITORY_URL);
localRepository.setVersion(LocalRepositoryConnector.REPOSITORY_VERSION);
localRepository.setRepositoryLabel(LocalRepositoryConnector.REPOSITORY_LABEL);
repositoryManager.addRepository(localRepository);
}
return localRepository;
}
@Override
public void stop(BundleContext context) throws Exception {
try {
if (formColors != null) {
formColors.dispose();
formColors = null;
}
if (taskActivityMonitor != null) {
taskActivityMonitor.stop();
}
if (ResourcesPlugin.getWorkspace() != null) {
ResourcesPlugin.getWorkspace().removeSaveParticipant(this);
}
if (proxyServiceReference != null) {
IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference);
if (proxyService != null) {
proxyService.removeProxyChangeListener(proxyChangeListener);
}
context.ungetService(proxyServiceReference);
}
if (PlatformUI.isWorkbenchRunning()) {
getPreferenceStore().removePropertyChangeListener(taskListNotificationManager);
getPreferenceStore().removePropertyChangeListener(taskListBackupManager);
getPreferenceStore().removePropertyChangeListener(PROPERTY_LISTENER);
//taskListManager.getTaskList().removeChangeListener(taskListSaveManager);
CommonColors.dispose();
// if (ContextCorePlugin.getDefault() != null) {
// ContextCorePlugin.getDefault().getPluginPreferences().removePropertyChangeListener(
// PREFERENCE_LISTENER);
// }
taskEditorBloatManager.dispose(PlatformUI.getWorkbench());
INSTANCE = null;
}
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Task list stop terminated abnormally", e)); //$NON-NLS-1$
} finally {
super.stop(context);
}
}
public String getDefaultDataDirectory() {
return ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/' + DIRECTORY_METADATA + '/'
+ NAME_DATA_DIR;
}
public String getDataDirectory() {
return getPreferenceStore().getString(ITasksUiPreferenceConstants.PREF_DATA_DIR);
}
/**
* Save first, then load from <code>newPath</code>. Sets the new data directory, which upon setting results in
* reload of task list information from the <code>newPath</code> supplied.
*
* @throws CoreException
*/
public void setDataDirectory(final String newPath, IProgressMonitor monitor) throws CoreException {
setDataDirectory(newPath, monitor, true);
}
@SuppressWarnings("restriction")
private void setDataDirectory(final String newPath, IProgressMonitor monitor, boolean setPreference)
throws CoreException {
// guard against updates from preference listeners that are triggered by the setValue() call below
if (settingDataDirectory) {
return;
}
// FIXME reset the preference in case switching to the new location fails?
try {
settingDataDirectory = true;
loadDataDirectory(newPath, !setPreference);
if (setPreference) {
getPreferenceStore().setValue(ITasksUiPreferenceConstants.PREF_DATA_DIR, newPath);
}
File newFile = new File(newPath, ITasksCoreConstants.CONTEXTS_DIRECTORY);
if (!newFile.exists()) {
newFile.mkdirs();
}
ContextCorePlugin.getContextStore().setContextDirectory(newFile);
} finally {
settingDataDirectory = false;
}
}
public void reloadDataDirectory() throws CoreException {
// no save just load what is there
loadDataDirectory(getDataDirectory(), false);
}
/**
* Load's data sources from <code>newPath</code> and executes with progress
*/
private synchronized void loadDataDirectory(final String newPath, final boolean save) throws CoreException {
IRunnableWithProgress setDirectoryRunnable = new IRunnableWithProgress() {
public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
try {
monitor.beginTask(Messages.TasksUiPlugin_Load_Data_Directory, IProgressMonitor.UNKNOWN);
if (save) {
externalizationManager.save(false);
}
Job.getJobManager().beginRule(ITasksCoreConstants.ROOT_SCHEDULING_RULE,
new SubProgressMonitor(monitor, 1));
if (monitor.isCanceled()) {
throw new InterruptedException();
}
TasksUi.getTaskActivityManager().deactivateActiveTask();
externalizationManager.setRootFolderPath(newPath);
loadDataSources();
} finally {
Job.getJobManager().endRule(ITasksCoreConstants.ROOT_SCHEDULING_RULE);
monitor.done();
}
}
};
IProgressService service = PlatformUI.getWorkbench().getProgressService();
try {
if (!CoreUtil.TEST_MODE) {
service.run(false, false, setDirectoryRunnable);
} else {
setDirectoryRunnable.run(new NullProgressMonitor());
}
} catch (InvocationTargetException e) {
throw new CoreException(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Failed to set data directory", //$NON-NLS-1$
e.getCause()));
} catch (InterruptedException e) {
throw new OperationCanceledException();
}
}
/**
* called on startup and when the mylyn data structures are reloaded from disk
*/
@SuppressWarnings("restriction")
private void loadDataSources() {
File storeFile = getContextStoreDir();
ContextCorePlugin.getContextStore().setContextDirectory(storeFile);
externalizationManager.load();
// TODO: Move management of template repositories to TaskRepositoryManager
loadTemplateRepositories();
taskActivityManager.clear();
ContextCorePlugin.getContextManager().loadActivityMetaContext();
taskActivityMonitor.reloadActivityTime();
taskActivityManager.reloadPlanningData();
for (final IRepositoryModelListener listener : listeners) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable exception) {
StatusHandler.log(new Status(IStatus.WARNING, TasksUiPlugin.ID_PLUGIN, "Listener failed: " //$NON-NLS-1$
+ listener.getClass(), exception));
}
public void run() throws Exception {
listener.loaded();
}
});
}
}
private File getContextStoreDir() {
File storeFile = new File(getDataDirectory(), ITasksCoreConstants.CONTEXTS_DIRECTORY);
if (!storeFile.exists()) {
storeFile.mkdirs();
}
return storeFile;
}
private void initializePreferences(IPreferenceStore store) {
store.setDefault(ITasksUiPreferenceConstants.PREF_DATA_DIR, getDefaultDataDirectory());
store.setDefault(ITasksUiPreferenceConstants.GROUP_SUBTASKS, true);
store.setDefault(ITasksUiPreferenceConstants.NOTIFICATIONS_ENABLED, true);
store.setDefault(ITasksUiPreferenceConstants.FILTER_PRIORITY, PriorityLevel.P5.toString());
store.setDefault(ITasksUiPreferenceConstants.EDITOR_TASKS_RICH, true);
store.setDefault(ITasksUiPreferenceConstants.ACTIVATE_WHEN_OPENED, false);
store.setDefault(ITasksUiPreferenceConstants.SHOW_TRIM, false);
// remove preference
store.setToDefault(ITasksUiPreferenceConstants.LOCAL_SUB_TASKS_ENABLED);
store.setDefault(ITasksUiPreferenceConstants.USE_STRIKETHROUGH_FOR_COMPLETED, true);
store.setDefault(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_ENABLED, true);
store.setDefault(ITasksUiPreferenceConstants.REPOSITORY_SYNCH_SCHEDULE_MILISECONDS, "" + (20 * 60 * 1000)); //$NON-NLS-1$
//store.setDefault(TasksUiPreferenceConstants.BACKUP_SCHEDULE, 1);
store.setDefault(ITasksUiPreferenceConstants.BACKUP_MAXFILES, 20);
store.setDefault(ITasksUiPreferenceConstants.BACKUP_LAST, 0f);
store.setDefault(ITasksUiPreferenceConstants.FILTER_ARCHIVE_MODE, true);
store.setDefault(ITasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false);
store.setValue(ITasksUiPreferenceConstants.ACTIVATE_MULTIPLE, false);
store.setDefault(ITasksUiPreferenceConstants.WEEK_START_DAY, Calendar.getInstance().getFirstDayOfWeek());
//store.setDefault(TasksUiPreferenceConstants.PLANNING_STARTHOUR, 9);
store.setDefault(ITasksUiPreferenceConstants.PLANNING_ENDHOUR, 18);
}
public static TaskActivityManager getTaskActivityManager() {
return taskActivityManager;
}
public static TaskListNotificationManager getTaskListNotificationManager() {
return INSTANCE.taskListNotificationManager;
}
/**
* Returns the shared instance.
*/
public static TasksUiPlugin getDefault() {
return INSTANCE;
}
public boolean groupSubtasks(ITaskContainer element) {
boolean groupSubtasks = TasksUiPlugin.getDefault().getPreferenceStore().getBoolean(
ITasksUiPreferenceConstants.GROUP_SUBTASKS);
if (element instanceof ITask) {
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((ITask) element).getConnectorKind());
if (connectorUi != null) {
if (connectorUi.hasStrictSubtaskHierarchy()) {
groupSubtasks = true;
}
}
}
if (element instanceof IRepositoryQuery) {
AbstractRepositoryConnectorUi connectorUi = TasksUiPlugin.getConnectorUi(((IRepositoryQuery) element).getConnectorKind());
if (connectorUi != null) {
if (connectorUi.hasStrictSubtaskHierarchy()) {
groupSubtasks = true;
}
}
}
return groupSubtasks;
}
private final Map<String, List<IDynamicSubMenuContributor>> menuContributors = new HashMap<String, List<IDynamicSubMenuContributor>>();
public Map<String, List<IDynamicSubMenuContributor>> getDynamicMenuMap() {
return menuContributors;
}
public void addDynamicPopupContributor(String menuPath, IDynamicSubMenuContributor contributor) {
List<IDynamicSubMenuContributor> contributors = menuContributors.get(menuPath);
if (contributors == null) {
contributors = new ArrayList<IDynamicSubMenuContributor>();
menuContributors.put(menuPath, contributors);
}
contributors.add(contributor);
}
public String[] getSaveOptions() {
String[] options = { TaskListSaveMode.ONE_HOUR.toString(), TaskListSaveMode.THREE_HOURS.toString(),
TaskListSaveMode.DAY.toString() };
return options;
}
public String getBackupFolderPath() {
return getDataDirectory() + DEFAULT_PATH_SEPARATOR + ITasksCoreConstants.DEFAULT_BACKUP_FOLDER_NAME;
}
public ITaskHighlighter getHighlighter() {
return highlighter;
}
public void setHighlighter(ITaskHighlighter highlighter) {
this.highlighter = highlighter;
}
/**
* @since 3.0
*/
public AbstractTaskEditorPageFactory[] getTaskEditorPageFactories() {
return taskEditorPageFactories.toArray(new AbstractTaskEditorPageFactory[0]);
}
/**
* @since 3.0
*/
public void addTaskEditorPageFactory(AbstractTaskEditorPageFactory factory) {
Assert.isNotNull(factory);
taskEditorPageFactories.add(factory);
}
/**
* @since 3.0
*/
public void removeTaskEditorPageFactory(AbstractTaskEditorPageFactory factory) {
Assert.isNotNull(factory);
taskEditorPageFactories.remove(factory);
}
public static TaskRepositoryManager getRepositoryManager() {
return repositoryManager;
}
/**
* @since 3.0
*/
public static RepositoryTemplateManager getRepositoryTemplateManager() {
return INSTANCE.repositoryTemplateManager;
}
public void addBrandingIcon(String repositoryType, Image icon) {
brandingIcons.put(repositoryType, icon);
}
public Image getBrandingIcon(String repositoryType) {
return brandingIcons.get(repositoryType);
}
public void addOverlayIcon(String repositoryType, ImageDescriptor icon) {
overlayIcons.put(repositoryType, icon);
}
public ImageDescriptor getOverlayIcon(String repositoryType) {
return overlayIcons.get(repositoryType);
}
public void addRepositoryLinkProvider(AbstractTaskRepositoryLinkProvider repositoryLinkProvider) {
if (repositoryLinkProvider != null) {
this.repositoryLinkProviders.add(repositoryLinkProvider);
}
}
public static TaskListBackupManager getBackupManager() {
return INSTANCE.taskListBackupManager;
}
public void addRepositoryConnectorUi(AbstractRepositoryConnectorUi repositoryConnectorUi) {
if (!repositoryConnectorUiMap.values().contains(repositoryConnectorUi)) {
repositoryConnectorUiMap.put(repositoryConnectorUi.getConnectorKind(), repositoryConnectorUi);
}
}
/**
* @since 3.0
*/
public static AbstractRepositoryConnector getConnector(String kind) {
return getRepositoryManager().getRepositoryConnector(kind);
}
public static AbstractRepositoryConnectorUi getConnectorUi(String kind) {
return repositoryConnectorUiMap.get(kind);
}
public static TaskListSynchronizationScheduler getSynchronizationScheduler() {
return synchronizationScheduler;
}
/**
* @since 3.0
*/
public static TaskDataManager getTaskDataManager() {
return taskDataManager;
}
/**
* @since 3.0
*/
public static TaskJobFactory getTaskJobFactory() {
return INSTANCE.taskJobFactory;
}
public void addDuplicateDetector(AbstractDuplicateDetector duplicateDetector) {
Assert.isNotNull(duplicateDetector);
duplicateDetectors.add(duplicateDetector);
}
public Set<AbstractDuplicateDetector> getDuplicateSearchCollectorsList() {
return duplicateDetectors;
}
public String getRepositoriesFilePath() {
return getDataDirectory() + File.separator + TaskRepositoryManager.DEFAULT_REPOSITORIES_FILE;
}
public void addModelListener(IRepositoryModelListener listener) {
listeners.add(listener);
}
public void removeModelListener(IRepositoryModelListener listener) {
listeners.remove(listener);
}
public boolean canSetRepositoryForResource(final IResource resource) {
if (resource == null) {
return false;
}
// if a repository has already been linked only that provider should be queried to ensure that it is the same
// provider that is used by getRepositoryForResource()
final boolean result[] = new boolean[1];
final boolean found[] = new boolean[1];
for (final AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Task repository link provider failed: \"" + linkProvider.getId() + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void run() throws Exception {
if (linkProvider.getTaskRepository(resource, getRepositoryManager()) != null) {
found[0] = true;
result[0] = linkProvider.canSetTaskRepository(resource);
}
}
});
if (found[0]) {
return result[0];
}
}
// find a provider that can set new repository
for (final AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Task repository link provider failed: \"" + linkProvider.getId() + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void run() throws Exception {
if (linkProvider.canSetTaskRepository(resource)) {
result[0] = true;
}
}
});
if (result[0]) {
return true;
}
}
return false;
}
/**
* Associate a Task Repository with a workbench project
*
* @param resource
* project or resource belonging to a project
* @param repository
* task repository to associate with given project
* @throws CoreException
*/
public void setRepositoryForResource(final IResource resource, final TaskRepository repository) {
Assert.isNotNull(resource);
for (final AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) {
SafeRunner.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN,
"Task repository link provider failed: \"" + linkProvider.getId() + "\"", e)); //$NON-NLS-1$ //$NON-NLS-2$
}
public void run() throws Exception {
boolean canSetRepository = linkProvider.canSetTaskRepository(resource);
if (canSetRepository) {
linkProvider.setTaskRepository(resource, repository);
}
}
});
}
}
/**
* Retrieve the task repository that has been associated with the given project (or resource belonging to a project)
*
* NOTE: if call does not return in LINK_PROVIDER_TIMEOUT_SECONDS, the provide will be disabled until the next time
* that the Workbench starts.
*/
public TaskRepository getRepositoryForResource(final IResource resource) {
Assert.isNotNull(resource);
long timeout;
try {
timeout = Long.parseLong(System.getProperty(ITasksCoreConstants.PROPERTY_LINK_PROVIDER_TIMEOUT,
DEFAULT_LINK_PROVIDER_TIMEOUT + "")); //$NON-NLS-1$
} catch (NumberFormatException e) {
timeout = DEFAULT_LINK_PROVIDER_TIMEOUT;
}
Set<AbstractTaskRepositoryLinkProvider> defectiveLinkProviders = new HashSet<AbstractTaskRepositoryLinkProvider>();
for (final AbstractTaskRepositoryLinkProvider linkProvider : repositoryLinkProviders) {
long startTime = System.currentTimeMillis();
final TaskRepository[] repository = new TaskRepository[1];
SafeRunnable.run(new ISafeRunnable() {
public void handleException(Throwable e) {
StatusHandler.log(new Status(IStatus.ERROR, ID_PLUGIN, "Task repository link provider failed: \"" //$NON-NLS-1$
+ linkProvider.getId() + "\"", e)); //$NON-NLS-1$
}
public void run() throws Exception {
repository[0] = linkProvider.getTaskRepository(resource, getRepositoryManager());
}
});
long elapsed = System.currentTimeMillis() - startTime;
if (timeout >= 0 && elapsed > timeout) {
defectiveLinkProviders.add(linkProvider);
}
if (repository[0] != null) {
return repository[0];
}
}
if (!defectiveLinkProviders.isEmpty()) {
repositoryLinkProviders.removeAll(defectiveLinkProviders);
StatusHandler.log(new Status(IStatus.WARNING, ID_PLUGIN, "Repository link provider took over " + timeout //$NON-NLS-1$
+ " ms to execute and was timed out: \"" + defectiveLinkProviders + "\"")); //$NON-NLS-1$ //$NON-NLS-2$
}
return null;
}
public static ExternalizationManager getExternalizationManager() {
return externalizationManager;
}
public static TaskActivityMonitor getTaskActivityMonitor() {
return INSTANCE.taskActivityMonitor;
}
public static TaskList getTaskList() {
return taskList;
}
public static RepositoryModel getRepositoryModel() {
return repositoryModel;
}
/**
* Note: This is provisional API that is used by connectors.
* <p>
* DO NOT CHANGE.
*/
public void addSearchHandler(AbstractSearchHandler searchHandler) {
searchHandlers.add(searchHandler);
}
/**
* Note: This is provisional API that is used by connectors.
* <p>
* DO NOT CHANGE.
*/
public void removeSearchHandler(AbstractSearchHandler searchHandler) {
searchHandlers.remove(searchHandler);
}
public AbstractSearchHandler getSearchHandler(String connectorKind) {
Assert.isNotNull(connectorKind);
for (AbstractSearchHandler searchHandler : searchHandlers) {
if (searchHandler.getConnectorKind().equals(connectorKind)) {
return searchHandler;
}
}
return null;
}
public FormColors getFormColors(Display display) {
if (formColors == null) {
formColors = new FormColors(display);
formColors.markShared();
}
return formColors;
}
public void removeRepositoryLinkProvider(AbstractTaskRepositoryLinkProvider provider) {
repositoryLinkProviders.remove(provider);
}
public static TaskListElementImporter getTaskListWriter() {
return taskListImporter;
}
public static TaskListExternalizationParticipant getTaskListExternalizationParticipant() {
return taskListExternalizationParticipant;
}
public static TasksUiFactory getUiFactory() {
if (uiFactory == null) {
uiFactory = new TasksUiFactory();
}
return uiFactory;
}
}
| false | true | public void start(BundleContext context) throws Exception {
super.start(context);
// NOTE: startup order is very sensitive
try {
// initialize framework and settings
WebUtil.init();
if (DEBUG_HTTPCLIENT) {
initHttpLogging();
}
initializePreferences(getPreferenceStore());
// initialize CommonFonts from UI thread: bug 240076
if (CommonFonts.BOLD == null) {
// ignore
}
File dataDir = new File(getDataDirectory());
dataDir.mkdirs();
// create data model
externalizationManager = new ExternalizationManager(getDataDirectory());
repositoryManager = new TaskRepositoryManager();
IExternalizationParticipant repositoryParticipant = new RepositoryExternalizationParticipant(
externalizationManager, repositoryManager);
externalizationManager.addParticipant(repositoryParticipant);
taskList = new TaskList();
repositoryModel = new RepositoryModel(taskList, repositoryManager);
taskListExternalizer = new TaskListExternalizer(repositoryModel, repositoryManager);
taskListImporter = new TaskListElementImporter(repositoryManager, repositoryModel);
taskListExternalizationParticipant = new TaskListExternalizationParticipant(repositoryModel, taskList,
taskListExternalizer, externalizationManager, repositoryManager);
//externalizationManager.load(taskListSaveParticipant);
externalizationManager.addParticipant(taskListExternalizationParticipant);
taskList.addChangeListener(taskListExternalizationParticipant);
taskActivityManager = new TaskActivityManager(repositoryManager, taskList);
taskActivityManager.addActivationListener(taskListExternalizationParticipant);
// initialize
updateTaskActivityManager();
proxyServiceReference = context.getServiceReference(IProxyService.class.getName());
if (proxyServiceReference != null) {
IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference);
if (proxyService != null) {
proxyChangeListener = new IProxyChangeListener() {
public void proxyInfoChanged(IProxyChangeEvent event) {
List<TaskRepository> repos = repositoryManager.getAllRepositories();
for (TaskRepository repo : repos) {
if (repo.isDefaultProxyEnabled()) {
repositoryManager.notifyRepositorySettingsChanged(repo);
}
}
}
};
proxyService.addProxyChangeListener(proxyChangeListener);
}
}
repositoryTemplateManager = new RepositoryTemplateManager();
// NOTE: initializing extensions in start(..) has caused race
// conditions previously
TasksUiExtensionReader.initStartupExtensions(taskListExternalizer, taskListImporter);
// instantiate taskDataManager
TaskDataStore taskDataStore = new TaskDataStore(repositoryManager);
taskDataManager = new TaskDataManager(taskDataStore, repositoryManager, taskList, taskActivityManager);
taskDataManager.setDataPath(getDataDirectory());
taskJobFactory = new TaskJobFactory(taskList, taskDataManager, repositoryManager, repositoryModel);
taskActivityManager.addActivationListener(CONTEXT_TASK_ACTIVATION_LISTENER);
taskActivityMonitor = new TaskActivityMonitor(taskActivityManager, ContextCorePlugin.getContextManager());
taskActivityMonitor.start();
saveParticipant = new ISaveParticipant() {
public void doneSaving(ISaveContext context) {
}
public void prepareToSave(ISaveContext context) throws CoreException {
}
public void rollback(ISaveContext context) {
}
public void saving(ISaveContext context) throws CoreException {
if (context.getKind() == ISaveContext.FULL_SAVE) {
externalizationManager.stop();
}
}
};
ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant);
ActivityExternalizationParticipant ACTIVITY_EXTERNALIZTAION_PARTICIPANT = new ActivityExternalizationParticipant(
externalizationManager);
externalizationManager.addParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
taskActivityManager.addActivityListener(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
taskActivityMonitor.setExternalizationParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
loadDataSources();
new TasksUiInitializationJob().schedule();
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Task list initialization failed", e)); //$NON-NLS-1$
}
}
| public void start(BundleContext context) throws Exception {
super.start(context);
// NOTE: startup order is very sensitive
try {
// initialize framework and settings
if (DEBUG_HTTPCLIENT) {
// do this before anything else, once commons logging is initialized and an instance
// of Log has been created it's too late
initHttpLogging();
}
WebUtil.init();
initializePreferences(getPreferenceStore());
// initialize CommonFonts from UI thread: bug 240076
if (CommonFonts.BOLD == null) {
// ignore
}
File dataDir = new File(getDataDirectory());
dataDir.mkdirs();
// create data model
externalizationManager = new ExternalizationManager(getDataDirectory());
repositoryManager = new TaskRepositoryManager();
IExternalizationParticipant repositoryParticipant = new RepositoryExternalizationParticipant(
externalizationManager, repositoryManager);
externalizationManager.addParticipant(repositoryParticipant);
taskList = new TaskList();
repositoryModel = new RepositoryModel(taskList, repositoryManager);
taskListExternalizer = new TaskListExternalizer(repositoryModel, repositoryManager);
taskListImporter = new TaskListElementImporter(repositoryManager, repositoryModel);
taskListExternalizationParticipant = new TaskListExternalizationParticipant(repositoryModel, taskList,
taskListExternalizer, externalizationManager, repositoryManager);
//externalizationManager.load(taskListSaveParticipant);
externalizationManager.addParticipant(taskListExternalizationParticipant);
taskList.addChangeListener(taskListExternalizationParticipant);
taskActivityManager = new TaskActivityManager(repositoryManager, taskList);
taskActivityManager.addActivationListener(taskListExternalizationParticipant);
// initialize
updateTaskActivityManager();
proxyServiceReference = context.getServiceReference(IProxyService.class.getName());
if (proxyServiceReference != null) {
IProxyService proxyService = (IProxyService) context.getService(proxyServiceReference);
if (proxyService != null) {
proxyChangeListener = new IProxyChangeListener() {
public void proxyInfoChanged(IProxyChangeEvent event) {
List<TaskRepository> repos = repositoryManager.getAllRepositories();
for (TaskRepository repo : repos) {
if (repo.isDefaultProxyEnabled()) {
repositoryManager.notifyRepositorySettingsChanged(repo);
}
}
}
};
proxyService.addProxyChangeListener(proxyChangeListener);
}
}
repositoryTemplateManager = new RepositoryTemplateManager();
// NOTE: initializing extensions in start(..) has caused race
// conditions previously
TasksUiExtensionReader.initStartupExtensions(taskListExternalizer, taskListImporter);
// instantiate taskDataManager
TaskDataStore taskDataStore = new TaskDataStore(repositoryManager);
taskDataManager = new TaskDataManager(taskDataStore, repositoryManager, taskList, taskActivityManager);
taskDataManager.setDataPath(getDataDirectory());
taskJobFactory = new TaskJobFactory(taskList, taskDataManager, repositoryManager, repositoryModel);
taskActivityManager.addActivationListener(CONTEXT_TASK_ACTIVATION_LISTENER);
taskActivityMonitor = new TaskActivityMonitor(taskActivityManager, ContextCorePlugin.getContextManager());
taskActivityMonitor.start();
saveParticipant = new ISaveParticipant() {
public void doneSaving(ISaveContext context) {
}
public void prepareToSave(ISaveContext context) throws CoreException {
}
public void rollback(ISaveContext context) {
}
public void saving(ISaveContext context) throws CoreException {
if (context.getKind() == ISaveContext.FULL_SAVE) {
externalizationManager.stop();
}
}
};
ResourcesPlugin.getWorkspace().addSaveParticipant(this, saveParticipant);
ActivityExternalizationParticipant ACTIVITY_EXTERNALIZTAION_PARTICIPANT = new ActivityExternalizationParticipant(
externalizationManager);
externalizationManager.addParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
taskActivityManager.addActivityListener(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
taskActivityMonitor.setExternalizationParticipant(ACTIVITY_EXTERNALIZTAION_PARTICIPANT);
loadDataSources();
new TasksUiInitializationJob().schedule();
} catch (Exception e) {
StatusHandler.log(new Status(IStatus.ERROR, TasksUiPlugin.ID_PLUGIN, "Task list initialization failed", e)); //$NON-NLS-1$
}
}
|
diff --git a/src/mx/ferreyra/dogapp/DogUtil.java b/src/mx/ferreyra/dogapp/DogUtil.java
index f45c9da..5316089 100644
--- a/src/mx/ferreyra/dogapp/DogUtil.java
+++ b/src/mx/ferreyra/dogapp/DogUtil.java
@@ -1,150 +1,150 @@
package mx.ferreyra.dogapp;
import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Build;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
import com.facebook.android.Util;
import com.google.android.apps.analytics.GoogleAnalyticsTracker;
public class DogUtil extends Application{
public static final int DOGWELFARE = 0x01;
public static final int STATISTICS = 0x02;
public static final int LOAD_ROUTE = 0x03;
public static final int NEW_ROUTE = 0x04;
private Integer currentUserId;
private static DogUtil app;
public static final String FACEBOOK_APPID = "360694843999854"; //"120875961350018";
//public static final String APP_ID = "124807174259375";
public static final String TRACK_ID = "UA-27608007-1";
public Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner;
private String routeName;
private static String DEVICE_ID;
public String getRouteName() {
return routeName;
}
public void setRouteName(String routeName) {
this.routeName = routeName;
}
private static final String[] PERMISSIONS =
new String[] {Utilities.PERMISSION_OFFLINE_ACCESS, Utilities.PERMISSION_USER_RELATIONSHIP,
Utilities.PERMISSION_EMAIL,Utilities.PERMISSION_PUBLISH_STREAM, Utilities.PERMISSION_READ_STREAM};
private GoogleAnalyticsTracker gTracker;
public static int TRACKER_VALUE = 55613156;
public void onCreate() {
super.onCreate();
if(app == null)
app = this;
// Loading preferences
String prefer = getString(R.string.preferences_name);
String userId = getString(R.string.preference_user_id);
SharedPreferences pref = getSharedPreferences(prefer, 0);
- userId = pref.getString(userId, null);
- if(userId!=null)
- this.currentUserId = Integer.valueOf(userId);
+ int possibleUserId = pref.getInt(userId, -1);
+ if(possibleUserId>0)
+ this.currentUserId = possibleUserId;
initFacebook();
if(gTracker == null){
gTracker = GoogleAnalyticsTracker.getInstance();
gTracker.startNewSession(TRACK_ID, this);
setTrackerInformation();
}
}
public void initFacebook(){
if (DogUtil.FACEBOOK_APPID == null) {
Util.showAlert(getApplicationContext(), getResources().getString(R.string.warning) , getResources().getString(R.string.invalid_facebook_id));
}
if(mFacebook ==null)
mFacebook = new Facebook(DogUtil.FACEBOOK_APPID);
if(mAsyncRunner ==null)
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
}
public Facebook getFacebook(){
return mFacebook;
}
public AsyncFacebookRunner getAsyncFacebookRunner(){
return mAsyncRunner;
}
public String[] getPermissions(){
return PERMISSIONS;
}
public GoogleAnalyticsTracker getTracker(){
if(gTracker == null){
gTracker = GoogleAnalyticsTracker.getInstance();
gTracker.startNewSession(TRACK_ID, this);
}
return gTracker;
}
public void setTrackerInformation(){
gTracker.setCustomVar(1, "Application Details", "Android, "+getVersionName(this, DogUtil.class) +", "+
Build.MODEL+ ", "+android.os.Build.VERSION.RELEASE , 1);
}
public static String getVersionName(Context context, Class cls)
{
try {
ComponentName comp = new ComponentName(context, cls);
PackageInfo pinfo = context.getPackageManager().getPackageInfo(comp.getPackageName(), 0);
return pinfo.versionName;
} catch (android.content.pm.PackageManager.NameNotFoundException e) {
return null;
}
}
public static boolean checkNumber(String string){
try{
for (int i = 0; i < string.length(); i++) {
if (!Character.isDigit(string.charAt(i)))
return false;
}
}catch (NumberFormatException e) {
return false;
}
return true;
}
public static void setDeviceID(String deviceId){
DEVICE_ID = deviceId;
}
public static String getDeviceUniqueNumber(){
return DEVICE_ID;
}
public static DogUtil getInstance() {
return app;
}
public Integer getCurrentUserId() {
return this.currentUserId;
}
}
| true | true | public void onCreate() {
super.onCreate();
if(app == null)
app = this;
// Loading preferences
String prefer = getString(R.string.preferences_name);
String userId = getString(R.string.preference_user_id);
SharedPreferences pref = getSharedPreferences(prefer, 0);
userId = pref.getString(userId, null);
if(userId!=null)
this.currentUserId = Integer.valueOf(userId);
initFacebook();
if(gTracker == null){
gTracker = GoogleAnalyticsTracker.getInstance();
gTracker.startNewSession(TRACK_ID, this);
setTrackerInformation();
}
}
| public void onCreate() {
super.onCreate();
if(app == null)
app = this;
// Loading preferences
String prefer = getString(R.string.preferences_name);
String userId = getString(R.string.preference_user_id);
SharedPreferences pref = getSharedPreferences(prefer, 0);
int possibleUserId = pref.getInt(userId, -1);
if(possibleUserId>0)
this.currentUserId = possibleUserId;
initFacebook();
if(gTracker == null){
gTracker = GoogleAnalyticsTracker.getInstance();
gTracker.startNewSession(TRACK_ID, this);
setTrackerInformation();
}
}
|
diff --git a/contrib/stress/src/org/apache/cassandra/contrib/stress/Session.java b/contrib/stress/src/org/apache/cassandra/contrib/stress/Session.java
index 853d5987..99811408 100644
--- a/contrib/stress/src/org/apache/cassandra/contrib/stress/Session.java
+++ b/contrib/stress/src/org/apache/cassandra/contrib/stress/Session.java
@@ -1,384 +1,384 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.contrib.stress;
import org.apache.cassandra.db.ColumnFamilyType;
import org.apache.cassandra.thrift.*;
import org.apache.commons.cli.*;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLongArray;
public class Session
{
// command line options
public static final Options availableOptions = new Options();
public final AtomicIntegerArray operationCount;
public final AtomicIntegerArray keyCount;
public final AtomicLongArray latencies;
static
{
availableOptions.addOption("h", "help", false, "Show this help message and exit");
availableOptions.addOption("n", "num-keys", true, "Number of keys, default:1000000");
availableOptions.addOption("N", "skip-keys", true, "Fraction of keys to skip initially, default:0");
availableOptions.addOption("t", "threads", true, "Number of threads to use, default:50");
availableOptions.addOption("c", "columns", true, "Number of columns per key, default:5");
availableOptions.addOption("S", "column-size", true, "Size of column values in bytes, default:34");
availableOptions.addOption("C", "cardinality", true, "Number of unique values stored in columns, default:50");
availableOptions.addOption("d", "nodes", true, "Host nodes (comma separated), default:locahost");
availableOptions.addOption("s", "stdev", true, "Standard Deviation Factor, default:0.1");
availableOptions.addOption("r", "random", false, "Use random key generator (STDEV will have no effect), default:false");
availableOptions.addOption("f", "file", true, "Write output to given file");
availableOptions.addOption("p", "port", true, "Thrift port, default:9160");
availableOptions.addOption("m", "unframed", false, "Use unframed transport, default:false");
availableOptions.addOption("o", "operation", true, "Operation to perform (INSERT, READ, RANGE_SLICE, INDEXED_RANGE_SLICE, MULTI_GET), default:INSERT");
availableOptions.addOption("u", "supercolumns", true, "Number of super columns per key, default:1");
availableOptions.addOption("y", "family-type", true, "Column Family Type (Super, Standard), default:Standard");
availableOptions.addOption("k", "keep-going", false, "Ignore errors inserting or reading, default:false");
availableOptions.addOption("i", "progress-interval", true, "Progress Report Interval (seconds), default:10");
availableOptions.addOption("g", "keys-per-call", true, "Number of keys to get_range_slices or multiget per call, default:1000");
availableOptions.addOption("l", "replication-factor", true, "Replication Factor to use when creating needed column families, default:1");
availableOptions.addOption("e", "consistency-level", true, "Consistency Level to use (ONE, QUORUM, LOCAL_QUORUM, EACH_QUORUM, ALL, ANY), default:ONE");
availableOptions.addOption("x", "create-index", true, "Type of index to create on needed column families (KEYS)");
}
private int numKeys = 1000 * 1000;
private float skipKeys = 0;
private int threads = 50;
private int columns = 5;
private int columnSize = 34;
private int cardinality = 50;
private String[] nodes = new String[] { "127.0.0.1" };
private boolean random = false;
private boolean unframed = false;
private boolean ignoreErrors = false;
private int port = 9160;
private int superColumns = 1;
private int progressInterval = 10;
private int keysPerCall = 1000;
private int replicationFactor = 1;
private PrintStream out = System.out;
private IndexType indexType = null;
private Stress.Operation operation = Stress.Operation.INSERT;
private ColumnFamilyType columnFamilyType = ColumnFamilyType.Standard;
private ConsistencyLevel consistencyLevel = ConsistencyLevel.ONE;
// required by Gaussian distribution.
protected int mean;
protected float sigma;
public Session(String[] arguments) throws IllegalArgumentException
{
float STDev = 0.1f;
CommandLineParser parser = new PosixParser();
try
{
CommandLine cmd = parser.parse(availableOptions, arguments);
if (cmd.hasOption("h"))
throw new IllegalArgumentException("help");
if (cmd.hasOption("n"))
numKeys = Integer.parseInt(cmd.getOptionValue("n"));
if (cmd.hasOption("N"))
skipKeys = Float.parseFloat(cmd.getOptionValue("N"));
if (cmd.hasOption("t"))
threads = Integer.parseInt(cmd.getOptionValue("t"));
if (cmd.hasOption("c"))
columns = Integer.parseInt(cmd.getOptionValue("c"));
if (cmd.hasOption("S"))
columnSize = Integer.parseInt(cmd.getOptionValue("S"));
if (cmd.hasOption("C"))
- cardinality = Integer.parseInt(cmd.getOptionValue("t"));
+ cardinality = Integer.parseInt(cmd.getOptionValue("C"));
if (cmd.hasOption("d"))
nodes = cmd.getOptionValue("d").split(",");
if (cmd.hasOption("s"))
STDev = Float.parseFloat(cmd.getOptionValue("s"));
if (cmd.hasOption("r"))
random = Boolean.parseBoolean(cmd.getOptionValue("r"));
if (cmd.hasOption("f"))
{
try
{
out = new PrintStream(new FileOutputStream(cmd.getOptionValue("f")));
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
if (cmd.hasOption("p"))
port = Integer.parseInt(cmd.getOptionValue("p"));
if (cmd.hasOption("m"))
unframed = Boolean.parseBoolean(cmd.getOptionValue("m"));
if (cmd.hasOption("o"))
operation = Stress.Operation.valueOf(cmd.getOptionValue("o").toUpperCase());
if (cmd.hasOption("u"))
superColumns = Integer.parseInt(cmd.getOptionValue("u"));
if (cmd.hasOption("y"))
columnFamilyType = ColumnFamilyType.valueOf(cmd.getOptionValue("y"));
if (cmd.hasOption("k"))
ignoreErrors = true;
if (cmd.hasOption("i"))
progressInterval = Integer.parseInt(cmd.getOptionValue("i"));
if (cmd.hasOption("g"))
keysPerCall = Integer.parseInt(cmd.getOptionValue("g"));
if (cmd.hasOption("l"))
replicationFactor = Integer.parseInt(cmd.getOptionValue("l"));
if (cmd.hasOption("e"))
consistencyLevel = ConsistencyLevel.valueOf(cmd.getOptionValue("e").toUpperCase());
if (cmd.hasOption("x"))
indexType = IndexType.valueOf(cmd.getOptionValue("x").toUpperCase());
}
catch (ParseException e)
{
throw new IllegalArgumentException(e.getMessage(), e);
}
mean = numKeys / 2;
sigma = numKeys * STDev;
operationCount = new AtomicIntegerArray(threads);
keyCount = new AtomicIntegerArray(threads);
latencies = new AtomicLongArray(threads);
}
public int getCardinality()
{
return cardinality;
}
public int getColumnSize()
{
return columnSize;
}
public boolean isUnframed()
{
return unframed;
}
public int getColumnsPerKey()
{
return columns;
}
public ColumnFamilyType getColumnFamilyType()
{
return columnFamilyType;
}
public int getNumKeys()
{
return numKeys;
}
public int getThreads()
{
return threads;
}
public float getSkipKeys()
{
return skipKeys;
}
public int getSuperColumns()
{
return superColumns;
}
public int getKeysPerThread()
{
return numKeys / threads;
}
public int getTotalKeysLength()
{
return Integer.toString(numKeys).length();
}
public ConsistencyLevel getConsistencyLevel()
{
return consistencyLevel;
}
public boolean ignoreErrors()
{
return ignoreErrors;
}
public Stress.Operation getOperation()
{
return operation;
}
public PrintStream getOutputStream()
{
return out;
}
public int getProgressInterval()
{
return progressInterval;
}
public boolean useRandomGenerator()
{
return random;
}
public int getKeysPerCall()
{
return keysPerCall;
}
// required by Gaussian distribution
public int getMean()
{
return mean;
}
// required by Gaussian distribution
public float getSigma()
{
return sigma;
}
/**
* Create Keyspace1 with Standard1 and Super1 column families
*/
public void createKeySpaces()
{
KsDef keyspace = new KsDef();
ColumnDef standardColumn = new ColumnDef(ByteBuffer.wrap("C1".getBytes()), "UTF8Type");
ColumnDef superSubColumn = new ColumnDef(ByteBuffer.wrap("S1".getBytes()), "UTF8Type");
if (indexType != null)
standardColumn.setIndex_type(indexType).setIndex_name("Idx1");
// column family for standard columns
CfDef standardCfDef = new CfDef("Keyspace1", "Standard1").setColumn_metadata(Arrays.asList(standardColumn));
// column family with super columns
CfDef superCfDef = new CfDef("Keyspace1", "Super1").setColumn_metadata(Arrays.asList(superSubColumn)).setColumn_type("Super");
keyspace.setName("Keyspace1");
keyspace.setStrategy_class("org.apache.cassandra.locator.SimpleStrategy");
keyspace.setReplication_factor(replicationFactor);
keyspace.setCf_defs(new ArrayList<CfDef>(Arrays.asList(standardCfDef, superCfDef)));
Cassandra.Client client = getClient(false);
try
{
client.system_add_keyspace(keyspace);
out.println(String.format("Created keyspaces. Sleeping %ss for propagation.", nodes.length));
Thread.sleep(nodes.length * 1000); // seconds
}
catch (InvalidRequestException e)
{
out.println(e.getWhy());
}
catch (Exception e)
{
out.println(e.getMessage());
}
}
/**
* Thrift client connection with Keyspace1 set.
* @return cassandra client connection
*/
public Cassandra.Client getClient()
{
return getClient(true);
}
/**
* Thrift client connection
* @param setKeyspace - should we set keyspace for client or not
* @return cassandra client connection
*/
public Cassandra.Client getClient(boolean setKeyspace)
{
// random node selection for fake load balancing
String currentNode = nodes[Stress.randomizer.nextInt(nodes.length)];
TSocket socket = new TSocket(currentNode, port);
TTransport transport = (isUnframed()) ? socket : new TFramedTransport(socket);
Cassandra.Client client = new Cassandra.Client(new TBinaryProtocol(transport));
try
{
transport.open();
if (setKeyspace)
{
client.set_keyspace("Keyspace1");
}
}
catch (InvalidRequestException e)
{
throw new RuntimeException(e.getWhy());
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
return client;
}
}
| true | true | public Session(String[] arguments) throws IllegalArgumentException
{
float STDev = 0.1f;
CommandLineParser parser = new PosixParser();
try
{
CommandLine cmd = parser.parse(availableOptions, arguments);
if (cmd.hasOption("h"))
throw new IllegalArgumentException("help");
if (cmd.hasOption("n"))
numKeys = Integer.parseInt(cmd.getOptionValue("n"));
if (cmd.hasOption("N"))
skipKeys = Float.parseFloat(cmd.getOptionValue("N"));
if (cmd.hasOption("t"))
threads = Integer.parseInt(cmd.getOptionValue("t"));
if (cmd.hasOption("c"))
columns = Integer.parseInt(cmd.getOptionValue("c"));
if (cmd.hasOption("S"))
columnSize = Integer.parseInt(cmd.getOptionValue("S"));
if (cmd.hasOption("C"))
cardinality = Integer.parseInt(cmd.getOptionValue("t"));
if (cmd.hasOption("d"))
nodes = cmd.getOptionValue("d").split(",");
if (cmd.hasOption("s"))
STDev = Float.parseFloat(cmd.getOptionValue("s"));
if (cmd.hasOption("r"))
random = Boolean.parseBoolean(cmd.getOptionValue("r"));
if (cmd.hasOption("f"))
{
try
{
out = new PrintStream(new FileOutputStream(cmd.getOptionValue("f")));
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
if (cmd.hasOption("p"))
port = Integer.parseInt(cmd.getOptionValue("p"));
if (cmd.hasOption("m"))
unframed = Boolean.parseBoolean(cmd.getOptionValue("m"));
if (cmd.hasOption("o"))
operation = Stress.Operation.valueOf(cmd.getOptionValue("o").toUpperCase());
if (cmd.hasOption("u"))
superColumns = Integer.parseInt(cmd.getOptionValue("u"));
if (cmd.hasOption("y"))
columnFamilyType = ColumnFamilyType.valueOf(cmd.getOptionValue("y"));
if (cmd.hasOption("k"))
ignoreErrors = true;
if (cmd.hasOption("i"))
progressInterval = Integer.parseInt(cmd.getOptionValue("i"));
if (cmd.hasOption("g"))
keysPerCall = Integer.parseInt(cmd.getOptionValue("g"));
if (cmd.hasOption("l"))
replicationFactor = Integer.parseInt(cmd.getOptionValue("l"));
if (cmd.hasOption("e"))
consistencyLevel = ConsistencyLevel.valueOf(cmd.getOptionValue("e").toUpperCase());
if (cmd.hasOption("x"))
indexType = IndexType.valueOf(cmd.getOptionValue("x").toUpperCase());
}
catch (ParseException e)
{
throw new IllegalArgumentException(e.getMessage(), e);
}
mean = numKeys / 2;
sigma = numKeys * STDev;
operationCount = new AtomicIntegerArray(threads);
keyCount = new AtomicIntegerArray(threads);
latencies = new AtomicLongArray(threads);
}
| public Session(String[] arguments) throws IllegalArgumentException
{
float STDev = 0.1f;
CommandLineParser parser = new PosixParser();
try
{
CommandLine cmd = parser.parse(availableOptions, arguments);
if (cmd.hasOption("h"))
throw new IllegalArgumentException("help");
if (cmd.hasOption("n"))
numKeys = Integer.parseInt(cmd.getOptionValue("n"));
if (cmd.hasOption("N"))
skipKeys = Float.parseFloat(cmd.getOptionValue("N"));
if (cmd.hasOption("t"))
threads = Integer.parseInt(cmd.getOptionValue("t"));
if (cmd.hasOption("c"))
columns = Integer.parseInt(cmd.getOptionValue("c"));
if (cmd.hasOption("S"))
columnSize = Integer.parseInt(cmd.getOptionValue("S"));
if (cmd.hasOption("C"))
cardinality = Integer.parseInt(cmd.getOptionValue("C"));
if (cmd.hasOption("d"))
nodes = cmd.getOptionValue("d").split(",");
if (cmd.hasOption("s"))
STDev = Float.parseFloat(cmd.getOptionValue("s"));
if (cmd.hasOption("r"))
random = Boolean.parseBoolean(cmd.getOptionValue("r"));
if (cmd.hasOption("f"))
{
try
{
out = new PrintStream(new FileOutputStream(cmd.getOptionValue("f")));
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
}
if (cmd.hasOption("p"))
port = Integer.parseInt(cmd.getOptionValue("p"));
if (cmd.hasOption("m"))
unframed = Boolean.parseBoolean(cmd.getOptionValue("m"));
if (cmd.hasOption("o"))
operation = Stress.Operation.valueOf(cmd.getOptionValue("o").toUpperCase());
if (cmd.hasOption("u"))
superColumns = Integer.parseInt(cmd.getOptionValue("u"));
if (cmd.hasOption("y"))
columnFamilyType = ColumnFamilyType.valueOf(cmd.getOptionValue("y"));
if (cmd.hasOption("k"))
ignoreErrors = true;
if (cmd.hasOption("i"))
progressInterval = Integer.parseInt(cmd.getOptionValue("i"));
if (cmd.hasOption("g"))
keysPerCall = Integer.parseInt(cmd.getOptionValue("g"));
if (cmd.hasOption("l"))
replicationFactor = Integer.parseInt(cmd.getOptionValue("l"));
if (cmd.hasOption("e"))
consistencyLevel = ConsistencyLevel.valueOf(cmd.getOptionValue("e").toUpperCase());
if (cmd.hasOption("x"))
indexType = IndexType.valueOf(cmd.getOptionValue("x").toUpperCase());
}
catch (ParseException e)
{
throw new IllegalArgumentException(e.getMessage(), e);
}
mean = numKeys / 2;
sigma = numKeys * STDev;
operationCount = new AtomicIntegerArray(threads);
keyCount = new AtomicIntegerArray(threads);
latencies = new AtomicLongArray(threads);
}
|
diff --git a/crypto/src/org/bouncycastle/cms/CMSEnvelopedGenerator.java b/crypto/src/org/bouncycastle/cms/CMSEnvelopedGenerator.java
index b086f88d..23c63025 100644
--- a/crypto/src/org/bouncycastle/cms/CMSEnvelopedGenerator.java
+++ b/crypto/src/org/bouncycastle/cms/CMSEnvelopedGenerator.java
@@ -1,325 +1,325 @@
package org.bouncycastle.cms;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.DEREncodable;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.DERObjectIdentifier;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.cms.KEKIdentifier;
import org.bouncycastle.asn1.cms.OriginatorIdentifierOrKey;
import org.bouncycastle.asn1.cms.OriginatorPublicKey;
import org.bouncycastle.asn1.cms.ecc.MQVuserKeyingMaterial;
import org.bouncycastle.asn1.kisa.KISAObjectIdentifiers;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.ntt.NTTObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PBKDF2Params;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.x9.X9ObjectIdentifiers;
import org.bouncycastle.jce.spec.MQVPrivateKeySpec;
import org.bouncycastle.jce.spec.MQVPublicKeySpec;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKey;
import javax.crypto.spec.RC2ParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.AlgorithmParameterGenerator;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Provider;
import java.security.cert.X509Certificate;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECParameterSpec;
import java.util.ArrayList;
import java.util.List;
/**
* General class for generating a CMS enveloped-data message.
*
* A simple example of usage.
*
* <pre>
* CMSEnvelopedDataGenerator fact = new CMSEnvelopedDataGenerator();
*
* fact.addKeyTransRecipient(cert);
*
* CMSEnvelopedData data = fact.generate(content, algorithm, "BC");
* </pre>
*/
public class CMSEnvelopedGenerator
{
public static final String DES_EDE3_CBC = PKCSObjectIdentifiers.des_EDE3_CBC.getId();
public static final String RC2_CBC = PKCSObjectIdentifiers.RC2_CBC.getId();
public static final String IDEA_CBC = "1.3.6.1.4.1.188.7.1.1.2";
public static final String CAST5_CBC = "1.2.840.113533.7.66.10";
public static final String AES128_CBC = NISTObjectIdentifiers.id_aes128_CBC.getId();
public static final String AES192_CBC = NISTObjectIdentifiers.id_aes192_CBC.getId();
public static final String AES256_CBC = NISTObjectIdentifiers.id_aes256_CBC.getId();
public static final String CAMELLIA128_CBC = NTTObjectIdentifiers.id_camellia128_cbc.getId();
public static final String CAMELLIA192_CBC = NTTObjectIdentifiers.id_camellia192_cbc.getId();
public static final String CAMELLIA256_CBC = NTTObjectIdentifiers.id_camellia256_cbc.getId();
public static final String SEED_CBC = KISAObjectIdentifiers.id_seedCBC.getId();
public static final String DES_EDE3_WRAP = PKCSObjectIdentifiers.id_alg_CMS3DESwrap.getId();
public static final String AES128_WRAP = NISTObjectIdentifiers.id_aes128_wrap.getId();
public static final String AES192_WRAP = NISTObjectIdentifiers.id_aes192_wrap.getId();
public static final String AES256_WRAP = NISTObjectIdentifiers.id_aes256_wrap.getId();
public static final String CAMELLIA128_WRAP = NTTObjectIdentifiers.id_camellia128_wrap.getId();
public static final String CAMELLIA192_WRAP = NTTObjectIdentifiers.id_camellia192_wrap.getId();
public static final String CAMELLIA256_WRAP = NTTObjectIdentifiers.id_camellia256_wrap.getId();
public static final String SEED_WRAP = KISAObjectIdentifiers.id_npki_app_cmsSeed_wrap.getId();
public static final String ECDH_SHA1KDF = X9ObjectIdentifiers.dhSinglePass_stdDH_sha1kdf_scheme.getId();
public static final String ECMQV_SHA1KDF = X9ObjectIdentifiers.mqvSinglePass_sha1kdf_scheme.getId();
final List recipientInfoGenerators = new ArrayList();
final SecureRandom rand;
/**
* base constructor
*/
public CMSEnvelopedGenerator()
{
this(new SecureRandom());
}
/**
* constructor allowing specific source of randomness
* @param rand instance of SecureRandom to use
*/
public CMSEnvelopedGenerator(
SecureRandom rand)
{
this.rand = rand;
}
/**
* add a recipient.
*
* @param cert recipient's public key certificate
* @exception IllegalArgumentException if there is a problem with the certificate
*/
public void addKeyTransRecipient(
X509Certificate cert)
throws IllegalArgumentException
{
KeyTransRecipientInfoGenerator ktrig = new KeyTransRecipientInfoGenerator();
ktrig.setRecipientCert(cert);
recipientInfoGenerators.add(ktrig);
}
/**
* add a recipient
*
* @param key the public key used by the recipient
* @param subKeyId the identifier for the recipient's public key
* @exception IllegalArgumentException if there is a problem with the key
*/
public void addKeyTransRecipient(
PublicKey key,
byte[] subKeyId)
throws IllegalArgumentException
{
KeyTransRecipientInfoGenerator ktrig = new KeyTransRecipientInfoGenerator();
ktrig.setRecipientPublicKey(key);
ktrig.setSubjectKeyIdentifier(new DEROctetString(subKeyId));
recipientInfoGenerators.add(ktrig);
}
/**
* add a KEK recipient.
* @param key the secret key to use for wrapping
* @param keyIdentifier the byte string that identifies the key
*/
public void addKEKRecipient(
SecretKey key,
byte[] keyIdentifier)
{
KEKRecipientInfoGenerator kekrig = new KEKRecipientInfoGenerator();
kekrig.setKEKIdentifier(new KEKIdentifier(keyIdentifier, null, null));
kekrig.setWrapKey(key);
recipientInfoGenerators.add(kekrig);
}
public void addPasswordRecipient(
CMSPBEKey pbeKey,
String kekAlgorithmOid)
{
PBKDF2Params params = new PBKDF2Params(pbeKey.getSalt(), pbeKey.getIterationCount());
PasswordRecipientInfoGenerator prig = new PasswordRecipientInfoGenerator();
prig.setDerivationAlg(new AlgorithmIdentifier(PKCSObjectIdentifiers.id_PBKDF2, params));
prig.setWrapKey(new SecretKeySpec(pbeKey.getEncoded(kekAlgorithmOid), kekAlgorithmOid));
recipientInfoGenerators.add(prig);
}
/**
* Add a key agreement based recipient.
*
* @param agreementAlgorithm key agreement algorithm to use.
* @param senderPrivateKey private key to initialise sender side of agreement with.
* @param senderPublicKey sender public key to include with message.
* @param recipientCert recipient's public key certificate.
* @param cekWrapAlgorithm OID for key wrapping algorithm to use.
* @param provider provider to use for the agreement calculation.
* @exception NoSuchProviderException if the specified provider cannot be found
* @exception NoSuchAlgorithmException if the algorithm requested cannot be found
* @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
*/
public void addKeyAgreementRecipient(
String agreementAlgorithm,
PrivateKey senderPrivateKey,
PublicKey senderPublicKey,
X509Certificate recipientCert,
String cekWrapAlgorithm,
String provider)
throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeyException
{
addKeyAgreementRecipient(agreementAlgorithm, senderPrivateKey, senderPublicKey, recipientCert, cekWrapAlgorithm, CMSUtils.getProvider(provider));
}
/**
* Add a key agreement based recipient.
*
* @param agreementAlgorithm key agreement algorithm to use.
* @param senderPrivateKey private key to initialise sender side of agreement with.
* @param senderPublicKey sender public key to include with message.
* @param recipientCert recipient's public key certificate.
* @param cekWrapAlgorithm OID for key wrapping algorithm to use.
* @param provider provider to use for the agreement calculation.
* @exception NoSuchAlgorithmException if the algorithm requested cannot be found
* @exception InvalidKeyException if the keys are inappropriate for the algorithm specified
*/
public void addKeyAgreementRecipient(
String agreementAlgorithm,
PrivateKey senderPrivateKey,
PublicKey senderPublicKey,
X509Certificate recipientCert,
String cekWrapAlgorithm,
Provider provider)
throws NoSuchAlgorithmException, InvalidKeyException
{
try
{
OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
createOriginatorPublicKey(senderPublicKey));
PublicKey recipientPublicKey = recipientCert.getPublicKey();
ASN1OctetString ukm = null;
if (agreementAlgorithm.equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF))
{
ECParameterSpec ecParamSpec = ((ECPublicKey)senderPublicKey).getParams();
KeyPairGenerator ephemKPG = KeyPairGenerator.getInstance(agreementAlgorithm, provider);
ephemKPG.initialize(ecParamSpec, rand);
KeyPair ephemKP = ephemKPG.generateKeyPair();
ukm = new DEROctetString(
new MQVuserKeyingMaterial(
createOriginatorPublicKey(ephemKP.getPublic()), null));
recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey);
senderPrivateKey = new MQVPrivateKeySpec(
senderPrivateKey, ephemKP.getPrivate(), ephemKP.getPublic());
}
KeyAgreement agreement = KeyAgreement.getInstance(agreementAlgorithm, provider);
agreement.init(senderPrivateKey, rand);
agreement.doPhase(recipientPublicKey, true);
SecretKey wrapKey = agreement.generateSecret(cekWrapAlgorithm);
KeyAgreeRecipientInfoGenerator karig = new KeyAgreeRecipientInfoGenerator();
karig.setAlgorithmOID(new DERObjectIdentifier(agreementAlgorithm));
karig.setOriginator(originator);
karig.setRecipientCert(recipientCert);
karig.setUKM(ukm);
karig.setWrapKey(wrapKey);
karig.setWrapAlgorithmOID(new DERObjectIdentifier(cekWrapAlgorithm));
recipientInfoGenerators.add(karig);
}
catch (InvalidAlgorithmParameterException e)
{
- throw new InvalidKeyException("can't determine ephemeral key pair parameters from public key: " + e);
+ throw new InvalidKeyException("cannot determine ephemeral key pair parameters from public key: " + e);
}
catch (IOException e)
{
throw new InvalidKeyException("cannot extract originator public key: " + e);
}
}
protected AlgorithmIdentifier getAlgorithmIdentifier(String encryptionOID, AlgorithmParameters params) throws IOException
{
DEREncodable asn1Params;
if (params != null)
{
asn1Params = ASN1Object.fromByteArray(params.getEncoded("ASN.1"));
}
else
{
asn1Params = DERNull.INSTANCE;
}
return new AlgorithmIdentifier(
new DERObjectIdentifier(encryptionOID),
asn1Params);
}
protected AlgorithmParameters generateParameters(String encryptionOID, SecretKey encKey, Provider encProvider)
throws CMSException
{
try
{
AlgorithmParameterGenerator pGen = AlgorithmParameterGenerator.getInstance(encryptionOID, encProvider);
if (encryptionOID.equals(RC2_CBC))
{
byte[] iv = new byte[8];
rand.nextBytes(iv);
try
{
pGen.init(new RC2ParameterSpec(encKey.getEncoded().length * 8, iv), rand);
}
catch (InvalidAlgorithmParameterException e)
{
throw new CMSException("parameters generation error: " + e, e);
}
}
return pGen.generateParameters();
}
catch (NoSuchAlgorithmException e)
{
return null;
}
}
private static OriginatorPublicKey createOriginatorPublicKey(PublicKey publicKey)
throws IOException
{
SubjectPublicKeyInfo spki = SubjectPublicKeyInfo.getInstance(
ASN1Object.fromByteArray(publicKey.getEncoded()));
return new OriginatorPublicKey(
new AlgorithmIdentifier(spki.getAlgorithmId().getObjectId(), DERNull.INSTANCE),
spki.getPublicKeyData().getBytes());
}
}
| true | true | public void addKeyAgreementRecipient(
String agreementAlgorithm,
PrivateKey senderPrivateKey,
PublicKey senderPublicKey,
X509Certificate recipientCert,
String cekWrapAlgorithm,
Provider provider)
throws NoSuchAlgorithmException, InvalidKeyException
{
try
{
OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
createOriginatorPublicKey(senderPublicKey));
PublicKey recipientPublicKey = recipientCert.getPublicKey();
ASN1OctetString ukm = null;
if (agreementAlgorithm.equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF))
{
ECParameterSpec ecParamSpec = ((ECPublicKey)senderPublicKey).getParams();
KeyPairGenerator ephemKPG = KeyPairGenerator.getInstance(agreementAlgorithm, provider);
ephemKPG.initialize(ecParamSpec, rand);
KeyPair ephemKP = ephemKPG.generateKeyPair();
ukm = new DEROctetString(
new MQVuserKeyingMaterial(
createOriginatorPublicKey(ephemKP.getPublic()), null));
recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey);
senderPrivateKey = new MQVPrivateKeySpec(
senderPrivateKey, ephemKP.getPrivate(), ephemKP.getPublic());
}
KeyAgreement agreement = KeyAgreement.getInstance(agreementAlgorithm, provider);
agreement.init(senderPrivateKey, rand);
agreement.doPhase(recipientPublicKey, true);
SecretKey wrapKey = agreement.generateSecret(cekWrapAlgorithm);
KeyAgreeRecipientInfoGenerator karig = new KeyAgreeRecipientInfoGenerator();
karig.setAlgorithmOID(new DERObjectIdentifier(agreementAlgorithm));
karig.setOriginator(originator);
karig.setRecipientCert(recipientCert);
karig.setUKM(ukm);
karig.setWrapKey(wrapKey);
karig.setWrapAlgorithmOID(new DERObjectIdentifier(cekWrapAlgorithm));
recipientInfoGenerators.add(karig);
}
catch (InvalidAlgorithmParameterException e)
{
throw new InvalidKeyException("can't determine ephemeral key pair parameters from public key: " + e);
}
catch (IOException e)
{
throw new InvalidKeyException("cannot extract originator public key: " + e);
}
}
| public void addKeyAgreementRecipient(
String agreementAlgorithm,
PrivateKey senderPrivateKey,
PublicKey senderPublicKey,
X509Certificate recipientCert,
String cekWrapAlgorithm,
Provider provider)
throws NoSuchAlgorithmException, InvalidKeyException
{
try
{
OriginatorIdentifierOrKey originator = new OriginatorIdentifierOrKey(
createOriginatorPublicKey(senderPublicKey));
PublicKey recipientPublicKey = recipientCert.getPublicKey();
ASN1OctetString ukm = null;
if (agreementAlgorithm.equals(CMSEnvelopedGenerator.ECMQV_SHA1KDF))
{
ECParameterSpec ecParamSpec = ((ECPublicKey)senderPublicKey).getParams();
KeyPairGenerator ephemKPG = KeyPairGenerator.getInstance(agreementAlgorithm, provider);
ephemKPG.initialize(ecParamSpec, rand);
KeyPair ephemKP = ephemKPG.generateKeyPair();
ukm = new DEROctetString(
new MQVuserKeyingMaterial(
createOriginatorPublicKey(ephemKP.getPublic()), null));
recipientPublicKey = new MQVPublicKeySpec(recipientPublicKey, recipientPublicKey);
senderPrivateKey = new MQVPrivateKeySpec(
senderPrivateKey, ephemKP.getPrivate(), ephemKP.getPublic());
}
KeyAgreement agreement = KeyAgreement.getInstance(agreementAlgorithm, provider);
agreement.init(senderPrivateKey, rand);
agreement.doPhase(recipientPublicKey, true);
SecretKey wrapKey = agreement.generateSecret(cekWrapAlgorithm);
KeyAgreeRecipientInfoGenerator karig = new KeyAgreeRecipientInfoGenerator();
karig.setAlgorithmOID(new DERObjectIdentifier(agreementAlgorithm));
karig.setOriginator(originator);
karig.setRecipientCert(recipientCert);
karig.setUKM(ukm);
karig.setWrapKey(wrapKey);
karig.setWrapAlgorithmOID(new DERObjectIdentifier(cekWrapAlgorithm));
recipientInfoGenerators.add(karig);
}
catch (InvalidAlgorithmParameterException e)
{
throw new InvalidKeyException("cannot determine ephemeral key pair parameters from public key: " + e);
}
catch (IOException e)
{
throw new InvalidKeyException("cannot extract originator public key: " + e);
}
}
|
diff --git a/deegree-services/src/main/java/org/deegree/services/controller/ows/OWSException100XMLAdapter.java b/deegree-services/src/main/java/org/deegree/services/controller/ows/OWSException100XMLAdapter.java
index 085ffd48e0..e658484cb2 100644
--- a/deegree-services/src/main/java/org/deegree/services/controller/ows/OWSException100XMLAdapter.java
+++ b/deegree-services/src/main/java/org/deegree/services/controller/ows/OWSException100XMLAdapter.java
@@ -1,81 +1,81 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2.1 of the License, or (at your option)
any later version.
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.services.controller.ows;
import static org.deegree.commons.xml.CommonNamespaces.XSINS;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.deegree.services.controller.exception.serializer.XMLExceptionSerializer;
/**
* {@link XMLExceptionSerializer} for OWS Commons 1.0.0 ExceptionReports.
*
* @author <a href="mailto:[email protected]">Markus Schneider</a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class OWSException100XMLAdapter extends XMLExceptionSerializer<OWSException> {
private static final String OWS_NS = "http://www.opengis.net/ows";
private static final String OWS_SCHEMA = "http://schemas.opengis.net/ows/1.0.0/owsExceptionReport.xsd";
@Override
public void serializeExceptionToXML( XMLStreamWriter writer, OWSException ex )
throws XMLStreamException {
if ( ex == null || writer == null ) {
return;
}
writer.setPrefix( "ows", OWS_NS );
writer.setPrefix( "xsi", XSINS );
writer.writeStartElement( OWS_NS, "ExceptionReport" );
writer.writeAttribute( XSINS, "schemaLocation", OWS_NS + " " + OWS_SCHEMA );
writer.writeAttribute( "version", "1.0.0" );
writer.writeStartElement( OWS_NS, "Exception" );
writer.writeAttribute( "exceptionCode", ex.getExceptionCode() );
if ( ex.getLocator() != null && !"".equals( ex.getLocator().trim() ) ) {
writer.writeAttribute( "locator", ex.getLocator() );
}
writer.writeStartElement( OWS_NS, "ExceptionText" );
- writer.writeCharacters( ex.getMessage() );
+ writer.writeCharacters( ex.getMessage() != null ? ex.getMessage() : "not available" );
writer.writeEndElement();
writer.writeEndElement(); // Exception
writer.writeEndElement(); // ExceptionReport
}
}
| true | true | public void serializeExceptionToXML( XMLStreamWriter writer, OWSException ex )
throws XMLStreamException {
if ( ex == null || writer == null ) {
return;
}
writer.setPrefix( "ows", OWS_NS );
writer.setPrefix( "xsi", XSINS );
writer.writeStartElement( OWS_NS, "ExceptionReport" );
writer.writeAttribute( XSINS, "schemaLocation", OWS_NS + " " + OWS_SCHEMA );
writer.writeAttribute( "version", "1.0.0" );
writer.writeStartElement( OWS_NS, "Exception" );
writer.writeAttribute( "exceptionCode", ex.getExceptionCode() );
if ( ex.getLocator() != null && !"".equals( ex.getLocator().trim() ) ) {
writer.writeAttribute( "locator", ex.getLocator() );
}
writer.writeStartElement( OWS_NS, "ExceptionText" );
writer.writeCharacters( ex.getMessage() );
writer.writeEndElement();
writer.writeEndElement(); // Exception
writer.writeEndElement(); // ExceptionReport
}
| public void serializeExceptionToXML( XMLStreamWriter writer, OWSException ex )
throws XMLStreamException {
if ( ex == null || writer == null ) {
return;
}
writer.setPrefix( "ows", OWS_NS );
writer.setPrefix( "xsi", XSINS );
writer.writeStartElement( OWS_NS, "ExceptionReport" );
writer.writeAttribute( XSINS, "schemaLocation", OWS_NS + " " + OWS_SCHEMA );
writer.writeAttribute( "version", "1.0.0" );
writer.writeStartElement( OWS_NS, "Exception" );
writer.writeAttribute( "exceptionCode", ex.getExceptionCode() );
if ( ex.getLocator() != null && !"".equals( ex.getLocator().trim() ) ) {
writer.writeAttribute( "locator", ex.getLocator() );
}
writer.writeStartElement( OWS_NS, "ExceptionText" );
writer.writeCharacters( ex.getMessage() != null ? ex.getMessage() : "not available" );
writer.writeEndElement();
writer.writeEndElement(); // Exception
writer.writeEndElement(); // ExceptionReport
}
|
diff --git a/src/uk/org/ponder/rsf/state/guards/BeanGuardProcessor.java b/src/uk/org/ponder/rsf/state/guards/BeanGuardProcessor.java
index 6648957..f63ff88 100644
--- a/src/uk/org/ponder/rsf/state/guards/BeanGuardProcessor.java
+++ b/src/uk/org/ponder/rsf/state/guards/BeanGuardProcessor.java
@@ -1,98 +1,98 @@
/*
* Created on 25 Jul 2006
*/
package uk.org.ponder.rsf.state.guards;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.validation.BindException;
import org.springframework.validation.Validator;
import uk.org.ponder.beanutil.BeanModelAlterer;
import uk.org.ponder.beanutil.PathUtil;
import uk.org.ponder.beanutil.WriteableBeanLocator;
import uk.org.ponder.errorutil.TargettedMessage;
import uk.org.ponder.errorutil.TargettedMessageList;
import uk.org.ponder.mapping.BeanInvalidationModel;
import uk.org.ponder.springutil.errors.SpringErrorConverter;
public class BeanGuardProcessor implements ApplicationContextAware {
private BeanGuard[] guards;
private BeanModelAlterer darapplier;
public void setApplicationContext(ApplicationContext applicationContext) {
String[] guardnames = applicationContext.getBeanNamesForType(BeanGuard.class, false, false);
guards = new BeanGuard[guardnames.length];
for (int i = 0; i < guardnames.length; ++ i) {
guards[i] = (BeanGuard) applicationContext.getBean(guardnames[i]);
}
}
public void setBeanModelAlterer(BeanModelAlterer darapplier) {
this.darapplier = darapplier;
}
public void processPostGuards(BeanInvalidationModel bim, TargettedMessageList errors,
WriteableBeanLocator rbl) {
BindException springerrors = null;
for (int i = 0; i < guards.length; ++ i) {
BeanGuard guarddef = guards[i];
String mode = guarddef.getGuardMode();
String timing = guarddef.getGuardTiming();
String guardedpath = guarddef.getGuardedPath();
String guardmethod = guarddef.getGuardMethod();
String guardEL = guarddef.getGuardEL();
String guardproperty = guarddef.getGuardProperty();
if (guardEL != null && guardmethod != null) {
guardmethod = PathUtil.composePath(guardEL, guardmethod);
}
if (mode.equals(BeanGuard.WRITE) &&
timing == null || timing.equals(BeanGuard.POST)) {
// for each POST-WRITE guard for an invalidated path, execute it.
String match = bim.invalidPathMatch(guardedpath);
if (match != null) {
Object guard = guarddef.getGuard();
if (guard == null && guardEL == null) {
if (guardmethod != null) {
guardEL = PathUtil.getToTailPath(guardmethod);
guardmethod = PathUtil.getTailPath(guardmethod);
}
else if (guardproperty != null) {
guardEL = PathUtil.getToTailPath(guardproperty);
guardproperty = PathUtil.getTailPath(guardproperty);
}
}
if (guardEL != null) {
guard = darapplier.getBeanValue(guardEL, rbl);
}
Object guarded = darapplier.getBeanValue(match, rbl);
try {
if (guardmethod != null) {
- darapplier.invokeBeanMethod(guardmethod, rbl);
+ darapplier.invokeBeanMethod(guardmethod, guard);
}
else if (guardproperty != null) {
darapplier.setBeanValue(guardproperty, guard, guarded, errors);
}
else if (guard instanceof Validator) {
Validator guardv = (Validator) guard;
springerrors = new BindException(guarded, guardedpath);
// TODO: We could try to store this excess info somewhere.
guardv.validate(guarded, springerrors);
SpringErrorConverter.appendErrors(errors, springerrors);
}
}
catch (Exception e) {
TargettedMessage message = new TargettedMessage(e.getMessage(), e, match);
errors.addMessage(message);
}
}
}
}
// if (springerrors != null) {
// throw UniversalRuntimeException.accumulate(springerrors);
// }
}
}
| true | true | public void processPostGuards(BeanInvalidationModel bim, TargettedMessageList errors,
WriteableBeanLocator rbl) {
BindException springerrors = null;
for (int i = 0; i < guards.length; ++ i) {
BeanGuard guarddef = guards[i];
String mode = guarddef.getGuardMode();
String timing = guarddef.getGuardTiming();
String guardedpath = guarddef.getGuardedPath();
String guardmethod = guarddef.getGuardMethod();
String guardEL = guarddef.getGuardEL();
String guardproperty = guarddef.getGuardProperty();
if (guardEL != null && guardmethod != null) {
guardmethod = PathUtil.composePath(guardEL, guardmethod);
}
if (mode.equals(BeanGuard.WRITE) &&
timing == null || timing.equals(BeanGuard.POST)) {
// for each POST-WRITE guard for an invalidated path, execute it.
String match = bim.invalidPathMatch(guardedpath);
if (match != null) {
Object guard = guarddef.getGuard();
if (guard == null && guardEL == null) {
if (guardmethod != null) {
guardEL = PathUtil.getToTailPath(guardmethod);
guardmethod = PathUtil.getTailPath(guardmethod);
}
else if (guardproperty != null) {
guardEL = PathUtil.getToTailPath(guardproperty);
guardproperty = PathUtil.getTailPath(guardproperty);
}
}
if (guardEL != null) {
guard = darapplier.getBeanValue(guardEL, rbl);
}
Object guarded = darapplier.getBeanValue(match, rbl);
try {
if (guardmethod != null) {
darapplier.invokeBeanMethod(guardmethod, rbl);
}
else if (guardproperty != null) {
darapplier.setBeanValue(guardproperty, guard, guarded, errors);
}
else if (guard instanceof Validator) {
Validator guardv = (Validator) guard;
springerrors = new BindException(guarded, guardedpath);
// TODO: We could try to store this excess info somewhere.
guardv.validate(guarded, springerrors);
SpringErrorConverter.appendErrors(errors, springerrors);
}
}
catch (Exception e) {
TargettedMessage message = new TargettedMessage(e.getMessage(), e, match);
errors.addMessage(message);
}
}
}
}
// if (springerrors != null) {
// throw UniversalRuntimeException.accumulate(springerrors);
// }
}
| public void processPostGuards(BeanInvalidationModel bim, TargettedMessageList errors,
WriteableBeanLocator rbl) {
BindException springerrors = null;
for (int i = 0; i < guards.length; ++ i) {
BeanGuard guarddef = guards[i];
String mode = guarddef.getGuardMode();
String timing = guarddef.getGuardTiming();
String guardedpath = guarddef.getGuardedPath();
String guardmethod = guarddef.getGuardMethod();
String guardEL = guarddef.getGuardEL();
String guardproperty = guarddef.getGuardProperty();
if (guardEL != null && guardmethod != null) {
guardmethod = PathUtil.composePath(guardEL, guardmethod);
}
if (mode.equals(BeanGuard.WRITE) &&
timing == null || timing.equals(BeanGuard.POST)) {
// for each POST-WRITE guard for an invalidated path, execute it.
String match = bim.invalidPathMatch(guardedpath);
if (match != null) {
Object guard = guarddef.getGuard();
if (guard == null && guardEL == null) {
if (guardmethod != null) {
guardEL = PathUtil.getToTailPath(guardmethod);
guardmethod = PathUtil.getTailPath(guardmethod);
}
else if (guardproperty != null) {
guardEL = PathUtil.getToTailPath(guardproperty);
guardproperty = PathUtil.getTailPath(guardproperty);
}
}
if (guardEL != null) {
guard = darapplier.getBeanValue(guardEL, rbl);
}
Object guarded = darapplier.getBeanValue(match, rbl);
try {
if (guardmethod != null) {
darapplier.invokeBeanMethod(guardmethod, guard);
}
else if (guardproperty != null) {
darapplier.setBeanValue(guardproperty, guard, guarded, errors);
}
else if (guard instanceof Validator) {
Validator guardv = (Validator) guard;
springerrors = new BindException(guarded, guardedpath);
// TODO: We could try to store this excess info somewhere.
guardv.validate(guarded, springerrors);
SpringErrorConverter.appendErrors(errors, springerrors);
}
}
catch (Exception e) {
TargettedMessage message = new TargettedMessage(e.getMessage(), e, match);
errors.addMessage(message);
}
}
}
}
// if (springerrors != null) {
// throw UniversalRuntimeException.accumulate(springerrors);
// }
}
|
diff --git a/weasis-core/weasis-core-ui/src/main/java/org/weasis/core/ui/graphic/AbstractDragGraphicArea.java b/weasis-core/weasis-core-ui/src/main/java/org/weasis/core/ui/graphic/AbstractDragGraphicArea.java
index 8738a89b4..a4999267a 100644
--- a/weasis-core/weasis-core-ui/src/main/java/org/weasis/core/ui/graphic/AbstractDragGraphicArea.java
+++ b/weasis-core/weasis-core-ui/src/main/java/org/weasis/core/ui/graphic/AbstractDragGraphicArea.java
@@ -1,208 +1,216 @@
/*******************************************************************************
* Copyright (c) 2010 Nicolas Roduit.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Nicolas Roduit - initial API and implementation
******************************************************************************/
package org.weasis.core.ui.graphic;
import java.awt.Color;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.Point2D;
import java.awt.image.RenderedImage;
import java.util.ArrayList;
import java.util.List;
import javax.media.jai.OpImage;
import javax.media.jai.ROIShape;
import javax.media.jai.RenderedOp;
import org.weasis.core.api.image.op.ImageStatistics2Descriptor;
import org.weasis.core.api.image.op.ImageStatisticsDescriptor;
import org.weasis.core.api.image.util.ImageLayer;
import org.weasis.core.api.media.data.ImageElement;
import org.weasis.core.api.media.data.TagW;
/**
* @author Nicolas Roduit, Benoit Jacquemoud
*/
public abstract class AbstractDragGraphicArea extends AbstractDragGraphic implements ImageStatistics {
public AbstractDragGraphicArea(int handlePointTotalNumber) {
this(handlePointTotalNumber, Color.YELLOW, 1f, true);
}
public AbstractDragGraphicArea(int handlePointTotalNumber, Color paintColor, float lineThickness,
boolean labelVisible) {
this(handlePointTotalNumber, paintColor, lineThickness, labelVisible, false);
}
public AbstractDragGraphicArea(int handlePointTotalNumber, Color paintColor, float lineThickness,
boolean labelVisible, boolean filled) {
this(null, handlePointTotalNumber, paintColor, lineThickness, labelVisible, filled);
}
public AbstractDragGraphicArea(List<Point2D> handlePointList, int handlePointTotalNumber, Color paintColor,
float lineThickness, boolean labelVisible, boolean filled) {
super(handlePointList, handlePointTotalNumber, paintColor, lineThickness, labelVisible, filled);
}
// /////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public Area getArea(AffineTransform transform) {
if (shape == null) {
return new Area();
} else {
Area area = super.getArea(transform);
area.add(new Area(shape)); // Add inside area for closed shape
return area;
}
}
public List<MeasureItem> getImageStatistics(ImageLayer layer, boolean releaseEvent) {
if (layer != null) {
ImageElement imageElement = layer.getSourceImage();
if (imageElement != null && isShapeValid()) {
ArrayList<MeasureItem> measVal = new ArrayList<MeasureItem>();
if (IMAGE_MIN.isComputed() || IMAGE_MAX.isComputed() || IMAGE_MEAN.isComputed()) {
Double[] min = null;
Double[] max = null;
Double[] mean = null;
Double[] stdv = null;
Double[] skew = null;
Double[] kurtosis = null;
if (releaseEvent && shape != null) {
RenderedImage image = layer.getSourceRenderedImage();
// long startTime = System.currentTimeMillis();
- ROIShape roi = new ROIShape(shape);
+ double scaleX = imageElement.getRescaleX();
+ double scaleY = imageElement.getRescaleY();
+ ROIShape roi;
+ if (scaleX != scaleY) {
+ AffineTransform transform = AffineTransform.getScaleInstance(1.0 / scaleX, 1.0 / scaleY);
+ roi = new ROIShape(transform.createTransformedShape(shape));
+ } else {
+ roi = new ROIShape(shape);
+ }
// Get padding values => exclude values
Double excludedMin = null;
Double excludedMax = null;
Integer paddingValue = (Integer) imageElement.getTagValue(TagW.PixelPaddingValue);
Integer paddingLimit = (Integer) imageElement.getTagValue(TagW.PixelPaddingRangeLimit);
if (paddingValue != null) {
if (paddingLimit == null) {
paddingLimit = paddingValue;
} else if (paddingLimit < paddingValue) {
int temp = paddingValue;
paddingValue = paddingLimit;
paddingLimit = temp;
}
excludedMin = paddingValue == null ? null : new Double(paddingValue);
excludedMax = paddingLimit == null ? null : new Double(paddingLimit);
}
RenderedOp dst =
ImageStatisticsDescriptor.create(image, roi, 1, 1, excludedMin, excludedMax, null);
// To ensure this image is not stored in tile cache
((OpImage) dst.getRendering()).setTileCache(null);
// For basic statistics, rescale values can be computed afterwards
double[][] extrema = (double[][]) dst.getProperty("statistics"); //$NON-NLS-1$
if (extrema == null || extrema.length < 1 || extrema[0].length < 1) {
return null;
}
min = new Double[extrema[0].length];
max = new Double[extrema[0].length];
mean = new Double[extrema[0].length];
// LOGGER.error("Basic stats [ms]: {}", System.currentTimeMillis() - startTime);
// unit = pixelValue * rescale slope + rescale intercept
Float slopeVal = (Float) imageElement.getTagValue(TagW.RescaleSlope);
Float interceptVal = (Float) imageElement.getTagValue(TagW.RescaleIntercept);
double slope = slopeVal == null ? 1.0f : slopeVal.doubleValue();
double intercept = interceptVal == null ? 0.0f : interceptVal.doubleValue();
for (int i = 0; i < extrema[0].length; i++) {
min[i] = extrema[0][i] * slope + intercept;
max[i] = extrema[1][i] * slope + intercept;
mean[i] = extrema[2][i] * slope + intercept;
}
if (IMAGE_STD.isComputed() || IMAGE_SKEW.isComputed() || IMAGE_KURTOSIS.isComputed()) {
// startTime = System.currentTimeMillis();
// Required the mean value (not rescaled), slope and intercept to calculate correctly std,
// skew and kurtosis
dst =
ImageStatistics2Descriptor.create(image, roi, 1, 1, extrema[2][0], excludedMin,
excludedMax, slope, intercept, null);
// To ensure this image is not stored in tile cache
((OpImage) dst.getRendering()).setTileCache(null);
double[][] extrema2 = (double[][]) dst.getProperty("statistics"); //$NON-NLS-1$
if (extrema != null && extrema.length > 0 && extrema[0].length > 0) {
stdv = new Double[extrema2[0].length];
skew = new Double[extrema2[0].length];
kurtosis = new Double[extrema2[0].length];
// LOGGER.info("Adv. stats [ms]: {}", System.currentTimeMillis() - startTime);
for (int i = 0; i < extrema2[0].length; i++) {
stdv[i] = extrema2[0][i];
skew[i] = extrema2[1][i];
kurtosis[i] = extrema2[2][i];
}
}
}
}
String unit = imageElement.getPixelValueUnit();
if (IMAGE_MIN.isComputed()) {
addMeasure(measVal, IMAGE_MIN, min, unit);
}
if (IMAGE_MAX.isComputed()) {
addMeasure(measVal, IMAGE_MAX, max, unit);
}
if (IMAGE_MEAN.isComputed()) {
addMeasure(measVal, IMAGE_MEAN, mean, unit);
}
if (IMAGE_STD.isComputed()) {
addMeasure(measVal, IMAGE_STD, stdv, unit);
}
if (IMAGE_SKEW.isComputed()) {
addMeasure(measVal, IMAGE_SKEW, skew, unit);
}
if (IMAGE_KURTOSIS.isComputed()) {
addMeasure(measVal, IMAGE_KURTOSIS, kurtosis, unit);
}
Double suv = (Double) imageElement.getTagValue(TagW.SuvFactor);
if (suv != null) {
unit = "SUVbw"; //$NON-NLS-1$
if (IMAGE_MIN.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MIN, min == null || min[0] == null ? null : min[0] * suv,
unit));
}
if (IMAGE_MAX.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MAX, max == null || max[0] == null ? null : max[0] * suv,
unit));
}
if (IMAGE_MEAN.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MEAN, mean == null || mean[0] == null ? null : mean[0]
* suv, unit));
}
}
}
return measVal;
}
}
return null;
}
private static void addMeasure(ArrayList<MeasureItem> measVal, Measurement measure, Double[] val, String unit) {
if (val == null) {
measVal.add(new MeasureItem(measure, null, unit));
} else if (val.length == 1) {
measVal.add(new MeasureItem(measure, val[0], unit));
} else {
for (int i = 0; i < val.length; i++) {
measVal.add(new MeasureItem(measure, " " + (i + 1), val[i], unit)); //$NON-NLS-1$
}
}
}
}
| true | true | public List<MeasureItem> getImageStatistics(ImageLayer layer, boolean releaseEvent) {
if (layer != null) {
ImageElement imageElement = layer.getSourceImage();
if (imageElement != null && isShapeValid()) {
ArrayList<MeasureItem> measVal = new ArrayList<MeasureItem>();
if (IMAGE_MIN.isComputed() || IMAGE_MAX.isComputed() || IMAGE_MEAN.isComputed()) {
Double[] min = null;
Double[] max = null;
Double[] mean = null;
Double[] stdv = null;
Double[] skew = null;
Double[] kurtosis = null;
if (releaseEvent && shape != null) {
RenderedImage image = layer.getSourceRenderedImage();
// long startTime = System.currentTimeMillis();
ROIShape roi = new ROIShape(shape);
// Get padding values => exclude values
Double excludedMin = null;
Double excludedMax = null;
Integer paddingValue = (Integer) imageElement.getTagValue(TagW.PixelPaddingValue);
Integer paddingLimit = (Integer) imageElement.getTagValue(TagW.PixelPaddingRangeLimit);
if (paddingValue != null) {
if (paddingLimit == null) {
paddingLimit = paddingValue;
} else if (paddingLimit < paddingValue) {
int temp = paddingValue;
paddingValue = paddingLimit;
paddingLimit = temp;
}
excludedMin = paddingValue == null ? null : new Double(paddingValue);
excludedMax = paddingLimit == null ? null : new Double(paddingLimit);
}
RenderedOp dst =
ImageStatisticsDescriptor.create(image, roi, 1, 1, excludedMin, excludedMax, null);
// To ensure this image is not stored in tile cache
((OpImage) dst.getRendering()).setTileCache(null);
// For basic statistics, rescale values can be computed afterwards
double[][] extrema = (double[][]) dst.getProperty("statistics"); //$NON-NLS-1$
if (extrema == null || extrema.length < 1 || extrema[0].length < 1) {
return null;
}
min = new Double[extrema[0].length];
max = new Double[extrema[0].length];
mean = new Double[extrema[0].length];
// LOGGER.error("Basic stats [ms]: {}", System.currentTimeMillis() - startTime);
// unit = pixelValue * rescale slope + rescale intercept
Float slopeVal = (Float) imageElement.getTagValue(TagW.RescaleSlope);
Float interceptVal = (Float) imageElement.getTagValue(TagW.RescaleIntercept);
double slope = slopeVal == null ? 1.0f : slopeVal.doubleValue();
double intercept = interceptVal == null ? 0.0f : interceptVal.doubleValue();
for (int i = 0; i < extrema[0].length; i++) {
min[i] = extrema[0][i] * slope + intercept;
max[i] = extrema[1][i] * slope + intercept;
mean[i] = extrema[2][i] * slope + intercept;
}
if (IMAGE_STD.isComputed() || IMAGE_SKEW.isComputed() || IMAGE_KURTOSIS.isComputed()) {
// startTime = System.currentTimeMillis();
// Required the mean value (not rescaled), slope and intercept to calculate correctly std,
// skew and kurtosis
dst =
ImageStatistics2Descriptor.create(image, roi, 1, 1, extrema[2][0], excludedMin,
excludedMax, slope, intercept, null);
// To ensure this image is not stored in tile cache
((OpImage) dst.getRendering()).setTileCache(null);
double[][] extrema2 = (double[][]) dst.getProperty("statistics"); //$NON-NLS-1$
if (extrema != null && extrema.length > 0 && extrema[0].length > 0) {
stdv = new Double[extrema2[0].length];
skew = new Double[extrema2[0].length];
kurtosis = new Double[extrema2[0].length];
// LOGGER.info("Adv. stats [ms]: {}", System.currentTimeMillis() - startTime);
for (int i = 0; i < extrema2[0].length; i++) {
stdv[i] = extrema2[0][i];
skew[i] = extrema2[1][i];
kurtosis[i] = extrema2[2][i];
}
}
}
}
String unit = imageElement.getPixelValueUnit();
if (IMAGE_MIN.isComputed()) {
addMeasure(measVal, IMAGE_MIN, min, unit);
}
if (IMAGE_MAX.isComputed()) {
addMeasure(measVal, IMAGE_MAX, max, unit);
}
if (IMAGE_MEAN.isComputed()) {
addMeasure(measVal, IMAGE_MEAN, mean, unit);
}
if (IMAGE_STD.isComputed()) {
addMeasure(measVal, IMAGE_STD, stdv, unit);
}
if (IMAGE_SKEW.isComputed()) {
addMeasure(measVal, IMAGE_SKEW, skew, unit);
}
if (IMAGE_KURTOSIS.isComputed()) {
addMeasure(measVal, IMAGE_KURTOSIS, kurtosis, unit);
}
Double suv = (Double) imageElement.getTagValue(TagW.SuvFactor);
if (suv != null) {
unit = "SUVbw"; //$NON-NLS-1$
if (IMAGE_MIN.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MIN, min == null || min[0] == null ? null : min[0] * suv,
unit));
}
if (IMAGE_MAX.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MAX, max == null || max[0] == null ? null : max[0] * suv,
unit));
}
if (IMAGE_MEAN.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MEAN, mean == null || mean[0] == null ? null : mean[0]
* suv, unit));
}
}
}
return measVal;
}
}
return null;
}
| public List<MeasureItem> getImageStatistics(ImageLayer layer, boolean releaseEvent) {
if (layer != null) {
ImageElement imageElement = layer.getSourceImage();
if (imageElement != null && isShapeValid()) {
ArrayList<MeasureItem> measVal = new ArrayList<MeasureItem>();
if (IMAGE_MIN.isComputed() || IMAGE_MAX.isComputed() || IMAGE_MEAN.isComputed()) {
Double[] min = null;
Double[] max = null;
Double[] mean = null;
Double[] stdv = null;
Double[] skew = null;
Double[] kurtosis = null;
if (releaseEvent && shape != null) {
RenderedImage image = layer.getSourceRenderedImage();
// long startTime = System.currentTimeMillis();
double scaleX = imageElement.getRescaleX();
double scaleY = imageElement.getRescaleY();
ROIShape roi;
if (scaleX != scaleY) {
AffineTransform transform = AffineTransform.getScaleInstance(1.0 / scaleX, 1.0 / scaleY);
roi = new ROIShape(transform.createTransformedShape(shape));
} else {
roi = new ROIShape(shape);
}
// Get padding values => exclude values
Double excludedMin = null;
Double excludedMax = null;
Integer paddingValue = (Integer) imageElement.getTagValue(TagW.PixelPaddingValue);
Integer paddingLimit = (Integer) imageElement.getTagValue(TagW.PixelPaddingRangeLimit);
if (paddingValue != null) {
if (paddingLimit == null) {
paddingLimit = paddingValue;
} else if (paddingLimit < paddingValue) {
int temp = paddingValue;
paddingValue = paddingLimit;
paddingLimit = temp;
}
excludedMin = paddingValue == null ? null : new Double(paddingValue);
excludedMax = paddingLimit == null ? null : new Double(paddingLimit);
}
RenderedOp dst =
ImageStatisticsDescriptor.create(image, roi, 1, 1, excludedMin, excludedMax, null);
// To ensure this image is not stored in tile cache
((OpImage) dst.getRendering()).setTileCache(null);
// For basic statistics, rescale values can be computed afterwards
double[][] extrema = (double[][]) dst.getProperty("statistics"); //$NON-NLS-1$
if (extrema == null || extrema.length < 1 || extrema[0].length < 1) {
return null;
}
min = new Double[extrema[0].length];
max = new Double[extrema[0].length];
mean = new Double[extrema[0].length];
// LOGGER.error("Basic stats [ms]: {}", System.currentTimeMillis() - startTime);
// unit = pixelValue * rescale slope + rescale intercept
Float slopeVal = (Float) imageElement.getTagValue(TagW.RescaleSlope);
Float interceptVal = (Float) imageElement.getTagValue(TagW.RescaleIntercept);
double slope = slopeVal == null ? 1.0f : slopeVal.doubleValue();
double intercept = interceptVal == null ? 0.0f : interceptVal.doubleValue();
for (int i = 0; i < extrema[0].length; i++) {
min[i] = extrema[0][i] * slope + intercept;
max[i] = extrema[1][i] * slope + intercept;
mean[i] = extrema[2][i] * slope + intercept;
}
if (IMAGE_STD.isComputed() || IMAGE_SKEW.isComputed() || IMAGE_KURTOSIS.isComputed()) {
// startTime = System.currentTimeMillis();
// Required the mean value (not rescaled), slope and intercept to calculate correctly std,
// skew and kurtosis
dst =
ImageStatistics2Descriptor.create(image, roi, 1, 1, extrema[2][0], excludedMin,
excludedMax, slope, intercept, null);
// To ensure this image is not stored in tile cache
((OpImage) dst.getRendering()).setTileCache(null);
double[][] extrema2 = (double[][]) dst.getProperty("statistics"); //$NON-NLS-1$
if (extrema != null && extrema.length > 0 && extrema[0].length > 0) {
stdv = new Double[extrema2[0].length];
skew = new Double[extrema2[0].length];
kurtosis = new Double[extrema2[0].length];
// LOGGER.info("Adv. stats [ms]: {}", System.currentTimeMillis() - startTime);
for (int i = 0; i < extrema2[0].length; i++) {
stdv[i] = extrema2[0][i];
skew[i] = extrema2[1][i];
kurtosis[i] = extrema2[2][i];
}
}
}
}
String unit = imageElement.getPixelValueUnit();
if (IMAGE_MIN.isComputed()) {
addMeasure(measVal, IMAGE_MIN, min, unit);
}
if (IMAGE_MAX.isComputed()) {
addMeasure(measVal, IMAGE_MAX, max, unit);
}
if (IMAGE_MEAN.isComputed()) {
addMeasure(measVal, IMAGE_MEAN, mean, unit);
}
if (IMAGE_STD.isComputed()) {
addMeasure(measVal, IMAGE_STD, stdv, unit);
}
if (IMAGE_SKEW.isComputed()) {
addMeasure(measVal, IMAGE_SKEW, skew, unit);
}
if (IMAGE_KURTOSIS.isComputed()) {
addMeasure(measVal, IMAGE_KURTOSIS, kurtosis, unit);
}
Double suv = (Double) imageElement.getTagValue(TagW.SuvFactor);
if (suv != null) {
unit = "SUVbw"; //$NON-NLS-1$
if (IMAGE_MIN.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MIN, min == null || min[0] == null ? null : min[0] * suv,
unit));
}
if (IMAGE_MAX.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MAX, max == null || max[0] == null ? null : max[0] * suv,
unit));
}
if (IMAGE_MEAN.isComputed()) {
measVal.add(new MeasureItem(IMAGE_MEAN, mean == null || mean[0] == null ? null : mean[0]
* suv, unit));
}
}
}
return measVal;
}
}
return null;
}
|
diff --git a/src/main/java/com/philihp/weblabora/model/Board.java b/src/main/java/com/philihp/weblabora/model/Board.java
index 327f3fd..20a1552 100644
--- a/src/main/java/com/philihp/weblabora/model/Board.java
+++ b/src/main/java/com/philihp/weblabora/model/Board.java
@@ -1,664 +1,664 @@
package com.philihp.weblabora.model;
import static com.philihp.weblabora.model.building.BuildingEnum.LB1;
import static com.philihp.weblabora.model.building.BuildingEnum.LB2;
import static com.philihp.weblabora.model.building.BuildingEnum.LB3;
import static com.philihp.weblabora.model.building.BuildingEnum.LG1;
import static com.philihp.weblabora.model.building.BuildingEnum.LG2;
import static com.philihp.weblabora.model.building.BuildingEnum.LG3;
import static com.philihp.weblabora.model.building.BuildingEnum.LR1;
import static com.philihp.weblabora.model.building.BuildingEnum.LR2;
import static com.philihp.weblabora.model.building.BuildingEnum.LR3;
import static com.philihp.weblabora.model.building.BuildingEnum.LW1;
import static com.philihp.weblabora.model.building.BuildingEnum.LW2;
import static com.philihp.weblabora.model.building.BuildingEnum.LW3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import com.philihp.weblabora.jpa.Game;
import com.philihp.weblabora.jpa.State;
import com.philihp.weblabora.model.building.Building;
import com.philihp.weblabora.model.building.BuildingEnum;
import com.philihp.weblabora.model.building.ClayMound;
import com.philihp.weblabora.model.building.CloisterOffice;
import com.philihp.weblabora.model.building.Farmyard;
import com.philihp.weblabora.model.building.Settlement;
import com.philihp.weblabora.model.building.SettlementEnum;
public class Board {
public static final int[] PLOT_PURCHASE_PRICE = {3,4,4,5,5,5,6,6,7};
public static final int[] DISTRICT_PURCHASE_PRICE = {2,3,4,4,5,5,6,7,8};
protected final GamePlayers gamePlayers;
protected final GameLength gameLength;
protected final GameCountry gameCountry;
protected Wheel wheel;
protected Player[] players;
private int activePlayer;
private List<Building> unbuiltBuildings;
private int plotsPurchased;
private int districtsPurchased;
private int startingPlayer;
private StartingMarker startingMarker;
private int round;
private SettlementRound settlementRound;
private int moveInRound;
private boolean settling;
private boolean extraRound;
private boolean gameOver = false;
private List<HistoryEntry> moveList = new ArrayList<HistoryEntry>();
private State nextState;
/**
* This makes lookups from {@link CommandUse CommandUse}
*/
private EnumMap<BuildingEnum, Building> allBuildings =
new EnumMap<BuildingEnum, Building>(BuildingEnum.class);;
private List<Wonder> unclaimedWonders;
public Board(GamePlayers gamePlayers, GameLength gameLength, GameCountry gameCountry) {
int i;
this.gamePlayers = gamePlayers;
this.gameLength = gameLength;
this.gameCountry = gameCountry;
settlementRound = SettlementRound.S;
int[] armValues = null;
if(gameLength == GameLength.SHORT && gamePlayers == GamePlayers.TWO) {
armValues = new int[]{0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 10};
}
else {
armValues = new int[]{0, 2, 3, 4, 5, 6, 6, 7, 7, 8, 8, 9, 10};
}
wheel = new Wheel(this,armValues);
activePlayer = 0;
players = new Player[gamePlayers.getAsNumber()];
for(i = 0;i < players.length; i++) {
players[i] = new Player(this, Color.toColor(i));
players[i].gameStart();
}
players[0].setActive(true);
unclaimedWonders = gameStartWonders();
addLandscapeBuildings();
unbuiltBuildings = roundBuildings(SettlementRound.S);
for(Player player : players) {
player.getUnbuiltSettlements().addAll(roundSettlements(SettlementRound.S));
}
round = 1;
moveInRound = 1;
startingPlayer = 0;
startingMarker = new StartingMarker(players[0]);
}
public Wheel getWheel() {
return wheel;
}
public Player getPlayer(int i) {
return players[i];
}
public Player[] getPlayers() {
return players;
}
public int getActivePlayer() {
return activePlayer;
}
private List<Settlement> roundSettlements(SettlementRound round) {
List<Settlement> settlements = new ArrayList<Settlement>(8);
if(round == null) return settlements;
for (SettlementEnum settlementId : SettlementEnum.values()) {
Settlement settlement = settlementId.getInstance();
if (round == settlement.getRound())
settlements.add(settlement);
}
return settlements;
}
private List<Building> roundBuildings(SettlementRound round) {
List<Building> buildings = new ArrayList<Building>();
if(round == null) return buildings;
//TODO: should change this later so buildings use Round enum
String phase = round.toString();
if(phase.equals("S")) phase = "";
if(gamePlayers == GamePlayers.TWO && gameLength == GameLength.LONG) {
//two player long game uses all buildings except C-grapevine, C-quarry and Carpentry
for (BuildingEnum buildingId : BuildingEnum.values()) {
if(buildingId == BuildingEnum.F10) continue;
if(buildingId == BuildingEnum.F31) continue;
if(buildingId == BuildingEnum.F29) continue;
Building building = buildingId.getInstance();
if (phase.equals(building.getStage())) {
buildings.add(building);
allBuildings.put(BuildingEnum.valueOf(building.getId()), building);
}
}
}
else {
for (BuildingEnum buildingId : BuildingEnum.values()) {
Building building = buildingId.getInstance();
if (phase.equals(building.getStage()) && building.getPlayers().ordinal() <= gamePlayers.ordinal()) {
buildings.add(building);
allBuildings.put(BuildingEnum.valueOf(building.getId()), building);
}
}
}
return buildings;
}
public List<Building> getFutureBuildings() {
List<Building> buildings = new ArrayList<Building>();
for(BuildingEnum buildingId : BuildingEnum.values()) {
Building building = buildingId.getInstance();
if(allBuildings.containsKey(buildingId) == false && building.getPlayers().ordinal() <= gamePlayers.ordinal()) {
buildings.add(building);
}
}
return buildings;
}
public List<Settlement> getFutureSettlements() {
List<Settlement> settlements = new ArrayList<Settlement>();
for(SettlementEnum settlementId : SettlementEnum.values()) {
Settlement settlement = settlementId.getInstance();
if(settlement.getRound().ordinal() > getSettlementRound().ordinal()) {
settlements.add(settlementId.getInstance());
}
}
return settlements;
}
private void addLandscapeBuildings() {
if(players.length >= 1) {
allBuildings.put(LR1, (ClayMound)players[0].getLandscape().getTerrainAt(new Coordinate(4, 0)).getErection());
allBuildings.put(LR2, (Farmyard)players[0].getLandscape().getTerrainAt(new Coordinate(2, 1)).getErection());
allBuildings.put(LR3, (CloisterOffice)players[0].getLandscape().getTerrainAt(new Coordinate(4, 1)).getErection());
}
if(players.length >= 2) {
allBuildings.put(LG1, (ClayMound)players[1].getLandscape().getTerrainAt(new Coordinate(4, 0)).getErection());
allBuildings.put(LG2, (Farmyard)players[1].getLandscape().getTerrainAt(new Coordinate(2, 1)).getErection());
allBuildings.put(LG3, (CloisterOffice)players[1].getLandscape().getTerrainAt(new Coordinate(4, 1)).getErection());
}
if(players.length >= 3) {
allBuildings.put(LB1, (ClayMound)players[2].getLandscape().getTerrainAt(new Coordinate(4, 0)).getErection());
allBuildings.put(LB2, (Farmyard)players[2].getLandscape().getTerrainAt(new Coordinate(2, 1)).getErection());
allBuildings.put(LB3, (CloisterOffice)players[2].getLandscape().getTerrainAt(new Coordinate(4, 1)).getErection());
}
if(players.length >= 4) {
allBuildings.put(LW1, (ClayMound)players[3].getLandscape().getTerrainAt(new Coordinate(4, 0)).getErection());
allBuildings.put(LW2, (Farmyard)players[3].getLandscape().getTerrainAt(new Coordinate(2, 1)).getErection());
allBuildings.put(LW3, (CloisterOffice)players[3].getLandscape().getTerrainAt(new Coordinate(4, 1)).getErection());
}
}
public Building findBuildingInstance(BuildingEnum buildingId) {
return allBuildings.get(buildingId);
}
private List<Wonder> gameStartWonders() {
List<Wonder> wonders = new ArrayList<Wonder>(8);
wonders.add(new Wonder());
wonders.add(new Wonder());
wonders.add(new Wonder());
wonders.add(new Wonder());
wonders.add(new Wonder());
wonders.add(new Wonder());
wonders.add(new Wonder());
wonders.add(new Wonder());
return wonders;
}
public Wonder claimWonder() {
return unclaimedWonders.remove(unclaimedWonders.size() - 1);
}
public List<Building> getUnbuiltBuildings() {
return unbuiltBuildings;
}
public void nextActivePlayer() {
players[activePlayer].setActive(false);
if (++activePlayer >= players.length)
activePlayer = 0;
players[activePlayer].setActive(true);
}
public void populateDetails(Game game) {
if(players.length >= 1)
players[0].populatePlayer(game.getPlayer1());
if(players.length >= 2)
players[1].populatePlayer(game.getPlayer2());
if(players.length >= 3)
players[2].populatePlayer(game.getPlayer3());
if(players.length >= 4)
players[3].populatePlayer(game.getPlayer4());
}
public void testValidity() throws WeblaboraException {
for(Player player : players) {
player.testValidity();
}
}
public int purchasePlot() {
return PLOT_PURCHASE_PRICE[plotsPurchased++];
}
public int purchaseDistrict() {
return DISTRICT_PURCHASE_PRICE[districtsPurchased++];
}
public StartingMarker getStartingMarker() {
return startingMarker;
}
public boolean isSettling() {
return settling;
}
public void setSettling(boolean settling) {
this.settling = settling;
}
public float getArmOffset() {
return isSettling()?27.692f:13.846f;
}
public void setSettlementRound(SettlementRound settlementRound) {
this.settlementRound = settlementRound;
}
public SettlementRound getSettlementRound() {
return settlementRound;
}
public boolean isRoundBeforeSettlement(int round) {
return roundBeforeSettlement(round) != null;
}
public boolean isExtraRound(int round) {
switch(gamePlayers) {
case TWO:
//there is no extra round for TWO
return false;
case THREE:
case FOUR:
return round >= 24;
default:
throw new RuntimeException("Unsupported game players for extra round");
}
}
public SettlementRound roundBeforeSettlement(int round) {
switch(gamePlayers) {
case TWO:
switch (round) {
case 6:
return SettlementRound.A;
- case 12:
+ case 13:
return SettlementRound.B;
- case 19:
+ case 20:
return SettlementRound.C;
- case 26:
+ case 27:
return SettlementRound.D;
default:
return null;
}
case THREE:
switch (round) {
case 5:
return SettlementRound.A;
case 10:
return SettlementRound.B;
case 14:
return SettlementRound.C;
case 19:
return SettlementRound.D;
case 25:
return SettlementRound.E;
default:
return null;
}
case FOUR:
switch (round) {
case 6:
return SettlementRound.A;
case 9:
return SettlementRound.B;
case 15:
return SettlementRound.C;
case 18:
return SettlementRound.D;
case 25:
return SettlementRound.E;
default:
return null;
}
default: throw new RuntimeException("Unknown game players mode "+gamePlayers);
}
}
/**
* Called before every round.
*/
public void preRound() {
getMoveList().add(new HistoryEntry("Round "+round));
//1 - reset clergymen
for(Player player : getPlayers()) {
if(player.isClergymenAllPlaced())
player.resetClergymen();
}
//2 - push arm
getWheel().pushArm(round);
//3 - check to see if grapes/stone should become active
if(round == grapeActiveOnRound()) getWheel().getGrape().setActive(true);
if(round == stoneActiveOnRound()) getWheel().getStone().setActive(true);
}
public void preSettling() {
System.out.println("------Begin Settlement------");
setSettlementRound(getSettlementRound().next());
getMoveList().add(new HistoryEntry("Settlement ("+getSettlementRound()+")"));
}
public void preExtraRound() {
System.out.println("------FINAL ROUND--------");
for(Player player : players) {
player.getPrior().clearLocation();
}
setExtraRound(true);
getMoveList().add(new HistoryEntry("Extra Round"));
}
/**
* Called before every move.
*/
public void preMove(State state) {
if(isGameOver()) return;
if(isExtraRound() && moveInRound == 1) {
preExtraRound();
}
else if(isSettling() && moveInRound == 1) {
preSettling();
}
else if(moveInRound == 1) {
preRound();
}
getMoveList().add(new HistoryEntry(state, getPlayer(getActivePlayer()).getColor()));
}
/**
* Called after every move.
*/
public void postMove() {
switch(gamePlayers) {
case TWO:
if(moveInRound == 2 || isSettling()) {
nextActivePlayer();
}
++moveInRound;
if(isSettling() == true && moveInRound == 3) {
postSettlement();
}
else if(isSettling() == false && moveInRound == 4) {
postRound();
}
break;
case THREE:
case FOUR:
nextActivePlayer();
++moveInRound;
if(isExtraRound() && moveInRound == players.length+1) {
postExtraRound();
}
if(isSettling() && moveInRound == players.length+1) {
postSettlement();
}
else if(!isSettling() && moveInRound == players.length+2) {
postRound();
}
break;
default:
throw new RuntimeException("One player mode not supported");
}
}
/**
* Called after every round.
*/
public void postRound() {
//end of normal round
moveInRound = 1;
//end of round
if(isExtraRound(round)) {
round++;
setExtraRound(true);
}
else if(isRoundBeforeSettlement(round)) {
setSettling(true);
}
else {
round++;
}
if(gamePlayers == GamePlayers.TWO
&& gameLength == GameLength.LONG
&& isSettling() == false
&& settlementRound == SettlementRound.D
&& unbuiltBuildings.size() <= 3) {
setGameOver(true);
getMoveList().add(new HistoryEntry("Game Over"));
}
//5 -- pass starting player
if(++startingPlayer == players.length) startingPlayer = 0;
startingMarker.setOwner(players[startingPlayer]);
}
public void postSettlement() {
//end of settlement round
setSettling(false);
List<Building> newBuildings = roundBuildings(settlementRound);
unbuiltBuildings.addAll(newBuildings);
for(Player player : players) {
player.getUnbuiltSettlements().addAll(roundSettlements(settlementRound));
}
if(settlementRound == SettlementRound.E) {
setGameOver(true);
getMoveList().add(new HistoryEntry("Game Over"));
}
round++;
moveInRound=1;
}
public boolean isGameOver() {
return gameOver;
}
public void setGameOver(boolean gameOver) {
this.gameOver = gameOver;
}
public void postExtraRound() {
setExtraRound(false);
setSettling(true);
wheel.pushArm(round);
moveInRound=1;
}
public int getRound() {
return round;
}
public String getMove() {
if(isExtraRound()) return "extra";
if(gamePlayers == GamePlayers.FOUR) {
switch (moveInRound) {
case 1:
return "first";
case 2:
return "second";
case 3:
return "third";
case 4:
return "fourth";
case 5:
return "last";
default:
throw new RuntimeException("Illegal Move Number " + moveInRound);
}
}
else if(gamePlayers == GamePlayers.THREE) {
switch (moveInRound) {
case 1:
return "first";
case 2:
return "second";
case 3:
return "third";
case 4:
return "last";
default:
throw new RuntimeException("Illegal Move Number " + moveInRound);
}
}
else if(gamePlayers == GamePlayers.TWO) {
switch (moveInRound) {
case 1:
return "first half of first";
case 2:
return "second half of first";
case 3:
return "second";
default:
throw new RuntimeException("Illegal Move Number " + moveInRound);
}
}
else return "ERROR";
}
public String getActivePlayerColor() {
return getPlayer(getActivePlayer()).getColor().toString();
}
public int[] getPlotCosts() {
return Arrays.copyOfRange(PLOT_PURCHASE_PRICE, plotsPurchased, PLOT_PURCHASE_PRICE.length);
}
public int[] getDistrictCosts() {
return Arrays.copyOfRange(DISTRICT_PURCHASE_PRICE, districtsPurchased, DISTRICT_PURCHASE_PRICE.length);
}
public List<HistoryEntry> getMoveList() {
return moveList;
}
public List<HistoryEntry> getMoveListReversed() {
List<HistoryEntry> newList = new ArrayList<HistoryEntry>(getMoveList());
Collections.reverse(newList);
return newList;
}
public boolean isExtraRound() {
return extraRound;
}
public void setExtraRound(boolean extraRound) {
this.extraRound = extraRound;
}
public Scorecard getScorecard() {
return new Scorecard(this);
}
public State getNextState() {
return nextState;
}
public void setNextState(State nextState) {
this.nextState = nextState;
}
public GamePlayers getGamePlayers() {
return gamePlayers;
}
public GameLength getGameLength() {
return gameLength;
}
public GameCountry getGameCountry() {
return gameCountry;
}
private int grapeActiveOnRound() {
switch(gamePlayers) {
case TWO:
return 11;
case THREE:
case FOUR:
return 8;
default:
throw new RuntimeException("Unknown Game Players");
}
}
private int stoneActiveOnRound() {
switch(gamePlayers) {
case TWO:
return 18;
case THREE:
case FOUR:
return 13;
default:
throw new RuntimeException("Unknown Game Players");
}
}
}
| false | true | public SettlementRound roundBeforeSettlement(int round) {
switch(gamePlayers) {
case TWO:
switch (round) {
case 6:
return SettlementRound.A;
case 12:
return SettlementRound.B;
case 19:
return SettlementRound.C;
case 26:
return SettlementRound.D;
default:
return null;
}
case THREE:
switch (round) {
case 5:
return SettlementRound.A;
case 10:
return SettlementRound.B;
case 14:
return SettlementRound.C;
case 19:
return SettlementRound.D;
case 25:
return SettlementRound.E;
default:
return null;
}
case FOUR:
switch (round) {
case 6:
return SettlementRound.A;
case 9:
return SettlementRound.B;
case 15:
return SettlementRound.C;
case 18:
return SettlementRound.D;
case 25:
return SettlementRound.E;
default:
return null;
}
default: throw new RuntimeException("Unknown game players mode "+gamePlayers);
}
}
| public SettlementRound roundBeforeSettlement(int round) {
switch(gamePlayers) {
case TWO:
switch (round) {
case 6:
return SettlementRound.A;
case 13:
return SettlementRound.B;
case 20:
return SettlementRound.C;
case 27:
return SettlementRound.D;
default:
return null;
}
case THREE:
switch (round) {
case 5:
return SettlementRound.A;
case 10:
return SettlementRound.B;
case 14:
return SettlementRound.C;
case 19:
return SettlementRound.D;
case 25:
return SettlementRound.E;
default:
return null;
}
case FOUR:
switch (round) {
case 6:
return SettlementRound.A;
case 9:
return SettlementRound.B;
case 15:
return SettlementRound.C;
case 18:
return SettlementRound.D;
case 25:
return SettlementRound.E;
default:
return null;
}
default: throw new RuntimeException("Unknown game players mode "+gamePlayers);
}
}
|
diff --git a/src/java/fedora/server/utilities/rebuild/Rebuild.java b/src/java/fedora/server/utilities/rebuild/Rebuild.java
index cce6011ea..64af75790 100755
--- a/src/java/fedora/server/utilities/rebuild/Rebuild.java
+++ b/src/java/fedora/server/utilities/rebuild/Rebuild.java
@@ -1,382 +1,383 @@
/* The contents of this file are subject to the license and copyright terms
* detailed in the license directory at the root of the source tree (also
* available online at http://www.fedora.info/license/).
*/
package fedora.server.utilities.rebuild;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import fedora.common.Constants;
import fedora.server.config.Configuration;
import fedora.server.config.ModuleConfiguration;
import fedora.server.config.Parameter;
import fedora.server.config.ServerConfiguration;
import fedora.server.config.ServerConfigurationParser;
import fedora.server.storage.lowlevel.DefaultLowlevelStorage;
import fedora.server.storage.lowlevel.FileSystem;
import fedora.server.storage.translation.DODeserializer;
import fedora.server.storage.translation.DOTranslationUtility;
import fedora.server.storage.translation.FOXMLDODeserializer;
import fedora.server.storage.types.BasicDigitalObject;
import fedora.server.storage.types.DigitalObject;
import fedora.server.utilities.ServerUtility;
import fedora.utilities.FileComparator;
/**
* Entry-point for rebuilding various aspects of the repository.
*
* @@version $Id$
*/
public class Rebuild implements Constants {
private FileSystem fs;
private static FileComparator _REVERSE_FILE_COMPARATOR = new FileComparator(
true);
/**
* Rebuilders that the rebuild utility knows about.
*/
public static String[] REBUILDERS = new String[] {
"fedora.server.resourceIndex.ResourceIndexRebuilder",
"fedora.server.utilities.rebuild.SQLRebuilder" };
public Rebuild(File serverDir, String profile) throws Exception {
ServerConfiguration serverConfig = getServerConfig(serverDir, profile);
// set these here so DOTranslationUtility doesn't try to get a Server
// instance
System.setProperty("fedoraServerHost", serverConfig.getParameter(
"fedoraServerHost").getValue());
System.setProperty("fedoraServerPort", serverConfig.getParameter(
"fedoraServerPort").getValue());
System.err.println();
System.err.println(" Fedora Rebuild Utility");
System.err.println(" ..........................");
System.err.println();
System.err
.println("WARNING: Live rebuilds are not currently supported.");
System.err
.println(" Make sure your server is stopped before continuing.");
System.err.println();
System.err.println("Server directory is " + serverDir.toString());
if (profile != null) {
System.err.print("Server profile is " + profile);
}
System.err.println();
System.err
.println("---------------------------------------------------------------------");
System.err.println();
Rebuilder rebuilder = getRebuilder(serverDir, serverConfig);
if (rebuilder != null) {
System.err.println();
System.err.println(rebuilder.getAction());
System.err.println();
Map options = getOptions(rebuilder.init(serverDir, serverConfig));
boolean serverIsRunning = ServerUtility.pingServer("http", null, null);
if (serverIsRunning && rebuilder.shouldStopServer()) {
throw new Exception("The Fedora server appears to be running."
+ " It must be stopped before the rebuilder can run.");
}
if (options != null) {
System.err.println();
System.err.println("Rebuilding...");
try {
rebuilder.start(options);
// fedora.server.storage.lowlevel.Configuration conf =
// fedora.server.storage.lowlevel.Configuration.getInstance();
// String objStoreBaseStr = conf.getObjectStoreBase();
String role = "fedora.server.storage.lowlevel.ILowlevelStorage";
ModuleConfiguration mcfg = serverConfig
.getModuleConfiguration(role);
Iterator parameters = mcfg.getParameters().iterator();
Map config = new HashMap();
while (parameters.hasNext()) {
Parameter p = (Parameter) parameters.next();
config.put(p.getName(), p.getValue(p.getIsFilePath()));
}
getFilesystem(config);
Parameter param = mcfg
.getParameter(DefaultLowlevelStorage.OBJECT_STORE_BASE);
String objStoreBaseStr = param.getValue(param
.getIsFilePath());
File dir = new File(objStoreBaseStr);
rebuildFromDirectory(rebuilder, dir, "FedoraBDefObject");
rebuildFromDirectory(rebuilder, dir, "FedoraBMechObject");
rebuildFromDirectory(rebuilder, dir, "FedoraObject");
+ rebuildFromDirectory(rebuilder, dir, "FedoraCModelObject");
} finally {
rebuilder.finish();
}
System.err.println("Finished.");
System.err.println();
}
}
}
private void getFilesystem(Map configuration) {
String filesystemClassName = (String) configuration
.get(DefaultLowlevelStorage.FILESYSTEM);
Object[] parameters = new Object[] { configuration };
Class[] parameterTypes = new Class[] { Map.class };
ClassLoader loader = getClass().getClassLoader();
Class cclass;
Constructor constructor;
try {
cclass = loader.loadClass(filesystemClassName);
constructor = cclass.getConstructor(parameterTypes);
fs = (FileSystem) constructor.newInstance(parameters);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Recurse directories in reverse order (latest time first) looking for
* files that contain searchString, and call rebuilder.addObject on them.
*/
private void rebuildFromDirectory(Rebuilder rebuilder, File dir,
String searchString) throws Exception {
String[] filenames = fs.list(dir);
if (filenames == null) {
return;
}
Arrays.sort(filenames);
for (int i = 0; i < filenames.length; i++) {
File f = new File(dir.getAbsolutePath() + File.separator
+ filenames[i]);
if (fs.isDirectory(f)) {
rebuildFromDirectory(rebuilder, f, searchString);
} else {
BufferedReader reader = null;
InputStream in;
try {
in = null;
reader = new BufferedReader(new InputStreamReader(fs
.read(f)));
String line = reader.readLine();
while (line != null) {
if (line.indexOf(searchString) != -1) {
in = fs.read(f);
line = null;
} else {
line = reader.readLine();
}
}
if (in != null) {
try {
System.out.println(f.getAbsoluteFile());
DigitalObject obj = new BasicDigitalObject();
DODeserializer deser = new FOXMLDODeserializer();
deser
.deserialize(
in,
obj,
"UTF-8",
DOTranslationUtility.SERIALIZE_STORAGE_INTERNAL);
rebuilder.addObject(obj);
} catch (Exception e) {
System.out.println("WARNING: Skipped " + f.getAbsoluteFile() + " due to following exception:");
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
}
} finally {
if (reader != null)
try {
reader.close();
} catch (Exception e) {
}
}
}
}
}
private Map getOptions(Map descs) throws IOException {
Map options = new HashMap();
Iterator iter = descs.keySet().iterator();
while (iter.hasNext()) {
String name = (String) iter.next();
String desc = (String) descs.get(name);
options.put(name, getOptionValue(name, desc));
}
int c = getChoice("Start rebuilding with the above options?",
new String[] { "Yes", "No, let me re-enter the options.",
"No, exit." });
if (c == 0)
return options;
if (c == 1) {
System.err.println();
return getOptions(descs);
}
return null;
}
private String getOptionValue(String name, String desc) throws IOException {
System.err.println("[" + name + "]");
System.err.println(desc);
System.err.println();
System.err.print("Enter a value --> ");
String val = new BufferedReader(new InputStreamReader(System.in))
.readLine();
System.err.println();
return val;
}
private Rebuilder getRebuilder(File serverDir,
ServerConfiguration serverConfig) throws Exception {
String[] labels = new String[REBUILDERS.length + 1];
Rebuilder[] rebuilders = new Rebuilder[REBUILDERS.length];
int i = 0;
for (i = 0; i < REBUILDERS.length; i++) {
Rebuilder r = (Rebuilder) Class.forName(REBUILDERS[i])
.newInstance();
labels[i] = r.getAction();
rebuilders[i] = r;
}
labels[i] = "Exit";
int choiceNum = getChoice("What do you want to do?", labels);
if (choiceNum == i) {
return null;
} else {
return rebuilders[choiceNum];
}
}
private int getChoice(String title, String[] labels) throws IOException {
boolean validChoice = false;
int choiceIndex = -1;
System.err.println(title);
System.err.println();
for (int i = 1; i <= labels.length; i++) {
System.err.println(" " + i + ") " + labels[i - 1]);
}
System.err.println();
while (!validChoice) {
System.err.print("Enter (1-" + labels.length + ") --> ");
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String line = in.readLine();
try {
int choiceNum = Integer.parseInt(line);
if (choiceNum > 0 && choiceNum <= labels.length) {
choiceIndex = choiceNum - 1;
validChoice = true;
}
} catch (NumberFormatException nfe) {
}
}
return choiceIndex;
}
private static ServerConfiguration getServerConfig(File serverDir,
String profile) throws IOException {
ServerConfigurationParser parser = new ServerConfigurationParser(
new FileInputStream(new File(serverDir, "config/fedora.fcfg")));
ServerConfiguration serverConfig = parser.parse();
// set all the values according to the profile, if specified
if (profile != null) {
int c = setValuesForProfile(serverConfig, profile);
c += setValuesForProfile(serverConfig.getModuleConfigurations(),
profile);
c += setValuesForProfile(serverConfig.getDatastoreConfigurations(),
profile);
if (c == 0) {
throw new IOException("Unrecognized server-profile: " + profile);
}
}
return serverConfig;
}
private static int setValuesForProfile(Configuration config, String profile) {
int c = 0;
Iterator iter = config.getParameters().iterator();
while (iter.hasNext()) {
Parameter param = (Parameter) iter.next();
String profileValue = (String) param.getProfileValues()
.get(profile);
if (profileValue != null) {
param.setValue(profileValue);
c++;
}
}
return c;
}
private static int setValuesForProfile(List configs, String profile) {
Iterator iter = configs.iterator();
int c = 0;
while (iter.hasNext()) {
c += setValuesForProfile((Configuration) iter.next(), profile);
}
return c;
}
public static void fail(String message, boolean showUsage, boolean exit) {
System.err.println("Error: " + message);
System.err.println();
if (showUsage) {
System.err.println("Usage: fedora-rebuild [server-profile]");
System.err.println();
System.err
.println("server-profile : the argument you start Fedora with, such as 'mckoi'");
System.err
.println(" or 'oracle'. If you start fedora with 'fedora-start'");
System.err
.println(" (without arguments), don't specify a server-profile here either.");
System.err.println();
}
if (exit) {
System.exit(1);
}
}
public static void main(String[] args) {
// tell commons-logging to use log4j
System.setProperty("org.apache.commons.logging.LogFactory",
"org.apache.commons.logging.impl.Log4jFactory");
System.setProperty("org.apache.commons.logging.Log",
"org.apache.commons.logging.impl.Log4JLogger");
// log4j
// File log4jConfig = new File(new File(homeDir), "config/log4j.xml");
// DOMConfigurator.configure(log4jConfig.getPath());
String profile = null;
if (args.length == 1) {
profile = args[0];
}
if (args.length > 1) {
fail("Too many arguments", true, true);
}
try {
File serverDir = new File(new File(Constants.FEDORA_HOME), "server");
if (args.length > 0)
profile = args[0];
new Rebuild(serverDir, profile);
} catch (Throwable th) {
String msg = th.getMessage();
if (msg == null)
msg = th.getClass().getName();
fail(msg, false, false);
th.printStackTrace();
}
}
}
| true | true | public Rebuild(File serverDir, String profile) throws Exception {
ServerConfiguration serverConfig = getServerConfig(serverDir, profile);
// set these here so DOTranslationUtility doesn't try to get a Server
// instance
System.setProperty("fedoraServerHost", serverConfig.getParameter(
"fedoraServerHost").getValue());
System.setProperty("fedoraServerPort", serverConfig.getParameter(
"fedoraServerPort").getValue());
System.err.println();
System.err.println(" Fedora Rebuild Utility");
System.err.println(" ..........................");
System.err.println();
System.err
.println("WARNING: Live rebuilds are not currently supported.");
System.err
.println(" Make sure your server is stopped before continuing.");
System.err.println();
System.err.println("Server directory is " + serverDir.toString());
if (profile != null) {
System.err.print("Server profile is " + profile);
}
System.err.println();
System.err
.println("---------------------------------------------------------------------");
System.err.println();
Rebuilder rebuilder = getRebuilder(serverDir, serverConfig);
if (rebuilder != null) {
System.err.println();
System.err.println(rebuilder.getAction());
System.err.println();
Map options = getOptions(rebuilder.init(serverDir, serverConfig));
boolean serverIsRunning = ServerUtility.pingServer("http", null, null);
if (serverIsRunning && rebuilder.shouldStopServer()) {
throw new Exception("The Fedora server appears to be running."
+ " It must be stopped before the rebuilder can run.");
}
if (options != null) {
System.err.println();
System.err.println("Rebuilding...");
try {
rebuilder.start(options);
// fedora.server.storage.lowlevel.Configuration conf =
// fedora.server.storage.lowlevel.Configuration.getInstance();
// String objStoreBaseStr = conf.getObjectStoreBase();
String role = "fedora.server.storage.lowlevel.ILowlevelStorage";
ModuleConfiguration mcfg = serverConfig
.getModuleConfiguration(role);
Iterator parameters = mcfg.getParameters().iterator();
Map config = new HashMap();
while (parameters.hasNext()) {
Parameter p = (Parameter) parameters.next();
config.put(p.getName(), p.getValue(p.getIsFilePath()));
}
getFilesystem(config);
Parameter param = mcfg
.getParameter(DefaultLowlevelStorage.OBJECT_STORE_BASE);
String objStoreBaseStr = param.getValue(param
.getIsFilePath());
File dir = new File(objStoreBaseStr);
rebuildFromDirectory(rebuilder, dir, "FedoraBDefObject");
rebuildFromDirectory(rebuilder, dir, "FedoraBMechObject");
rebuildFromDirectory(rebuilder, dir, "FedoraObject");
} finally {
rebuilder.finish();
}
System.err.println("Finished.");
System.err.println();
}
}
}
| public Rebuild(File serverDir, String profile) throws Exception {
ServerConfiguration serverConfig = getServerConfig(serverDir, profile);
// set these here so DOTranslationUtility doesn't try to get a Server
// instance
System.setProperty("fedoraServerHost", serverConfig.getParameter(
"fedoraServerHost").getValue());
System.setProperty("fedoraServerPort", serverConfig.getParameter(
"fedoraServerPort").getValue());
System.err.println();
System.err.println(" Fedora Rebuild Utility");
System.err.println(" ..........................");
System.err.println();
System.err
.println("WARNING: Live rebuilds are not currently supported.");
System.err
.println(" Make sure your server is stopped before continuing.");
System.err.println();
System.err.println("Server directory is " + serverDir.toString());
if (profile != null) {
System.err.print("Server profile is " + profile);
}
System.err.println();
System.err
.println("---------------------------------------------------------------------");
System.err.println();
Rebuilder rebuilder = getRebuilder(serverDir, serverConfig);
if (rebuilder != null) {
System.err.println();
System.err.println(rebuilder.getAction());
System.err.println();
Map options = getOptions(rebuilder.init(serverDir, serverConfig));
boolean serverIsRunning = ServerUtility.pingServer("http", null, null);
if (serverIsRunning && rebuilder.shouldStopServer()) {
throw new Exception("The Fedora server appears to be running."
+ " It must be stopped before the rebuilder can run.");
}
if (options != null) {
System.err.println();
System.err.println("Rebuilding...");
try {
rebuilder.start(options);
// fedora.server.storage.lowlevel.Configuration conf =
// fedora.server.storage.lowlevel.Configuration.getInstance();
// String objStoreBaseStr = conf.getObjectStoreBase();
String role = "fedora.server.storage.lowlevel.ILowlevelStorage";
ModuleConfiguration mcfg = serverConfig
.getModuleConfiguration(role);
Iterator parameters = mcfg.getParameters().iterator();
Map config = new HashMap();
while (parameters.hasNext()) {
Parameter p = (Parameter) parameters.next();
config.put(p.getName(), p.getValue(p.getIsFilePath()));
}
getFilesystem(config);
Parameter param = mcfg
.getParameter(DefaultLowlevelStorage.OBJECT_STORE_BASE);
String objStoreBaseStr = param.getValue(param
.getIsFilePath());
File dir = new File(objStoreBaseStr);
rebuildFromDirectory(rebuilder, dir, "FedoraBDefObject");
rebuildFromDirectory(rebuilder, dir, "FedoraBMechObject");
rebuildFromDirectory(rebuilder, dir, "FedoraObject");
rebuildFromDirectory(rebuilder, dir, "FedoraCModelObject");
} finally {
rebuilder.finish();
}
System.err.println("Finished.");
System.err.println();
}
}
}
|
diff --git a/src/pudgewars/entities/PudgeEntity.java b/src/pudgewars/entities/PudgeEntity.java
index 0c0d45c..7519ed8 100644
--- a/src/pudgewars/entities/PudgeEntity.java
+++ b/src/pudgewars/entities/PudgeEntity.java
@@ -1,371 +1,375 @@
package pudgewars.entities;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.util.List;
import pudgewars.Game;
import pudgewars.Window;
import pudgewars.components.Stats;
import pudgewars.entities.hooks.GrappleHookEntity;
import pudgewars.entities.hooks.HookEntity;
import pudgewars.entities.hooks.HookType;
import pudgewars.entities.hooks.NormalHookEntity;
import pudgewars.interfaces.BBOwner;
import pudgewars.level.Tile;
import pudgewars.particles.ParticleTypes;
import pudgewars.util.Animation;
import pudgewars.util.CollisionBox;
import pudgewars.util.ImageHandler;
import pudgewars.util.Time;
import pudgewars.util.Vector2;
public class PudgeEntity extends Entity implements LightSource {
public final static int CLICK_SIZE = 8;
public final static int MAX_LIFE = 20;
public final static double COLLISION_WIDTH = 1;
public final static double COLLISION_HEIGHT = 1;
public final static double HOOK_COOLDOWN = 3;
public final static double GRAPPLEHOOK_COOLDOWN = 15;
public final static double ATK_RANGE = 2;
public final static double RESPAWN_INTERVAL = 2;
public Stats stats;
// Whether or not you can control this Pudge
public boolean controllable = false;
// Hooking
public double hookCooldown;
public double grappleCooldown;
public boolean isHooking;
public boolean canMove;
public boolean canTileCollide;
public boolean canEntityCollide;
public NormalHookEntity attachedHook;
// Attacking
public double attackInterval;
// Target
protected Image clicker;
protected PudgeEntity targetEnemy;
protected Vector2 target;
protected double targetRotation;
protected Vector2 hookTarget;
protected boolean isGrapple;
// Rendering
protected Animation ani;
protected Image fullLife;
protected Image emptyLife;
public double respawnInterval = RESPAWN_INTERVAL;
public PudgeEntity(Vector2 position, Team team) {
super(position, new Vector2(COLLISION_WIDTH, COLLISION_HEIGHT));
transform.drawScale = new Vector2(2, 2);
this.team = team;
canTileCollide = true;
canEntityCollide = true;
canMove = true;
stats = new Stats(this);
stats.restoreDefaults();
stats.subLife(5);
rigidbody.physicsSlide = true;
ani = Animation.makeAnimation("horse2", 8, 32, 32, 0.05);
ani.startAnimation();
clicker = ImageHandler.get().getImage("selector");
target = null;
fullLife = ImageHandler.get().getImage("life_full");
emptyLife = ImageHandler.get().getImage("life_empty");
}
public void update() {
if (rigidbody.isMoving()) ani.update();
if (!canMove) target = null;
// Stats
if (controllable && Game.keyInput.buyMode.wasPressed()) {
stats.isOpen ^= true; // Cool way to NOT
}
// Controls
hookTarget = null;
isGrapple = false;
if (controllable && canMove && !stats.isOpen) {
if (hookCooldown > 0) hookCooldown -= Time.getTickInterval();
if (hookCooldown < 0) hookCooldown = 0;
if (grappleCooldown > 0) grappleCooldown -= Time.getTickInterval();
if (grappleCooldown < 0) grappleCooldown = 0;
// Change Cursor
if (Game.keyInput.specialHook.isDown) Game.cursor.setCursor("Special");
else Game.cursor.setCursor("Default");
// Hover
if (Game.keyInput.space.isDown) Game.focus = transform.position.clone();
Vector2 left = Game.mouseInput.left.wasPressed();
if (left != null) {
if (!Game.keyInput.specialHook.isDown) {
if (hookCooldown <= 0) {
if (setHook(Game.s.screenToWorldPoint(left), HookType.NORMAL)) hookCooldown = HOOK_COOLDOWN;
hookTarget = Game.s.screenToWorldPoint(left);
shouldSendNetworkData = true;
}
canEntityCollide = true;
} else {
if (grappleCooldown <= 0) {
if (setHook(Game.s.screenToWorldPoint(left), HookType.GRAPPLE)) grappleCooldown = GRAPPLEHOOK_COOLDOWN;
hookTarget = Game.s.screenToWorldPoint(left);
isGrapple = true;
shouldSendNetworkData = true;
}
}
}
Vector2 right = Game.mouseInput.right.wasPressed();
if (right != null) {
right = Game.s.screenToWorldPoint(right);
// See if right clicked on any player
clickedOnPlayer(right);
shouldSendNetworkData = true;
}
// Rotate the Clicker
if (target != null) targetRotation += -0.1;
}
// Target Movement
if (target != null) {
transform.rotateTowards(target, 0.1);
double dist = transform.position.distance(target);
if (dist < rigidbody.velocity.magnitude() * Time.getTickInterval()) {
rigidbody.velocity = new Vector2(0, 0);
target = null;
} else {
rigidbody.setDirection(target);
}
}
// Attacking
if (attackInterval > 0) attackInterval -= Time.getTickInterval();
if (attackInterval < 0) attackInterval = 0;
if (targetEnemy != null) {
if (targetEnemy.transform.position.distance(transform.position) < ATK_RANGE) {
if (attackInterval == 0) {
attackInterval = 0.5;
targetEnemy.stats.subLife(4);
Game.entities.addParticle(ParticleTypes.DIE, targetEnemy, null, 0.25);
}
}
}
// send the movement made to the server
// if (controllable && actionCommitted) {
// Game.net.sendEntityData(getNetworkString());
// }
rigidbody.updateVelocity();
if(respawning){
if (respawnInterval < 0) {
this.stats.set_life(20);
+ String position = (team == Team.leftTeam) ? "4.0 " : "20.0 ";
+ position += 8 * (ClientID/2) + 4;
+ transform.position.setNetString(position);
+ rigidbody.velocity.setNetString("0.0 0.0");
respawnInterval = RESPAWN_INTERVAL;
remove = false;
respawn = true;
}
respawnInterval -= Time.getTickInterval();
}
}
public void clickedOnPlayer(Vector2 right) {
List<CollisionBox> l = Game.entities.getEntityListCollisionBoxes(right);
targetEnemy = null;
for (CollisionBox b : l) {
if (b.owner instanceof PudgeEntity && b.owner != this) {
PudgeEntity p = (PudgeEntity) b.owner;
if (!this.isTeammate(p) && p.shouldRender) {
System.out.println("Clicked on: " + p.name);
targetEnemy = p;
break;
}
}
}
if (targetEnemy == null) target = right;
else target = targetEnemy.transform.position.clone();
}
public void render() {
if (!shouldRender) return;
// Draw Pudge
Game.s.g.drawImage(ani.getImage(), transform.getAffineTransformation(), null);
/*
* LIFE DRAWING
*/
// Dimension Definitions!
Vector2 v = Game.s.worldToScreenPoint(transform.position);
v.y -= Game.TILE_SIZE / 2;
int lifebarWidth = fullLife.getWidth(null);
int lifebarHeight = fullLife.getHeight(null);
int lifebarActual = (int) (fullLife.getWidth(null) * stats.lifePercentage());
Game.s.g.drawImage(emptyLife, (int) v.x - lifebarWidth / 2, (int) v.y - lifebarHeight / 2, (int) v.x + lifebarWidth / 2, (int) v.y + lifebarHeight / 2, //
0, 0, lifebarWidth, lifebarHeight, null);
Game.s.g.drawImage(fullLife, (int) v.x - lifebarWidth / 2, (int) v.y - lifebarHeight / 2, (int) v.x - lifebarWidth / 2 + lifebarActual, (int) v.y + lifebarHeight / 2, //
0, 0, lifebarActual, lifebarHeight, null);
}
public void onGUI() {
if (controllable) {
// Draw Target Reticle
if (target != null) {
Vector2 targetLocation = Game.s.worldToScreenPoint(target);
AffineTransform a = new AffineTransform();
a.translate((int) (targetLocation.x - CLICK_SIZE / 2), (int) (targetLocation.y - CLICK_SIZE / 2));
a.rotate(targetRotation, CLICK_SIZE / 2, CLICK_SIZE / 2);
Game.s.g.drawImage(clicker, a, null);
}
// Draw Stats
stats.onGUI();
}
}
public boolean setHook(Vector2 click, int hookType) {
if (!isHooking) {
Entity e = null;
switch (hookType) {
case HookType.NORMAL:
e = new NormalHookEntity(this, click);
break;
case HookType.GRAPPLE:
e = new GrappleHookEntity(this, click);
break;
}
Game.entities.entities.add(e);
isHooking = true;
return true;
}
return false;
}
/*
* Collisions
*/
public boolean shouldBlock(BBOwner b) {
if (b instanceof HookEntity) return true;
if (b instanceof PudgeEntity) {
return canEntityCollide ? true : isHooking;
}
if (canTileCollide) {
if (b instanceof Tile) {
if (((Tile) b).isPudgeSolid()) return true;
}
}
return false;
}
public void collides(Entity e, double vx, double vy) {
if (e instanceof PudgeEntity) {
PudgeEntity p = (PudgeEntity) e;
if (p.attachedHook != null) {
if (p.attachedHook.owner == this) {
p.attachedHook.detachPudge();
p.rigidbody.velocity = Vector2.ZERO.clone();
}
}
}
}
public void kill() {
if(Game.isServer) {
System.out.println("Pudge was Killed");
respawning = true;
super.kill();
}
}
/*
* Network
*/
public void sendNetworkData() {
if (controllable) {
super.sendNetworkData();
}
}
public String getNetworkString() {
String s = "PUDGE:";
s += ClientID + ":";
s += transform.position.getNetString();
s += ":" + rigidbody.velocity.getNetString() + ":";
s += (target == null) ? "null" : target.getNetString();
s += ":" + team + ":";
s += (hookTarget == null) ? "null" : hookTarget.getNetString();
s += ":" + isGrapple;
s += ":" + stats.getNetString();
return s;
}
public void setNetworkString(String s) {
wasUpdated = true;
String[] t = s.split(":");
transform.position.setNetString(t[2]);
rigidbody.velocity.setNetString(t[3]);
if (t[4].equals("null")) {
target = null;
} else {
target = new Vector2();
target.setNetString(t[4]);
clickedOnPlayer(target);
}
if (!t[6].equals("null")) {
String[] u = t[6].split(" ");
Vector2 hookTarget = new Vector2(Float.parseFloat(u[0]), Float.parseFloat(u[1]));
if (t[7].equals("false")) setHook(hookTarget, HookType.NORMAL);
else setHook(hookTarget, HookType.GRAPPLE);
}
this.stats.setNetString(t[8]);
}
/*
* Light Source
*/
public Shape getLightShape() {
Vector2 v = Game.s.worldToScreenPoint(transform.position);
v.scale(1.0 / Window.LIGHTMAP_MULT);
double r = (4 * Game.TILE_SIZE) / Window.LIGHTMAP_MULT;
Shape circle = new Ellipse2D.Double(v.x - r, v.y - r, r * 2, r * 2);
return circle;
}
}
| true | true | public void update() {
if (rigidbody.isMoving()) ani.update();
if (!canMove) target = null;
// Stats
if (controllable && Game.keyInput.buyMode.wasPressed()) {
stats.isOpen ^= true; // Cool way to NOT
}
// Controls
hookTarget = null;
isGrapple = false;
if (controllable && canMove && !stats.isOpen) {
if (hookCooldown > 0) hookCooldown -= Time.getTickInterval();
if (hookCooldown < 0) hookCooldown = 0;
if (grappleCooldown > 0) grappleCooldown -= Time.getTickInterval();
if (grappleCooldown < 0) grappleCooldown = 0;
// Change Cursor
if (Game.keyInput.specialHook.isDown) Game.cursor.setCursor("Special");
else Game.cursor.setCursor("Default");
// Hover
if (Game.keyInput.space.isDown) Game.focus = transform.position.clone();
Vector2 left = Game.mouseInput.left.wasPressed();
if (left != null) {
if (!Game.keyInput.specialHook.isDown) {
if (hookCooldown <= 0) {
if (setHook(Game.s.screenToWorldPoint(left), HookType.NORMAL)) hookCooldown = HOOK_COOLDOWN;
hookTarget = Game.s.screenToWorldPoint(left);
shouldSendNetworkData = true;
}
canEntityCollide = true;
} else {
if (grappleCooldown <= 0) {
if (setHook(Game.s.screenToWorldPoint(left), HookType.GRAPPLE)) grappleCooldown = GRAPPLEHOOK_COOLDOWN;
hookTarget = Game.s.screenToWorldPoint(left);
isGrapple = true;
shouldSendNetworkData = true;
}
}
}
Vector2 right = Game.mouseInput.right.wasPressed();
if (right != null) {
right = Game.s.screenToWorldPoint(right);
// See if right clicked on any player
clickedOnPlayer(right);
shouldSendNetworkData = true;
}
// Rotate the Clicker
if (target != null) targetRotation += -0.1;
}
// Target Movement
if (target != null) {
transform.rotateTowards(target, 0.1);
double dist = transform.position.distance(target);
if (dist < rigidbody.velocity.magnitude() * Time.getTickInterval()) {
rigidbody.velocity = new Vector2(0, 0);
target = null;
} else {
rigidbody.setDirection(target);
}
}
// Attacking
if (attackInterval > 0) attackInterval -= Time.getTickInterval();
if (attackInterval < 0) attackInterval = 0;
if (targetEnemy != null) {
if (targetEnemy.transform.position.distance(transform.position) < ATK_RANGE) {
if (attackInterval == 0) {
attackInterval = 0.5;
targetEnemy.stats.subLife(4);
Game.entities.addParticle(ParticleTypes.DIE, targetEnemy, null, 0.25);
}
}
}
// send the movement made to the server
// if (controllable && actionCommitted) {
// Game.net.sendEntityData(getNetworkString());
// }
rigidbody.updateVelocity();
if(respawning){
if (respawnInterval < 0) {
this.stats.set_life(20);
respawnInterval = RESPAWN_INTERVAL;
remove = false;
respawn = true;
}
respawnInterval -= Time.getTickInterval();
}
}
| public void update() {
if (rigidbody.isMoving()) ani.update();
if (!canMove) target = null;
// Stats
if (controllable && Game.keyInput.buyMode.wasPressed()) {
stats.isOpen ^= true; // Cool way to NOT
}
// Controls
hookTarget = null;
isGrapple = false;
if (controllable && canMove && !stats.isOpen) {
if (hookCooldown > 0) hookCooldown -= Time.getTickInterval();
if (hookCooldown < 0) hookCooldown = 0;
if (grappleCooldown > 0) grappleCooldown -= Time.getTickInterval();
if (grappleCooldown < 0) grappleCooldown = 0;
// Change Cursor
if (Game.keyInput.specialHook.isDown) Game.cursor.setCursor("Special");
else Game.cursor.setCursor("Default");
// Hover
if (Game.keyInput.space.isDown) Game.focus = transform.position.clone();
Vector2 left = Game.mouseInput.left.wasPressed();
if (left != null) {
if (!Game.keyInput.specialHook.isDown) {
if (hookCooldown <= 0) {
if (setHook(Game.s.screenToWorldPoint(left), HookType.NORMAL)) hookCooldown = HOOK_COOLDOWN;
hookTarget = Game.s.screenToWorldPoint(left);
shouldSendNetworkData = true;
}
canEntityCollide = true;
} else {
if (grappleCooldown <= 0) {
if (setHook(Game.s.screenToWorldPoint(left), HookType.GRAPPLE)) grappleCooldown = GRAPPLEHOOK_COOLDOWN;
hookTarget = Game.s.screenToWorldPoint(left);
isGrapple = true;
shouldSendNetworkData = true;
}
}
}
Vector2 right = Game.mouseInput.right.wasPressed();
if (right != null) {
right = Game.s.screenToWorldPoint(right);
// See if right clicked on any player
clickedOnPlayer(right);
shouldSendNetworkData = true;
}
// Rotate the Clicker
if (target != null) targetRotation += -0.1;
}
// Target Movement
if (target != null) {
transform.rotateTowards(target, 0.1);
double dist = transform.position.distance(target);
if (dist < rigidbody.velocity.magnitude() * Time.getTickInterval()) {
rigidbody.velocity = new Vector2(0, 0);
target = null;
} else {
rigidbody.setDirection(target);
}
}
// Attacking
if (attackInterval > 0) attackInterval -= Time.getTickInterval();
if (attackInterval < 0) attackInterval = 0;
if (targetEnemy != null) {
if (targetEnemy.transform.position.distance(transform.position) < ATK_RANGE) {
if (attackInterval == 0) {
attackInterval = 0.5;
targetEnemy.stats.subLife(4);
Game.entities.addParticle(ParticleTypes.DIE, targetEnemy, null, 0.25);
}
}
}
// send the movement made to the server
// if (controllable && actionCommitted) {
// Game.net.sendEntityData(getNetworkString());
// }
rigidbody.updateVelocity();
if(respawning){
if (respawnInterval < 0) {
this.stats.set_life(20);
String position = (team == Team.leftTeam) ? "4.0 " : "20.0 ";
position += 8 * (ClientID/2) + 4;
transform.position.setNetString(position);
rigidbody.velocity.setNetString("0.0 0.0");
respawnInterval = RESPAWN_INTERVAL;
remove = false;
respawn = true;
}
respawnInterval -= Time.getTickInterval();
}
}
|
diff --git a/pluginsource/org/enigma/backend/EnigmaCallbacks.java b/pluginsource/org/enigma/backend/EnigmaCallbacks.java
index 653fc75c..a5d178aa 100644
--- a/pluginsource/org/enigma/backend/EnigmaCallbacks.java
+++ b/pluginsource/org/enigma/backend/EnigmaCallbacks.java
@@ -1,121 +1,121 @@
package org.enigma.backend;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.enigma.EnigmaFrame;
import com.sun.jna.Callback;
import com.sun.jna.Structure;
public class EnigmaCallbacks extends Structure
{
public Callback coo = new OutputOpen(); //void (*coo) (void)
public Callback coa = new OutputAppend(); //void (*coa) (String)
public Callback cock = new OutputClear(); //void (*cock) (void)
public Callback cop = new OutputProgress(); //void (*cop) (int)
public Callback cot = new OutputTip(); //void (*cot) (String)
public Callback cof = new OpenFile(); //void (*cof) (String)
public Callback ccf = new CloseFile(); //void (*ccf) ()
public EnigmaCallbacks(EnigmaFrame ef)
{
((OutputHolder) coo).ef = ef;
((OutputHolder) coa).ef = ef;
((OutputHolder) cock).ef = ef;
((OutputHolder) cop).ef = ef;
((OutputHolder) cot).ef = ef;
((OutputHolder) cof).ef = ef;
((OutputHolder) ccf).ef = ef;
}
public static class OutputHolder
{
EnigmaFrame ef;
}
public static class OutputOpen extends OutputHolder implements Callback
{
public void callback()
{
ef.setVisible(true);
}
}
public static class OutputAppend extends OutputHolder implements Callback
{
public void callback(String msg)
{
ef.ta.append(msg);
ef.ta.setCaretPosition(ef.ta.getDocument().getLength());
}
}
public static class OutputClear extends OutputHolder implements Callback
{
public void callback()
{
ef.ta.setText("");
}
}
public static class OutputProgress extends OutputHolder implements Callback
{
public void callback(int amt)
{
ef.pb.setValue(amt);
}
}
public static class OutputTip extends OutputHolder implements Callback
{
public void callback(String tip)
{
ef.pb.setString(tip);
}
}
public static class OpenFile extends OutputHolder implements Callback
{
public void callback(final String file)
{
new Thread()
{
public void run()
{
int data;
try
{
InputStream in = new FileInputStream(new File(file));
while (true)
{
if (in.available() > 0)
{
data = in.read();
if (data == -1) break;
ef.ta.append("" + (char) data);
ef.ta.setCaretPosition(ef.ta.getDocument().getLength());
- System.out.print(data);
+ System.out.print("" + (char) data);
}
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}
}
public static class CloseFile extends OutputHolder implements Callback
{
public void callback()
{
}
}
}
| true | true | public void callback(final String file)
{
new Thread()
{
public void run()
{
int data;
try
{
InputStream in = new FileInputStream(new File(file));
while (true)
{
if (in.available() > 0)
{
data = in.read();
if (data == -1) break;
ef.ta.append("" + (char) data);
ef.ta.setCaretPosition(ef.ta.getDocument().getLength());
System.out.print(data);
}
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}
| public void callback(final String file)
{
new Thread()
{
public void run()
{
int data;
try
{
InputStream in = new FileInputStream(new File(file));
while (true)
{
if (in.available() > 0)
{
data = in.read();
if (data == -1) break;
ef.ta.append("" + (char) data);
ef.ta.setCaretPosition(ef.ta.getDocument().getLength());
System.out.print("" + (char) data);
}
}
in.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}.start();
}
|
diff --git a/timemeasurement-core/src/test/java/com/coremedia/contribution/timemeasurement/TimeMeasurementTest.java b/timemeasurement-core/src/test/java/com/coremedia/contribution/timemeasurement/TimeMeasurementTest.java
index 32af36a..721cde6 100644
--- a/timemeasurement-core/src/test/java/com/coremedia/contribution/timemeasurement/TimeMeasurementTest.java
+++ b/timemeasurement-core/src/test/java/com/coremedia/contribution/timemeasurement/TimeMeasurementTest.java
@@ -1,151 +1,151 @@
package com.coremedia.contribution.timemeasurement;
import etm.core.monitor.EtmPoint;
import junit.framework.TestCase;
import org.junit.Test;
/**
*
*/
public class TimeMeasurementTest extends TestCase {
@Test
public void testWorkingJetmConnector() {
System.setProperty("timemeasurement.enabled", "true");
TimeMeasurement.reset();
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start("testWorkingJetmConnector");
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
assertTrue(TimeMeasurement.getMeasurementResults().contains("testWorkingJetmConnector"));
}
}
@Test
public void testStartWithNullParameter() {
System.setProperty("timemeasurement.enabled", "true");
TimeMeasurement.reset();
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start(null);
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
assertTrue(TimeMeasurement.getMeasurementResults().contains("default"));
}
}
@Test
public void testStopWithNullParameter() {
System.setProperty("timemeasurement.enabled", "true");
TimeMeasurement.reset();
TimeMeasurement.stop(null);
}
@Test
public void testIsActive() {
System.setProperty("timemeasurement.enabled", "true");
TimeMeasurement.reset();
assertTrue(TimeMeasurement.getMBean().isActive());
}
@Test
public void testStdOut() {
System.setProperty("timemeasurement.enabled", "true");
TimeMeasurement.reset();
TimeMeasurement.toStdOut();
}
@Test
public void testUseNested() {
System.setProperty("timemeasurement.enabled", "true");
System.setProperty("timemeasurement.useNested", "true");
TimeMeasurement.reset();
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start("testUseNested");
Thread.sleep(5);
nestedMethod();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
assertTrue(TimeMeasurement.getMeasurementResults().contains("testUseNested"));
assertTrue(TimeMeasurement.getMeasurementResults().contains("nestedMethod"));
TimeMeasurement.toLog();
}
}
private void nestedMethod() {
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start("nestedMethod");
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
}
}
@Test
public void testUseMillis() {
System.setProperty("timemeasurement.enabled", "true");
System.setProperty("timemeasurement.useMillis", "true");
TimeMeasurement.reset();
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start("testUseMillis");
//although most systems, Thread.sleep(millis,nanos) does not work (Thread sleeps only for given milliseconds),
//it's extremly unlikely that this thread would sleep exactly 5 milliseconds.
//if measured in nanoseconds, it's sleeping ~5100
- Thread.sleep(5);
+ Thread.sleep(5,999);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
assertTrue(TimeMeasurement.getMeasurementResults().contains("testUseMillis"));
- assertTrue(TimeMeasurement.getMeasurementResults().contains("5"));
+ assertTrue(TimeMeasurement.getMeasurementResults().contains("6"));
TimeMeasurement.toLog();
}
}
@Test
public void testDummyJetmConnector() {
//unfortunately, the SystemPropery is ignored because TimeMeasurement is initialized in a static block.
//if one test with "timemeasurement.enabled" set to "true" runs before this test, TimeMeasurement will be
//initialized with a WorkingJetmConnector and vice versa.
System.setProperty("timemeasurement.enabled", "false");
//therefore, I have to manually set it to false, so the DummyJetmConnector is loaded
TimeMeasurement.getMBean().setActive(false);
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start("testDummyJetmConnector");
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
assertTrue(!TimeMeasurement.getMBean().isActive());
assertTrue(TimeMeasurement.getMeasurementResults().contains("disabled"));
}
}
}
| false | true | public void testUseMillis() {
System.setProperty("timemeasurement.enabled", "true");
System.setProperty("timemeasurement.useMillis", "true");
TimeMeasurement.reset();
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start("testUseMillis");
//although most systems, Thread.sleep(millis,nanos) does not work (Thread sleeps only for given milliseconds),
//it's extremly unlikely that this thread would sleep exactly 5 milliseconds.
//if measured in nanoseconds, it's sleeping ~5100
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
assertTrue(TimeMeasurement.getMeasurementResults().contains("testUseMillis"));
assertTrue(TimeMeasurement.getMeasurementResults().contains("5"));
TimeMeasurement.toLog();
}
}
| public void testUseMillis() {
System.setProperty("timemeasurement.enabled", "true");
System.setProperty("timemeasurement.useMillis", "true");
TimeMeasurement.reset();
EtmPoint etmPoint = null;
try {
etmPoint = TimeMeasurement.start("testUseMillis");
//although most systems, Thread.sleep(millis,nanos) does not work (Thread sleeps only for given milliseconds),
//it's extremly unlikely that this thread would sleep exactly 5 milliseconds.
//if measured in nanoseconds, it's sleeping ~5100
Thread.sleep(5,999);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
TimeMeasurement.stop(etmPoint);
assertTrue(TimeMeasurement.getMeasurementResults().contains("testUseMillis"));
assertTrue(TimeMeasurement.getMeasurementResults().contains("6"));
TimeMeasurement.toLog();
}
}
|
diff --git a/gnu/testlet/java/io/InputStreamReader/hang.java b/gnu/testlet/java/io/InputStreamReader/hang.java
index 1e61ede8..9515723d 100644
--- a/gnu/testlet/java/io/InputStreamReader/hang.java
+++ b/gnu/testlet/java/io/InputStreamReader/hang.java
@@ -1,65 +1,65 @@
// Regression test for InputStreamReader hang.
// Written by Tom Tromey <[email protected]>
// This file is part of Mauve.
// Mauve is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
// Mauve is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, 59 Temple Place - Suite 330,
// Boston, MA 02111-1307, USA.
// Tags: JDK1.4
package gnu.testlet.java.io.InputStreamReader;
import gnu.testlet.Testlet;
import gnu.testlet.TestHarness;
import java.io.*;
import java.util.Arrays;
public class hang implements Testlet
{
public void test (TestHarness h)
{
try
{
// We make a buffer where a multi-byte UTF-8 character is
// carefully positioned so that the BufferedInputStream we create
// will split it.
byte[] bytes = new byte[20];
Arrays.fill(bytes, (byte) 'a');
- bytes[9] = (byte) 0xc0;
- bytes[10] = (byte) 0x80;
+ bytes[9] = (byte) 208;
+ bytes[10] = (byte) 164;
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedInputStream bis = new BufferedInputStream(bais, 10);
// Note that the encoding name matters for this particular
// regression. It must be exactly 'utf8'.
InputStreamReader reader = new InputStreamReader(bis, "utf8");
char[] result = new char[5];
for (int i = 0; i < 4; ++i)
reader.read(result);
h.check(true);
}
catch (IOException _)
{
h.debug(_);
h.check(false);
}
}
}
| true | true | public void test (TestHarness h)
{
try
{
// We make a buffer where a multi-byte UTF-8 character is
// carefully positioned so that the BufferedInputStream we create
// will split it.
byte[] bytes = new byte[20];
Arrays.fill(bytes, (byte) 'a');
bytes[9] = (byte) 0xc0;
bytes[10] = (byte) 0x80;
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedInputStream bis = new BufferedInputStream(bais, 10);
// Note that the encoding name matters for this particular
// regression. It must be exactly 'utf8'.
InputStreamReader reader = new InputStreamReader(bis, "utf8");
char[] result = new char[5];
for (int i = 0; i < 4; ++i)
reader.read(result);
h.check(true);
}
catch (IOException _)
{
h.debug(_);
h.check(false);
}
}
| public void test (TestHarness h)
{
try
{
// We make a buffer where a multi-byte UTF-8 character is
// carefully positioned so that the BufferedInputStream we create
// will split it.
byte[] bytes = new byte[20];
Arrays.fill(bytes, (byte) 'a');
bytes[9] = (byte) 208;
bytes[10] = (byte) 164;
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
BufferedInputStream bis = new BufferedInputStream(bais, 10);
// Note that the encoding name matters for this particular
// regression. It must be exactly 'utf8'.
InputStreamReader reader = new InputStreamReader(bis, "utf8");
char[] result = new char[5];
for (int i = 0; i < 4; ++i)
reader.read(result);
h.check(true);
}
catch (IOException _)
{
h.debug(_);
h.check(false);
}
}
|
diff --git a/jsf-ri/src/main/java/com/sun/faces/application/view/StateManagementStrategyImpl.java b/jsf-ri/src/main/java/com/sun/faces/application/view/StateManagementStrategyImpl.java
index cb8d7d5ba..ded24e605 100644
--- a/jsf-ri/src/main/java/com/sun/faces/application/view/StateManagementStrategyImpl.java
+++ b/jsf-ri/src/main/java/com/sun/faces/application/view/StateManagementStrategyImpl.java
@@ -1,379 +1,376 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.sun.faces.application.view;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.FactoryFinder;
import javax.faces.component.UIComponent;
import javax.faces.component.UIViewRoot;
import javax.faces.component.visit.VisitResult;
import javax.faces.context.FacesContext;
import javax.faces.render.ResponseStateManager;
import com.sun.faces.context.StateContext;
import com.sun.faces.renderkit.RenderKitUtils;
import com.sun.faces.util.ComponentStruct;
import com.sun.faces.util.FacesLogger;
import com.sun.faces.util.MessageUtils;
import com.sun.faces.util.Util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import javax.faces.application.StateManager;
import javax.faces.component.ContextCallback;
import javax.faces.component.visit.VisitCallback;
import javax.faces.component.visit.VisitContext;
import javax.faces.view.StateManagementStrategy;
import javax.faces.FacesException;
import javax.faces.application.Application;
import javax.faces.event.PostRestoreStateEvent;
import javax.faces.view.ViewDeclarationLanguage;
import javax.faces.view.ViewDeclarationLanguageFactory;
/**
* <p>
* A <code>StateManager</code> implementation to meet the requirements
* of the specification.
* </p>
*
* <p>
* For those who had compile dependencies on this class, we're sorry for any
* inconvenience, but this had to be re-worked as the version you depended on
* was incorrectly implemented.
* </p>
*/
public class StateManagementStrategyImpl extends StateManagementStrategy {
private static final Logger LOGGER = FacesLogger.APPLICATION_VIEW.getLogger();
private final ViewDeclarationLanguageFactory vdlFactory;
private static final String CLIENTIDS_TO_REMOVE_NAME =
"com.sun.faces.application.view.CLIENTIDS_TO_REMOVE";
private static final String CLIENTIDS_TO_ADD_NAME =
"com.sun.faces.application.view.CLIENTIDS_TO_ADD";
// ------------------------------------------------------------ Constructors
/**
* Create a new <code>StateManagerImpl</code> instance.
*/
public StateManagementStrategyImpl() {
vdlFactory = (ViewDeclarationLanguageFactory)
FactoryFinder.getFactory(FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
}
// ----------------------------------------------- Methods from StateManager
/**
* @see {@link javax.faces.application.StateManager#saveView(javax.faces.context.FacesContext))
*/
@Override
public Object saveView(FacesContext context) {
if (context == null) {
return null;
}
// irrespective of method to save the tree, if the root is transient
// no state information needs to be persisted.
UIViewRoot viewRoot = context.getViewRoot();
if (viewRoot.isTransient()) {
return null;
}
// honor the requirement to check for id uniqueness
Util.checkIdUniqueness(context,
viewRoot,
new HashSet<String>(viewRoot.getChildCount() << 1));
final Map<String,Object> stateMap = new HashMap<String,Object>();
// -----------------------------------------------------------------------------
// COMMENTED OUT DUE TO ISSUE 1310 UNTIL NEW VISIT HINTS CAN BE
// ADDED TO THE API
// -----------------------------------------------------------------------------
// VisitContext visitContext = VisitContext.createVisitContext(context);
// final FacesContext finalContext = context;
// viewRoot.visitTree(visitContext, new VisitCallback() {
//
// public VisitResult visit(VisitContext context, UIComponent target) {
// VisitResult result = VisitResult.ACCEPT;
// Object stateObj;
// if (!target.isTransient()) {
// if (target.getAttributes().containsKey(DYNAMIC_COMPONENT)) {
// stateObj = new StateHolderSaver(finalContext, target);
// } else {
// stateObj = target.saveState(context.getFacesContext());
// }
// if (null != stateObj) {
// stateMap.put(target.getClientId(context.getFacesContext()),
// stateObj);
// }
// } else {
// return result;
// }
//
// return result;
// }
//
// });
// -----------------------------------------------------------------------------
StateContext stateContext = StateContext.getStateContext(context);
// ADDED FOR ISSUE 1310 - REMOVE ONCE NEW VISIT HINTS ARE ADDED TO THE
// API
saveComponentState(viewRoot, context, stateContext, stateMap);
// handle dynamic adds/removes
List<String> removeList = stateContext.getDynamicRemoves();
if (null != removeList && !removeList.isEmpty()) {
stateMap.put(CLIENTIDS_TO_REMOVE_NAME, removeList);
}
Map<String, ComponentStruct> addList = stateContext.getDynamicAdds();
if (null != addList && !addList.isEmpty()) {
List<Object> savedAddList = new ArrayList<Object>(addList.size());
for (ComponentStruct s : addList.values()) {
savedAddList.add(s.saveState(context));
}
stateMap.put(CLIENTIDS_TO_ADD_NAME, savedAddList.toArray());
}
//return stateMap;
return new Object[] { null, stateMap };
}
/**
* @see {@link StateManager#restoreView(javax.faces.context.FacesContext, String, String)}
*/
@Override
public UIViewRoot restoreView(FacesContext context,
String viewId,
String renderKitId) {
ResponseStateManager rsm =
RenderKitUtils.getResponseStateManager(context, renderKitId);
boolean processingEvents = context.isProcessingEvents();
// Build the tree to initial state
UIViewRoot viewRoot;
try {
ViewDeclarationLanguage vdl = vdlFactory.getViewDeclarationLanguage(viewId);
viewRoot = vdl.getViewMetadata(context, viewId).createMetadataView(context);
context.setViewRoot(viewRoot);
context.setProcessingEvents(true);
vdl.buildView(context, viewRoot);
} catch (IOException ioe) {
throw new FacesException(ioe);
}
Object[] rawState = (Object[]) rsm.getState(context, viewId);
if (rawState == null) {
return null; // trigger a ViewExpiredException
}
//noinspection unchecked
final Map<String, Object> state = (Map<String,Object>) rawState[1];
final StateContext stateContext = StateContext.getStateContext(context);
if (null != state) {
final Application app = context.getApplication();
// We need to clone the tree, otherwise we run the risk
// of being left in a state where the restored
// UIComponent instances are in the session instead
// of the TreeNode instances. This is a problem
// for servers that persist session data since
// UIComponent instances are not serializable.
VisitContext visitContext = VisitContext.createVisitContext(context);
viewRoot.visitTree(visitContext, new VisitCallback() {
public VisitResult visit(VisitContext context, UIComponent target) {
VisitResult result = VisitResult.ACCEPT;
String cid = target.getClientId(context.getFacesContext());
Object stateObj = state.get(cid);
if (stateObj != null && !stateContext.componentAddedDynamically(target)) {
try {
target.restoreState(context.getFacesContext(),
stateObj);
} catch (Exception e) {
String msg =
MessageUtils.getExceptionMessageString(
MessageUtils.PARTIAL_STATE_ERROR_RESTORING_ID,
cid,
e.toString());
throw new FacesException(msg, e);
}
- app.publishEvent(context.getFacesContext(),
- PostRestoreStateEvent.class,
- target);
}
return result;
}
});
// Handle dynamic add/removes
//noinspection unchecked
List<String> removeList = (List<String>) state.get(CLIENTIDS_TO_REMOVE_NAME);
if (null != removeList && !removeList.isEmpty()) {
for (String cur : removeList) {
boolean trackMods = stateContext.trackViewModifications();
if (trackMods) {
stateContext.setTrackViewModifications(false);
}
viewRoot.invokeOnComponent(context, cur, new ContextCallback() {
public void invokeContextCallback(FacesContext context, UIComponent target) {
UIComponent parent = target.getParent();
if (null != parent) {
parent.getChildren().remove(target);
}
}
});
if (trackMods) {
stateContext.setTrackViewModifications(true);
}
}
}
Object restoredAddList[] = (Object []) state.get(CLIENTIDS_TO_ADD_NAME);
if (restoredAddList != null && restoredAddList.length > 0) {
// Restore the list of added components
List<ComponentStruct> addList = new ArrayList<ComponentStruct>(restoredAddList.length);
for (Object aRestoredAddList : restoredAddList) {
ComponentStruct cur = new ComponentStruct();
cur.restoreState(context, aRestoredAddList);
addList.add(cur);
}
// restore the components themselves
for (ComponentStruct cur : addList) {
final ComponentStruct finalCur = cur;
// Find the parent
viewRoot.invokeOnComponent(context, finalCur.parentClientId,
new ContextCallback() {
public void invokeContextCallback(FacesContext context, UIComponent parent) {
// Create the child
StateHolderSaver saver = (StateHolderSaver) state.get(finalCur.clientId);
UIComponent toAdd = (UIComponent) saver.restore(context);
int idx = finalCur.indexOfChildInParent;
if (idx == -1) {
// add facet to the parent
parent.getFacets().put(finalCur.facetName, toAdd);
} else {
// add the child to the parent at correct index
try {
parent.getChildren().add(finalCur.indexOfChildInParent, toAdd);
} catch (IndexOutOfBoundsException ioobe) {
// the indexing within the parent list is off during the restore.
// This is most likely due to a transient component added during
// RENDER_REPONSE phase.
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"Unable to insert child with client ID {0} into parent with client ID {1} into list at index {2}.",
new Object[] { finalCur.clientId,
finalCur.parentClientId,
finalCur.indexOfChildInParent});
}
parent.getChildren().add(toAdd);
}
}
}
});
}
}
} else {
viewRoot = null;
}
context.setProcessingEvents(processingEvents);
return viewRoot;
}
// --------------------------------------------------------- Private Methods
/**
* Temporary method added for issue 1310 to perform state saving as it
* was done in 1.2 as calling VisitTree in its current incarnation may
* have unintended side effects.
*
* @param c the component to process
* @param ctx the <code>FacesContext</code> for the current request
* @param stateMap a <code>Map</code> to push saved state keyed by
* client ID
*/
private void saveComponentState(UIComponent c,
FacesContext ctx,
StateContext stateContext,
Map<String, Object> stateMap) {
if (!c.isTransient()) {
Object stateObj;
if (stateContext.componentAddedDynamically(c)) {
stateObj = new StateHolderSaver(ctx, c);
} else {
stateObj = c.saveState(ctx);
}
if (null != stateObj) {
stateMap.put(c.getClientId(ctx), stateObj);
}
for (Iterator<UIComponent> i = c.getFacetsAndChildren(); i.hasNext();) {
saveComponentState(i.next(), ctx, stateContext, stateMap);
}
}
}
}
| true | true | public UIViewRoot restoreView(FacesContext context,
String viewId,
String renderKitId) {
ResponseStateManager rsm =
RenderKitUtils.getResponseStateManager(context, renderKitId);
boolean processingEvents = context.isProcessingEvents();
// Build the tree to initial state
UIViewRoot viewRoot;
try {
ViewDeclarationLanguage vdl = vdlFactory.getViewDeclarationLanguage(viewId);
viewRoot = vdl.getViewMetadata(context, viewId).createMetadataView(context);
context.setViewRoot(viewRoot);
context.setProcessingEvents(true);
vdl.buildView(context, viewRoot);
} catch (IOException ioe) {
throw new FacesException(ioe);
}
Object[] rawState = (Object[]) rsm.getState(context, viewId);
if (rawState == null) {
return null; // trigger a ViewExpiredException
}
//noinspection unchecked
final Map<String, Object> state = (Map<String,Object>) rawState[1];
final StateContext stateContext = StateContext.getStateContext(context);
if (null != state) {
final Application app = context.getApplication();
// We need to clone the tree, otherwise we run the risk
// of being left in a state where the restored
// UIComponent instances are in the session instead
// of the TreeNode instances. This is a problem
// for servers that persist session data since
// UIComponent instances are not serializable.
VisitContext visitContext = VisitContext.createVisitContext(context);
viewRoot.visitTree(visitContext, new VisitCallback() {
public VisitResult visit(VisitContext context, UIComponent target) {
VisitResult result = VisitResult.ACCEPT;
String cid = target.getClientId(context.getFacesContext());
Object stateObj = state.get(cid);
if (stateObj != null && !stateContext.componentAddedDynamically(target)) {
try {
target.restoreState(context.getFacesContext(),
stateObj);
} catch (Exception e) {
String msg =
MessageUtils.getExceptionMessageString(
MessageUtils.PARTIAL_STATE_ERROR_RESTORING_ID,
cid,
e.toString());
throw new FacesException(msg, e);
}
app.publishEvent(context.getFacesContext(),
PostRestoreStateEvent.class,
target);
}
return result;
}
});
// Handle dynamic add/removes
//noinspection unchecked
List<String> removeList = (List<String>) state.get(CLIENTIDS_TO_REMOVE_NAME);
if (null != removeList && !removeList.isEmpty()) {
for (String cur : removeList) {
boolean trackMods = stateContext.trackViewModifications();
if (trackMods) {
stateContext.setTrackViewModifications(false);
}
viewRoot.invokeOnComponent(context, cur, new ContextCallback() {
public void invokeContextCallback(FacesContext context, UIComponent target) {
UIComponent parent = target.getParent();
if (null != parent) {
parent.getChildren().remove(target);
}
}
});
if (trackMods) {
stateContext.setTrackViewModifications(true);
}
}
}
Object restoredAddList[] = (Object []) state.get(CLIENTIDS_TO_ADD_NAME);
if (restoredAddList != null && restoredAddList.length > 0) {
// Restore the list of added components
List<ComponentStruct> addList = new ArrayList<ComponentStruct>(restoredAddList.length);
for (Object aRestoredAddList : restoredAddList) {
ComponentStruct cur = new ComponentStruct();
cur.restoreState(context, aRestoredAddList);
addList.add(cur);
}
// restore the components themselves
for (ComponentStruct cur : addList) {
final ComponentStruct finalCur = cur;
// Find the parent
viewRoot.invokeOnComponent(context, finalCur.parentClientId,
new ContextCallback() {
public void invokeContextCallback(FacesContext context, UIComponent parent) {
// Create the child
StateHolderSaver saver = (StateHolderSaver) state.get(finalCur.clientId);
UIComponent toAdd = (UIComponent) saver.restore(context);
int idx = finalCur.indexOfChildInParent;
if (idx == -1) {
// add facet to the parent
parent.getFacets().put(finalCur.facetName, toAdd);
} else {
// add the child to the parent at correct index
try {
parent.getChildren().add(finalCur.indexOfChildInParent, toAdd);
} catch (IndexOutOfBoundsException ioobe) {
// the indexing within the parent list is off during the restore.
// This is most likely due to a transient component added during
// RENDER_REPONSE phase.
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"Unable to insert child with client ID {0} into parent with client ID {1} into list at index {2}.",
new Object[] { finalCur.clientId,
finalCur.parentClientId,
finalCur.indexOfChildInParent});
}
parent.getChildren().add(toAdd);
}
}
}
});
}
}
} else {
viewRoot = null;
}
context.setProcessingEvents(processingEvents);
return viewRoot;
}
| public UIViewRoot restoreView(FacesContext context,
String viewId,
String renderKitId) {
ResponseStateManager rsm =
RenderKitUtils.getResponseStateManager(context, renderKitId);
boolean processingEvents = context.isProcessingEvents();
// Build the tree to initial state
UIViewRoot viewRoot;
try {
ViewDeclarationLanguage vdl = vdlFactory.getViewDeclarationLanguage(viewId);
viewRoot = vdl.getViewMetadata(context, viewId).createMetadataView(context);
context.setViewRoot(viewRoot);
context.setProcessingEvents(true);
vdl.buildView(context, viewRoot);
} catch (IOException ioe) {
throw new FacesException(ioe);
}
Object[] rawState = (Object[]) rsm.getState(context, viewId);
if (rawState == null) {
return null; // trigger a ViewExpiredException
}
//noinspection unchecked
final Map<String, Object> state = (Map<String,Object>) rawState[1];
final StateContext stateContext = StateContext.getStateContext(context);
if (null != state) {
final Application app = context.getApplication();
// We need to clone the tree, otherwise we run the risk
// of being left in a state where the restored
// UIComponent instances are in the session instead
// of the TreeNode instances. This is a problem
// for servers that persist session data since
// UIComponent instances are not serializable.
VisitContext visitContext = VisitContext.createVisitContext(context);
viewRoot.visitTree(visitContext, new VisitCallback() {
public VisitResult visit(VisitContext context, UIComponent target) {
VisitResult result = VisitResult.ACCEPT;
String cid = target.getClientId(context.getFacesContext());
Object stateObj = state.get(cid);
if (stateObj != null && !stateContext.componentAddedDynamically(target)) {
try {
target.restoreState(context.getFacesContext(),
stateObj);
} catch (Exception e) {
String msg =
MessageUtils.getExceptionMessageString(
MessageUtils.PARTIAL_STATE_ERROR_RESTORING_ID,
cid,
e.toString());
throw new FacesException(msg, e);
}
}
return result;
}
});
// Handle dynamic add/removes
//noinspection unchecked
List<String> removeList = (List<String>) state.get(CLIENTIDS_TO_REMOVE_NAME);
if (null != removeList && !removeList.isEmpty()) {
for (String cur : removeList) {
boolean trackMods = stateContext.trackViewModifications();
if (trackMods) {
stateContext.setTrackViewModifications(false);
}
viewRoot.invokeOnComponent(context, cur, new ContextCallback() {
public void invokeContextCallback(FacesContext context, UIComponent target) {
UIComponent parent = target.getParent();
if (null != parent) {
parent.getChildren().remove(target);
}
}
});
if (trackMods) {
stateContext.setTrackViewModifications(true);
}
}
}
Object restoredAddList[] = (Object []) state.get(CLIENTIDS_TO_ADD_NAME);
if (restoredAddList != null && restoredAddList.length > 0) {
// Restore the list of added components
List<ComponentStruct> addList = new ArrayList<ComponentStruct>(restoredAddList.length);
for (Object aRestoredAddList : restoredAddList) {
ComponentStruct cur = new ComponentStruct();
cur.restoreState(context, aRestoredAddList);
addList.add(cur);
}
// restore the components themselves
for (ComponentStruct cur : addList) {
final ComponentStruct finalCur = cur;
// Find the parent
viewRoot.invokeOnComponent(context, finalCur.parentClientId,
new ContextCallback() {
public void invokeContextCallback(FacesContext context, UIComponent parent) {
// Create the child
StateHolderSaver saver = (StateHolderSaver) state.get(finalCur.clientId);
UIComponent toAdd = (UIComponent) saver.restore(context);
int idx = finalCur.indexOfChildInParent;
if (idx == -1) {
// add facet to the parent
parent.getFacets().put(finalCur.facetName, toAdd);
} else {
// add the child to the parent at correct index
try {
parent.getChildren().add(finalCur.indexOfChildInParent, toAdd);
} catch (IndexOutOfBoundsException ioobe) {
// the indexing within the parent list is off during the restore.
// This is most likely due to a transient component added during
// RENDER_REPONSE phase.
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.log(Level.FINE,
"Unable to insert child with client ID {0} into parent with client ID {1} into list at index {2}.",
new Object[] { finalCur.clientId,
finalCur.parentClientId,
finalCur.indexOfChildInParent});
}
parent.getChildren().add(toAdd);
}
}
}
});
}
}
} else {
viewRoot = null;
}
context.setProcessingEvents(processingEvents);
return viewRoot;
}
|
diff --git a/core/src/main/java/hudson/model/Job.java b/core/src/main/java/hudson/model/Job.java
index 4f9f24989..ab511f587 100644
--- a/core/src/main/java/hudson/model/Job.java
+++ b/core/src/main/java/hudson/model/Job.java
@@ -1,1153 +1,1157 @@
package hudson.model;
import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.XmlFile;
import hudson.PermalinkList;
import hudson.model.Descriptor.FormException;
import hudson.model.listeners.ItemListener;
import hudson.model.PermalinkProjectAction.Permalink;
import hudson.search.QuickSilver;
import hudson.search.SearchIndex;
import hudson.search.SearchIndexBuilder;
import hudson.search.SearchItem;
import hudson.search.SearchItems;
import hudson.tasks.LogRotator;
import hudson.util.AtomicFileWriter;
import hudson.util.ChartUtil;
import hudson.util.ColorPalette;
import hudson.util.CopyOnWriteList;
import hudson.util.DataSetBuilder;
import hudson.util.IOException2;
import hudson.util.RunList;
import hudson.util.ShiftedCategoryAxis;
import hudson.util.StackedAreaRenderer2;
import hudson.util.TextFile;
import hudson.widgets.HistoryWidget;
import hudson.widgets.Widget;
import hudson.widgets.HistoryWidget.Adapter;
import java.awt.Color;
import java.awt.Paint;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import net.sf.json.JSONObject;
import net.sf.json.JSONException;
import org.apache.tools.ant.taskdefs.Copy;
import org.apache.tools.ant.types.FileSet;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.StackedAreaRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.WebMethod;
import org.kohsuke.stapler.export.Exported;
/**
* A job is an runnable entity under the monitoring of Hudson.
*
* <p>
* Every time it "runs", it will be recorded as a {@link Run} object.
*
* <p>
* To create a custom job type, add it to {@link Items#LIST}.
*
* @author Kohsuke Kawaguchi
*/
public abstract class Job<JobT extends Job<JobT, RunT>, RunT extends Run<JobT, RunT>>
extends AbstractItem implements ExtensionPoint {
/**
* Next build number. Kept in a separate file because this is the only
* information that gets updated often. This allows the rest of the
* configuration to be in the VCS.
* <p>
* In 1.28 and earlier, this field was stored in the project configuration
* file, so even though this is marked as transient, don't move it around.
*/
protected transient volatile int nextBuildNumber = 1;
private volatile LogRotator logRotator;
/**
* Not all plugins are good at calculating their health report quickly.
* These fields are used to cache the health reports to speed up rendering
* the main page.
*/
private transient Integer cachedBuildHealthReportsBuildNumber = null;
private transient List<HealthReport> cachedBuildHealthReports = null;
private boolean keepDependencies;
/**
* List of {@link UserProperty}s configured for this project.
*/
protected CopyOnWriteList<JobProperty<? super JobT>> properties = new CopyOnWriteList<JobProperty<? super JobT>>();
protected Job(ItemGroup parent, String name) {
super(parent, name);
}
public void onLoad(ItemGroup<? extends Item> parent, String name)
throws IOException {
super.onLoad(parent, name);
TextFile f = getNextBuildNumberFile();
if (f.exists()) {
// starting 1.28, we store nextBuildNumber in a separate file.
// but old Hudson didn't do it, so if the file doesn't exist,
// assume that nextBuildNumber was read from config.xml
try {
this.nextBuildNumber = Integer.parseInt(f.readTrim());
} catch (NumberFormatException e) {
throw new IOException2(f + " doesn't contain a number", e);
}
} else {
// this must be the old Hudson. create this file now.
saveNextBuildNumber();
save(); // and delete it from the config.xml
}
if (properties == null) // didn't exist < 1.72
properties = new CopyOnWriteList<JobProperty<? super JobT>>();
for (JobProperty p : properties)
p.setOwner(this);
}
@Override
public void onCopiedFrom(Item src) {
super.onCopiedFrom(src);
this.nextBuildNumber = 1; // reset the next build number
}
protected void performDelete() throws IOException {
// if a build is in progress. Cancel it.
RunT lb = getLastBuild();
if (lb != null) {
Executor e = lb.getExecutor();
if (e != null) {
e.interrupt();
// should we block until the build is cancelled?
}
}
super.performDelete();
}
private TextFile getNextBuildNumberFile() {
return new TextFile(new File(this.getRootDir(), "nextBuildNumber"));
}
protected void saveNextBuildNumber() throws IOException {
getNextBuildNumberFile().write(String.valueOf(nextBuildNumber) + '\n');
}
@Exported
public boolean isInQueue() {
return false;
}
/**
* If this job is in the build queue, return its item.
*/
@Exported
public Queue.Item getQueueItem() {
return null;
}
/**
* Get the term used in the UI to represent this kind of
* {@link AbstractProject}. Must start with a capital letter.
*/
public String getPronoun() {
return Messages.Job_Pronoun();
}
/**
* Returns whether the name of this job can be changed by user.
*/
public boolean isNameEditable() {
return true;
}
/**
* If true, it will keep all the build logs of dependency components.
*/
@Exported
public boolean isKeepDependencies() {
return keepDependencies;
}
/**
* Allocates a new buildCommand number.
*/
public synchronized int assignBuildNumber() throws IOException {
int r = nextBuildNumber++;
saveNextBuildNumber();
return r;
}
/**
* Peeks the next build number.
*/
@Exported
public int getNextBuildNumber() {
return nextBuildNumber;
}
/**
* Programatically updates the next build number.
*
* <p>
* Much of Hudson assumes that the build number is unique and monotonic, so
* this method can only accept a new value that's bigger than
* {@link #getNextBuildNumber()} returns. Otherwise it'll be no-op.
*
* @since 1.199 (before that, this method was package private.)
*/
public void updateNextBuildNumber(int next) throws IOException {
if (next > nextBuildNumber) {
this.nextBuildNumber = next;
saveNextBuildNumber();
}
}
/**
* Returns the log rotator for this job, or null if none.
*/
public LogRotator getLogRotator() {
return logRotator;
}
public void setLogRotator(LogRotator logRotator) {
this.logRotator = logRotator;
}
/**
* Perform log rotation.
*/
public void logRotate() throws IOException {
LogRotator lr = getLogRotator();
if (lr != null)
lr.perform(this);
}
/**
* True if this instance supports log rotation configuration.
*/
public boolean supportsLogRotator() {
return true;
}
protected SearchIndexBuilder makeSearchIndex() {
return super.makeSearchIndex().add(new SearchIndex() {
public void find(String token, List<SearchItem> result) {
try {
if (token.startsWith("#"))
token = token.substring(1); // ignore leading '#'
int n = Integer.parseInt(token);
Run b = getBuildByNumber(n);
if (b == null)
return; // no such build
result.add(SearchItems.create("#" + n, "" + n, b));
} catch (NumberFormatException e) {
// not a number.
}
}
public void suggest(String token, List<SearchItem> result) {
find(token, result);
}
}).add("configure", "config", "configure");
}
public Collection<? extends Job> getAllJobs() {
return Collections.<Job> singleton(this);
}
/**
* Adds {@link JobProperty}.
*
* @since 1.188
*/
public void addProperty(JobProperty<? super JobT> jobProp)
throws IOException {
properties.add(jobProp);
save();
}
/**
* Gets all the job properties configured for this job.
*/
@SuppressWarnings("unchecked")
public Map<JobPropertyDescriptor, JobProperty<? super JobT>> getProperties() {
return Descriptor.toMap((Iterable) properties);
}
/**
* Gets the specific property, or null if the propert is not configured for
* this job.
*/
public <T extends JobProperty> T getProperty(Class<T> clazz) {
for (JobProperty p : properties) {
if (clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
public List<Widget> getWidgets() {
ArrayList<Widget> r = new ArrayList<Widget>();
r.add(createHistoryWidget());
return r;
}
protected HistoryWidget createHistoryWidget() {
return new HistoryWidget<Job, RunT>(this, getBuilds(), HISTORY_ADAPTER);
}
protected static final HistoryWidget.Adapter<Run> HISTORY_ADAPTER = new Adapter<Run>() {
public int compare(Run record, String key) {
try {
int k = Integer.parseInt(key);
return record.getNumber() - k;
} catch (NumberFormatException nfe) {
return String.valueOf(record.getNumber()).compareTo(key);
}
}
public String getKey(Run record) {
return String.valueOf(record.getNumber());
}
public boolean isBuilding(Run record) {
return record.isBuilding();
}
public String getNextKey(String key) {
try {
int k = Integer.parseInt(key);
return String.valueOf(k + 1);
} catch (NumberFormatException nfe) {
return "-unable to determine next key-";
}
}
};
/**
* Renames a job.
*
* <p>
* This method is defined on {@link Job} but really only applicable for
* {@link Job}s that are top-level items.
*/
public void renameTo(String newName) throws IOException {
// always synchronize from bigger objects first
final Hudson parent = Hudson.getInstance();
assert this instanceof TopLevelItem;
synchronized (parent) {
synchronized (this) {
// sanity check
if (newName == null)
throw new IllegalArgumentException("New name is not given");
TopLevelItem existing = parent.getItem(newName);
if (existing != null && existing!=this)
// the look up is case insensitive, so we need "existing!=this"
// to allow people to rename "Foo" to "foo", for example.
// see http://www.nabble.com/error-on-renaming-project-tt18061629.html
throw new IllegalArgumentException("Job " + newName
+ " already exists");
// noop?
if (this.name.equals(newName))
return;
String oldName = this.name;
File oldRoot = this.getRootDir();
doSetName(newName);
File newRoot = this.getRootDir();
boolean success = false;
try {// rename data files
boolean interrupted = false;
boolean renamed = false;
// try to rename the job directory.
// this may fail on Windows due to some other processes
// accessing a file.
// so retry few times before we fall back to copy.
for (int retry = 0; retry < 5; retry++) {
if (oldRoot.renameTo(newRoot)) {
renamed = true;
break; // succeeded
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// process the interruption later
interrupted = true;
}
}
if (interrupted)
Thread.currentThread().interrupt();
if (!renamed) {
// failed to rename. it must be that some lengthy
// process is going on
// to prevent a rename operation. So do a copy. Ideally
// we'd like to
// later delete the old copy, but we can't reliably do
// so, as before the VM
// shuts down there might be a new job created under the
// old name.
Copy cp = new Copy();
cp.setProject(new org.apache.tools.ant.Project());
cp.setTodir(newRoot);
FileSet src = new FileSet();
src.setDir(getRootDir());
cp.addFileset(src);
cp.setOverwrite(true);
cp.setPreserveLastModified(true);
cp.setFailOnError(false); // keep going even if
// there's an error
cp.execute();
// try to delete as much as possible
try {
Util.deleteRecursive(oldRoot);
} catch (IOException e) {
// but ignore the error, since we expect that
e.printStackTrace();
}
}
success = true;
} finally {
// if failed, back out the rename.
if (!success)
doSetName(oldName);
}
parent.onRenamed((TopLevelItem) this, oldName, newName);
for (ItemListener l : Hudson.getInstance().getJobListeners())
l.onRenamed(this, oldName, newName);
}
}
}
/**
* Returns true if we should display "build now" icon
*/
@Exported
public abstract boolean isBuildable();
/**
* Gets all the builds.
*
* @return never null. The first entry is the latest build.
*/
@Exported(visibility=-1)
public List<RunT> getBuilds() {
return new ArrayList<RunT>(_getRuns().values());
}
/**
* Gets all the builds in a map.
*/
public SortedMap<Integer, RunT> getBuildsAsMap() {
return Collections.unmodifiableSortedMap(_getRuns());
}
/**
* @deprecated This is only used to support backward compatibility with old
* URLs.
*/
@Deprecated
public RunT getBuild(String id) {
for (RunT r : _getRuns().values()) {
if (r.getId().equals(id))
return r;
}
return null;
}
/**
* @param n
* The build number.
* @return null if no such build exists.
* @see Run#getNumber()
*/
public RunT getBuildByNumber(int n) {
return _getRuns().get(n);
}
/**
* Gets the youngest build #m that satisfies <tt>n<=m</tt>.
*
* This is useful when you'd like to fetch a build but the exact build might
* be already gone (deleted, rotated, etc.)
*/
public final RunT getNearestBuild(int n) {
SortedMap<Integer, ? extends RunT> m = _getRuns().headMap(n - 1); // the
// map
// should
// include
// n,
// so
// n-1
if (m.isEmpty())
return null;
return m.get(m.lastKey());
}
/**
* Gets the latest build #m that satisfies <tt>m<=n</tt>.
*
* This is useful when you'd like to fetch a build but the exact build might
* be already gone (deleted, rotated, etc.)
*/
public final RunT getNearestOldBuild(int n) {
SortedMap<Integer, ? extends RunT> m = _getRuns().tailMap(n);
if (m.isEmpty())
return null;
return m.get(m.firstKey());
}
public Object getDynamic(String token, StaplerRequest req,
StaplerResponse rsp) {
try {
// try to interpret the token as build number
return _getRuns().get(Integer.valueOf(token));
} catch (NumberFormatException e) {
// try to map that to widgets
for (Widget w : getWidgets()) {
if (w.getUrlName().equals(token))
return w;
}
// is this a permalink?
for (Permalink p : getPermalinks()) {
if(p.getId().equals(token))
return p.resolve(this);
}
return super.getDynamic(token, req, rsp);
}
}
/**
* Directory for storing {@link Run} records.
* <p>
* Some {@link Job}s may not have backing data store for {@link Run}s, but
* those {@link Job}s that use file system for storing data should use this
* directory for consistency.
*
* @see RunMap
*/
protected File getBuildDir() {
return new File(getRootDir(), "builds");
}
/**
* Gets all the runs.
*
* The resulting map must be immutable (by employing copy-on-write
* semantics.) The map is descending order, with newest builds at the top.
*/
protected abstract SortedMap<Integer, ? extends RunT> _getRuns();
/**
* Called from {@link Run} to remove it from this job.
*
* The files are deleted already. So all the callee needs to do is to remove
* a reference from this {@link Job}.
*/
protected abstract void removeRun(RunT run);
/**
* Returns the last build.
*/
@Exported
@QuickSilver
public RunT getLastBuild() {
SortedMap<Integer, ? extends RunT> runs = _getRuns();
if (runs.isEmpty())
return null;
return runs.get(runs.firstKey());
}
/**
* Returns the oldest build in the record.
*/
@Exported
@QuickSilver
public RunT getFirstBuild() {
SortedMap<Integer, ? extends RunT> runs = _getRuns();
if (runs.isEmpty())
return null;
return runs.get(runs.lastKey());
}
/**
* Returns the last successful build, if any. Otherwise null. A successful build
* would include either {@link Result#SUCCESS} or {@link Result#UNSTABLE}.
*
* @see #getLastStableBuild()
*/
@Exported
@QuickSilver
public RunT getLastSuccessfulBuild() {
RunT r = getLastBuild();
// temporary hack till we figure out what's causing this bug
while (r != null
&& (r.isBuilding() || r.getResult() == null || r.getResult()
.isWorseThan(Result.UNSTABLE)))
r = r.getPreviousBuild();
return r;
}
/**
* Returns the last stable build, if any. Otherwise null.
* @see #getLastSuccessfulBuild
*/
@Exported
@QuickSilver
public RunT getLastStableBuild() {
RunT r = getLastBuild();
while (r != null
&& (r.isBuilding() || r.getResult().isWorseThan(Result.SUCCESS)))
r = r.getPreviousBuild();
return r;
}
/**
* Returns the last failed build, if any. Otherwise null.
*/
@Exported
@QuickSilver
public RunT getLastFailedBuild() {
RunT r = getLastBuild();
while (r != null && (r.isBuilding() || r.getResult() != Result.FAILURE))
r = r.getPreviousBuild();
return r;
}
/**
* Returns the last completed build, if any. Otherwise null.
*/
@Exported
@QuickSilver
public RunT getLastCompletedBuild() {
RunT r = getLastBuild();
while (r != null && r.isBuilding())
r = r.getPreviousBuild();
return r;
}
/**
* Gets all the {@link Permalink}s defined for this job.
*
* @return never null
*/
public PermalinkList getPermalinks() {
// TODO: shall we cache this?
PermalinkList permalinks = new PermalinkList(Permalink.BUILTIN);
for (Action a : getActions()) {
if (a instanceof PermalinkProjectAction) {
PermalinkProjectAction ppa = (PermalinkProjectAction) a;
permalinks.addAll(ppa.getPermalinks());
}
}
return permalinks;
}
/**
* Used as the color of the status ball for the project.
*/
@Exported(visibility = 2, name = "color")
public BallColor getIconColor() {
RunT lastBuild = getLastBuild();
while (lastBuild != null && lastBuild.hasntStartedYet())
lastBuild = lastBuild.getPreviousBuild();
if (lastBuild != null)
return lastBuild.getIconColor();
else
return BallColor.GREY;
}
/**
* Get the current health report for a job.
*
* @return the health report. Never returns null
*/
public HealthReport getBuildHealth() {
List<HealthReport> reports = getBuildHealthReports();
return reports.isEmpty() ? new HealthReport() : reports.get(0);
}
@Exported(name = "healthReport")
public List<HealthReport> getBuildHealthReports() {
List<HealthReport> reports = new ArrayList<HealthReport>();
RunT lastBuild = getLastBuild();
if (lastBuild != null && lastBuild.isBuilding()) {
// show the previous build's report until the current one is
// finished building.
lastBuild = lastBuild.getPreviousBuild();
}
// check the cache
if (cachedBuildHealthReportsBuildNumber != null
&& cachedBuildHealthReports != null
&& lastBuild != null
&& cachedBuildHealthReportsBuildNumber.intValue() == lastBuild
.getNumber()) {
reports.addAll(cachedBuildHealthReports);
} else if (lastBuild != null) {
for (HealthReportingAction healthReportingAction : lastBuild
.getActions(HealthReportingAction.class)) {
final HealthReport report = healthReportingAction
.getBuildHealth();
if (report != null) {
if (report.isAggregateReport()) {
reports.addAll(report.getAggregatedReports());
} else {
reports.add(report);
}
}
}
final HealthReport report = getBuildStabilityHealthReport();
if (report != null) {
if (report.isAggregateReport()) {
reports.addAll(report.getAggregatedReports());
} else {
reports.add(report);
}
}
Collections.sort(reports);
// store the cache
cachedBuildHealthReportsBuildNumber = lastBuild.getNumber();
cachedBuildHealthReports = new ArrayList<HealthReport>(reports);
}
return reports;
}
private HealthReport getBuildStabilityHealthReport() {
// we can give a simple view of build health from the last five builds
int failCount = 0;
int totalCount = 0;
RunT i = getLastBuild();
while (totalCount < 5 && i != null) {
switch (i.getIconColor()) {
case BLUE:
case YELLOW:
// failCount stays the same
totalCount++;
break;
case RED:
failCount++;
totalCount++;
break;
default:
// do nothing as these are inconclusive statuses
break;
}
i = i.getPreviousBuild();
}
if (totalCount > 0) {
int score = (int) ((100.0 * (totalCount - failCount)) / totalCount);
if (score < 100 && score > 0) {
// HACK
// force e.g. 4/5 to be in the 60-79 range
score--;
}
String description;
if (failCount == 0) {
description = Messages.Job_NoRecentBuildFailed();
} else if (totalCount == failCount) {
// this should catch the case where totalCount == 1
// as failCount must be between 0 and totalCount
// and we can't get here if failCount == 0
description = Messages.Job_AllRecentBuildFailed();
} else {
description = Messages.Job_NOfMFailed(failCount, totalCount);
}
return new HealthReport(score, Messages._Job_BuildStability(description));
}
return null;
}
//
//
// actions
//
//
/**
* Accepts submission from the configuration page.
*/
public synchronized void doConfigSubmit(StaplerRequest req,
StaplerResponse rsp) throws IOException, ServletException {
checkPermission(CONFIGURE);
req.setCharacterEncoding("UTF-8");
description = req.getParameter("description");
keepDependencies = req.getParameter("keepDependencies") != null;
try {
properties.clear();
JSONObject json = req.getSubmittedForm();
if (req.getParameter("logrotate") != null)
logRotator = LogRotator.DESCRIPTOR.newInstance(req,json.getJSONObject("logrotate"));
else
logRotator = null;
int i = 0;
for (JobPropertyDescriptor d : JobPropertyDescriptor
.getPropertyDescriptors(Job.this.getClass())) {
String name = "jobProperty" + (i++);
JobProperty prop = d.newInstance(req, json.getJSONObject(name));
if (prop != null) {
prop.setOwner(this);
properties.add(prop);
}
}
submit(req, rsp);
save();
String newName = req.getParameter("name");
if (newName != null && !newName.equals(name)) {
// check this error early to avoid HTTP response splitting.
try {
Hudson.checkGoodName(newName);
} catch (ParseException e) {
sendError(e, req, rsp);
return;
}
rsp.sendRedirect("rename?newName=" + newName);
} else {
rsp.sendRedirect(".");
}
} catch (FormException e) {
rsp.setStatus(SC_BAD_REQUEST);
sendError(e, req, rsp);
} catch (JSONException e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw
.println("Failed to parse form data. Please report this probelm as a bug");
pw.println("JSON=" + req.getSubmittedForm());
pw.println();
e.printStackTrace(pw);
rsp.setStatus(SC_BAD_REQUEST);
sendError(sw.toString(), req, rsp);
}
}
/**
* Accepts <tt>config.xml</tt> submission, as well as serve it.
*/
@WebMethod(name = "config.xml")
public void doConfigDotXml(StaplerRequest req, StaplerResponse rsp)
throws IOException {
checkPermission(CONFIGURE);
if (req.getMethod().equals("GET")) {
// read
rsp.setContentType("application/xml;charset=UTF-8");
getConfigFile().writeRawTo(rsp.getWriter());
return;
}
if (req.getMethod().equals("POST")) {
// submission
XmlFile configXmlFile = getConfigFile();
AtomicFileWriter out = new AtomicFileWriter(configXmlFile.getFile());
try {
// this allows us to use UTF-8 for storing data,
// plus it checks any well-formedness issue in the submitted
// data
Transformer t = TransformerFactory.newInstance()
.newTransformer();
t.transform(new StreamSource(req.getReader()),
new StreamResult(out));
out.close();
} catch (TransformerException e) {
throw new IOException2("Failed to persist configuration.xml", e);
}
// try to reflect the changes by reloading
new XmlFile(Items.XSTREAM, out.getTemporaryFile()).unmarshal(this);
onLoad(getParent(), getRootDir().getName());
// if everything went well, commit this new version
out.commit();
return;
}
// huh?
rsp.sendError(SC_BAD_REQUEST);
}
/**
* Derived class can override this to perform additional config submission
* work.
*/
protected void submit(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException, FormException {
}
/**
* Returns the image that shows the current buildCommand status.
*/
public void doBuildStatus(StaplerRequest req, StaplerResponse rsp)
throws IOException {
rsp.sendRedirect2(req.getContextPath() + "/nocacheImages/48x48/"
+ getBuildStatusUrl());
}
public String getBuildStatusUrl() {
return getIconColor().getImage();
}
/**
* Returns the graph that shows how long each build took.
*/
public void doBuildTimeGraph(StaplerRequest req, StaplerResponse rsp)
throws IOException {
if (getLastBuild() == null) {
rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (req.checkIfModified(getLastBuild().getTimestamp(), rsp))
return;
ChartUtil
.generateGraph(req, rsp, createBuildTimeTrendChart(), 500, 400);
}
/**
* Returns the clickable map for the build time graph. Loaded lazily by
* AJAX.
*/
public void doBuildTimeGraphMap(StaplerRequest req, StaplerResponse rsp)
throws IOException {
if (getLastBuild() == null) {
rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (req.checkIfModified(getLastBuild().getTimestamp(), rsp))
return;
ChartUtil.generateClickableMap(req, rsp, createBuildTimeTrendChart(),
500, 400);
}
private JFreeChart createBuildTimeTrendChart() {
class ChartLabel implements Comparable<ChartLabel> {
final Run run;
public ChartLabel(Run r) {
this.run = r;
}
public int compareTo(ChartLabel that) {
return this.run.number - that.run.number;
}
public boolean equals(Object o) {
- if(!(o instanceof ChartLabel)) return false;
+ // HUDSON-2682 workaround for Eclipse compilation bug
+ // on (c instanceof ChartLabel)
+ if (o == null || !ChartLabel.class.isAssignableFrom( o.getClass() )) {
+ return false;
+ }
ChartLabel that = (ChartLabel) o;
return run == that.run;
}
public Color getColor() {
// TODO: consider gradation. See
// http://www.javadrive.jp/java2d/shape/index9.html
Result r = run.getResult();
if (r == Result.FAILURE)
return ColorPalette.RED;
else if (r == Result.UNSTABLE)
return ColorPalette.YELLOW;
else if (r == Result.ABORTED || r == Result.NOT_BUILT)
return ColorPalette.GREY;
else
return ColorPalette.BLUE;
}
public int hashCode() {
return run.hashCode();
}
public String toString() {
String l = run.getDisplayName();
if (run instanceof Build) {
String s = ((Build) run).getBuiltOnStr();
if (s != null)
l += ' ' + s;
}
return l;
}
}
DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
for (Run r : getBuilds()) {
if (r.isBuilding())
continue;
data.add(((double) r.getDuration()) / (1000 * 60), "min",
new ChartLabel(r));
}
final CategoryDataset dataset = data.build();
final JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart
// title
null, // unused
Messages.Job_minutes(), // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setForegroundAlpha(0.8f);
// plot.setDomainGridlinesVisible(true);
// plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
ChartUtil.adjustChebyshev(dataset, rangeAxis);
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
StackedAreaRenderer ar = new StackedAreaRenderer2() {
@Override
public Paint getItemPaint(int row, int column) {
ChartLabel key = (ChartLabel) dataset.getColumnKey(column);
return key.getColor();
}
@Override
public String generateURL(CategoryDataset dataset, int row,
int column) {
ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
return String.valueOf(label.run.number);
}
@Override
public String generateToolTip(CategoryDataset dataset, int row,
int column) {
ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
return label.run.getDisplayName() + " : "
+ label.run.getDurationString();
}
};
plot.setRenderer(ar);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));
return chart;
}
/**
* Renames this job.
*/
public/* not synchronized. see renameTo() */void doDoRename(
StaplerRequest req, StaplerResponse rsp) throws IOException,
ServletException {
// rename is essentially delete followed by a create
checkPermission(CREATE);
checkPermission(DELETE);
String newName = req.getParameter("newName");
try {
Hudson.checkGoodName(newName);
} catch (ParseException e) {
sendError(e, req, rsp);
return;
}
renameTo(newName);
// send to the new job page
// note we can't use getUrl() because that would pick up old name in the
// Ancestor.getUrl()
rsp.sendRedirect2(req.getContextPath() + '/' + getParent().getUrl()
+ getShortUrl());
}
public void doRssAll(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
rss(req, rsp, " all builds", new RunList(this));
}
public void doRssFailed(StaplerRequest req, StaplerResponse rsp)
throws IOException, ServletException {
rss(req, rsp, " failed builds", new RunList(this).failureOnly());
}
private void rss(StaplerRequest req, StaplerResponse rsp, String suffix,
RunList runs) throws IOException, ServletException {
RSS.forwardToRss(getDisplayName() + suffix, getUrl(), runs.newBuilds(),
Run.FEED_ADAPTER, req, rsp);
}
}
| true | true | private JFreeChart createBuildTimeTrendChart() {
class ChartLabel implements Comparable<ChartLabel> {
final Run run;
public ChartLabel(Run r) {
this.run = r;
}
public int compareTo(ChartLabel that) {
return this.run.number - that.run.number;
}
public boolean equals(Object o) {
if(!(o instanceof ChartLabel)) return false;
ChartLabel that = (ChartLabel) o;
return run == that.run;
}
public Color getColor() {
// TODO: consider gradation. See
// http://www.javadrive.jp/java2d/shape/index9.html
Result r = run.getResult();
if (r == Result.FAILURE)
return ColorPalette.RED;
else if (r == Result.UNSTABLE)
return ColorPalette.YELLOW;
else if (r == Result.ABORTED || r == Result.NOT_BUILT)
return ColorPalette.GREY;
else
return ColorPalette.BLUE;
}
public int hashCode() {
return run.hashCode();
}
public String toString() {
String l = run.getDisplayName();
if (run instanceof Build) {
String s = ((Build) run).getBuiltOnStr();
if (s != null)
l += ' ' + s;
}
return l;
}
}
DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
for (Run r : getBuilds()) {
if (r.isBuilding())
continue;
data.add(((double) r.getDuration()) / (1000 * 60), "min",
new ChartLabel(r));
}
final CategoryDataset dataset = data.build();
final JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart
// title
null, // unused
Messages.Job_minutes(), // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setForegroundAlpha(0.8f);
// plot.setDomainGridlinesVisible(true);
// plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
ChartUtil.adjustChebyshev(dataset, rangeAxis);
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
StackedAreaRenderer ar = new StackedAreaRenderer2() {
@Override
public Paint getItemPaint(int row, int column) {
ChartLabel key = (ChartLabel) dataset.getColumnKey(column);
return key.getColor();
}
@Override
public String generateURL(CategoryDataset dataset, int row,
int column) {
ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
return String.valueOf(label.run.number);
}
@Override
public String generateToolTip(CategoryDataset dataset, int row,
int column) {
ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
return label.run.getDisplayName() + " : "
+ label.run.getDurationString();
}
};
plot.setRenderer(ar);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));
return chart;
}
| private JFreeChart createBuildTimeTrendChart() {
class ChartLabel implements Comparable<ChartLabel> {
final Run run;
public ChartLabel(Run r) {
this.run = r;
}
public int compareTo(ChartLabel that) {
return this.run.number - that.run.number;
}
public boolean equals(Object o) {
// HUDSON-2682 workaround for Eclipse compilation bug
// on (c instanceof ChartLabel)
if (o == null || !ChartLabel.class.isAssignableFrom( o.getClass() )) {
return false;
}
ChartLabel that = (ChartLabel) o;
return run == that.run;
}
public Color getColor() {
// TODO: consider gradation. See
// http://www.javadrive.jp/java2d/shape/index9.html
Result r = run.getResult();
if (r == Result.FAILURE)
return ColorPalette.RED;
else if (r == Result.UNSTABLE)
return ColorPalette.YELLOW;
else if (r == Result.ABORTED || r == Result.NOT_BUILT)
return ColorPalette.GREY;
else
return ColorPalette.BLUE;
}
public int hashCode() {
return run.hashCode();
}
public String toString() {
String l = run.getDisplayName();
if (run instanceof Build) {
String s = ((Build) run).getBuiltOnStr();
if (s != null)
l += ' ' + s;
}
return l;
}
}
DataSetBuilder<String, ChartLabel> data = new DataSetBuilder<String, ChartLabel>();
for (Run r : getBuilds()) {
if (r.isBuilding())
continue;
data.add(((double) r.getDuration()) / (1000 * 60), "min",
new ChartLabel(r));
}
final CategoryDataset dataset = data.build();
final JFreeChart chart = ChartFactory.createStackedAreaChart(null, // chart
// title
null, // unused
Messages.Job_minutes(), // range axis label
dataset, // data
PlotOrientation.VERTICAL, // orientation
false, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
// plot.setAxisOffset(new Spacer(Spacer.ABSOLUTE, 5.0, 5.0, 5.0, 5.0));
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setForegroundAlpha(0.8f);
// plot.setDomainGridlinesVisible(true);
// plot.setDomainGridlinePaint(Color.white);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
CategoryAxis domainAxis = new ShiftedCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
ChartUtil.adjustChebyshev(dataset, rangeAxis);
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
StackedAreaRenderer ar = new StackedAreaRenderer2() {
@Override
public Paint getItemPaint(int row, int column) {
ChartLabel key = (ChartLabel) dataset.getColumnKey(column);
return key.getColor();
}
@Override
public String generateURL(CategoryDataset dataset, int row,
int column) {
ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
return String.valueOf(label.run.number);
}
@Override
public String generateToolTip(CategoryDataset dataset, int row,
int column) {
ChartLabel label = (ChartLabel) dataset.getColumnKey(column);
return label.run.getDisplayName() + " : "
+ label.run.getDurationString();
}
};
plot.setRenderer(ar);
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));
return chart;
}
|
diff --git a/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/debug/core/ocl/DummyFile.java b/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/debug/core/ocl/DummyFile.java
index a3ebc36c..be7cd20b 100644
--- a/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/debug/core/ocl/DummyFile.java
+++ b/plugins/org.eclipse.m2m.atl.adt.debug/src/org/eclipse/m2m/atl/adt/debug/core/ocl/DummyFile.java
@@ -1,983 +1,983 @@
/*******************************************************************************
* Copyright (c) 2006 INRIA.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Frederic Jouault (INRIA) - initial API and implementation
*******************************************************************************/
package org.eclipse.m2m.atl.adt.debug.core.ocl;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.net.URI;
import java.util.Collections;
import java.util.Map;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFileState;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResourceProxy;
import org.eclipse.core.resources.IResourceProxyVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourceAttributes;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
/**
* Dummy file class.
*
* @author <a href="mailto:[email protected]">Frederic Jouault</a>
*/
public class DummyFile implements IFile {
private String location;
/**
* Constructor.
*
* @param location
* the file location
*/
public DummyFile(String location) {
this.location = location;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#appendContents(java.io.InputStream, boolean, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void appendContents(InputStream source, boolean force, boolean keepHistory,
IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#appendContents(java.io.InputStream, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void appendContents(InputStream source, int updateFlags, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#create(java.io.InputStream, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void create(InputStream source, boolean force, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#create(java.io.InputStream, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void create(InputStream source, int updateFlags, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#createLink(org.eclipse.core.runtime.IPath, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void createLink(IPath localLocation, int updateFlags, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#delete(boolean, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void delete(boolean force, boolean keepHistory, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getCharset()
*/
public String getCharset() throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getCharset(boolean)
*/
public String getCharset(boolean checkImplicit) throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getCharsetFor(java.io.Reader)
*/
public String getCharsetFor(Reader reader) throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getContentDescription()
*/
public IContentDescription getContentDescription() throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getContents()
*/
public InputStream getContents() throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getContents(boolean)
*/
public InputStream getContents(boolean force) throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getEncoding()
*/
public int getEncoding() throws CoreException {
return 0;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getFullPath()
*/
public IPath getFullPath() {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getHistory(org.eclipse.core.runtime.IProgressMonitor)
*/
public IFileState[] getHistory(IProgressMonitor monitor) throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#getName()
*/
public String getName() {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#isReadOnly()
*/
public boolean isReadOnly() {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#move(org.eclipse.core.runtime.IPath, boolean, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void move(IPath destination, boolean force, boolean keepHistory, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#setCharset(java.lang.String)
*/
public void setCharset(String newCharset) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#setCharset(java.lang.String,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void setCharset(String newCharset, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#setContents(java.io.InputStream, boolean, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void setContents(InputStream source, boolean force, boolean keepHistory, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#setContents(org.eclipse.core.resources.IFileState, boolean,
* boolean, org.eclipse.core.runtime.IProgressMonitor)
*/
public void setContents(IFileState source, boolean force, boolean keepHistory, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#setContents(java.io.InputStream, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void setContents(InputStream source, int updateFlags, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#setContents(org.eclipse.core.resources.IFileState, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void setContents(IFileState source, int updateFlags, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#accept(org.eclipse.core.resources.IResourceProxyVisitor, int)
*/
public void accept(IResourceProxyVisitor visitor, int memberFlags) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#accept(org.eclipse.core.resources.IResourceVisitor)
*/
public void accept(IResourceVisitor visitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#accept(org.eclipse.core.resources.IResourceVisitor, int,
* boolean)
*/
public void accept(IResourceVisitor visitor, int depth, boolean includePhantoms) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#accept(org.eclipse.core.resources.IResourceVisitor, int, int)
*/
public void accept(IResourceVisitor visitor, int depth, int memberFlags) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#clearHistory(org.eclipse.core.runtime.IProgressMonitor)
*/
public void clearHistory(IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#copy(org.eclipse.core.runtime.IPath, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void copy(IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#copy(org.eclipse.core.runtime.IPath, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void copy(IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#copy(org.eclipse.core.resources.IProjectDescription, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void copy(IProjectDescription description, boolean force, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#copy(org.eclipse.core.resources.IProjectDescription, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void copy(IProjectDescription description, int updateFlags, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#createMarker(java.lang.String)
*/
public IMarker createMarker(String type) throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#delete(boolean, org.eclipse.core.runtime.IProgressMonitor)
*/
public void delete(boolean force, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#delete(int, org.eclipse.core.runtime.IProgressMonitor)
*/
public void delete(int updateFlags, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#deleteMarkers(java.lang.String, boolean, int)
*/
public void deleteMarkers(String type, boolean includeSubtypes, int depth) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#exists()
*/
public boolean exists() {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#findMarker(long)
*/
public IMarker findMarker(long id) throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#findMarkers(java.lang.String, boolean, int)
*/
public IMarker[] findMarkers(String type, boolean includeSubtypes, int depth) throws CoreException {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getFileExtension()
*/
public String getFileExtension() {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getLocalTimeStamp()
*/
public long getLocalTimeStamp() {
return 0;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getLocation()
*/
public IPath getLocation() {
return new IPath() {
public String toString() {
return location;
}
public IPath addFileExtension(String extension) {
return null;
}
public IPath addTrailingSeparator() {
return null;
}
public IPath append(String path) {
return null;
}
public IPath append(IPath path) {
return null;
}
public Object clone() {
return null;
}
public String getDevice() {
return null;
}
public String getFileExtension() {
return null;
}
public boolean hasTrailingSeparator() {
return false;
}
public boolean isAbsolute() {
return false;
}
public boolean isEmpty() {
return false;
}
public boolean isPrefixOf(IPath anotherPath) {
return false;
}
public boolean isRoot() {
return false;
}
public boolean isUNC() {
return false;
}
public boolean isValidPath(String path) {
return false;
}
public boolean isValidSegment(String segment) {
return false;
}
public String lastSegment() {
return null;
}
public IPath makeAbsolute() {
return null;
}
public IPath makeRelative() {
return null;
}
- public IPath makeRelative(IPath anotherPath) {
+ public IPath makeRelativeTo(IPath anotherPath) {
return null;
}
public IPath makeUNC(boolean toUNC) {
return null;
}
public int matchingFirstSegments(IPath anotherPath) {
return 0;
}
public IPath removeFileExtension() {
return null;
}
public IPath removeFirstSegments(int count) {
return null;
}
public IPath removeLastSegments(int count) {
return null;
}
public IPath removeTrailingSeparator() {
return null;
}
public String segment(int index) {
return null;
}
public int segmentCount() {
return 0;
}
public String[] segments() {
return null;
}
public IPath setDevice(String device) {
return null;
}
public File toFile() {
return null;
}
public String toOSString() {
return null;
}
public String toPortableString() {
return null;
}
public IPath uptoSegment(int count) {
return null;
}
};
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getMarker(long)
*/
public IMarker getMarker(long id) {
return null;
}
public long getModificationStamp() {
return 0;
}
public IContainer getParent() {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getPersistentProperty(org.eclipse.core.runtime.QualifiedName)
*/
public String getPersistentProperty(QualifiedName key) throws CoreException {
return null;
}
public IProject getProject() {
return null;
}
public IPath getProjectRelativePath() {
return null;
}
public IPath getRawLocation() {
return null;
}
public ResourceAttributes getResourceAttributes() {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getSessionProperty(org.eclipse.core.runtime.QualifiedName)
*/
public Object getSessionProperty(QualifiedName key) throws CoreException {
return null;
}
public int getType() {
return 0;
}
public IWorkspace getWorkspace() {
return null;
}
public boolean isAccessible() {
return false;
}
public boolean isDerived() {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#isLocal(int)
*/
public boolean isLocal(int depth) {
return false;
}
public boolean isLinked() {
return false;
}
public boolean isPhantom() {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#isSynchronized(int)
*/
public boolean isSynchronized(int depth) {
return false;
}
public boolean isTeamPrivateMember() {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#move(org.eclipse.core.runtime.IPath, boolean,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void move(IPath destination, boolean force, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#move(org.eclipse.core.runtime.IPath, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void move(IPath destination, int updateFlags, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#move(org.eclipse.core.resources.IProjectDescription, boolean,
* boolean, org.eclipse.core.runtime.IProgressMonitor)
*/
public void move(IProjectDescription description, boolean force, boolean keepHistory,
IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#move(org.eclipse.core.resources.IProjectDescription, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void move(IProjectDescription description, int updateFlags, IProgressMonitor monitor)
throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#refreshLocal(int, org.eclipse.core.runtime.IProgressMonitor)
*/
public void refreshLocal(int depth, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#revertModificationStamp(long)
*/
public void revertModificationStamp(long value) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setDerived(boolean)
*/
public void setDerived(boolean isDerived) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setLocal(boolean, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void setLocal(boolean flag, int depth, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setLocalTimeStamp(long)
*/
public long setLocalTimeStamp(long value) throws CoreException {
return 0;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setPersistentProperty(org.eclipse.core.runtime.QualifiedName,
* java.lang.String)
*/
public void setPersistentProperty(QualifiedName key, String value) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setReadOnly(boolean)
*/
public void setReadOnly(boolean readOnly) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setResourceAttributes(org.eclipse.core.resources.ResourceAttributes)
*/
public void setResourceAttributes(ResourceAttributes attributes) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setSessionProperty(org.eclipse.core.runtime.QualifiedName,
* java.lang.Object)
*/
public void setSessionProperty(QualifiedName key, Object value) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setTeamPrivateMember(boolean)
*/
public void setTeamPrivateMember(boolean isTeamPrivate) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#touch(org.eclipse.core.runtime.IProgressMonitor)
*/
public void touch(IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
*/
public Object getAdapter(Class adapter) {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.runtime.jobs.ISchedulingRule#contains(org.eclipse.core.runtime.jobs.ISchedulingRule)
*/
public boolean contains(ISchedulingRule rule) {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.runtime.jobs.ISchedulingRule#isConflicting(org.eclipse.core.runtime.jobs.ISchedulingRule)
*/
public boolean isConflicting(ISchedulingRule rule) {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IFile#createLink(java.net.URI, int,
* org.eclipse.core.runtime.IProgressMonitor)
*/
public void createLink(URI linkLocation, int updateFlags, IProgressMonitor monitor) throws CoreException {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#createProxy()
*/
public IResourceProxy createProxy() {
return null;
}
public URI getLocationURI() {
return null;
}
public URI getRawLocationURI() {
return null;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#isLinked(int)
*/
public boolean isLinked(int options) {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#findMaxProblemSeverity(java.lang.String, boolean, int)
*/
public int findMaxProblemSeverity(String type, boolean includeSubtypes, int depth) throws CoreException {
return 0;
}
/** eclipse 3.4M4 compatibility * */
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#isHidden()
*/
public boolean isHidden() {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#setHidden(boolean)
*/
public void setHidden(boolean val) {
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#isDerived(int)
*/
public boolean isDerived(int val) {
return false;
}
/** eclipse 3.4M6 compatibility * */
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getPersistentProperties()
*/
public Map getPersistentProperties() throws CoreException {
return Collections.EMPTY_MAP;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#getSessionProperties()
*/
public Map getSessionProperties() throws CoreException {
return Collections.EMPTY_MAP;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#isHidden(int)
*/
public boolean isHidden(int options) {
return false;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.core.resources.IResource#isTeamPrivateMember(int)
*/
public boolean isTeamPrivateMember(int options) {
return false;
}
}
| true | true | public IPath getLocation() {
return new IPath() {
public String toString() {
return location;
}
public IPath addFileExtension(String extension) {
return null;
}
public IPath addTrailingSeparator() {
return null;
}
public IPath append(String path) {
return null;
}
public IPath append(IPath path) {
return null;
}
public Object clone() {
return null;
}
public String getDevice() {
return null;
}
public String getFileExtension() {
return null;
}
public boolean hasTrailingSeparator() {
return false;
}
public boolean isAbsolute() {
return false;
}
public boolean isEmpty() {
return false;
}
public boolean isPrefixOf(IPath anotherPath) {
return false;
}
public boolean isRoot() {
return false;
}
public boolean isUNC() {
return false;
}
public boolean isValidPath(String path) {
return false;
}
public boolean isValidSegment(String segment) {
return false;
}
public String lastSegment() {
return null;
}
public IPath makeAbsolute() {
return null;
}
public IPath makeRelative() {
return null;
}
public IPath makeRelative(IPath anotherPath) {
return null;
}
public IPath makeUNC(boolean toUNC) {
return null;
}
public int matchingFirstSegments(IPath anotherPath) {
return 0;
}
public IPath removeFileExtension() {
return null;
}
public IPath removeFirstSegments(int count) {
return null;
}
public IPath removeLastSegments(int count) {
return null;
}
public IPath removeTrailingSeparator() {
return null;
}
public String segment(int index) {
return null;
}
public int segmentCount() {
return 0;
}
public String[] segments() {
return null;
}
public IPath setDevice(String device) {
return null;
}
public File toFile() {
return null;
}
public String toOSString() {
return null;
}
public String toPortableString() {
return null;
}
public IPath uptoSegment(int count) {
return null;
}
};
}
| public IPath getLocation() {
return new IPath() {
public String toString() {
return location;
}
public IPath addFileExtension(String extension) {
return null;
}
public IPath addTrailingSeparator() {
return null;
}
public IPath append(String path) {
return null;
}
public IPath append(IPath path) {
return null;
}
public Object clone() {
return null;
}
public String getDevice() {
return null;
}
public String getFileExtension() {
return null;
}
public boolean hasTrailingSeparator() {
return false;
}
public boolean isAbsolute() {
return false;
}
public boolean isEmpty() {
return false;
}
public boolean isPrefixOf(IPath anotherPath) {
return false;
}
public boolean isRoot() {
return false;
}
public boolean isUNC() {
return false;
}
public boolean isValidPath(String path) {
return false;
}
public boolean isValidSegment(String segment) {
return false;
}
public String lastSegment() {
return null;
}
public IPath makeAbsolute() {
return null;
}
public IPath makeRelative() {
return null;
}
public IPath makeRelativeTo(IPath anotherPath) {
return null;
}
public IPath makeUNC(boolean toUNC) {
return null;
}
public int matchingFirstSegments(IPath anotherPath) {
return 0;
}
public IPath removeFileExtension() {
return null;
}
public IPath removeFirstSegments(int count) {
return null;
}
public IPath removeLastSegments(int count) {
return null;
}
public IPath removeTrailingSeparator() {
return null;
}
public String segment(int index) {
return null;
}
public int segmentCount() {
return 0;
}
public String[] segments() {
return null;
}
public IPath setDevice(String device) {
return null;
}
public File toFile() {
return null;
}
public String toOSString() {
return null;
}
public String toPortableString() {
return null;
}
public IPath uptoSegment(int count) {
return null;
}
};
}
|
diff --git a/src/Model/Skills/Warrior/SkillThrowingAxe.java b/src/Model/Skills/Warrior/SkillThrowingAxe.java
index 065d4b3..561517a 100644
--- a/src/Model/Skills/Warrior/SkillThrowingAxe.java
+++ b/src/Model/Skills/Warrior/SkillThrowingAxe.java
@@ -1,60 +1,52 @@
package Model.Skills.Warrior;
import org.newdawn.slick.Image;
import org.newdawn.slick.SlickException;
import Model.Skills.Skill;
public class SkillThrowingAxe extends Skill {
public SkillThrowingAxe(){
//String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE
super("Throwing axe", 3000, 800, 0.4, 6, 10, 450, 300, 300, 300,"Throwing axe \n" +
"Level 1: 15 damage\n" +
"Level 2: 25 damage\n" +
"Level 3: 35 damage\n" +
"Level 4: 45 damage", false);
- Image[] attackImage = new Image[7];
+ Image attackImage = null;
Image[] animation = new Image[18];
Image[] skillBar = new Image[3];
try {
- attackImage[0] = new Image("res/animations/explode1.png");
- attackImage[1] = new Image("res/animations/explode2.png");
- attackImage[2] = new Image("res/animations/explode3.png");
- attackImage[3] = new Image("res/animations/explode4.png");
- attackImage[4] = new Image("res/animations/explode5.png");
- attackImage[5] = new Image("res/animations/explode6.png");
- attackImage[6] = new Image("res/animations/explode7.png");
animation[0] = new Image("res/animations/throwingAxe/axe1.png");
animation[1] = new Image("res/animations/throwingAxe/axe2.png");
animation[2] = new Image("res/animations/throwingAxe/axe3.png");
animation[3] = new Image("res/animations/throwingAxe/axe4.png");
animation[4] = new Image("res/animations/throwingAxe/axe5.png");
animation[5] = new Image("res/animations/throwingAxe/axe6.png");
animation[6] = new Image("res/animations/throwingAxe/axe7.png");
animation[7] = new Image("res/animations/throwingAxe/axe8.png");
animation[8] = new Image("res/animations/throwingAxe/axe9.png");
animation[9] = new Image("res/animations/throwingAxe/axe10.png");
animation[10] = new Image("res/animations/throwingAxe/axe11.png");
animation[11] = new Image("res/animations/throwingAxe/axe12.png");
animation[12] = new Image("res/animations/throwingAxe/axe13.png");
animation[13] = new Image("res/animations/throwingAxe/axe14.png");
animation[14] = new Image("res/animations/throwingAxe/axe15.png");
animation[15] = new Image("res/animations/throwingAxe/axe16.png");
animation[16] = new Image("res/animations/throwingAxe/axe17.png");
animation[17] = new Image("res/animations/throwingAxe/axe18.png");
skillBar[0] = new Image("res/skillIcons/throwingaxe.png");
skillBar[1] = new Image("res/skillIcons/throwingaxe_active.png");
skillBar[2] = new Image("res/skillIcons/throwingaxe_disabled.png");
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.setImage(animation, 200);
- super.setEndState(attackImage, 200, 400);
super.setSkillBarImages(skillBar);
}
}
| false | true | public SkillThrowingAxe(){
//String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE
super("Throwing axe", 3000, 800, 0.4, 6, 10, 450, 300, 300, 300,"Throwing axe \n" +
"Level 1: 15 damage\n" +
"Level 2: 25 damage\n" +
"Level 3: 35 damage\n" +
"Level 4: 45 damage", false);
Image[] attackImage = new Image[7];
Image[] animation = new Image[18];
Image[] skillBar = new Image[3];
try {
attackImage[0] = new Image("res/animations/explode1.png");
attackImage[1] = new Image("res/animations/explode2.png");
attackImage[2] = new Image("res/animations/explode3.png");
attackImage[3] = new Image("res/animations/explode4.png");
attackImage[4] = new Image("res/animations/explode5.png");
attackImage[5] = new Image("res/animations/explode6.png");
attackImage[6] = new Image("res/animations/explode7.png");
animation[0] = new Image("res/animations/throwingAxe/axe1.png");
animation[1] = new Image("res/animations/throwingAxe/axe2.png");
animation[2] = new Image("res/animations/throwingAxe/axe3.png");
animation[3] = new Image("res/animations/throwingAxe/axe4.png");
animation[4] = new Image("res/animations/throwingAxe/axe5.png");
animation[5] = new Image("res/animations/throwingAxe/axe6.png");
animation[6] = new Image("res/animations/throwingAxe/axe7.png");
animation[7] = new Image("res/animations/throwingAxe/axe8.png");
animation[8] = new Image("res/animations/throwingAxe/axe9.png");
animation[9] = new Image("res/animations/throwingAxe/axe10.png");
animation[10] = new Image("res/animations/throwingAxe/axe11.png");
animation[11] = new Image("res/animations/throwingAxe/axe12.png");
animation[12] = new Image("res/animations/throwingAxe/axe13.png");
animation[13] = new Image("res/animations/throwingAxe/axe14.png");
animation[14] = new Image("res/animations/throwingAxe/axe15.png");
animation[15] = new Image("res/animations/throwingAxe/axe16.png");
animation[16] = new Image("res/animations/throwingAxe/axe17.png");
animation[17] = new Image("res/animations/throwingAxe/axe18.png");
skillBar[0] = new Image("res/skillIcons/throwingaxe.png");
skillBar[1] = new Image("res/skillIcons/throwingaxe_active.png");
skillBar[2] = new Image("res/skillIcons/throwingaxe_disabled.png");
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.setImage(animation, 200);
super.setEndState(attackImage, 200, 400);
super.setSkillBarImages(skillBar);
}
| public SkillThrowingAxe(){
//String name, int cd, int range, double speed, int aoe, int cost, int damage, StatusEffect SE
super("Throwing axe", 3000, 800, 0.4, 6, 10, 450, 300, 300, 300,"Throwing axe \n" +
"Level 1: 15 damage\n" +
"Level 2: 25 damage\n" +
"Level 3: 35 damage\n" +
"Level 4: 45 damage", false);
Image attackImage = null;
Image[] animation = new Image[18];
Image[] skillBar = new Image[3];
try {
animation[0] = new Image("res/animations/throwingAxe/axe1.png");
animation[1] = new Image("res/animations/throwingAxe/axe2.png");
animation[2] = new Image("res/animations/throwingAxe/axe3.png");
animation[3] = new Image("res/animations/throwingAxe/axe4.png");
animation[4] = new Image("res/animations/throwingAxe/axe5.png");
animation[5] = new Image("res/animations/throwingAxe/axe6.png");
animation[6] = new Image("res/animations/throwingAxe/axe7.png");
animation[7] = new Image("res/animations/throwingAxe/axe8.png");
animation[8] = new Image("res/animations/throwingAxe/axe9.png");
animation[9] = new Image("res/animations/throwingAxe/axe10.png");
animation[10] = new Image("res/animations/throwingAxe/axe11.png");
animation[11] = new Image("res/animations/throwingAxe/axe12.png");
animation[12] = new Image("res/animations/throwingAxe/axe13.png");
animation[13] = new Image("res/animations/throwingAxe/axe14.png");
animation[14] = new Image("res/animations/throwingAxe/axe15.png");
animation[15] = new Image("res/animations/throwingAxe/axe16.png");
animation[16] = new Image("res/animations/throwingAxe/axe17.png");
animation[17] = new Image("res/animations/throwingAxe/axe18.png");
skillBar[0] = new Image("res/skillIcons/throwingaxe.png");
skillBar[1] = new Image("res/skillIcons/throwingaxe_active.png");
skillBar[2] = new Image("res/skillIcons/throwingaxe_disabled.png");
} catch (SlickException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.setImage(animation, 200);
super.setSkillBarImages(skillBar);
}
|
diff --git a/broadcast-transcoder/src/test/java/dk/statsbiblioteket/broadcasttranscoder/processors/FileMetadataFetcherProcessorTest.java b/broadcast-transcoder/src/test/java/dk/statsbiblioteket/broadcasttranscoder/processors/FileMetadataFetcherProcessorTest.java
index 65f20ba..f20da67 100644
--- a/broadcast-transcoder/src/test/java/dk/statsbiblioteket/broadcasttranscoder/processors/FileMetadataFetcherProcessorTest.java
+++ b/broadcast-transcoder/src/test/java/dk/statsbiblioteket/broadcasttranscoder/processors/FileMetadataFetcherProcessorTest.java
@@ -1,41 +1,41 @@
package dk.statsbiblioteket.broadcasttranscoder.processors;
import dk.statsbiblioteket.broadcasttranscoder.cli.SingleTranscodingContext;
import junit.framework.TestCase;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Created with IntelliJ IDEA.
* User: csr
* Date: 11/22/12
* Time: 12:39 PM
* To change this template use File | Settings | File Templates.
*/
public class FileMetadataFetcherProcessorTest {
@Before
public void setUp() {
try {
InetAddress.getByName("carme");
} catch (UnknownHostException e) {
Assume.assumeNoException(e);
}
}
@Test
public void testProcessIteratively() throws Exception {
FileMetadataFetcherProcessor processor = new FileMetadataFetcherProcessor();
TranscodeRequest request = new TranscodeRequest();
SingleTranscodingContext context = new SingleTranscodingContext();
- request.setObjectPid("uuid:d82107be-20cf-4524-b611-07d8534b97f8");
+ request.setObjectPid("uuid:3a1bdfce-497f-4bff-8804-22ac000cca83");
context.setDomsEndpoint("http://carme:7880/centralWebservice-service/central/");
context.setDomsUsername("fedoraAdmin");
context.setDomsPassword("spD68ZJl");
processor.processIteratively(request,context);
}
}
| true | true | public void testProcessIteratively() throws Exception {
FileMetadataFetcherProcessor processor = new FileMetadataFetcherProcessor();
TranscodeRequest request = new TranscodeRequest();
SingleTranscodingContext context = new SingleTranscodingContext();
request.setObjectPid("uuid:d82107be-20cf-4524-b611-07d8534b97f8");
context.setDomsEndpoint("http://carme:7880/centralWebservice-service/central/");
context.setDomsUsername("fedoraAdmin");
context.setDomsPassword("spD68ZJl");
processor.processIteratively(request,context);
}
| public void testProcessIteratively() throws Exception {
FileMetadataFetcherProcessor processor = new FileMetadataFetcherProcessor();
TranscodeRequest request = new TranscodeRequest();
SingleTranscodingContext context = new SingleTranscodingContext();
request.setObjectPid("uuid:3a1bdfce-497f-4bff-8804-22ac000cca83");
context.setDomsEndpoint("http://carme:7880/centralWebservice-service/central/");
context.setDomsUsername("fedoraAdmin");
context.setDomsPassword("spD68ZJl");
processor.processIteratively(request,context);
}
|
diff --git a/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetCalendarByIdTestCases.java b/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetCalendarByIdTestCases.java
index a64a3721..723b15d9 100644
--- a/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetCalendarByIdTestCases.java
+++ b/calendar-connector/src/test/java/org/mule/module/google/calendar/automation/testcases/GetCalendarByIdTestCases.java
@@ -1,70 +1,70 @@
package org.mule.module.google.calendar.automation.testcases;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.mule.api.MuleEvent;
import org.mule.api.processor.MessageProcessor;
import org.mule.module.google.calendar.model.Calendar;
public class GetCalendarByIdTestCases extends GoogleCalendarTestParent {
@SuppressWarnings("unchecked")
@Before
public void setUp() {
try {
testObjects = (Map<String, Object>) context.getBean("getCalendarById");
// Create the calendar
MessageProcessor flow = lookupFlowConstruct("create-calendar");
MuleEvent response = flow.process(getTestEvent(testObjects));
Calendar calendar = (Calendar) response.getMessage().getPayload();
testObjects.put("id", calendar.getId());
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
@Category({SmokeTests.class, SanityTests.class})
@Test
public void testGetCalendarById() {
try {
- Calendar createdCalendar = (Calendar) testObjects.get("calendarRef");
+ String createdCalendarId = testObjects.get("id").toString();
MessageProcessor flow = lookupFlowConstruct("get-calendar-by-id");
MuleEvent response = flow.process(getTestEvent(testObjects));
// Assertions on equality
Calendar returnedCalendar = (Calendar) response.getMessage().getPayload();
assertTrue(returnedCalendar != null);
- assertTrue(returnedCalendar.getId().equals(createdCalendar.getId()));
+ assertTrue(returnedCalendar.getId().equals(createdCalendarId));
}
catch (Exception ex) {
ex.printStackTrace();
fail();
}
}
@After
public void tearDown() {
try {
// Delete the calendar
MessageProcessor flow = lookupFlowConstruct("delete-calendar");
MuleEvent response = flow.process(getTestEvent(testObjects));
}
catch (Exception e) {
e.printStackTrace();
fail();
}
}
}
| false | true | public void testGetCalendarById() {
try {
Calendar createdCalendar = (Calendar) testObjects.get("calendarRef");
MessageProcessor flow = lookupFlowConstruct("get-calendar-by-id");
MuleEvent response = flow.process(getTestEvent(testObjects));
// Assertions on equality
Calendar returnedCalendar = (Calendar) response.getMessage().getPayload();
assertTrue(returnedCalendar != null);
assertTrue(returnedCalendar.getId().equals(createdCalendar.getId()));
}
catch (Exception ex) {
ex.printStackTrace();
fail();
}
}
| public void testGetCalendarById() {
try {
String createdCalendarId = testObjects.get("id").toString();
MessageProcessor flow = lookupFlowConstruct("get-calendar-by-id");
MuleEvent response = flow.process(getTestEvent(testObjects));
// Assertions on equality
Calendar returnedCalendar = (Calendar) response.getMessage().getPayload();
assertTrue(returnedCalendar != null);
assertTrue(returnedCalendar.getId().equals(createdCalendarId));
}
catch (Exception ex) {
ex.printStackTrace();
fail();
}
}
|
diff --git a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateCategoryPaneControllerImpl.java b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateCategoryPaneControllerImpl.java
index f6267f57..f6f8887a 100644
--- a/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateCategoryPaneControllerImpl.java
+++ b/OpERP/src/main/java/devopsdistilled/operp/client/items/panes/controllers/impl/CreateCategoryPaneControllerImpl.java
@@ -1,49 +1,49 @@
package devopsdistilled.operp.client.items.panes.controllers.impl;
import javax.inject.Inject;
import devopsdistilled.operp.client.items.exceptions.EntityNameExistsException;
import devopsdistilled.operp.client.items.exceptions.NullFieldException;
import devopsdistilled.operp.client.items.models.CategoryModel;
import devopsdistilled.operp.client.items.panes.CreateCategoryPane;
import devopsdistilled.operp.client.items.panes.controllers.CreateCategoryPaneController;
import devopsdistilled.operp.client.items.panes.models.CreateCategoryPaneModel;
import devopsdistilled.operp.server.data.entity.items.Category;
public class CreateCategoryPaneControllerImpl implements
CreateCategoryPaneController {
@Inject
private CreateCategoryPane view;
@Inject
private CreateCategoryPaneModel model;
@Inject
private CategoryModel categoryModel;
@Override
public void init() {
view.init();
model.registerObserver(view);
}
@Override
public void validate(Category category) throws NullFieldException,
EntityNameExistsException {
if (category.getCategoryName().equalsIgnoreCase("")) {
- throw new NullFieldException();
+ throw new NullFieldException("Category Name can't be empty");
}
if (categoryModel.getService().isCategoryNameExists(
category.getCategoryName())) {
- throw new EntityNameExistsException();
+ throw new EntityNameExistsException("Category Name already exists");
}
}
@Override
public Category save(Category category) {
return categoryModel.saveAndUpdateModel(category);
}
}
| false | true | public void validate(Category category) throws NullFieldException,
EntityNameExistsException {
if (category.getCategoryName().equalsIgnoreCase("")) {
throw new NullFieldException();
}
if (categoryModel.getService().isCategoryNameExists(
category.getCategoryName())) {
throw new EntityNameExistsException();
}
}
| public void validate(Category category) throws NullFieldException,
EntityNameExistsException {
if (category.getCategoryName().equalsIgnoreCase("")) {
throw new NullFieldException("Category Name can't be empty");
}
if (categoryModel.getService().isCategoryNameExists(
category.getCategoryName())) {
throw new EntityNameExistsException("Category Name already exists");
}
}
|
diff --git a/tconstruct/blocks/logic/CraftingStationLogic.java b/tconstruct/blocks/logic/CraftingStationLogic.java
index 673db1438..194edac40 100644
--- a/tconstruct/blocks/logic/CraftingStationLogic.java
+++ b/tconstruct/blocks/logic/CraftingStationLogic.java
@@ -1,34 +1,34 @@
package tconstruct.blocks.logic;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.world.World;
import tconstruct.inventory.CraftingStationContainer;
import tconstruct.library.blocks.InventoryLogic;
public class CraftingStationLogic extends InventoryLogic
{
public CraftingStationLogic()
{
super(11); //9 for crafting, 1 for output, 1 for plans
}
@Override
public Container getGuiContainer (InventoryPlayer inventoryplayer, World world, int x, int y, int z)
{
return new CraftingStationContainer(inventoryplayer, this, x, y, z);
}
@Override
protected String getDefaultName ()
{
return "crafters.craftingstation";
}
public boolean canDropInventorySlot (int slot)
{
- if (slot == 9 || slot == 0)
+ if (slot == 0)
return false;
return true;
}
}
| true | true | public boolean canDropInventorySlot (int slot)
{
if (slot == 9 || slot == 0)
return false;
return true;
}
| public boolean canDropInventorySlot (int slot)
{
if (slot == 0)
return false;
return true;
}
|
diff --git a/src/com/pomometer/PomometerApp/PomometerFinishActivity.java b/src/com/pomometer/PomometerApp/PomometerFinishActivity.java
index fe733d3..003f5ee 100644
--- a/src/com/pomometer/PomometerApp/PomometerFinishActivity.java
+++ b/src/com/pomometer/PomometerApp/PomometerFinishActivity.java
@@ -1,58 +1,58 @@
package com.pomometer.PomometerApp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.widget.Toast;
public class PomometerFinishActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomometer_finish);
Bundle extras = getIntent().getExtras();
final String sent_goal = extras.getString("goal");
String notes = "";
final Long sent_duration = extras.getLong("elapsed_duration"); //in ms
double decimal_duration = sent_duration/1000; //converts to seconds
decimal_duration /= 60; //converts to minutes
final int calculated_duration = (int)Math.ceil(decimal_duration); //round up to nearest minute
final String started_at = extras.getString("started_at");
final String ended_at = extras.getString("ended_at");
final int task_id = extras.getInt("task_id");
//set title to Complete: goal. No strings.xml entry as this is dynamic
((TextView) findViewById(R.id.finish_title)).setText("Complete: " + sent_goal);
- Button confirm_button = (Button) findViewById(R.id.confirm_button);
- confirm_button.setOnClickListener(new OnClickListener() {
+ Button confirm_button = (Button) findViewById(R.id.final_submit_button);
+ confirm_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//json to commit to webserver
/*
* sent_goal
* (EditText) findViewById(R.id.notes_edit_text)
* calculated_duation
* started_at
* ended_at
* task_id
*/
Toast.makeText(getBaseContext(), ((Integer)calculated_duration).toString(), Toast.LENGTH_SHORT).show();
//Intent i = new Intent(getApplicationContext(), PomometerTimerActivity.class);
//i.putExtra("task_id", task_id);
//startActivity(i);
}
});
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomometer_finish);
Bundle extras = getIntent().getExtras();
final String sent_goal = extras.getString("goal");
String notes = "";
final Long sent_duration = extras.getLong("elapsed_duration"); //in ms
double decimal_duration = sent_duration/1000; //converts to seconds
decimal_duration /= 60; //converts to minutes
final int calculated_duration = (int)Math.ceil(decimal_duration); //round up to nearest minute
final String started_at = extras.getString("started_at");
final String ended_at = extras.getString("ended_at");
final int task_id = extras.getInt("task_id");
//set title to Complete: goal. No strings.xml entry as this is dynamic
((TextView) findViewById(R.id.finish_title)).setText("Complete: " + sent_goal);
Button confirm_button = (Button) findViewById(R.id.confirm_button);
confirm_button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
//json to commit to webserver
/*
* sent_goal
* (EditText) findViewById(R.id.notes_edit_text)
* calculated_duation
* started_at
* ended_at
* task_id
*/
Toast.makeText(getBaseContext(), ((Integer)calculated_duration).toString(), Toast.LENGTH_SHORT).show();
//Intent i = new Intent(getApplicationContext(), PomometerTimerActivity.class);
//i.putExtra("task_id", task_id);
//startActivity(i);
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pomometer_finish);
Bundle extras = getIntent().getExtras();
final String sent_goal = extras.getString("goal");
String notes = "";
final Long sent_duration = extras.getLong("elapsed_duration"); //in ms
double decimal_duration = sent_duration/1000; //converts to seconds
decimal_duration /= 60; //converts to minutes
final int calculated_duration = (int)Math.ceil(decimal_duration); //round up to nearest minute
final String started_at = extras.getString("started_at");
final String ended_at = extras.getString("ended_at");
final int task_id = extras.getInt("task_id");
//set title to Complete: goal. No strings.xml entry as this is dynamic
((TextView) findViewById(R.id.finish_title)).setText("Complete: " + sent_goal);
Button confirm_button = (Button) findViewById(R.id.final_submit_button);
confirm_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
//json to commit to webserver
/*
* sent_goal
* (EditText) findViewById(R.id.notes_edit_text)
* calculated_duation
* started_at
* ended_at
* task_id
*/
Toast.makeText(getBaseContext(), ((Integer)calculated_duration).toString(), Toast.LENGTH_SHORT).show();
//Intent i = new Intent(getApplicationContext(), PomometerTimerActivity.class);
//i.putExtra("task_id", task_id);
//startActivity(i);
}
});
}
|
diff --git a/target_explorer/plugins/org.eclipse.tm.te.tcf.core/src/org/eclipse/tm/te/tcf/core/internal/Startup.java b/target_explorer/plugins/org.eclipse.tm.te.tcf.core/src/org/eclipse/tm/te/tcf/core/internal/Startup.java
index 5c3c363a4..4a0e4c0d6 100644
--- a/target_explorer/plugins/org.eclipse.tm.te.tcf.core/src/org/eclipse/tm/te/tcf/core/internal/Startup.java
+++ b/target_explorer/plugins/org.eclipse.tm.te.tcf.core/src/org/eclipse/tm/te/tcf/core/internal/Startup.java
@@ -1,82 +1,82 @@
/*******************************************************************************
* Copyright (c) 2011 Wind River Systems, Inc. and others. All rights reserved.
* This program and the accompanying materials are made available under the terms
* of the Eclipse Public License v1.0 which accompanies this distribution, and is
* available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Uwe Stieber (Wind River) - initial API and implementation
*******************************************************************************/
package org.eclipse.tm.te.tcf.core.internal;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.tm.tcf.protocol.Protocol;
import org.eclipse.tm.te.tcf.core.Tcf;
import org.eclipse.tm.te.tcf.core.activator.CoreBundleActivator;
/**
* Class loaded by the TCF core framework when the framework is fired up. The static
* constructor of the class will trigger whatever is necessary in this case.
* <p>
* <b>Note:</b> This will effectively trigger {@link CoreBundleActivator#start(org.osgi.framework.BundleContext)}
* to be called.
*/
public class Startup {
// Atomic boolean to store the started state of the TCF core framework
/* default */ final static AtomicBoolean STARTED = new AtomicBoolean(false);
static {
// We might get here on shutdown as well, and if TCF has not
// been loaded, than we will run into an NPE. Lets double check.
if (Protocol.getEventQueue() != null) {
// Initialize the framework status by scheduling a simple
// runnable to execute and be invoked once the framework
// is fully up and usable.
Protocol.invokeLater(new Runnable() {
public void run() {
// Core framework is scheduling the runnables, means it is started.
setStarted(true);
}
});
}
}
/**
* Set the core framework started state to the given state.
*
* @param started <code>True</code> when the framework is started, <code>false</code> otherwise.
*/
public static final void setStarted(boolean started) {
STARTED.set(started);
// Start/Stop should be called in the TCF protocol dispatch thread
if (Protocol.getEventQueue() != null) {
- Protocol.invokeLater(new Runnable() {
- public void run() {
- // Catch IllegalStateException: TCF event dispatcher has shut down
- try {
+ // Catch IllegalStateException: TCF event dispatcher has shut down
+ try {
+ Protocol.invokeLater(new Runnable() {
+ public void run() {
if (STARTED.get()) Tcf.start(); else Tcf.stop();
- } catch (IllegalStateException e) {
- if (!STARTED.get() && "TCF event dispatcher has shut down".equals(e.getLocalizedMessage())) { //$NON-NLS-1$
- // ignore the exception on shutdown
- } else {
- // re-throw in any other case
- throw e;
- }
}
+ });
+ } catch (IllegalStateException e) {
+ if (!STARTED.get() && "TCF event dispatcher has shut down".equals(e.getLocalizedMessage())) { //$NON-NLS-1$
+ // ignore the exception on shutdown
+ } else {
+ // re-throw in any other case
+ throw e;
}
- });
+ }
}
}
/**
* Returns if or if not the core framework has been started.
*
* @return <code>True</code> when the framework is started, <code>false</code> otherwise.
*/
public static final boolean isStarted() {
return STARTED.get();
}
}
| false | true | public static final void setStarted(boolean started) {
STARTED.set(started);
// Start/Stop should be called in the TCF protocol dispatch thread
if (Protocol.getEventQueue() != null) {
Protocol.invokeLater(new Runnable() {
public void run() {
// Catch IllegalStateException: TCF event dispatcher has shut down
try {
if (STARTED.get()) Tcf.start(); else Tcf.stop();
} catch (IllegalStateException e) {
if (!STARTED.get() && "TCF event dispatcher has shut down".equals(e.getLocalizedMessage())) { //$NON-NLS-1$
// ignore the exception on shutdown
} else {
// re-throw in any other case
throw e;
}
}
}
});
}
}
| public static final void setStarted(boolean started) {
STARTED.set(started);
// Start/Stop should be called in the TCF protocol dispatch thread
if (Protocol.getEventQueue() != null) {
// Catch IllegalStateException: TCF event dispatcher has shut down
try {
Protocol.invokeLater(new Runnable() {
public void run() {
if (STARTED.get()) Tcf.start(); else Tcf.stop();
}
});
} catch (IllegalStateException e) {
if (!STARTED.get() && "TCF event dispatcher has shut down".equals(e.getLocalizedMessage())) { //$NON-NLS-1$
// ignore the exception on shutdown
} else {
// re-throw in any other case
throw e;
}
}
}
}
|
diff --git a/SimSeqNBProject/src/simseq/SamWriter.java b/SimSeqNBProject/src/simseq/SamWriter.java
index fcd5a38..bbb2e4e 100644
--- a/SimSeqNBProject/src/simseq/SamWriter.java
+++ b/SimSeqNBProject/src/simseq/SamWriter.java
@@ -1,82 +1,86 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package simseq;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
public class SamWriter {
private final File file;
private final PrintWriter writer;
private final boolean informative_id;
public SamWriter(final File file, boolean inf_id) throws IOException {
this.file = file;
this.informative_id = inf_id;
this.writer = new PrintWriter(new BufferedWriter(new FileWriter(file, false)));
// this.writer = new PrintWriter(IoUtil.openFileForBufferedWriting(file));
}
public void write(final SamRecord rec) throws IOException {
//<QNAME> <FLAG> <RNAME> <POS> <MAPQ> <CIGAR> <MRNM> <MPOS> <ISIZE> <SEQ> <QUAL> \
//[<TAG>:<VTYPE>:<VALUE> [...]]
//print the informative id if desired
if(this.informative_id){
writer.print(rec.refname);
writer.print("_");
long start = Math.min(rec.pos, rec.mpos);
writer.print(start);
writer.print("_");
- writer.print(start+Math.abs(rec.isize));
+ //one based typically starts at 1 base and ends at 0 base
+ // for example a sequence of length 1 starting at 0 based position 0
+ // would have the location 1 to 1 while most CS apps typically
+ // would write the same thing as 0-1.
+ writer.print(start+Math.abs(rec.isize)-1);
if(rec.first && rec.query_reverse_strand || rec.second && rec.mate_reverse_strand){
writer.print("_R_");
}else{// from forward strand
writer.print("_F_");
}
}else{
writer.print(rec.seqHeaderPrefix);//print prefix
}
writer.print(Long.toHexString(rec.seqIndex)); //qname
writer.print("\t");
writer.print(Integer.toString(rec.getFlag()));//flag
writer.print("\t");
writer.print(rec.refname);
writer.print("\t");
writer.print(Integer.toString(rec.pos));//pos
writer.print("\t");
writer.print("255"); //mapq=255 means no map quality information
writer.print("\t");
writer.print(rec.cigar); //cigar
writer.print("\t");
writer.print("="); //name of mate's reference(MRNM) = for same
writer.print("\t");
writer.print(Integer.toString(rec.mpos));//mpos
writer.print("\t");
writer.print(Integer.toString(rec.isize));//isize
writer.print("\t");
writer.print(rec.seqLine.toString());//seq
writer.print("\t");
writer.print(rec.qualLine.toString());
writer.print("\t");
if(rec.chimeric) writer.print("YC:Z:"+rec.c_cigar);
else writer.print("YC:Z:"+rec.cigar);
writer.print("\n");
if (writer.checkError()) {
throw new IOException("Error in writing file "+file);
}
}
public void close() {
writer.close();
}
}
| true | true | public void write(final SamRecord rec) throws IOException {
//<QNAME> <FLAG> <RNAME> <POS> <MAPQ> <CIGAR> <MRNM> <MPOS> <ISIZE> <SEQ> <QUAL> \
//[<TAG>:<VTYPE>:<VALUE> [...]]
//print the informative id if desired
if(this.informative_id){
writer.print(rec.refname);
writer.print("_");
long start = Math.min(rec.pos, rec.mpos);
writer.print(start);
writer.print("_");
writer.print(start+Math.abs(rec.isize));
if(rec.first && rec.query_reverse_strand || rec.second && rec.mate_reverse_strand){
writer.print("_R_");
}else{// from forward strand
writer.print("_F_");
}
}else{
writer.print(rec.seqHeaderPrefix);//print prefix
}
writer.print(Long.toHexString(rec.seqIndex)); //qname
writer.print("\t");
writer.print(Integer.toString(rec.getFlag()));//flag
writer.print("\t");
writer.print(rec.refname);
writer.print("\t");
writer.print(Integer.toString(rec.pos));//pos
writer.print("\t");
writer.print("255"); //mapq=255 means no map quality information
writer.print("\t");
writer.print(rec.cigar); //cigar
writer.print("\t");
writer.print("="); //name of mate's reference(MRNM) = for same
writer.print("\t");
writer.print(Integer.toString(rec.mpos));//mpos
writer.print("\t");
writer.print(Integer.toString(rec.isize));//isize
writer.print("\t");
writer.print(rec.seqLine.toString());//seq
writer.print("\t");
writer.print(rec.qualLine.toString());
writer.print("\t");
if(rec.chimeric) writer.print("YC:Z:"+rec.c_cigar);
else writer.print("YC:Z:"+rec.cigar);
writer.print("\n");
if (writer.checkError()) {
throw new IOException("Error in writing file "+file);
}
}
| public void write(final SamRecord rec) throws IOException {
//<QNAME> <FLAG> <RNAME> <POS> <MAPQ> <CIGAR> <MRNM> <MPOS> <ISIZE> <SEQ> <QUAL> \
//[<TAG>:<VTYPE>:<VALUE> [...]]
//print the informative id if desired
if(this.informative_id){
writer.print(rec.refname);
writer.print("_");
long start = Math.min(rec.pos, rec.mpos);
writer.print(start);
writer.print("_");
//one based typically starts at 1 base and ends at 0 base
// for example a sequence of length 1 starting at 0 based position 0
// would have the location 1 to 1 while most CS apps typically
// would write the same thing as 0-1.
writer.print(start+Math.abs(rec.isize)-1);
if(rec.first && rec.query_reverse_strand || rec.second && rec.mate_reverse_strand){
writer.print("_R_");
}else{// from forward strand
writer.print("_F_");
}
}else{
writer.print(rec.seqHeaderPrefix);//print prefix
}
writer.print(Long.toHexString(rec.seqIndex)); //qname
writer.print("\t");
writer.print(Integer.toString(rec.getFlag()));//flag
writer.print("\t");
writer.print(rec.refname);
writer.print("\t");
writer.print(Integer.toString(rec.pos));//pos
writer.print("\t");
writer.print("255"); //mapq=255 means no map quality information
writer.print("\t");
writer.print(rec.cigar); //cigar
writer.print("\t");
writer.print("="); //name of mate's reference(MRNM) = for same
writer.print("\t");
writer.print(Integer.toString(rec.mpos));//mpos
writer.print("\t");
writer.print(Integer.toString(rec.isize));//isize
writer.print("\t");
writer.print(rec.seqLine.toString());//seq
writer.print("\t");
writer.print(rec.qualLine.toString());
writer.print("\t");
if(rec.chimeric) writer.print("YC:Z:"+rec.c_cigar);
else writer.print("YC:Z:"+rec.cigar);
writer.print("\n");
if (writer.checkError()) {
throw new IOException("Error in writing file "+file);
}
}
|
diff --git a/loci/plugins/LociUploader.java b/loci/plugins/LociUploader.java
index 3d8a13d3e..c916126cf 100644
--- a/loci/plugins/LociUploader.java
+++ b/loci/plugins/LociUploader.java
@@ -1,208 +1,216 @@
//
// LociUploader.java
//
/*
LOCI Plugins for ImageJ: a collection of ImageJ plugins including
the 4D Data Browser, OME Plugin and Bio-Formats Exporter.
Copyright (C) 2006-@year@ Melissa Linkert, Christopher Peterson,
Curtis Rueden, Philip Huettl and Francis Wong.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package loci.plugins;
import java.awt.TextField;
import java.util.Vector;
import ij.*;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
import ij.process.*;
import ij.io.FileInfo;
import loci.formats.*;
import loci.formats.ome.*;
/**
* ImageJ plugin for uploading images to an OME server.
*
* @author Melissa Linkert linket at wisc.edu
*/
public class LociUploader implements PlugIn {
// -- Fields --
private String server;
private String user;
private String pass;
// -- PlugIn API methods --
public synchronized void run(String arg) {
// check that we can safely execute the plugin
if (Util.checkVersion() && Util.checkLibraries(true, true, true, false)) {
promptForLogin();
uploadStack();
}
else {
}
}
// -- Helper methods --
/** Open a dialog box that prompts for a username, password, and server. */
private void promptForLogin() {
GenericDialog prompt = new GenericDialog("Login to OME");
prompt.addStringField("Server: ", Prefs.get("uploader.server", ""), 60);
prompt.addStringField("Username: ", Prefs.get("uploader.user", ""), 60);
prompt.addStringField("Password: ", "", 60);
((TextField) prompt.getStringFields().get(2)).setEchoChar('*');
prompt.showDialog();
server = prompt.getNextString();
user = prompt.getNextString();
pass = prompt.getNextString();
Prefs.set("uploader.server", server);
Prefs.set("uploader.user", user);
}
/** Log in to the OME server and upload the current image stack. */
private void uploadStack() {
try {
IJ.showStatus("Starting upload...");
OMEUploader ul = new OMEUploader(server, user, pass);
ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) {
IJ.error("No open images!");
IJ.showStatus("");
return;
}
ImageStack is = imp.getImageStack();
Vector pixels = new Vector();
FileInfo fi = imp.getOriginalFileInfo();
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
// if we opened this stack with the Bio-Formats importer, then the
// appropriate OME-XML is in fi.description
if (fi != null && fi.description != null &&
fi.description.endsWith("</OME>"))
{
store.createRoot(fi.description);
}
else {
store.createRoot();
int pixelType = FormatTools.UINT8;
switch (imp.getBitDepth()) {
case 16: pixelType = FormatTools.UINT16; break;
case 32: pixelType = FormatTools.FLOAT; break;
}
store.setPixels(
new Integer(imp.getWidth()),
new Integer(imp.getHeight()),
new Integer(imp.getNSlices()),
new Integer(imp.getNChannels()),
new Integer(imp.getNFrames()),
new Integer(pixelType),
fi == null ? Boolean.TRUE : new Boolean(!fi.intelByteOrder),
"XYCZT", // TODO : figure out a way to calculate the dimension order
null,
null);
String name = fi == null ? imp.getTitle() : fi.fileName;
store.setImage(name, null, fi == null ? null : fi.info, null);
}
if (is.getProcessor(1) instanceof ColorProcessor) {
store.setPixels(null, null, null, null, null,
new Integer(FormatTools.UINT8), null, null, null, null);
}
boolean little = !store.getBigEndian(null).booleanValue();
for (int i=0; i<is.getSize(); i++) {
IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize());
Object pix = is.getProcessor(i + 1).getPixels();
if (pix instanceof byte[]) {
pixels.add((byte[]) pix);
}
else if (pix instanceof short[]) {
short[] s = (short[]) pix;
byte[] b = new byte[s.length * 2];
for (int j=0; j<s.length; j++) {
- byte[] a = DataTools.shortToBytes(s[j], little);
- b[j*2] = a[0];
- b[j*2 + 1] = a[1];
+ b[j*2] = little ? (byte) (s[j] & 0xff) :
+ (byte) ((s[j] >>> 8) & 0xff);
+ b[j*2 + 1] = little ? (byte) ((s[j] >>> 8) & 0xff):
+ (byte) (s[j] & 0xff);
}
pixels.add(b);
}
else if (pix instanceof int[]) {
if (is.getProcessor(i+1) instanceof ColorProcessor) {
byte[][] rgb = new byte[3][((int[]) pix).length];
((ColorProcessor) is.getProcessor(i+1)).getRGB(rgb[0],
rgb[1], rgb[2]);
int channels = store.getSizeC(null).intValue();
if (channels > 3) channels = 3;
for (int j=0; j<channels; j++) {
pixels.add(rgb[j]);
}
}
else {
int[] p = (int[]) pix;
byte[] b = new byte[4 * p.length];
for (int j=0; j<p.length; j++) {
- byte[] a = DataTools.intToBytes(p[j], little);
- for (int k=0; k<a.length; k++) {
- b[j*a.length + k] = a[k];
- }
+ b[j*4] = little ? (byte) (p[j] & 0xff) :
+ (byte) ((p[j] >> 24) & 0xff);
+ b[j*4 + 1] = little ? (byte) ((p[j] >> 8) & 0xff) :
+ (byte) ((p[j] >> 16) & 0xff);
+ b[j*4 + 2] = little ? (byte) ((p[j] >> 16) & 0xff) :
+ (byte) ((p[j] >> 8) & 0xff);
+ b[j*4 + 3] = little ? (byte) ((p[j] >> 24) & 0xff) :
+ (byte) (p[j] & 0xff);
}
}
}
else if (pix instanceof float[]) {
float[] f = (float[]) pix;
byte[] b = new byte[f.length * 4];
for (int j=0; j<f.length; j++) {
int k = Float.floatToIntBits(f[j]);
- byte[] a = DataTools.intToBytes(k, little);
- b[j*4] = a[0];
- b[j*4 + 1] = a[1];
- b[j*4 + 2] = a[2];
- b[j*4 + 3] = a[3];
+ b[j*4] = little ? (byte) (k & 0xff) :
+ (byte) ((k >> 24) & 0xff);
+ b[j*4 + 1] = little ? (byte) ((k >> 8) & 0xff) :
+ (byte) ((k >> 16) & 0xff);
+ b[j*4 + 2] = little ? (byte) ((k >> 16) & 0xff) :
+ (byte) ((k >> 8) & 0xff);
+ b[j*4 + 3] = little ? (byte) ((k >> 24) & 0xff) :
+ (byte) (k & 0xff);
}
pixels.add(b);
}
}
byte[][] planes = new byte[pixels.size()][];
for (int i=0; i<pixels.size(); i++) {
planes[i] = (byte[]) pixels.get(i);
}
IJ.showStatus("Sending data to server...");
ul.uploadPlanes(planes, 0, planes.length - 1, 1, store, true);
ul.logout();
IJ.showStatus("Upload finished.");
}
catch (UploadException e) {
IJ.error("Upload failed:\n" + e);
e.printStackTrace();
}
}
}
| false | true | private void uploadStack() {
try {
IJ.showStatus("Starting upload...");
OMEUploader ul = new OMEUploader(server, user, pass);
ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) {
IJ.error("No open images!");
IJ.showStatus("");
return;
}
ImageStack is = imp.getImageStack();
Vector pixels = new Vector();
FileInfo fi = imp.getOriginalFileInfo();
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
// if we opened this stack with the Bio-Formats importer, then the
// appropriate OME-XML is in fi.description
if (fi != null && fi.description != null &&
fi.description.endsWith("</OME>"))
{
store.createRoot(fi.description);
}
else {
store.createRoot();
int pixelType = FormatTools.UINT8;
switch (imp.getBitDepth()) {
case 16: pixelType = FormatTools.UINT16; break;
case 32: pixelType = FormatTools.FLOAT; break;
}
store.setPixels(
new Integer(imp.getWidth()),
new Integer(imp.getHeight()),
new Integer(imp.getNSlices()),
new Integer(imp.getNChannels()),
new Integer(imp.getNFrames()),
new Integer(pixelType),
fi == null ? Boolean.TRUE : new Boolean(!fi.intelByteOrder),
"XYCZT", // TODO : figure out a way to calculate the dimension order
null,
null);
String name = fi == null ? imp.getTitle() : fi.fileName;
store.setImage(name, null, fi == null ? null : fi.info, null);
}
if (is.getProcessor(1) instanceof ColorProcessor) {
store.setPixels(null, null, null, null, null,
new Integer(FormatTools.UINT8), null, null, null, null);
}
boolean little = !store.getBigEndian(null).booleanValue();
for (int i=0; i<is.getSize(); i++) {
IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize());
Object pix = is.getProcessor(i + 1).getPixels();
if (pix instanceof byte[]) {
pixels.add((byte[]) pix);
}
else if (pix instanceof short[]) {
short[] s = (short[]) pix;
byte[] b = new byte[s.length * 2];
for (int j=0; j<s.length; j++) {
byte[] a = DataTools.shortToBytes(s[j], little);
b[j*2] = a[0];
b[j*2 + 1] = a[1];
}
pixels.add(b);
}
else if (pix instanceof int[]) {
if (is.getProcessor(i+1) instanceof ColorProcessor) {
byte[][] rgb = new byte[3][((int[]) pix).length];
((ColorProcessor) is.getProcessor(i+1)).getRGB(rgb[0],
rgb[1], rgb[2]);
int channels = store.getSizeC(null).intValue();
if (channels > 3) channels = 3;
for (int j=0; j<channels; j++) {
pixels.add(rgb[j]);
}
}
else {
int[] p = (int[]) pix;
byte[] b = new byte[4 * p.length];
for (int j=0; j<p.length; j++) {
byte[] a = DataTools.intToBytes(p[j], little);
for (int k=0; k<a.length; k++) {
b[j*a.length + k] = a[k];
}
}
}
}
else if (pix instanceof float[]) {
float[] f = (float[]) pix;
byte[] b = new byte[f.length * 4];
for (int j=0; j<f.length; j++) {
int k = Float.floatToIntBits(f[j]);
byte[] a = DataTools.intToBytes(k, little);
b[j*4] = a[0];
b[j*4 + 1] = a[1];
b[j*4 + 2] = a[2];
b[j*4 + 3] = a[3];
}
pixels.add(b);
}
}
byte[][] planes = new byte[pixels.size()][];
for (int i=0; i<pixels.size(); i++) {
planes[i] = (byte[]) pixels.get(i);
}
IJ.showStatus("Sending data to server...");
ul.uploadPlanes(planes, 0, planes.length - 1, 1, store, true);
ul.logout();
IJ.showStatus("Upload finished.");
}
catch (UploadException e) {
IJ.error("Upload failed:\n" + e);
e.printStackTrace();
}
}
| private void uploadStack() {
try {
IJ.showStatus("Starting upload...");
OMEUploader ul = new OMEUploader(server, user, pass);
ImagePlus imp = WindowManager.getCurrentImage();
if (imp == null) {
IJ.error("No open images!");
IJ.showStatus("");
return;
}
ImageStack is = imp.getImageStack();
Vector pixels = new Vector();
FileInfo fi = imp.getOriginalFileInfo();
OMEXMLMetadataStore store = new OMEXMLMetadataStore();
// if we opened this stack with the Bio-Formats importer, then the
// appropriate OME-XML is in fi.description
if (fi != null && fi.description != null &&
fi.description.endsWith("</OME>"))
{
store.createRoot(fi.description);
}
else {
store.createRoot();
int pixelType = FormatTools.UINT8;
switch (imp.getBitDepth()) {
case 16: pixelType = FormatTools.UINT16; break;
case 32: pixelType = FormatTools.FLOAT; break;
}
store.setPixels(
new Integer(imp.getWidth()),
new Integer(imp.getHeight()),
new Integer(imp.getNSlices()),
new Integer(imp.getNChannels()),
new Integer(imp.getNFrames()),
new Integer(pixelType),
fi == null ? Boolean.TRUE : new Boolean(!fi.intelByteOrder),
"XYCZT", // TODO : figure out a way to calculate the dimension order
null,
null);
String name = fi == null ? imp.getTitle() : fi.fileName;
store.setImage(name, null, fi == null ? null : fi.info, null);
}
if (is.getProcessor(1) instanceof ColorProcessor) {
store.setPixels(null, null, null, null, null,
new Integer(FormatTools.UINT8), null, null, null, null);
}
boolean little = !store.getBigEndian(null).booleanValue();
for (int i=0; i<is.getSize(); i++) {
IJ.showStatus("Reading plane " + (i+1) + "/" + is.getSize());
Object pix = is.getProcessor(i + 1).getPixels();
if (pix instanceof byte[]) {
pixels.add((byte[]) pix);
}
else if (pix instanceof short[]) {
short[] s = (short[]) pix;
byte[] b = new byte[s.length * 2];
for (int j=0; j<s.length; j++) {
b[j*2] = little ? (byte) (s[j] & 0xff) :
(byte) ((s[j] >>> 8) & 0xff);
b[j*2 + 1] = little ? (byte) ((s[j] >>> 8) & 0xff):
(byte) (s[j] & 0xff);
}
pixels.add(b);
}
else if (pix instanceof int[]) {
if (is.getProcessor(i+1) instanceof ColorProcessor) {
byte[][] rgb = new byte[3][((int[]) pix).length];
((ColorProcessor) is.getProcessor(i+1)).getRGB(rgb[0],
rgb[1], rgb[2]);
int channels = store.getSizeC(null).intValue();
if (channels > 3) channels = 3;
for (int j=0; j<channels; j++) {
pixels.add(rgb[j]);
}
}
else {
int[] p = (int[]) pix;
byte[] b = new byte[4 * p.length];
for (int j=0; j<p.length; j++) {
b[j*4] = little ? (byte) (p[j] & 0xff) :
(byte) ((p[j] >> 24) & 0xff);
b[j*4 + 1] = little ? (byte) ((p[j] >> 8) & 0xff) :
(byte) ((p[j] >> 16) & 0xff);
b[j*4 + 2] = little ? (byte) ((p[j] >> 16) & 0xff) :
(byte) ((p[j] >> 8) & 0xff);
b[j*4 + 3] = little ? (byte) ((p[j] >> 24) & 0xff) :
(byte) (p[j] & 0xff);
}
}
}
else if (pix instanceof float[]) {
float[] f = (float[]) pix;
byte[] b = new byte[f.length * 4];
for (int j=0; j<f.length; j++) {
int k = Float.floatToIntBits(f[j]);
b[j*4] = little ? (byte) (k & 0xff) :
(byte) ((k >> 24) & 0xff);
b[j*4 + 1] = little ? (byte) ((k >> 8) & 0xff) :
(byte) ((k >> 16) & 0xff);
b[j*4 + 2] = little ? (byte) ((k >> 16) & 0xff) :
(byte) ((k >> 8) & 0xff);
b[j*4 + 3] = little ? (byte) ((k >> 24) & 0xff) :
(byte) (k & 0xff);
}
pixels.add(b);
}
}
byte[][] planes = new byte[pixels.size()][];
for (int i=0; i<pixels.size(); i++) {
planes[i] = (byte[]) pixels.get(i);
}
IJ.showStatus("Sending data to server...");
ul.uploadPlanes(planes, 0, planes.length - 1, 1, store, true);
ul.logout();
IJ.showStatus("Upload finished.");
}
catch (UploadException e) {
IJ.error("Upload failed:\n" + e);
e.printStackTrace();
}
}
|
diff --git a/core/src/visad/trunk/data/mcidas/PointDataAdapter.java b/core/src/visad/trunk/data/mcidas/PointDataAdapter.java
index 0da67965c..17cea1dcd 100644
--- a/core/src/visad/trunk/data/mcidas/PointDataAdapter.java
+++ b/core/src/visad/trunk/data/mcidas/PointDataAdapter.java
@@ -1,346 +1,346 @@
//
// PointDataAdapter.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2006 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad.data.mcidas;
import edu.wisc.ssec.mcidas.*;
import edu.wisc.ssec.mcidas.adde.*;
import visad.*;
import visad.data.units.*;
import visad.jmet.MetUnits;
import java.util.Vector;
/**
* A class for adapting the results of an ADDE point data request into a
* VisAD Data object.
*
* @author Don Murray, Unidata
*/
public class PointDataAdapter {
AddePointDataReader reader;
FieldImpl field = null;
private boolean debug = false;
private boolean useAliases = true;
/**
* Construct a PointDataAdapter using the adde request passed as a string.
* This will take the data returned from the request and turn it into
* VisAD Data objects that can be returned by the getData() call.
*
* @param addePointRequest - string representing the ADDE request
* @throws VisADException bad request, no data available, VisAD error
* @see #getData()
*/
public PointDataAdapter(String addePointRequest)
throws VisADException
{
this(addePointRequest, true);
}
/**
* Construct a PointDataAdapter using the adde request passed as a string.
* This will take the data returned from the request and turn it into
* VisAD Data objects that can be returned by the getData() call.
*
* @param addePointRequest - string representing the ADDE request
* @param useAliases - for quantities like Latitude, Longitude,etc
* alias the RealTypes to the original McIDAS
* variable name.
* @throws VisADException bad request, no data available, VisAD error
* @see #getData()
*/
public PointDataAdapter(String addePointRequest, boolean useAliases)
throws VisADException
{
try
{
reader = new AddePointDataReader(addePointRequest);
debug = addePointRequest.indexOf("debug=true") > 0;
this.useAliases = useAliases;
}
catch (AddeException excp)
{
throw new VisADException("Problem accessing data");
}
makeField();
}
// out of this will either come a FieldImpl, a ObservationDBImpl,
// or a StationObDBImpl
private void makeField()
throws VisADException
{
// First, let's make a generic FieldImpl from the data
// the structure will be index -> parameter tuple
// get all the stuff from the reader
int[][] data;
String[] units;
String[] params;
Unit[] defaultUnits;
int[] scalingFactors;
try
{
data = reader.getData(reader.OB_ORDER);
units = reader.getUnits();
params = reader.getParams();
scalingFactors = reader.getScales();
}
catch (AddeException ae)
{
throw new VisADException("Error retrieving data info");
}
//int numObs = data[0].length;
int numObs = data.length;
if (numObs == 0)
throw new VisADException("No data available");
if (debug) System.out.println("Number of observations = " + numObs);
RealType domainType = RealType.getRealType("index");
Integer1DSet domain = new Integer1DSet(domainType, numObs);
// now make range (Tuple) type
MetUnits unitTranslator = new MetUnits();
int numParams = params.length;
if (debug) System.out.println("Number of parameters = " + numParams);
ScalarType[] types = new ScalarType[numParams];
defaultUnits = new Unit[numParams];
Vector usedUnits = new Vector();
boolean noText = true;
for (int i = 0; i < numParams; i++)
{
// get the name
String name = params[i];
if (units[i].equalsIgnoreCase("CHAR"))
{
noText = false;
if (debug) {
System.out.println(params[i] + " has units of CHAR");
}
types[i] = TextType.getTextType(params[i]);
defaultUnits[i] = null;
}
else
{
// make the unit
Unit unit = null;
try
{
unit =
(!name.equalsIgnoreCase("LON") )
? Parser.parse(unitTranslator.makeSymbol(units[i]))
: Parser.parse("degrees_west"); // fix McIDAS conv.
}
catch (NoSuchUnitException ne) {
if (debug)
System.out.println("Unknown unit: " + units[i] + " for " + name);
unit = null;
}
catch (ParseException pe) { unit = null;}
defaultUnits[i] = unit;
if (debug) {
System.out.println(params[i] + " has units " + unit);
System.out.println("scaling factor = " + scalingFactors[i]);
}
types[i] = getQuantity(params[i], unit);
}
}
TupleType rangeType;
if (noText) // all Reals
{
RealType[] newTypes = new RealType[types.length];
for (int i = 0; i < types.length; i++) {
newTypes[i] = (RealType) types[i];
}
rangeType = new RealTupleType(newTypes);
}
else // all Texts or mixture of Text and Reals
{
rangeType = new TupleType(types);
}
// make the field
FunctionType functionType = new FunctionType(domainType, rangeType);
/*
field = (noText)
? new FlatField(functionType, domain)
: new FieldImpl(functionType, domain);
*/
field = new FieldImpl(functionType, domain);
if (debug) System.out.println("filling in data" );
long millis = System.currentTimeMillis();
// now, fill in the data
Scalar[] firstTuple = null; // use this for saving memory/time
+ Unit[] actualUnits = null;
for (int i = 0; i < numObs; i++)
{
Scalar[] scalars = (noText == true) ? new Real[numParams]
: new Scalar[numParams];
for (int j = 0; j < numParams; j++)
{
if (types[j] instanceof TextType) {
try
{
scalars[j] =
new Text( (TextType) types[j],
McIDASUtil.intBitsToString(data[i][j]));
}
catch (VisADException ex) {;} // shouldn't happen
}
else
{
double value =
data[i][j] == McIDASUtil.MCMISSING
? Double.NaN
: data[i][j]/Math.pow(10.0,
(double) scalingFactors[j] );
if (firstTuple == null) { //
try
{
scalars[j] =
new Real(
(RealType) types[j], value, defaultUnits[j]);
} catch (VisADException excp) { // units problem
scalars[j] = new Real((RealType) types[j], value);
}
+ usedUnits.add(((Real) scalars[j]).getUnit());
} else {
scalars[j] = ((Real) firstTuple[j]).cloneButValue(value);
}
- usedUnits.add(((Real) scalars[j]).getUnit());
}
}
- Unit[] actualUnits = null;
- if (noText) {
+ if (noText && actualUnits == null) {
actualUnits = new Unit[usedUnits.size()];
for (int k = 0; k < usedUnits.size(); k++) actualUnits[k] = (Unit) usedUnits.get(k);
}
try
{
Data sample = (noText == true)
? new RealTuple(
(RealTupleType)rangeType, (Real[]) scalars, null, actualUnits, false)
: new Tuple(rangeType, scalars, false, false);
field.setSample(i, sample, false, (i==0)); // don't make copy, don't check type after first
}
catch (VisADException e) {e.printStackTrace();}
catch (java.rmi.RemoteException e) {;}
if (firstTuple == null)
{
firstTuple = scalars;
}
}
if (debug) {
System.out.println("data fill took " +
(System.currentTimeMillis() - millis) + " ms");
}
}
/**
* Get the VisAD Data object that represents the output from the
* request.
*
* @return requested data. The format is a FieldImpl of
* (obnum -> (tuple of parameters)
*/
public DataImpl getData()
{
return field;
}
/**
* test with 'java visad.data.mcidas.PointDataAdapter args'
* @param args ADDE point data request
*/
public static void main(String[] args)
throws Exception
{
if (args.length == 0)
{
System.out.println("You must specify an ADDE Point Data URL");
System.exit(-1);
}
try
{
PointDataAdapter pda = new PointDataAdapter(args[0]);
Field data = (Field) pda.getData();
//System.out.println(data.getType());
visad.python.JPythonMethods.dumpTypes(data);
/*
int length = data.getDomainSet().getLength() - 1;
System.out.println(
"Sample "+ length + " = " + data.getSample(length));
*/
}
catch (VisADException ve)
{
System.out.println("Error reading data");
}
}
/**
* First cut at a standard quantities database.
*/
private RealType getQuantity(String name, Unit unit)
throws VisADException
{
RealType type = null;
if (name.equalsIgnoreCase("lat")) {
type = RealType.Latitude;
} else if (name.equalsIgnoreCase("lon")) {
type = RealType.Longitude;
} else if (name.equalsIgnoreCase("z") ||
name.equalsIgnoreCase("zs") ) {
type = RealType.Altitude;
} else {
type = RealType.getRealType(name, unit);
if (type == null) {
System.err.println("Problem creating RealType with name " +
name + " and unit " + unit);
type = RealType.getRealTypeByName(name);
if (type == null) { // Still a problem
throw new VisADException(
"getQuantity(): Couldn't create RealType for " + name);
}
System.err.println("Using RealType with name " + name);
}
}
if (useAliases) {
if (RealType.getRealTypeByName(name) == null) {
type.alias(name);
} else if (!RealType.getRealTypeByName(name).equals(type)) { // alias used
throw new VisADException(
"getQuanity(): Two different variables can't have the same alias");
}
}
return type;
}
}
| false | true | private void makeField()
throws VisADException
{
// First, let's make a generic FieldImpl from the data
// the structure will be index -> parameter tuple
// get all the stuff from the reader
int[][] data;
String[] units;
String[] params;
Unit[] defaultUnits;
int[] scalingFactors;
try
{
data = reader.getData(reader.OB_ORDER);
units = reader.getUnits();
params = reader.getParams();
scalingFactors = reader.getScales();
}
catch (AddeException ae)
{
throw new VisADException("Error retrieving data info");
}
//int numObs = data[0].length;
int numObs = data.length;
if (numObs == 0)
throw new VisADException("No data available");
if (debug) System.out.println("Number of observations = " + numObs);
RealType domainType = RealType.getRealType("index");
Integer1DSet domain = new Integer1DSet(domainType, numObs);
// now make range (Tuple) type
MetUnits unitTranslator = new MetUnits();
int numParams = params.length;
if (debug) System.out.println("Number of parameters = " + numParams);
ScalarType[] types = new ScalarType[numParams];
defaultUnits = new Unit[numParams];
Vector usedUnits = new Vector();
boolean noText = true;
for (int i = 0; i < numParams; i++)
{
// get the name
String name = params[i];
if (units[i].equalsIgnoreCase("CHAR"))
{
noText = false;
if (debug) {
System.out.println(params[i] + " has units of CHAR");
}
types[i] = TextType.getTextType(params[i]);
defaultUnits[i] = null;
}
else
{
// make the unit
Unit unit = null;
try
{
unit =
(!name.equalsIgnoreCase("LON") )
? Parser.parse(unitTranslator.makeSymbol(units[i]))
: Parser.parse("degrees_west"); // fix McIDAS conv.
}
catch (NoSuchUnitException ne) {
if (debug)
System.out.println("Unknown unit: " + units[i] + " for " + name);
unit = null;
}
catch (ParseException pe) { unit = null;}
defaultUnits[i] = unit;
if (debug) {
System.out.println(params[i] + " has units " + unit);
System.out.println("scaling factor = " + scalingFactors[i]);
}
types[i] = getQuantity(params[i], unit);
}
}
TupleType rangeType;
if (noText) // all Reals
{
RealType[] newTypes = new RealType[types.length];
for (int i = 0; i < types.length; i++) {
newTypes[i] = (RealType) types[i];
}
rangeType = new RealTupleType(newTypes);
}
else // all Texts or mixture of Text and Reals
{
rangeType = new TupleType(types);
}
// make the field
FunctionType functionType = new FunctionType(domainType, rangeType);
/*
field = (noText)
? new FlatField(functionType, domain)
: new FieldImpl(functionType, domain);
*/
field = new FieldImpl(functionType, domain);
if (debug) System.out.println("filling in data" );
long millis = System.currentTimeMillis();
// now, fill in the data
Scalar[] firstTuple = null; // use this for saving memory/time
for (int i = 0; i < numObs; i++)
{
Scalar[] scalars = (noText == true) ? new Real[numParams]
: new Scalar[numParams];
for (int j = 0; j < numParams; j++)
{
if (types[j] instanceof TextType) {
try
{
scalars[j] =
new Text( (TextType) types[j],
McIDASUtil.intBitsToString(data[i][j]));
}
catch (VisADException ex) {;} // shouldn't happen
}
else
{
double value =
data[i][j] == McIDASUtil.MCMISSING
? Double.NaN
: data[i][j]/Math.pow(10.0,
(double) scalingFactors[j] );
if (firstTuple == null) { //
try
{
scalars[j] =
new Real(
(RealType) types[j], value, defaultUnits[j]);
} catch (VisADException excp) { // units problem
scalars[j] = new Real((RealType) types[j], value);
}
} else {
scalars[j] = ((Real) firstTuple[j]).cloneButValue(value);
}
usedUnits.add(((Real) scalars[j]).getUnit());
}
}
Unit[] actualUnits = null;
if (noText) {
actualUnits = new Unit[usedUnits.size()];
for (int k = 0; k < usedUnits.size(); k++) actualUnits[k] = (Unit) usedUnits.get(k);
}
try
{
Data sample = (noText == true)
? new RealTuple(
(RealTupleType)rangeType, (Real[]) scalars, null, actualUnits, false)
: new Tuple(rangeType, scalars, false, false);
field.setSample(i, sample, false, (i==0)); // don't make copy, don't check type after first
}
catch (VisADException e) {e.printStackTrace();}
catch (java.rmi.RemoteException e) {;}
if (firstTuple == null)
{
firstTuple = scalars;
}
}
if (debug) {
System.out.println("data fill took " +
(System.currentTimeMillis() - millis) + " ms");
}
}
| private void makeField()
throws VisADException
{
// First, let's make a generic FieldImpl from the data
// the structure will be index -> parameter tuple
// get all the stuff from the reader
int[][] data;
String[] units;
String[] params;
Unit[] defaultUnits;
int[] scalingFactors;
try
{
data = reader.getData(reader.OB_ORDER);
units = reader.getUnits();
params = reader.getParams();
scalingFactors = reader.getScales();
}
catch (AddeException ae)
{
throw new VisADException("Error retrieving data info");
}
//int numObs = data[0].length;
int numObs = data.length;
if (numObs == 0)
throw new VisADException("No data available");
if (debug) System.out.println("Number of observations = " + numObs);
RealType domainType = RealType.getRealType("index");
Integer1DSet domain = new Integer1DSet(domainType, numObs);
// now make range (Tuple) type
MetUnits unitTranslator = new MetUnits();
int numParams = params.length;
if (debug) System.out.println("Number of parameters = " + numParams);
ScalarType[] types = new ScalarType[numParams];
defaultUnits = new Unit[numParams];
Vector usedUnits = new Vector();
boolean noText = true;
for (int i = 0; i < numParams; i++)
{
// get the name
String name = params[i];
if (units[i].equalsIgnoreCase("CHAR"))
{
noText = false;
if (debug) {
System.out.println(params[i] + " has units of CHAR");
}
types[i] = TextType.getTextType(params[i]);
defaultUnits[i] = null;
}
else
{
// make the unit
Unit unit = null;
try
{
unit =
(!name.equalsIgnoreCase("LON") )
? Parser.parse(unitTranslator.makeSymbol(units[i]))
: Parser.parse("degrees_west"); // fix McIDAS conv.
}
catch (NoSuchUnitException ne) {
if (debug)
System.out.println("Unknown unit: " + units[i] + " for " + name);
unit = null;
}
catch (ParseException pe) { unit = null;}
defaultUnits[i] = unit;
if (debug) {
System.out.println(params[i] + " has units " + unit);
System.out.println("scaling factor = " + scalingFactors[i]);
}
types[i] = getQuantity(params[i], unit);
}
}
TupleType rangeType;
if (noText) // all Reals
{
RealType[] newTypes = new RealType[types.length];
for (int i = 0; i < types.length; i++) {
newTypes[i] = (RealType) types[i];
}
rangeType = new RealTupleType(newTypes);
}
else // all Texts or mixture of Text and Reals
{
rangeType = new TupleType(types);
}
// make the field
FunctionType functionType = new FunctionType(domainType, rangeType);
/*
field = (noText)
? new FlatField(functionType, domain)
: new FieldImpl(functionType, domain);
*/
field = new FieldImpl(functionType, domain);
if (debug) System.out.println("filling in data" );
long millis = System.currentTimeMillis();
// now, fill in the data
Scalar[] firstTuple = null; // use this for saving memory/time
Unit[] actualUnits = null;
for (int i = 0; i < numObs; i++)
{
Scalar[] scalars = (noText == true) ? new Real[numParams]
: new Scalar[numParams];
for (int j = 0; j < numParams; j++)
{
if (types[j] instanceof TextType) {
try
{
scalars[j] =
new Text( (TextType) types[j],
McIDASUtil.intBitsToString(data[i][j]));
}
catch (VisADException ex) {;} // shouldn't happen
}
else
{
double value =
data[i][j] == McIDASUtil.MCMISSING
? Double.NaN
: data[i][j]/Math.pow(10.0,
(double) scalingFactors[j] );
if (firstTuple == null) { //
try
{
scalars[j] =
new Real(
(RealType) types[j], value, defaultUnits[j]);
} catch (VisADException excp) { // units problem
scalars[j] = new Real((RealType) types[j], value);
}
usedUnits.add(((Real) scalars[j]).getUnit());
} else {
scalars[j] = ((Real) firstTuple[j]).cloneButValue(value);
}
}
}
if (noText && actualUnits == null) {
actualUnits = new Unit[usedUnits.size()];
for (int k = 0; k < usedUnits.size(); k++) actualUnits[k] = (Unit) usedUnits.get(k);
}
try
{
Data sample = (noText == true)
? new RealTuple(
(RealTupleType)rangeType, (Real[]) scalars, null, actualUnits, false)
: new Tuple(rangeType, scalars, false, false);
field.setSample(i, sample, false, (i==0)); // don't make copy, don't check type after first
}
catch (VisADException e) {e.printStackTrace();}
catch (java.rmi.RemoteException e) {;}
if (firstTuple == null)
{
firstTuple = scalars;
}
}
if (debug) {
System.out.println("data fill took " +
(System.currentTimeMillis() - millis) + " ms");
}
}
|
diff --git a/src/main/java/com/philihp/weblabora/model/building/ChamberOfWonders.java b/src/main/java/com/philihp/weblabora/model/building/ChamberOfWonders.java
index 4ed4869..5a555f4 100644
--- a/src/main/java/com/philihp/weblabora/model/building/ChamberOfWonders.java
+++ b/src/main/java/com/philihp/weblabora/model/building/ChamberOfWonders.java
@@ -1,33 +1,34 @@
package com.philihp.weblabora.model.building;
import static com.philihp.weblabora.model.TerrainTypeEnum.COAST;
import static com.philihp.weblabora.model.TerrainTypeEnum.HILLSIDE;
import static com.philihp.weblabora.model.TerrainTypeEnum.PLAINS;
import java.util.EnumSet;
import java.util.Set;
import com.philihp.weblabora.model.Board;
import com.philihp.weblabora.model.BuildCost;
import com.philihp.weblabora.model.Player;
import com.philihp.weblabora.model.SettlementRound;
import com.philihp.weblabora.model.TerrainTypeEnum;
import com.philihp.weblabora.model.UsageParam;
import com.philihp.weblabora.model.WeblaboraException;
public class ChamberOfWonders extends Building {
public ChamberOfWonders() {
super("F25", SettlementRound.B, 4, "Chamber of Wonders", BuildCost.is().wood(1).clay(1), 6, 0,
EnumSet.of(COAST, PLAINS, HILLSIDE), false);
}
@Override
public void use(Board board, UsageParam param) throws WeblaboraException {
Player player = board.getPlayer(board.getActivePlayer());
if(param.differentSingularGoods() == 13) {
player.subtractAll(param);
player.claimWonder(board.claimWonder());
}
+ else throw new WeblaboraException(getName() + " requires exactly 13 different goods, but was only given "+param.differentSingularGoods());
}
}
| true | true | public void use(Board board, UsageParam param) throws WeblaboraException {
Player player = board.getPlayer(board.getActivePlayer());
if(param.differentSingularGoods() == 13) {
player.subtractAll(param);
player.claimWonder(board.claimWonder());
}
}
| public void use(Board board, UsageParam param) throws WeblaboraException {
Player player = board.getPlayer(board.getActivePlayer());
if(param.differentSingularGoods() == 13) {
player.subtractAll(param);
player.claimWonder(board.claimWonder());
}
else throw new WeblaboraException(getName() + " requires exactly 13 different goods, but was only given "+param.differentSingularGoods());
}
|
diff --git a/src/tesseract/menuitems/TesseractMenuItem.java b/src/tesseract/menuitems/TesseractMenuItem.java
index 8076f28..5c79ba3 100644
--- a/src/tesseract/menuitems/TesseractMenuItem.java
+++ b/src/tesseract/menuitems/TesseractMenuItem.java
@@ -1,260 +1,262 @@
package tesseract.menuitems;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JTextField;
import javax.vecmath.Vector3f;
import tesseract.World;
/**
* Abstract class for menu items.
*
* @author Jesse Morgan, Steve Bradshaw
*/
public abstract class TesseractMenuItem
extends JMenuItem implements ActionListener {
/**
* Serial ID.
*/
private static final long serialVersionUID = 1839955501629795920L;
/**
* A Default radius.
*/
private static final float DEFAULT_RADIUS = 0.1f;
/**
* A Default position.
*/
private static final Vector3f DEFAULT_POSITION = new Vector3f(0,0,0);
/**
* The reference to the world.
*/
protected World myWorld;
/**
* The default button
*/
private JCheckBox my_default_button;
/**
* A Parameter setting JFrame
*/
private JFrame my_param_frame;
/**
* A position.
*/
private Vector3f my_position;
/**
* A radius field.
*/
private float my_radius;
/**
* A mass field.
*/
private float my_mass;
/**
* A position input.
*/
private JTextField my_position_input;
/**
* A radius input.
*/
private JTextField my_radius_input;
/**
* A mass input.
*/
private JTextField my_mass_input;
/**
* The button that get all inputs for shape
*/
private JButton my_enter_button;
/**
* Constructor.
*
* @param theWorld The world in which to add.
* @param theLabel The label for the menu item.
*/
public TesseractMenuItem(final World theWorld, final String theLabel) {
super(theLabel);
myWorld = theWorld;
my_position = new Vector3f(0,0,0);
my_radius = 0f;
my_mass = 1;
addActionListener(this);
}
/**
* Utility method to parse a string formatted as x,y,z into a vector3f.
*
* @param input A string to parse.
* @return A vector3f.
*/
protected Vector3f parseVector(final String input) {
String[] split = input.split(",");
float x = Float.parseFloat(split[0]);
float y = Float.parseFloat(split[1]);
float z = Float.parseFloat(split[2]);
return new Vector3f(x, y, z);
}
protected void createParameterMenu() {
my_param_frame = new JFrame("Parameters");
my_param_frame.setBackground(Color.GRAY);
my_param_frame.setLayout(new GridLayout(5,1));
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
my_param_frame.setSize(screenWidth / 4, screenHeight / 4);
my_param_frame.setLocation(screenWidth / 4, screenHeight / 4);
my_position_input = new JTextField(10);
my_position_input.setText("0,0,0");
my_radius_input = new JTextField(10);
my_radius_input.setText(".1");
my_mass_input = new JTextField(10);
my_mass_input.setText("1");
+ JLabel blank = new JLabel("");
JLabel position_label = new JLabel("Enter Position: ");
JLabel radius_label = new JLabel("Enter Radius: ");
JLabel mass_label = new JLabel("Enter Mass: ");
my_enter_button = new JButton("ENTER");
my_default_button = new JCheckBox("Default Shape ");
my_param_frame.add(my_default_button);
+ my_param_frame.add(blank);
my_param_frame.add(position_label);
my_param_frame.add(my_position_input);
my_param_frame.add(radius_label);
my_param_frame.add(my_radius_input);
my_param_frame.add(mass_label);
my_param_frame.add(my_mass_input);
my_param_frame.add(my_enter_button);
my_param_frame.setAlwaysOnTop(true);
my_param_frame.pack();
my_param_frame.setVisible(isVisible());
}
protected JCheckBox getDefaultButton() {
return my_default_button;
}
protected JFrame getParamFrame() {
return my_param_frame;
}
protected JButton getEnterButton() {
return my_enter_button;
}
/**
* @return the defaultRadius
*/
public static float getDefaultRadius() {
return DEFAULT_RADIUS;
}
/**
* @return the defaultPosition
*/
public static Vector3f getDefaultPosition() {
return DEFAULT_POSITION;
}
/**
* @return the input position.
*/
public Vector3f getPosition() {
return my_position;
}
/**
* @return the radius.
*/
public float getRadius() {
return my_radius;
}
/**
* @return the mass.
*/
public float getMass() {
return my_mass;
}
/**
*
* @param the_position the new position
*/
public void setPosition(final Vector3f the_position) {
my_position = the_position;
}
/**
* @param the_radius float sets the radius.
*/
public void setRadius(final float the_radius) {
my_radius = the_radius;
}
/**
* @param the_mass float sets the mass.
*/
public void setMass(final float the_mass) {
my_mass = the_mass;
}
/**
* @return the input position input
*/
public JTextField getPositionField() {
return my_position_input;
}
/**
* @return the radius input.
*/
public JTextField getRadiusField() {
return my_radius_input;
}
/**
* @return the mass input.
*/
public JTextField getMassField() {
return my_mass_input;
}
}
| false | true | protected void createParameterMenu() {
my_param_frame = new JFrame("Parameters");
my_param_frame.setBackground(Color.GRAY);
my_param_frame.setLayout(new GridLayout(5,1));
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
my_param_frame.setSize(screenWidth / 4, screenHeight / 4);
my_param_frame.setLocation(screenWidth / 4, screenHeight / 4);
my_position_input = new JTextField(10);
my_position_input.setText("0,0,0");
my_radius_input = new JTextField(10);
my_radius_input.setText(".1");
my_mass_input = new JTextField(10);
my_mass_input.setText("1");
JLabel position_label = new JLabel("Enter Position: ");
JLabel radius_label = new JLabel("Enter Radius: ");
JLabel mass_label = new JLabel("Enter Mass: ");
my_enter_button = new JButton("ENTER");
my_default_button = new JCheckBox("Default Shape ");
my_param_frame.add(my_default_button);
my_param_frame.add(position_label);
my_param_frame.add(my_position_input);
my_param_frame.add(radius_label);
my_param_frame.add(my_radius_input);
my_param_frame.add(mass_label);
my_param_frame.add(my_mass_input);
my_param_frame.add(my_enter_button);
my_param_frame.setAlwaysOnTop(true);
my_param_frame.pack();
my_param_frame.setVisible(isVisible());
}
| protected void createParameterMenu() {
my_param_frame = new JFrame("Parameters");
my_param_frame.setBackground(Color.GRAY);
my_param_frame.setLayout(new GridLayout(5,1));
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension screenSize = tk.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
my_param_frame.setSize(screenWidth / 4, screenHeight / 4);
my_param_frame.setLocation(screenWidth / 4, screenHeight / 4);
my_position_input = new JTextField(10);
my_position_input.setText("0,0,0");
my_radius_input = new JTextField(10);
my_radius_input.setText(".1");
my_mass_input = new JTextField(10);
my_mass_input.setText("1");
JLabel blank = new JLabel("");
JLabel position_label = new JLabel("Enter Position: ");
JLabel radius_label = new JLabel("Enter Radius: ");
JLabel mass_label = new JLabel("Enter Mass: ");
my_enter_button = new JButton("ENTER");
my_default_button = new JCheckBox("Default Shape ");
my_param_frame.add(my_default_button);
my_param_frame.add(blank);
my_param_frame.add(position_label);
my_param_frame.add(my_position_input);
my_param_frame.add(radius_label);
my_param_frame.add(my_radius_input);
my_param_frame.add(mass_label);
my_param_frame.add(my_mass_input);
my_param_frame.add(my_enter_button);
my_param_frame.setAlwaysOnTop(true);
my_param_frame.pack();
my_param_frame.setVisible(isVisible());
}
|
diff --git a/src/ualberta/g12/adventurecreator/CreateStoryActivity.java b/src/ualberta/g12/adventurecreator/CreateStoryActivity.java
index 9d04f67..b2d9c12 100644
--- a/src/ualberta/g12/adventurecreator/CreateStoryActivity.java
+++ b/src/ualberta/g12/adventurecreator/CreateStoryActivity.java
@@ -1,71 +1,71 @@
package ualberta.g12.adventurecreator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class CreateStoryActivity extends Activity {
Button createButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_story);
createButton = (Button) findViewById(R.id.button1);
createButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// create a new story object! id should be unique too!
// get the editTexts!
EditText title = (EditText) findViewById(R.id.editStoryTitle);
EditText author = (EditText) findViewById(R.id.editStoryAuthor);
// create a new story (might want to use a controller here instead!)
Story myNewStory = new Story(title.getText().toString(), author.getText().toString());
// TODO: make sure id is unique!
- myNewStory.setId(1);
+ myNewStory.setId(5);
// add the story with our story list controller!
StoryListController slc = AdventureCreatorApplication.getStoryListController();
slc.addStory(myNewStory);
// TODO discuss
// I'm changing it so that you can only create a story here
// it will return to our main screen where if they click on it it will let them edit
finish();
}
});
}
@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) {
// TODO Auto-generated method stub
return super.onOptionsItemSelected(item);
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_story);
createButton = (Button) findViewById(R.id.button1);
createButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// create a new story object! id should be unique too!
// get the editTexts!
EditText title = (EditText) findViewById(R.id.editStoryTitle);
EditText author = (EditText) findViewById(R.id.editStoryAuthor);
// create a new story (might want to use a controller here instead!)
Story myNewStory = new Story(title.getText().toString(), author.getText().toString());
// TODO: make sure id is unique!
myNewStory.setId(1);
// add the story with our story list controller!
StoryListController slc = AdventureCreatorApplication.getStoryListController();
slc.addStory(myNewStory);
// TODO discuss
// I'm changing it so that you can only create a story here
// it will return to our main screen where if they click on it it will let them edit
finish();
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_story);
createButton = (Button) findViewById(R.id.button1);
createButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// create a new story object! id should be unique too!
// get the editTexts!
EditText title = (EditText) findViewById(R.id.editStoryTitle);
EditText author = (EditText) findViewById(R.id.editStoryAuthor);
// create a new story (might want to use a controller here instead!)
Story myNewStory = new Story(title.getText().toString(), author.getText().toString());
// TODO: make sure id is unique!
myNewStory.setId(5);
// add the story with our story list controller!
StoryListController slc = AdventureCreatorApplication.getStoryListController();
slc.addStory(myNewStory);
// TODO discuss
// I'm changing it so that you can only create a story here
// it will return to our main screen where if they click on it it will let them edit
finish();
}
});
}
|
diff --git a/server/plugin/src/pt/webdetails/cdf/dd/packager/Concatenate.java b/server/plugin/src/pt/webdetails/cdf/dd/packager/Concatenate.java
index 0d9b8115..2bd8ace0 100644
--- a/server/plugin/src/pt/webdetails/cdf/dd/packager/Concatenate.java
+++ b/server/plugin/src/pt/webdetails/cdf/dd/packager/Concatenate.java
@@ -1,124 +1,124 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pt.webdetails.cdf.dd.packager;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.NoSuchElementException;
import org.apache.commons.lang.StringUtils;
import org.pentaho.platform.engine.core.system.PentahoSystem;
/**
*
* @author pdpi
*/
class Concatenate
{
public static InputStream concat(File[] files)
{
ListOfFiles mylist = new ListOfFiles(files);
return new SequenceInputStream(mylist);
}
public static InputStream concat(File[] files, String rootpath)
{
if (rootpath == null || StringUtils.isEmpty(rootpath))
{
return concat(files);
}
try
{
StringBuffer buffer = new StringBuffer();
for (File file : files)
{
StringBuffer tmp = new StringBuffer();
BufferedReader fr = new BufferedReader(new FileReader(file));
while (fr.ready())
{
tmp.append(fr.readLine());
}
rootpath = rootpath.replaceAll("\\\\", "/").replaceAll("/+", "/");
// Quick and dirty hack: if the path aims at the custom components, we point at getResource, else we point at the static resource folders
String fileLocation = "";
if (file.getPath().contains("resources/custom"))
{
fileLocation = file.getPath().replaceAll("\\\\", "/") // Fix windows slashes
.replaceAll(file.getName(), "") // Remove this file's name
.replaceAll(rootpath, "../"); //
//fileLocation = "";
}
buffer.append(tmp.toString() //
// We need to replace all the URL formats
- .replaceAll("(url\\(['\"]?)", "$1" + fileLocation).replaceAll("/+","/")); // Standard URLs
+ .replaceAll("(url\\(['\"]?)", "$1" + fileLocation.replaceAll("/+","/"))); // Standard URLs
//.replaceAll("(progid:DXImageTransform.Microsoft.AlphaImageLoader\\(src=')", "$1" + fileLocation + "../")); // these are IE-Only
}
return new ByteArrayInputStream(buffer.toString().getBytes("UTF8"));
}
catch (Exception e)
{
return null;
}
}
}
class ListOfFiles implements Enumeration<FileInputStream>
{
private File[] listOfFiles;
private int current = 0;
public ListOfFiles(File[] listOfFiles)
{
this.listOfFiles = listOfFiles;
}
public boolean hasMoreElements()
{
if (current < listOfFiles.length)
{
return true;
}
else
{
return false;
}
}
public FileInputStream nextElement()
{
FileInputStream in = null;
if (!hasMoreElements())
{
throw new NoSuchElementException("No more files.");
}
else
{
File nextElement = listOfFiles[current];
current++;
try
{
in = new FileInputStream(nextElement);
}
catch (FileNotFoundException e)
{
System.err.println("ListOfFiles: Can't open " + nextElement);
}
}
return in;
}
}
| true | true | public static InputStream concat(File[] files, String rootpath)
{
if (rootpath == null || StringUtils.isEmpty(rootpath))
{
return concat(files);
}
try
{
StringBuffer buffer = new StringBuffer();
for (File file : files)
{
StringBuffer tmp = new StringBuffer();
BufferedReader fr = new BufferedReader(new FileReader(file));
while (fr.ready())
{
tmp.append(fr.readLine());
}
rootpath = rootpath.replaceAll("\\\\", "/").replaceAll("/+", "/");
// Quick and dirty hack: if the path aims at the custom components, we point at getResource, else we point at the static resource folders
String fileLocation = "";
if (file.getPath().contains("resources/custom"))
{
fileLocation = file.getPath().replaceAll("\\\\", "/") // Fix windows slashes
.replaceAll(file.getName(), "") // Remove this file's name
.replaceAll(rootpath, "../"); //
//fileLocation = "";
}
buffer.append(tmp.toString() //
// We need to replace all the URL formats
.replaceAll("(url\\(['\"]?)", "$1" + fileLocation).replaceAll("/+","/")); // Standard URLs
//.replaceAll("(progid:DXImageTransform.Microsoft.AlphaImageLoader\\(src=')", "$1" + fileLocation + "../")); // these are IE-Only
}
return new ByteArrayInputStream(buffer.toString().getBytes("UTF8"));
}
catch (Exception e)
{
return null;
}
}
| public static InputStream concat(File[] files, String rootpath)
{
if (rootpath == null || StringUtils.isEmpty(rootpath))
{
return concat(files);
}
try
{
StringBuffer buffer = new StringBuffer();
for (File file : files)
{
StringBuffer tmp = new StringBuffer();
BufferedReader fr = new BufferedReader(new FileReader(file));
while (fr.ready())
{
tmp.append(fr.readLine());
}
rootpath = rootpath.replaceAll("\\\\", "/").replaceAll("/+", "/");
// Quick and dirty hack: if the path aims at the custom components, we point at getResource, else we point at the static resource folders
String fileLocation = "";
if (file.getPath().contains("resources/custom"))
{
fileLocation = file.getPath().replaceAll("\\\\", "/") // Fix windows slashes
.replaceAll(file.getName(), "") // Remove this file's name
.replaceAll(rootpath, "../"); //
//fileLocation = "";
}
buffer.append(tmp.toString() //
// We need to replace all the URL formats
.replaceAll("(url\\(['\"]?)", "$1" + fileLocation.replaceAll("/+","/"))); // Standard URLs
//.replaceAll("(progid:DXImageTransform.Microsoft.AlphaImageLoader\\(src=')", "$1" + fileLocation + "../")); // these are IE-Only
}
return new ByteArrayInputStream(buffer.toString().getBytes("UTF8"));
}
catch (Exception e)
{
return null;
}
}
|
diff --git a/c2n24.java b/c2n24.java
index e92d8a2..7726efe 100644
--- a/c2n24.java
+++ b/c2n24.java
@@ -1,49 +1,49 @@
// Aaron Zeng 20120207
import java.util.*;
import java.io.*;
public class c2n24
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
int a, b, c, d, e, min, max;
System.out.print( "Enter first integer: " );
a = input.nextInt();
min = a;
max = a;
System.out.print( "Enter second integer: " );
b = input.nextInt();
if ( b < min )
min = b;
if ( b > max )
max = b;
System.out.print( "Enter third integer: " );
c = input.nextInt();
if ( c < min )
min = c;
if ( c > max )
max = c;
System.out.print( "Enter fourth integer: " );
d = input.nextInt();
- if ( c < min )
+ if ( d < min )
min = d;
- if ( c > max )
+ if ( d > max )
max = d;
System.out.print( "Enter fifth integer: " );
e = input.nextInt();
if ( e < min )
min = e;
if ( e > max )
max = e;
System.out.printf( "Largest: %d\n", max );
System.out.printf( "Smallest: %d\n", min );
}
}
| false | true | public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
int a, b, c, d, e, min, max;
System.out.print( "Enter first integer: " );
a = input.nextInt();
min = a;
max = a;
System.out.print( "Enter second integer: " );
b = input.nextInt();
if ( b < min )
min = b;
if ( b > max )
max = b;
System.out.print( "Enter third integer: " );
c = input.nextInt();
if ( c < min )
min = c;
if ( c > max )
max = c;
System.out.print( "Enter fourth integer: " );
d = input.nextInt();
if ( c < min )
min = d;
if ( c > max )
max = d;
System.out.print( "Enter fifth integer: " );
e = input.nextInt();
if ( e < min )
min = e;
if ( e > max )
max = e;
System.out.printf( "Largest: %d\n", max );
System.out.printf( "Smallest: %d\n", min );
}
| public static void main( String[] args )
{
Scanner input = new Scanner( System.in );
int a, b, c, d, e, min, max;
System.out.print( "Enter first integer: " );
a = input.nextInt();
min = a;
max = a;
System.out.print( "Enter second integer: " );
b = input.nextInt();
if ( b < min )
min = b;
if ( b > max )
max = b;
System.out.print( "Enter third integer: " );
c = input.nextInt();
if ( c < min )
min = c;
if ( c > max )
max = c;
System.out.print( "Enter fourth integer: " );
d = input.nextInt();
if ( d < min )
min = d;
if ( d > max )
max = d;
System.out.print( "Enter fifth integer: " );
e = input.nextInt();
if ( e < min )
min = e;
if ( e > max )
max = e;
System.out.printf( "Largest: %d\n", max );
System.out.printf( "Smallest: %d\n", min );
}
|
diff --git a/src/id.java b/src/id.java
index 36ae603..24f4fda 100644
--- a/src/id.java
+++ b/src/id.java
@@ -1,1110 +1,1110 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.MinecraftServer;
public class id extends ej
implements ef {
public static Logger a = Logger.getLogger("Minecraft");
public bb b;
public boolean c = false;
private MinecraftServer d;
private ea e;
private int f = 0;
private double g;
private double h;
private double i;
private boolean j = true;
private gp k = null;
private List<String> onlyOneUseKits = new ArrayList<String>();
public id(MinecraftServer paramMinecraftServer, bb parambb, ea paramea) {
this.d = paramMinecraftServer;
this.b = parambb;
parambb.a(this);
this.e = paramea;
paramea.a = this;
}
public void a() {
this.b.a();
if (this.f++ % 20 == 0) {
this.b.a(new iz());
}
}
public void c(String paramString) {
this.b.a(new io(paramString));
this.b.c();
this.d.f.c(this.e);
this.c = true;
}
public void a(gf paramgf) {
double d1;
if (!this.j) {
d1 = paramgf.b - this.h;
if ((paramgf.a == this.g) && (d1 * d1 < 0.01D) && (paramgf.c == this.i)) {
this.j = true;
}
}
if (this.j) {
this.g = this.e.l;
this.h = this.e.m;
this.i = this.e.n;
d1 = this.e.l;
double d2 = this.e.m;
double d3 = this.e.n;
float f1 = this.e.r;
float f2 = this.e.s;
if (paramgf.h) {
d1 = paramgf.a;
d2 = paramgf.b;
d3 = paramgf.c;
double d4 = paramgf.d - paramgf.b;
if ((d4 > 1.65D) || (d4 < 0.1D)) {
c("Illegal stance");
a.warning(this.e.aq + " had an illegal stance: " + d4);
}
this.e.ai = paramgf.d;
}
if (paramgf.i) {
f1 = paramgf.e;
f2 = paramgf.f;
}
this.e.i();
this.e.M = 0.0F;
this.e.b(this.g, this.h, this.i, f1, f2);
double d4 = d1 - this.e.l;
double d5 = d2 - this.e.m;
double d6 = d3 - this.e.n;
float f3 = 0.0625F;
int m = this.d.e.a(this.e, this.e.v.b().e(f3, f3, f3)).size() == 0 ? 1 : 0;
this.e.c(d4, d5, d6);
d4 = d1 - this.e.l;
d5 = d2 - this.e.m;
if ((d5 > -0.5D) || (d5 < 0.5D)) {
d5 = 0.0D;
}
d6 = d3 - this.e.n;
double d7 = d4 * d4 + d5 * d5 + d6 * d6;
int n = 0;
if (d7 > 0.0625D) {
n = 1;
a.warning(this.e.aq + " moved wrongly!");
}
this.e.b(d1, d2, d3, f1, f2);
int i1 = this.d.e.a(this.e, this.e.v.b().e(f3, f3, f3)).size() == 0 ? 1 : 0;
if ((m != 0) && ((n != 0) || (i1 == 0))) {
a(this.g, this.h, this.i, f1, f2);
return;
}
this.e.w = paramgf.g;
this.d.f.b(this.e);
}
}
public void a(double paramDouble1, double paramDouble2, double paramDouble3, float paramFloat1, float paramFloat2) {
this.j = false;
this.g = paramDouble1;
this.h = paramDouble2;
this.i = paramDouble3;
this.e.b(paramDouble1, paramDouble2, paramDouble3, paramFloat1, paramFloat2);
this.e.a.b(new dq(paramDouble1, paramDouble2 + 1.620000004768372D, paramDouble2, paramDouble3, paramFloat1, paramFloat2, false));
}
public void a(hd paramhd) {
this.e.aj.a[this.e.aj.d] = this.k;
boolean bool = this.d.e.z = this.d.f.g(this.e.aq);
int m = 0;
if (paramhd.e == 0) {
m = 1;
}
if (paramhd.e == 1) {
m = 1;
}
if (m != 0) {
double d1 = this.e.m;
this.e.m = this.e.ai;
fr localfr = this.e.a(4.0D, 1.0F);
this.e.m = d1;
if (localfr == null) {
return;
}
if ((localfr.b != paramhd.a) || (localfr.c != paramhd.b) || (localfr.d != paramhd.c) || (localfr.e != paramhd.d)) {
return;
}
}
int n = paramhd.a;
int i1 = paramhd.b;
int i2 = paramhd.c;
int i3 = paramhd.d;
int i4 = (int) gj.e(n - this.d.e.n);
int i5 = (int) gj.e(i2 - this.d.e.p);
if (i4 > i5) {
i5 = i4;
}
if (paramhd.e == 0) {
if ((i5 > 16) || (bool)) {
this.e.ad.a(n, i1, i2);
}
} else if (paramhd.e == 2) {
this.e.ad.a();
} else if (paramhd.e == 1) {
if ((i5 > 16) || (bool)) {
this.e.ad.a(n, i1, i2, i3);
}
} else if (paramhd.e == 3) {
double d2 = this.e.l - (n + 0.5D);
double d3 = this.e.m - (i1 + 0.5D);
double d4 = this.e.n - (i2 + 0.5D);
double d5 = d2 * d2 + d3 * d3 + d4 * d4;
if (d5 < 256.0D) {
this.e.a.b(new et(n, i1, i2, this.d.e));
}
}
this.d.e.z = false;
}
public void a(fe paramfe) {
boolean bool = this.d.e.z = this.d.f.g(this.e.aq);
int m = paramfe.b;
int n = paramfe.c;
int i1 = paramfe.d;
int i2 = paramfe.e;
int i3 = (int) gj.e(m - this.d.e.n);
int i4 = (int) gj.e(i1 - this.d.e.p);
if (i3 > i4) {
i4 = i3;
}
if ((i4 > 16) || (bool)) {
gp localgp = paramfe.a >= 0 ? new gp(paramfe.a) : null;
this.e.ad.a(this.e, this.d.e, localgp, m, n, i1, i2);
}
this.e.a.b(new et(m, n, i1, this.d.e));
this.d.e.z = false;
}
/*public void a(hd paramhd) {
if (!etc.getInstance().canBuild(e)) {
return;
}
this.e.aj.a[this.e.aj.d] = this.k;
boolean bool = this.d.f.g(this.e.aq) || etc.getInstance().isAdmin(e);
this.d.e.x = true;
int m = 0;
if (paramhd.e == 0) {
m = 1;
}
if (paramhd.e == 1) {
m = 1;
}
if (m != 0) {
double d1 = this.e.m;
this.e.m = this.e.ai;
fr localfr = this.e.a(4.0D, 1.0F);
this.e.m = d1;
if (localfr == null) {
return;
}
//TODO: Figure out what this is. They're accessing private variables, so wtf?
//if ((localfr.b != paramhd.a) || (localfr.c != paramhd.b) || (localfr.d != paramhd.c) || (localfr.e != paramhd.d)) {
//return;
//}
}
int n = paramhd.a;
int i1 = paramhd.b;
int i2 = paramhd.c;
int i3 = paramhd.d;
int i4 = (int) gj.e(n - this.d.e.n);
int i5 = (int) gj.e(i2 - this.d.e.p);
if (i4 > i5) {
i5 = i4;
}
if (paramhd.e == 0) {
if (i5 > etc.getInstance().spawnProtectionSize || bool) {
this.e.ad.a(n, i1, i2);
}
} else if (paramhd.e == 2) {
this.e.ad.a();
} else if (paramhd.e == 1) {
if (i5 > etc.getInstance().spawnProtectionSize || bool) {
this.e.ad.a(n, i1, i2, i3);
}
} else if (paramhd.e == 3) {
double d2 = this.e.l - (n + 0.5D);
double d3 = this.e.m - (i1 + 0.5D);
double d4 = this.e.n - (i2 + 0.5D);
double d5 = d2 * d2 + d3 * d3 + d4 * d4;
if (d5 < 256.0D) {
this.e.a.b(new et(n, i1, i2, this.d.e));
}
}
this.d.e.z = false;
}
public void a(fe paramfe) {
if (!etc.getInstance().canBuild(e)) {
return;
}
boolean bool = this.d.f.g(this.e.aq) || etc.getInstance().isAdmin(e);
this.d.e.z = true;
int m = paramfe.b;
int n = paramfe.c;
int i1 = paramfe.d;
int i2 = paramfe.e;
int i3 = (int) gj.e(m - this.d.e.n);
int i4 = (int) gj.e(i1 - this.d.e.p);
if (i3 > i4) {
i4 = i3;
}
if (i4 > etc.getInstance().spawnProtectionSize || bool) {
gp localgp = paramfe.a >= 0 ? new gp(paramfe.a) : null;
if (localgp != null) {
if (!etc.getInstance().isOnItemBlacklist(localgp.c) || bool) {
this.e.ad.a(this.e, this.d.e, localgp, m, n, i1, i2);
}
} else {
// is this right?
this.e.ad.a(this.e, this.d.e, localgp, m, n, i1, i2);
}
}
this.e.a.b(new et(m, n, i1, this.d.e));
this.d.e.z = false;
}*/
public void a(String paramString) {
a.info(this.e.aq + " lost connection: " + paramString);
this.d.f.c(this.e);
this.c = true;
}
public void a(hp paramhp) {
a.warning(getClass() + " wasn't prepared to deal with a " + paramhp.getClass());
c("Protocol error, unexpected packet");
}
public void b(hp paramhp) {
this.b.a(paramhp);
}
public void a(fv paramfv) {
int m = paramfv.b;
this.e.aj.d = (this.e.aj.a.length - 1);
if (m == 0) {
this.k = null;
} else {
this.k = new gp(m);
}
this.e.aj.a[this.e.aj.d] = this.k;
this.d.k.a(this.e, new fv(this.e.c, m));
}
public void a(k paramk) {
double d1 = paramk.b / 32.0D;
double d2 = paramk.c / 32.0D;
double d3 = paramk.d / 32.0D;
fn localfn = new fn(this.d.e, d1, d2, d3, new gp(paramk.h, paramk.i));
localfn.o = (paramk.e / 128.0D);
localfn.p = (paramk.f / 128.0D);
localfn.q = (paramk.g / 128.0D);
localfn.ad = 10;
this.d.e.a(localfn);
}
public void a(ba paramba) {
String str = paramba.a;
if (str.length() > 100) {
b("Chat message too long");
return;
}
str = str.trim();
for (int k = 0; k < str.length(); ++k) {
if (" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_'abcdefghijklmnopqrstuvwxyz{|}~¦ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñѪº¿®¬½¼¡«»".indexOf(str.charAt(k)) < 0) {
b("Illegal characters in chat");
return;
}
}
if (str.startsWith("/")) {
d(str);
} else {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String message = "<" + etc.getInstance().getUserColor(e.aq) + this.e.aq + Colors.White + "> " + str;
a.log(Level.INFO, "<" + e.aq + "> " + str);
this.d.f.a(new ba(message));
}
}
private ea match(String name) {
ea player = null;
boolean found = false;
if (("`" + this.d.f.c().toUpperCase() + "`").split(name.toUpperCase()).length == 2) {
for (int i = 0; i < this.d.f.b.size() && !found; ++i) {
ea localea = (ea) this.d.f.b.get(i);
if (("`" + localea.aq.toUpperCase() + "`").split(name.toUpperCase()).length == 2) {
player = localea;
found = true;
}
}
} else if (("`" + this.d.f.c() + "`").split(name).length > 2) {
// Too many partial matches.
for (int i = 0; i < this.d.f.b.size() && !found; ++i) {
ea localea = (ea) this.d.f.b.get(i);
if (localea.aq.equalsIgnoreCase(name)) {
player = localea;
found = true;
}
}
}
return player;
}
public static String combineSplit(int startIndex, String[] string, String seperator) {
StringBuilder builder = new StringBuilder();
for (int i = startIndex; i < string.length; i++) {
builder.append(string[i]);
builder.append(seperator);
}
builder.deleteCharAt(builder.length() - seperator.length()); // remove the extra
// seperator
return builder.toString();
}
public boolean hasControlOver(ea player) {
boolean isInGroup = false;
if (etc.getInstance().getUser(player.aq) != null) {
for (String str : etc.getInstance().getUser(player.aq).Groups) {
if (etc.getInstance().isUserInGroup(e, str)) {
isInGroup = true;
}
}
} else {
return true;
}
return isInGroup;
}
public void msg(String msg) {
b(new ba(msg));
}
private void d(String paramString) {
try {
String[] split = paramString.split(" ");
if (!etc.getInstance().canUseCommand(e.aq, split[0]) && !split[0].startsWith("/#")) {
msg(Colors.Rose + "Unknown command.");
return;
}
if (split[0].equalsIgnoreCase("/help")) {
//Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().commands.entrySet()) {
if (etc.getInstance().canUseCommand(e.aq, entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getInstance().getDataSource().hasKits()) {
continue;
}
if (entry.getKey().equals("/listwarps") && !etc.getInstance().getDataSource().hasWarps()) {
continue;
}
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
}
msg(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2) {
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0) {
amount = (amount - 1) * 7;
} else {
amount = 0;
}
for (int i = amount; i < amount + 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
} catch (NumberFormatException ex) {
msg(Colors.Rose + "Not a valid page number.");
}
} else {
for (int i = 0; i < 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
}
} else if (split[0].equalsIgnoreCase("/reload")) {
etc.getInstance().load();
etc.getInstance().loadData();
a.info("Reloaded config");
msg("Successfuly reloaded config");
} else if ((split[0].equalsIgnoreCase("/modify") || split[0].equalsIgnoreCase("/mp"))) {
if (split.length < 4) {
msg(Colors.Rose + "Usage is: /modify [player] [key] [value]");
msg(Colors.Rose + "Keys:");
msg(Colors.Rose + "prefix: only the letter the color represents");
msg(Colors.Rose + "commands: list seperated by comma");
msg(Colors.Rose + "groups: list seperated by comma");
msg(Colors.Rose + "ignoresrestrictions: true or false");
msg(Colors.Rose + "admin: true or false");
msg(Colors.Rose + "modworld: true or false");
return;
}
ea player = match(split[1]);
if (player == null) {
msg(Colors.Rose + "Player does not exist.");
return;
}
String key = split[2];
String value = split[3];
User user = etc.getInstance().getUser(split[1]);
boolean newUser = false;
if (user == null) {
if (!key.equalsIgnoreCase("groups") && !key.equalsIgnoreCase("g")) {
msg(Colors.Rose + "When adding a new user, set their group(s) first.");
return;
}
msg(Colors.Rose + "Adding new user.");
newUser = true;
user = new User();
user.Name = split[1];
user.Administrator = false;
user.CanModifyWorld = true;
user.IgnoreRestrictions = false;
user.Commands = new String[]{""};
user.Prefix = "";
}
if (key.equalsIgnoreCase("prefix") || key.equalsIgnoreCase("p")) {
user.Prefix = value;
} else if (key.equalsIgnoreCase("commands") || key.equalsIgnoreCase("c")) {
user.Commands = value.split(",");
} else if (key.equalsIgnoreCase("groups") || key.equalsIgnoreCase("g")) {
user.Groups = value.split(",");
} else if (key.equalsIgnoreCase("ignoresrestrictions") || key.equalsIgnoreCase("ir")) {
user.IgnoreRestrictions = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("admin") || key.equalsIgnoreCase("a")) {
user.Administrator = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("modworld") || key.equalsIgnoreCase("mw")) {
user.CanModifyWorld = value.equalsIgnoreCase("true") || value.equals("1");
}
if (newUser) {
etc.getInstance().getDataSource().addUser(user);
} else {
etc.getInstance().getDataSource().modifyUser(user);
}
msg(Colors.Rose + "Modified user.");
a.info("Modifed user " + split[1] + ". " + key + " => " + value + " by " + e.aq);
} else if (split[0].equalsIgnoreCase("/whitelist")) {
if (split.length != 3) {
msg(Colors.Rose + "whitelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToWhitelist(split[2]);
msg(Colors.Rose + split[2] + " added to whitelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromWhitelist(split[2]);
msg(Colors.Rose + split[2] + " removed from whitelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/reservelist")) {
if (split.length != 3) {
msg(Colors.Rose + "reservelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToReserveList(split[2]);
msg(Colors.Rose + split[2] + " added to reservelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromReserveList(split[2]);
msg(Colors.Rose + split[2] + " removed from reservelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/mute")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
ea player = match(split[1]);
if (player != null) {
if (etc.getInstance().toggleMute(player)) {
msg(Colors.Rose + "player was muted");
} else {
msg(Colors.Rose + "player was unmuted");
}
} else {
msg(Colors.Rose + "Can't find player " + split[1]);
}
} else if ((split[0].equalsIgnoreCase("/msg") || split[0].equalsIgnoreCase("/tell")) || split[0].equalsIgnoreCase("/m")) {
if (split.length < 3) {
msg(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (player.aq.equals(e.aq)) {
msg(Colors.Rose + "You can't message yourself!");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
player.a.msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
} else {
msg(Colors.Rose + "Couldn't find player " + split[1]);
}
} else if (split[0].equalsIgnoreCase("/kit") && etc.getInstance().getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available kits: " + Colors.White + etc.getInstance().getDataSource().getKitNames(e.aq));
return;
}
ea toGive = e;
if (split.length > 2 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[1]);
}
Kit kit = etc.getInstance().getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!etc.getInstance().isUserInGroup(e, kit.Group) && !kit.Group.equals("")) {
msg(Colors.Rose + "That kit does not exist.");
} else if (onlyOneUseKits.contains(kit.Name)) {
msg(Colors.Rose + "You can only get this kit once per login.");
} else if (MinecraftServer.b.containsKey(this.e.aq + " " + kit.Name)) {
msg(Colors.Rose + "You can't get this kit again for a while.");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
if (kit.Delay >= 0) {
MinecraftServer.b.put(this.e.aq + " " + kit.Name, kit.Delay);
} else {
onlyOneUseKits.add(kit.Name);
}
}
a.info(this.e.aq + " got a kit!");
toGive.a.msg(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet()) {
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getInstance().getDataSource().getItem(entry.getKey());
}
int temp = kit.IDs.get(entry.getKey());
do {
if (temp - 64 >= 64) {
toGive.a(new gp(itemId, 64));
} else {
toGive.a(new gp(itemId, temp));
}
temp -= 64;
} while (temp >= 64);
} catch (Exception e1) {
a.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
msg(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
}
} else {
msg(Colors.Rose + "That kit does not exist.");
}
} else {
msg(Colors.Rose + "That user does not exist.");
}
} else if (split[0].equalsIgnoreCase("/tp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "You're already here!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported to " + player.aq);
a(player.l, player.m, player.n, player.r, player.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if ((split[0].equalsIgnoreCase("/tphere") || split[0].equalsIgnoreCase("/s"))) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported " + player.aq + " to their self.");
player.a.a(e.l, e.m, e.n, e.r, e.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/playerlist") || split[0].equalsIgnoreCase("/who")) {
msg(Colors.Rose + "Player list (" + d.f.b.size() + "/" + etc.getInstance().playerLimit + "): " + Colors.White + d.f.c());
} else if (split[0].equalsIgnoreCase("/item") || split[0].equalsIgnoreCase("/i") || split[0].equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount> <player> (optional)");
} else {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount>");
}
return;
}
ea toGive = e;
if (split.length == 4 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[3]);
}
if (toGive != null) {
try {
int i2 = 0;
try {
i2 = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
i2 = etc.getInstance().getDataSource().getItem(split[1]);
}
int i3 = 1;
if (split.length > 2) {
i3 = Integer.parseInt(split[2]);
}
String i2str = Integer.toString(i2);
if (i3 <= 0) {
i3 = 1;
}
if (i3 > 64 && !etc.getInstance().canIgnoreRestrictions(this.e)) {
i3 = 64;
}
boolean allowedItem = false;
if (!etc.getInstance().allowedItems[0].equals("") && (!etc.getInstance().canIgnoreRestrictions(this.e))) {
for (String str : etc.getInstance().allowedItems) {
if (i2str.equals(str)) {
allowedItem = true;
}
}
} else {
allowedItem = true;
}
if (!etc.getInstance().disallowedItems[0].equals("") && !etc.getInstance().canIgnoreRestrictions(this.e)) {
for (String str : etc.getInstance().disallowedItems) {
if (i2str.equals(str)) {
allowedItem = false;
}
}
}
- if (i2 < ff.n.length) {
- if (ff.n[i2] != null && (allowedItem || etc.getInstance().canIgnoreRestrictions(this.e))) {
+ if (i2 < ez.c.length) {
+ if (ez.c[i2] != null && (allowedItem || etc.getInstance().canIgnoreRestrictions(this.e))) {
a.log(Level.INFO, "Giving " + toGive.aq + " some " + i2);
int temp = i3;
do {
if (temp - 64 >= 64) {
toGive.a(new gp(i2, 64));
} else {
toGive.a(new gp(i2, temp));
}
temp -= 64;
} while (temp >= 64);
if (toGive == this.e) {
msg(Colors.Rose + "There you go c:");
} else {
msg(Colors.Rose + "Gift given! :D");
toGive.a.msg(Colors.Rose + "Enjoy your gift! :D");
}
- } else if ((!allowedItem) && (ff.n[i2] != null) && !etc.getInstance().canIgnoreRestrictions(this.e)) {
+ } else if ((!allowedItem) && (ez.c[i2] != null) && !etc.getInstance().canIgnoreRestrictions(this.e)) {
msg(Colors.Rose + "You are not allowed to spawn that item.");
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} catch (NumberFormatException localNumberFormatException) {
msg(Colors.Rose + "Improper ID and/or amount.");
}
} else {
msg(Colors.Rose + "Can't find user " + split[3]);
}
} else if (split[0].equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2) {
if (split[1].equalsIgnoreCase("ips")) {
type = 1;
}
}
if (type == 0) { //Regular user bans
msg(Colors.Blue + "Ban list:" + Colors.White + " " + d.f.getBans());
} else { //IP bans
msg(Colors.Blue + "IP Ban list:" + Colors.White + " " + d.f.getBans());
}
} else if (split[0].equalsIgnoreCase("/banip")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.c(player.a.b.b().toString());
a.log(Level.INFO, "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
msg(Colors.Rose + "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
if (split.length > 2) {
player.a.c("IP Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("IP Banned by " + e.aq + ".");
}
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/ban")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.a(player.aq);
if (split.length > 2) {
player.a.c("Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Banned by " + e.aq + ".");
}
a.log(Level.INFO, "Banning " + player.aq);
msg(Colors.Rose + "Banning " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/unban")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
this.d.f.b(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
this.d.f.d(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/kick")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't kick that user.");
return;
}
if (split.length > 2) {
player.a.c("Kicked by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Kicked by " + e.aq + ".");
}
a.log(Level.INFO, "Kicking " + player.aq);
msg(Colors.Rose + "Kicking " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/me")) {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
String paramString2 = "* " + prefix + this.e.aq + Colors.White + " " + paramString.substring(paramString.indexOf(" ")).trim();
a.info("* " + this.e.aq + " " + paramString.substring(paramString.indexOf(" ")).trim());
this.d.f.a(new ba(paramString2));
} else if (split[0].equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp home = new Warp();
home.Location = loc;
home.Group = ""; //no group neccessary, lol.
home.Name = e.aq;
etc.getInstance().changeHome(home);
msg(Colors.Rose + "Your home has been set.");
} else if (split[0].equalsIgnoreCase("/spawn")) {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
} else if (split[0].equalsIgnoreCase("/setspawn")) {
this.d.e.n = (int) Math.ceil(e.l);
//Too lazy to actually update this considering it's not even used anyways.
//this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis really matters since it tries to get the highest point iirc.
this.d.e.p = (int) Math.ceil(e.n);
a.info("Spawn position changed.");
msg(Colors.Rose + "You have set the spawn to your current position.");
} else if (split[0].equalsIgnoreCase("/home")) {
a.info(this.e.aq + " returned home");
Warp home = etc.getInstance().getDataSource().getHome(e.aq);
if (home != null) {
a(home.Location.x, home.Location.y, home.Location.z, home.Location.rotX, home.Location.rotY);
} else {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
}
} else if (split[0].equalsIgnoreCase("/warp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
ea toWarp = e;
Warp warp = null;
if (split.length == 3 && etc.getInstance().canIgnoreRestrictions(e)) {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
toWarp = match(split[2]);
} else {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
}
if (toWarp != null) {
if (warp != null) {
if (!etc.getInstance().isUserInGroup(e, warp.Group) && !warp.Group.equals("")) {
msg(Colors.Rose + "Warp not found.");
} else {
toWarp.a.a(warp.Location.x, warp.Location.y, warp.Location.z, warp.Location.rotX, warp.Location.rotY);
toWarp.a.msg(Colors.Rose + "Woosh!");
}
} else {
msg(Colors.Rose + "Warp not found");
}
} else {
msg(Colors.Rose + "Player not found.");
}
} else if (split[0].equalsIgnoreCase("/listwarps") && etc.getInstance().getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available warps: " + Colors.White + etc.getInstance().getDataSource().getWarpNames(e.aq));
return;
}
} else if (split[0].equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
} else {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname]");
}
return;
}
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = loc;
if (split.length == 3) {
warp.Group = split[2];
} else {
warp.Group = "";
}
etc.getInstance().setWarp(warp);
msg(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (split[0].equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(this.e.aq + " lighter")) {
a.info(this.e.aq + " failed to iron!");
msg(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
MinecraftServer.b.put(this.e.aq + " lighter", Integer.valueOf(6000));
}
a.info(this.e.aq + " created a lighter!");
this.e.a(new gp(259, 1));
}
} else if ((paramString.startsWith("/#")) && (this.d.f.g(this.e.aq))) {
String str = paramString.substring(2);
a.info(this.e.aq + " issued server command: " + str);
this.d.a(str, this);
} else if (split[0].equalsIgnoreCase("/time")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /time [time|day|night]");
return;
}
if (split[1].equalsIgnoreCase("day")) {
this.d.e.c = 0; //morning.
} else if (split[1].equalsIgnoreCase("night")) {
this.d.e.c = 500000; //approx value for midnight basically
} else {
try {
this.d.e.c = Long.parseLong(split[1]);
} catch (NumberFormatException e) {
msg(Colors.Rose + "Please enter numbers, not letters.");
}
}
} else if (split[0].equalsIgnoreCase("/getpos")) {
msg("Pos X: " + e.k + " Y: " + e.l + " Z " + e.m);
msg("Rotation X: " + e.q + " Y: " + e.r);
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (split[0].equalsIgnoreCase("/compass")) {
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (split[0].equalsIgnoreCase("/motd")) {
for (String str : etc.getInstance().motd) {
msg(str);
}
} else {
a.info(this.e.aq + " tried command " + paramString);
msg(Colors.Rose + "Unknown command");
}
} catch (Exception ex) {
a.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (etc.getInstance().isAdmin(e)) {
msg(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
}
public void a(o paramo) {
if (paramo.b == 1) {
this.e.y();
}
}
public void a(io paramio) {
this.b.a("Quitting");
}
public int b() {
return this.b.d();
}
public void b(String paramString) {
b(new ba("§7" + paramString));
}
public String c() {
return this.e.aq;
}
public void a(r paramr) {
if (paramr.a == -1) {
this.e.aj.a = paramr.b;
}
if (paramr.a == -2) {
this.e.aj.c = paramr.b;
}
if (paramr.a == -3) {
this.e.aj.b = paramr.b;
}
}
public void d() {
this.b.a(new r(-1, this.e.aj.a));
this.b.a(new r(-2, this.e.aj.c));
this.b.a(new r(-3, this.e.aj.b));
}
public void a(ib paramib) {
as localas = this.d.e.k(paramib.a, paramib.b, paramib.c);
if (localas != null) {
localas.a(paramib.e);
localas.c();
}
}
}
| false | true | private void d(String paramString) {
try {
String[] split = paramString.split(" ");
if (!etc.getInstance().canUseCommand(e.aq, split[0]) && !split[0].startsWith("/#")) {
msg(Colors.Rose + "Unknown command.");
return;
}
if (split[0].equalsIgnoreCase("/help")) {
//Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().commands.entrySet()) {
if (etc.getInstance().canUseCommand(e.aq, entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getInstance().getDataSource().hasKits()) {
continue;
}
if (entry.getKey().equals("/listwarps") && !etc.getInstance().getDataSource().hasWarps()) {
continue;
}
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
}
msg(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2) {
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0) {
amount = (amount - 1) * 7;
} else {
amount = 0;
}
for (int i = amount; i < amount + 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
} catch (NumberFormatException ex) {
msg(Colors.Rose + "Not a valid page number.");
}
} else {
for (int i = 0; i < 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
}
} else if (split[0].equalsIgnoreCase("/reload")) {
etc.getInstance().load();
etc.getInstance().loadData();
a.info("Reloaded config");
msg("Successfuly reloaded config");
} else if ((split[0].equalsIgnoreCase("/modify") || split[0].equalsIgnoreCase("/mp"))) {
if (split.length < 4) {
msg(Colors.Rose + "Usage is: /modify [player] [key] [value]");
msg(Colors.Rose + "Keys:");
msg(Colors.Rose + "prefix: only the letter the color represents");
msg(Colors.Rose + "commands: list seperated by comma");
msg(Colors.Rose + "groups: list seperated by comma");
msg(Colors.Rose + "ignoresrestrictions: true or false");
msg(Colors.Rose + "admin: true or false");
msg(Colors.Rose + "modworld: true or false");
return;
}
ea player = match(split[1]);
if (player == null) {
msg(Colors.Rose + "Player does not exist.");
return;
}
String key = split[2];
String value = split[3];
User user = etc.getInstance().getUser(split[1]);
boolean newUser = false;
if (user == null) {
if (!key.equalsIgnoreCase("groups") && !key.equalsIgnoreCase("g")) {
msg(Colors.Rose + "When adding a new user, set their group(s) first.");
return;
}
msg(Colors.Rose + "Adding new user.");
newUser = true;
user = new User();
user.Name = split[1];
user.Administrator = false;
user.CanModifyWorld = true;
user.IgnoreRestrictions = false;
user.Commands = new String[]{""};
user.Prefix = "";
}
if (key.equalsIgnoreCase("prefix") || key.equalsIgnoreCase("p")) {
user.Prefix = value;
} else if (key.equalsIgnoreCase("commands") || key.equalsIgnoreCase("c")) {
user.Commands = value.split(",");
} else if (key.equalsIgnoreCase("groups") || key.equalsIgnoreCase("g")) {
user.Groups = value.split(",");
} else if (key.equalsIgnoreCase("ignoresrestrictions") || key.equalsIgnoreCase("ir")) {
user.IgnoreRestrictions = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("admin") || key.equalsIgnoreCase("a")) {
user.Administrator = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("modworld") || key.equalsIgnoreCase("mw")) {
user.CanModifyWorld = value.equalsIgnoreCase("true") || value.equals("1");
}
if (newUser) {
etc.getInstance().getDataSource().addUser(user);
} else {
etc.getInstance().getDataSource().modifyUser(user);
}
msg(Colors.Rose + "Modified user.");
a.info("Modifed user " + split[1] + ". " + key + " => " + value + " by " + e.aq);
} else if (split[0].equalsIgnoreCase("/whitelist")) {
if (split.length != 3) {
msg(Colors.Rose + "whitelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToWhitelist(split[2]);
msg(Colors.Rose + split[2] + " added to whitelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromWhitelist(split[2]);
msg(Colors.Rose + split[2] + " removed from whitelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/reservelist")) {
if (split.length != 3) {
msg(Colors.Rose + "reservelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToReserveList(split[2]);
msg(Colors.Rose + split[2] + " added to reservelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromReserveList(split[2]);
msg(Colors.Rose + split[2] + " removed from reservelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/mute")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
ea player = match(split[1]);
if (player != null) {
if (etc.getInstance().toggleMute(player)) {
msg(Colors.Rose + "player was muted");
} else {
msg(Colors.Rose + "player was unmuted");
}
} else {
msg(Colors.Rose + "Can't find player " + split[1]);
}
} else if ((split[0].equalsIgnoreCase("/msg") || split[0].equalsIgnoreCase("/tell")) || split[0].equalsIgnoreCase("/m")) {
if (split.length < 3) {
msg(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (player.aq.equals(e.aq)) {
msg(Colors.Rose + "You can't message yourself!");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
player.a.msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
} else {
msg(Colors.Rose + "Couldn't find player " + split[1]);
}
} else if (split[0].equalsIgnoreCase("/kit") && etc.getInstance().getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available kits: " + Colors.White + etc.getInstance().getDataSource().getKitNames(e.aq));
return;
}
ea toGive = e;
if (split.length > 2 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[1]);
}
Kit kit = etc.getInstance().getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!etc.getInstance().isUserInGroup(e, kit.Group) && !kit.Group.equals("")) {
msg(Colors.Rose + "That kit does not exist.");
} else if (onlyOneUseKits.contains(kit.Name)) {
msg(Colors.Rose + "You can only get this kit once per login.");
} else if (MinecraftServer.b.containsKey(this.e.aq + " " + kit.Name)) {
msg(Colors.Rose + "You can't get this kit again for a while.");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
if (kit.Delay >= 0) {
MinecraftServer.b.put(this.e.aq + " " + kit.Name, kit.Delay);
} else {
onlyOneUseKits.add(kit.Name);
}
}
a.info(this.e.aq + " got a kit!");
toGive.a.msg(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet()) {
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getInstance().getDataSource().getItem(entry.getKey());
}
int temp = kit.IDs.get(entry.getKey());
do {
if (temp - 64 >= 64) {
toGive.a(new gp(itemId, 64));
} else {
toGive.a(new gp(itemId, temp));
}
temp -= 64;
} while (temp >= 64);
} catch (Exception e1) {
a.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
msg(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
}
} else {
msg(Colors.Rose + "That kit does not exist.");
}
} else {
msg(Colors.Rose + "That user does not exist.");
}
} else if (split[0].equalsIgnoreCase("/tp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "You're already here!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported to " + player.aq);
a(player.l, player.m, player.n, player.r, player.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if ((split[0].equalsIgnoreCase("/tphere") || split[0].equalsIgnoreCase("/s"))) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported " + player.aq + " to their self.");
player.a.a(e.l, e.m, e.n, e.r, e.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/playerlist") || split[0].equalsIgnoreCase("/who")) {
msg(Colors.Rose + "Player list (" + d.f.b.size() + "/" + etc.getInstance().playerLimit + "): " + Colors.White + d.f.c());
} else if (split[0].equalsIgnoreCase("/item") || split[0].equalsIgnoreCase("/i") || split[0].equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount> <player> (optional)");
} else {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount>");
}
return;
}
ea toGive = e;
if (split.length == 4 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[3]);
}
if (toGive != null) {
try {
int i2 = 0;
try {
i2 = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
i2 = etc.getInstance().getDataSource().getItem(split[1]);
}
int i3 = 1;
if (split.length > 2) {
i3 = Integer.parseInt(split[2]);
}
String i2str = Integer.toString(i2);
if (i3 <= 0) {
i3 = 1;
}
if (i3 > 64 && !etc.getInstance().canIgnoreRestrictions(this.e)) {
i3 = 64;
}
boolean allowedItem = false;
if (!etc.getInstance().allowedItems[0].equals("") && (!etc.getInstance().canIgnoreRestrictions(this.e))) {
for (String str : etc.getInstance().allowedItems) {
if (i2str.equals(str)) {
allowedItem = true;
}
}
} else {
allowedItem = true;
}
if (!etc.getInstance().disallowedItems[0].equals("") && !etc.getInstance().canIgnoreRestrictions(this.e)) {
for (String str : etc.getInstance().disallowedItems) {
if (i2str.equals(str)) {
allowedItem = false;
}
}
}
if (i2 < ff.n.length) {
if (ff.n[i2] != null && (allowedItem || etc.getInstance().canIgnoreRestrictions(this.e))) {
a.log(Level.INFO, "Giving " + toGive.aq + " some " + i2);
int temp = i3;
do {
if (temp - 64 >= 64) {
toGive.a(new gp(i2, 64));
} else {
toGive.a(new gp(i2, temp));
}
temp -= 64;
} while (temp >= 64);
if (toGive == this.e) {
msg(Colors.Rose + "There you go c:");
} else {
msg(Colors.Rose + "Gift given! :D");
toGive.a.msg(Colors.Rose + "Enjoy your gift! :D");
}
} else if ((!allowedItem) && (ff.n[i2] != null) && !etc.getInstance().canIgnoreRestrictions(this.e)) {
msg(Colors.Rose + "You are not allowed to spawn that item.");
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} catch (NumberFormatException localNumberFormatException) {
msg(Colors.Rose + "Improper ID and/or amount.");
}
} else {
msg(Colors.Rose + "Can't find user " + split[3]);
}
} else if (split[0].equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2) {
if (split[1].equalsIgnoreCase("ips")) {
type = 1;
}
}
if (type == 0) { //Regular user bans
msg(Colors.Blue + "Ban list:" + Colors.White + " " + d.f.getBans());
} else { //IP bans
msg(Colors.Blue + "IP Ban list:" + Colors.White + " " + d.f.getBans());
}
} else if (split[0].equalsIgnoreCase("/banip")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.c(player.a.b.b().toString());
a.log(Level.INFO, "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
msg(Colors.Rose + "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
if (split.length > 2) {
player.a.c("IP Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("IP Banned by " + e.aq + ".");
}
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/ban")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.a(player.aq);
if (split.length > 2) {
player.a.c("Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Banned by " + e.aq + ".");
}
a.log(Level.INFO, "Banning " + player.aq);
msg(Colors.Rose + "Banning " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/unban")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
this.d.f.b(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
this.d.f.d(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/kick")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't kick that user.");
return;
}
if (split.length > 2) {
player.a.c("Kicked by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Kicked by " + e.aq + ".");
}
a.log(Level.INFO, "Kicking " + player.aq);
msg(Colors.Rose + "Kicking " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/me")) {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
String paramString2 = "* " + prefix + this.e.aq + Colors.White + " " + paramString.substring(paramString.indexOf(" ")).trim();
a.info("* " + this.e.aq + " " + paramString.substring(paramString.indexOf(" ")).trim());
this.d.f.a(new ba(paramString2));
} else if (split[0].equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp home = new Warp();
home.Location = loc;
home.Group = ""; //no group neccessary, lol.
home.Name = e.aq;
etc.getInstance().changeHome(home);
msg(Colors.Rose + "Your home has been set.");
} else if (split[0].equalsIgnoreCase("/spawn")) {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
} else if (split[0].equalsIgnoreCase("/setspawn")) {
this.d.e.n = (int) Math.ceil(e.l);
//Too lazy to actually update this considering it's not even used anyways.
//this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis really matters since it tries to get the highest point iirc.
this.d.e.p = (int) Math.ceil(e.n);
a.info("Spawn position changed.");
msg(Colors.Rose + "You have set the spawn to your current position.");
} else if (split[0].equalsIgnoreCase("/home")) {
a.info(this.e.aq + " returned home");
Warp home = etc.getInstance().getDataSource().getHome(e.aq);
if (home != null) {
a(home.Location.x, home.Location.y, home.Location.z, home.Location.rotX, home.Location.rotY);
} else {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
}
} else if (split[0].equalsIgnoreCase("/warp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
ea toWarp = e;
Warp warp = null;
if (split.length == 3 && etc.getInstance().canIgnoreRestrictions(e)) {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
toWarp = match(split[2]);
} else {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
}
if (toWarp != null) {
if (warp != null) {
if (!etc.getInstance().isUserInGroup(e, warp.Group) && !warp.Group.equals("")) {
msg(Colors.Rose + "Warp not found.");
} else {
toWarp.a.a(warp.Location.x, warp.Location.y, warp.Location.z, warp.Location.rotX, warp.Location.rotY);
toWarp.a.msg(Colors.Rose + "Woosh!");
}
} else {
msg(Colors.Rose + "Warp not found");
}
} else {
msg(Colors.Rose + "Player not found.");
}
} else if (split[0].equalsIgnoreCase("/listwarps") && etc.getInstance().getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available warps: " + Colors.White + etc.getInstance().getDataSource().getWarpNames(e.aq));
return;
}
} else if (split[0].equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
} else {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname]");
}
return;
}
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = loc;
if (split.length == 3) {
warp.Group = split[2];
} else {
warp.Group = "";
}
etc.getInstance().setWarp(warp);
msg(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (split[0].equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(this.e.aq + " lighter")) {
a.info(this.e.aq + " failed to iron!");
msg(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
MinecraftServer.b.put(this.e.aq + " lighter", Integer.valueOf(6000));
}
a.info(this.e.aq + " created a lighter!");
this.e.a(new gp(259, 1));
}
} else if ((paramString.startsWith("/#")) && (this.d.f.g(this.e.aq))) {
String str = paramString.substring(2);
a.info(this.e.aq + " issued server command: " + str);
this.d.a(str, this);
} else if (split[0].equalsIgnoreCase("/time")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /time [time|day|night]");
return;
}
if (split[1].equalsIgnoreCase("day")) {
this.d.e.c = 0; //morning.
} else if (split[1].equalsIgnoreCase("night")) {
this.d.e.c = 500000; //approx value for midnight basically
} else {
try {
this.d.e.c = Long.parseLong(split[1]);
} catch (NumberFormatException e) {
msg(Colors.Rose + "Please enter numbers, not letters.");
}
}
} else if (split[0].equalsIgnoreCase("/getpos")) {
msg("Pos X: " + e.k + " Y: " + e.l + " Z " + e.m);
msg("Rotation X: " + e.q + " Y: " + e.r);
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (split[0].equalsIgnoreCase("/compass")) {
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (split[0].equalsIgnoreCase("/motd")) {
for (String str : etc.getInstance().motd) {
msg(str);
}
} else {
a.info(this.e.aq + " tried command " + paramString);
msg(Colors.Rose + "Unknown command");
}
} catch (Exception ex) {
a.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (etc.getInstance().isAdmin(e)) {
msg(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
}
| private void d(String paramString) {
try {
String[] split = paramString.split(" ");
if (!etc.getInstance().canUseCommand(e.aq, split[0]) && !split[0].startsWith("/#")) {
msg(Colors.Rose + "Unknown command.");
return;
}
if (split[0].equalsIgnoreCase("/help")) {
//Meh, not the greatest way, but not the worst either.
List<String> availableCommands = new ArrayList<String>();
for (Entry<String, String> entry : etc.getInstance().commands.entrySet()) {
if (etc.getInstance().canUseCommand(e.aq, entry.getKey())) {
if (entry.getKey().equals("/kit") && !etc.getInstance().getDataSource().hasKits()) {
continue;
}
if (entry.getKey().equals("/listwarps") && !etc.getInstance().getDataSource().hasWarps()) {
continue;
}
availableCommands.add(entry.getKey() + " " + entry.getValue());
}
}
msg(Colors.Blue + "Available commands (Page " + (split.length == 2 ? split[1] : "1") + " of " + (int) Math.ceil((double) availableCommands.size() / (double) 7) + ") [] = required <> = optional:");
if (split.length == 2) {
try {
int amount = Integer.parseInt(split[1]);
if (amount > 0) {
amount = (amount - 1) * 7;
} else {
amount = 0;
}
for (int i = amount; i < amount + 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
} catch (NumberFormatException ex) {
msg(Colors.Rose + "Not a valid page number.");
}
} else {
for (int i = 0; i < 7; i++) {
if (availableCommands.size() > i) {
msg(Colors.Rose + availableCommands.get(i));
}
}
}
} else if (split[0].equalsIgnoreCase("/reload")) {
etc.getInstance().load();
etc.getInstance().loadData();
a.info("Reloaded config");
msg("Successfuly reloaded config");
} else if ((split[0].equalsIgnoreCase("/modify") || split[0].equalsIgnoreCase("/mp"))) {
if (split.length < 4) {
msg(Colors.Rose + "Usage is: /modify [player] [key] [value]");
msg(Colors.Rose + "Keys:");
msg(Colors.Rose + "prefix: only the letter the color represents");
msg(Colors.Rose + "commands: list seperated by comma");
msg(Colors.Rose + "groups: list seperated by comma");
msg(Colors.Rose + "ignoresrestrictions: true or false");
msg(Colors.Rose + "admin: true or false");
msg(Colors.Rose + "modworld: true or false");
return;
}
ea player = match(split[1]);
if (player == null) {
msg(Colors.Rose + "Player does not exist.");
return;
}
String key = split[2];
String value = split[3];
User user = etc.getInstance().getUser(split[1]);
boolean newUser = false;
if (user == null) {
if (!key.equalsIgnoreCase("groups") && !key.equalsIgnoreCase("g")) {
msg(Colors.Rose + "When adding a new user, set their group(s) first.");
return;
}
msg(Colors.Rose + "Adding new user.");
newUser = true;
user = new User();
user.Name = split[1];
user.Administrator = false;
user.CanModifyWorld = true;
user.IgnoreRestrictions = false;
user.Commands = new String[]{""};
user.Prefix = "";
}
if (key.equalsIgnoreCase("prefix") || key.equalsIgnoreCase("p")) {
user.Prefix = value;
} else if (key.equalsIgnoreCase("commands") || key.equalsIgnoreCase("c")) {
user.Commands = value.split(",");
} else if (key.equalsIgnoreCase("groups") || key.equalsIgnoreCase("g")) {
user.Groups = value.split(",");
} else if (key.equalsIgnoreCase("ignoresrestrictions") || key.equalsIgnoreCase("ir")) {
user.IgnoreRestrictions = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("admin") || key.equalsIgnoreCase("a")) {
user.Administrator = value.equalsIgnoreCase("true") || value.equals("1");
} else if (key.equalsIgnoreCase("modworld") || key.equalsIgnoreCase("mw")) {
user.CanModifyWorld = value.equalsIgnoreCase("true") || value.equals("1");
}
if (newUser) {
etc.getInstance().getDataSource().addUser(user);
} else {
etc.getInstance().getDataSource().modifyUser(user);
}
msg(Colors.Rose + "Modified user.");
a.info("Modifed user " + split[1] + ". " + key + " => " + value + " by " + e.aq);
} else if (split[0].equalsIgnoreCase("/whitelist")) {
if (split.length != 3) {
msg(Colors.Rose + "whitelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToWhitelist(split[2]);
msg(Colors.Rose + split[2] + " added to whitelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromWhitelist(split[2]);
msg(Colors.Rose + split[2] + " removed from whitelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/reservelist")) {
if (split.length != 3) {
msg(Colors.Rose + "reservelist [operation (add or remove)] [player]");
return;
}
if (split[1].equalsIgnoreCase("add")) {
etc.getInstance().getDataSource().addToReserveList(split[2]);
msg(Colors.Rose + split[2] + " added to reservelist");
} else if (split[1].equalsIgnoreCase("remove")) {
etc.getInstance().getDataSource().removeFromReserveList(split[2]);
msg(Colors.Rose + split[2] + " removed from reservelist");
} else {
msg(Colors.Rose + "Invalid operation.");
}
} else if (split[0].equalsIgnoreCase("/mute")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /mute [player]");
return;
}
ea player = match(split[1]);
if (player != null) {
if (etc.getInstance().toggleMute(player)) {
msg(Colors.Rose + "player was muted");
} else {
msg(Colors.Rose + "player was unmuted");
}
} else {
msg(Colors.Rose + "Can't find player " + split[1]);
}
} else if ((split[0].equalsIgnoreCase("/msg") || split[0].equalsIgnoreCase("/tell")) || split[0].equalsIgnoreCase("/m")) {
if (split.length < 3) {
msg(Colors.Rose + "Correct usage is: /msg [player] [message]");
return;
}
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (player.aq.equals(e.aq)) {
msg(Colors.Rose + "You can't message yourself!");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
player.a.msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
msg("(MSG) " + prefix + "<" + e.aq + "> " + Colors.White + combineSplit(2, split, " "));
} else {
msg(Colors.Rose + "Couldn't find player " + split[1]);
}
} else if (split[0].equalsIgnoreCase("/kit") && etc.getInstance().getDataSource().hasKits()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available kits: " + Colors.White + etc.getInstance().getDataSource().getKitNames(e.aq));
return;
}
ea toGive = e;
if (split.length > 2 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[1]);
}
Kit kit = etc.getInstance().getDataSource().getKit(split[1]);
if (toGive != null) {
if (kit != null) {
if (!etc.getInstance().isUserInGroup(e, kit.Group) && !kit.Group.equals("")) {
msg(Colors.Rose + "That kit does not exist.");
} else if (onlyOneUseKits.contains(kit.Name)) {
msg(Colors.Rose + "You can only get this kit once per login.");
} else if (MinecraftServer.b.containsKey(this.e.aq + " " + kit.Name)) {
msg(Colors.Rose + "You can't get this kit again for a while.");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
if (kit.Delay >= 0) {
MinecraftServer.b.put(this.e.aq + " " + kit.Name, kit.Delay);
} else {
onlyOneUseKits.add(kit.Name);
}
}
a.info(this.e.aq + " got a kit!");
toGive.a.msg(Colors.Rose + "Enjoy this kit!");
for (Map.Entry<String, Integer> entry : kit.IDs.entrySet()) {
try {
int itemId = 0;
try {
itemId = Integer.parseInt(entry.getKey());
} catch (NumberFormatException n) {
itemId = etc.getInstance().getDataSource().getItem(entry.getKey());
}
int temp = kit.IDs.get(entry.getKey());
do {
if (temp - 64 >= 64) {
toGive.a(new gp(itemId, 64));
} else {
toGive.a(new gp(itemId, temp));
}
temp -= 64;
} while (temp >= 64);
} catch (Exception e1) {
a.info("Got an exception while giving out a kit (Kit name \"" + kit.Name + "\"). Are you sure all the Ids are numbers?");
msg(Colors.Rose + "The server encountered a problem while giving the kit :(");
}
}
}
} else {
msg(Colors.Rose + "That kit does not exist.");
}
} else {
msg(Colors.Rose + "That user does not exist.");
}
} else if (split[0].equalsIgnoreCase("/tp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tp [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "You're already here!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported to " + player.aq);
a(player.l, player.m, player.n, player.r, player.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if ((split[0].equalsIgnoreCase("/tphere") || split[0].equalsIgnoreCase("/s"))) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /tphere [player]");
return;
}
ea player = match(split[1]);
if (this.e.aq.equalsIgnoreCase(split[1])) {
msg(Colors.Rose + "Wow look at that! You teleported yourself to yourself!");
return;
}
if (player != null) {
a.info(this.e.aq + " teleported " + player.aq + " to their self.");
player.a.a(e.l, e.m, e.n, e.r, e.s);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/playerlist") || split[0].equalsIgnoreCase("/who")) {
msg(Colors.Rose + "Player list (" + d.f.b.size() + "/" + etc.getInstance().playerLimit + "): " + Colors.White + d.f.c());
} else if (split[0].equalsIgnoreCase("/item") || split[0].equalsIgnoreCase("/i") || split[0].equalsIgnoreCase("/give")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount> <player> (optional)");
} else {
msg(Colors.Rose + "Correct usage is: /item [itemid] <amount>");
}
return;
}
ea toGive = e;
if (split.length == 4 && etc.getInstance().canIgnoreRestrictions(e)) {
toGive = match(split[3]);
}
if (toGive != null) {
try {
int i2 = 0;
try {
i2 = Integer.parseInt(split[1]);
} catch (NumberFormatException n) {
i2 = etc.getInstance().getDataSource().getItem(split[1]);
}
int i3 = 1;
if (split.length > 2) {
i3 = Integer.parseInt(split[2]);
}
String i2str = Integer.toString(i2);
if (i3 <= 0) {
i3 = 1;
}
if (i3 > 64 && !etc.getInstance().canIgnoreRestrictions(this.e)) {
i3 = 64;
}
boolean allowedItem = false;
if (!etc.getInstance().allowedItems[0].equals("") && (!etc.getInstance().canIgnoreRestrictions(this.e))) {
for (String str : etc.getInstance().allowedItems) {
if (i2str.equals(str)) {
allowedItem = true;
}
}
} else {
allowedItem = true;
}
if (!etc.getInstance().disallowedItems[0].equals("") && !etc.getInstance().canIgnoreRestrictions(this.e)) {
for (String str : etc.getInstance().disallowedItems) {
if (i2str.equals(str)) {
allowedItem = false;
}
}
}
if (i2 < ez.c.length) {
if (ez.c[i2] != null && (allowedItem || etc.getInstance().canIgnoreRestrictions(this.e))) {
a.log(Level.INFO, "Giving " + toGive.aq + " some " + i2);
int temp = i3;
do {
if (temp - 64 >= 64) {
toGive.a(new gp(i2, 64));
} else {
toGive.a(new gp(i2, temp));
}
temp -= 64;
} while (temp >= 64);
if (toGive == this.e) {
msg(Colors.Rose + "There you go c:");
} else {
msg(Colors.Rose + "Gift given! :D");
toGive.a.msg(Colors.Rose + "Enjoy your gift! :D");
}
} else if ((!allowedItem) && (ez.c[i2] != null) && !etc.getInstance().canIgnoreRestrictions(this.e)) {
msg(Colors.Rose + "You are not allowed to spawn that item.");
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} else {
msg(Colors.Rose + "No item with ID " + split[1]);
}
} catch (NumberFormatException localNumberFormatException) {
msg(Colors.Rose + "Improper ID and/or amount.");
}
} else {
msg(Colors.Rose + "Can't find user " + split[3]);
}
} else if (split[0].equalsIgnoreCase("/banlist")) {
byte type = 0;
if (split.length == 2) {
if (split[1].equalsIgnoreCase("ips")) {
type = 1;
}
}
if (type == 0) { //Regular user bans
msg(Colors.Blue + "Ban list:" + Colors.White + " " + d.f.getBans());
} else { //IP bans
msg(Colors.Blue + "IP Ban list:" + Colors.White + " " + d.f.getBans());
}
} else if (split[0].equalsIgnoreCase("/banip")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /banip [player] <reason> (optional) NOTE: this permabans IPs.");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.c(player.a.b.b().toString());
a.log(Level.INFO, "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
msg(Colors.Rose + "IP Banning " + player.aq + " (IP: " + player.a.b.b().toString() + ")");
if (split.length > 2) {
player.a.c("IP Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("IP Banned by " + e.aq + ".");
}
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/ban")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /ban [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't ban that user.");
return;
}
// adds player to ban list
this.d.f.a(player.aq);
if (split.length > 2) {
player.a.c("Banned by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Banned by " + e.aq + ".");
}
a.log(Level.INFO, "Banning " + player.aq);
msg(Colors.Rose + "Banning " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/unban")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unban [player]");
return;
}
this.d.f.b(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/unbanip")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /unbanip [ip]");
return;
}
this.d.f.d(split[1]);
msg(Colors.Rose + "Unbanned " + split[1]);
} else if (split[0].equalsIgnoreCase("/kick")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /kick [player] <reason> (optional)");
return;
}
ea player = match(split[1]);
if (player != null) {
if (!hasControlOver(player)) {
msg(Colors.Rose + "You can't kick that user.");
return;
}
if (split.length > 2) {
player.a.c("Kicked by " + e.aq + ": " + combineSplit(2, split, " "));
} else {
player.a.c("Kicked by " + e.aq + ".");
}
a.log(Level.INFO, "Kicking " + player.aq);
msg(Colors.Rose + "Kicking " + player.aq);
} else {
msg(Colors.Rose + "Can't find user " + split[1] + ".");
}
} else if (split[0].equalsIgnoreCase("/me")) {
if (etc.getInstance().isMuted(e)) {
msg(Colors.Rose + "You are currently muted.");
return;
}
String prefix = etc.getInstance().getUserColor(e.aq);
String paramString2 = "* " + prefix + this.e.aq + Colors.White + " " + paramString.substring(paramString.indexOf(" ")).trim();
a.info("* " + this.e.aq + " " + paramString.substring(paramString.indexOf(" ")).trim());
this.d.f.a(new ba(paramString2));
} else if (split[0].equalsIgnoreCase("/sethome")) {
// player.k, player.l, player.m
// x, y, z
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp home = new Warp();
home.Location = loc;
home.Group = ""; //no group neccessary, lol.
home.Name = e.aq;
etc.getInstance().changeHome(home);
msg(Colors.Rose + "Your home has been set.");
} else if (split[0].equalsIgnoreCase("/spawn")) {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
} else if (split[0].equalsIgnoreCase("/setspawn")) {
this.d.e.n = (int) Math.ceil(e.l);
//Too lazy to actually update this considering it's not even used anyways.
//this.d.e.n = (int) Math.ceil(e.m); //Not that the Y axis really matters since it tries to get the highest point iirc.
this.d.e.p = (int) Math.ceil(e.n);
a.info("Spawn position changed.");
msg(Colors.Rose + "You have set the spawn to your current position.");
} else if (split[0].equalsIgnoreCase("/home")) {
a.info(this.e.aq + " returned home");
Warp home = etc.getInstance().getDataSource().getHome(e.aq);
if (home != null) {
a(home.Location.x, home.Location.y, home.Location.z, home.Location.rotX, home.Location.rotY);
} else {
int m = this.d.e.d(this.d.e.n, this.d.e.p);
a(this.d.e.n + 0.5D, m + 1.5D, this.d.e.p + 0.5D, 0.0F, 0.0F);
}
} else if (split[0].equalsIgnoreCase("/warp")) {
if (split.length < 2) {
msg(Colors.Rose + "Correct usage is: /warp [warpname]");
return;
}
ea toWarp = e;
Warp warp = null;
if (split.length == 3 && etc.getInstance().canIgnoreRestrictions(e)) {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
toWarp = match(split[2]);
} else {
warp = etc.getInstance().getDataSource().getWarp(split[1]);
}
if (toWarp != null) {
if (warp != null) {
if (!etc.getInstance().isUserInGroup(e, warp.Group) && !warp.Group.equals("")) {
msg(Colors.Rose + "Warp not found.");
} else {
toWarp.a.a(warp.Location.x, warp.Location.y, warp.Location.z, warp.Location.rotX, warp.Location.rotY);
toWarp.a.msg(Colors.Rose + "Woosh!");
}
} else {
msg(Colors.Rose + "Warp not found");
}
} else {
msg(Colors.Rose + "Player not found.");
}
} else if (split[0].equalsIgnoreCase("/listwarps") && etc.getInstance().getDataSource().hasWarps()) {
if (split.length != 2 && split.length != 3) {
msg(Colors.Rose + "Available warps: " + Colors.White + etc.getInstance().getDataSource().getWarpNames(e.aq));
return;
}
} else if (split[0].equalsIgnoreCase("/setwarp")) {
if (split.length < 2) {
if (etc.getInstance().canIgnoreRestrictions(e)) {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname] [group]");
} else {
msg(Colors.Rose + "Correct usage is: /setwarp [warpname]");
}
return;
}
Location loc = new Location();
loc.x = e.l;
loc.y = e.m;
loc.z = e.n;
loc.rotX = e.r;
loc.rotY = e.s;
Warp warp = new Warp();
warp.Name = split[1];
warp.Location = loc;
if (split.length == 3) {
warp.Group = split[2];
} else {
warp.Group = "";
}
etc.getInstance().setWarp(warp);
msg(Colors.Rose + "Created warp point " + split[1] + ".");
} else if (split[0].equalsIgnoreCase("/lighter")) {
if (MinecraftServer.b.containsKey(this.e.aq + " lighter")) {
a.info(this.e.aq + " failed to iron!");
msg(Colors.Rose + "You can't create another lighter again so soon");
} else {
if (!etc.getInstance().canIgnoreRestrictions(e)) {
MinecraftServer.b.put(this.e.aq + " lighter", Integer.valueOf(6000));
}
a.info(this.e.aq + " created a lighter!");
this.e.a(new gp(259, 1));
}
} else if ((paramString.startsWith("/#")) && (this.d.f.g(this.e.aq))) {
String str = paramString.substring(2);
a.info(this.e.aq + " issued server command: " + str);
this.d.a(str, this);
} else if (split[0].equalsIgnoreCase("/time")) {
if (split.length != 2) {
msg(Colors.Rose + "Correct usage is: /time [time|day|night]");
return;
}
if (split[1].equalsIgnoreCase("day")) {
this.d.e.c = 0; //morning.
} else if (split[1].equalsIgnoreCase("night")) {
this.d.e.c = 500000; //approx value for midnight basically
} else {
try {
this.d.e.c = Long.parseLong(split[1]);
} catch (NumberFormatException e) {
msg(Colors.Rose + "Please enter numbers, not letters.");
}
}
} else if (split[0].equalsIgnoreCase("/getpos")) {
msg("Pos X: " + e.k + " Y: " + e.l + " Z " + e.m);
msg("Rotation X: " + e.q + " Y: " + e.r);
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg("Compass: " + etc.getCompassPointForDirection(degreeRotation) + " (" + (Math.round(degreeRotation * 10) / 10.0) + ")");
} else if (split[0].equalsIgnoreCase("/compass")) {
double degreeRotation = ((e.q - 90) % 360);
if (degreeRotation < 0) {
degreeRotation += 360.0;
}
msg(Colors.Rose + "Compass: " + etc.getCompassPointForDirection(degreeRotation));
} else if (split[0].equalsIgnoreCase("/motd")) {
for (String str : etc.getInstance().motd) {
msg(str);
}
} else {
a.info(this.e.aq + " tried command " + paramString);
msg(Colors.Rose + "Unknown command");
}
} catch (Exception ex) {
a.log(Level.SEVERE, "Exception in command handler (Report this to hey0 unless you did something dumb like enter letters as numbers):", ex);
if (etc.getInstance().isAdmin(e)) {
msg(Colors.Rose + "Exception occured. Check the server for more info.");
}
}
}
|
diff --git a/src/main/java/org/thymeleaf/templateparser/TemplatePreprocessingReader.java b/src/main/java/org/thymeleaf/templateparser/TemplatePreprocessingReader.java
index 2978ec5c..b0467788 100644
--- a/src/main/java/org/thymeleaf/templateparser/TemplatePreprocessingReader.java
+++ b/src/main/java/org/thymeleaf/templateparser/TemplatePreprocessingReader.java
@@ -1,885 +1,885 @@
/*
* =============================================================================
*
* Copyright (c) 2011-2012, The THYMELEAF team (http://www.thymeleaf.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.thymeleaf.templateparser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.exceptions.TemplateInputException;
/**
*
* @author Daniel Fernández
*
* @since 2.0.7
*
*/
public final class TemplatePreprocessingReader extends Reader {
private static final Logger readerLogger = LoggerFactory.getLogger(TemplatePreprocessingReader.class);
public static final char CHAR_ENTITY_START_SUBSTITUTE = '\uFFF8';
private static final char CHAR_OPTIONAL_WHITESPACE_WILDCARD = '\u0358';
private static final char CHAR_WHITESPACE_WILDCARD = '\u0359';
private static final char CHAR_ALPHANUMERIC_WILDCARD = '\u0360';
private static final char CHAR_ANY_WILDCARD = '\u0361';
private static final char[] LOWER_CHARS =
("[]<>!=-_.,:;+*()&/%$\"'@#~^ \t\n\rabcdefghijklmnopqrstuvwxyz" +
String.valueOf(CHAR_OPTIONAL_WHITESPACE_WILDCARD) + String.valueOf(CHAR_WHITESPACE_WILDCARD) +
String.valueOf(CHAR_ALPHANUMERIC_WILDCARD) + String.valueOf(CHAR_ANY_WILDCARD)).toCharArray();
private static final char[] UPPER_CHARS =
("[]<>!=-_.,:;+*()&/%$\"'@#~^ \t\n\rABCDEFGHIJKLMNOPQRSTUVWXYZ" +
String.valueOf(CHAR_OPTIONAL_WHITESPACE_WILDCARD) + String.valueOf(CHAR_WHITESPACE_WILDCARD) +
String.valueOf(CHAR_ALPHANUMERIC_WILDCARD) + String.valueOf(CHAR_ANY_WILDCARD)).toCharArray();
private static final int[] COMMENT_START = convertToIndexes("<!--".toCharArray());
private static final int[] COMMENT_END = convertToIndexes("-->".toCharArray());
private static final int[] ENTITY = convertToIndexes(("&" + String.valueOf(CHAR_ALPHANUMERIC_WILDCARD) + ";").toCharArray());
private static final int[] DOCTYPE =
convertToIndexes(("<!DOCTYPE" + String.valueOf(CHAR_WHITESPACE_WILDCARD) + String.valueOf(CHAR_ANY_WILDCARD) + ">").toCharArray());
private static final char[] NORMALIZED_DOCTYPE_PREFIX = "<!DOCTYPE ".toCharArray();
private static final char[] NORMALIZED_DOCTYPE_PUBLIC = "PUBLIC ".toCharArray();
private static final char[] NORMALIZED_DOCTYPE_SYSTEM = "SYSTEM ".toCharArray();
private static final char[] ENTITY_START_SUBSTITUTE_CHAR_ARRAY = new char[] { CHAR_ENTITY_START_SUBSTITUTE };
public static final String SYNTHETIC_ROOT_ELEMENT_NAME = "THYMELEAF_ROOT";
private static final char[] SYNTHETIC_ROOT_ELEMENT_START_CHARS = ("<" + SYNTHETIC_ROOT_ELEMENT_NAME + ">").toCharArray();
private static final char[] SYNTHETIC_ROOT_ELEMENT_END_CHARS = ("</" + SYNTHETIC_ROOT_ELEMENT_NAME + ">").toCharArray();
private final Reader innerReader;
private final BufferedReader bufferedReader;
private final boolean addSyntheticRootElement;
private char[] buffer;
private char[] overflow;
private int overflowIndex;
private boolean inComment = false;
private boolean docTypeClauseRead = false;
private boolean syntheticRootElementOpeningProcessed = false;
private boolean syntheticRootElementClosingSent = false;
private int rootElementClosingOffset = 0;
private boolean noMoreToRead = false;
private String docTypeClause = null;
private static int[] convertToIndexes(final char[] chars) {
final int charsLen = chars.length;
final int[] result = new int[charsLen];
for (int i = 0; i < charsLen; i++) {
final char c = chars[i];
boolean found = false;
for (int j = 0; !found && j < UPPER_CHARS.length; j++) {
if (UPPER_CHARS[j] == c) {
result[i] = j;
found = true;
}
}
for (int j = 0; !found && j < LOWER_CHARS.length; j++) {
if (LOWER_CHARS[j] == c) {
result[i] = j;
found = true;
}
}
if (!found) {
throw new RuntimeException(
"Cannot convert to index character: '" + c + "' (value: " + ((int)c) + ")");
}
}
return result;
}
/*
*
* TODO Add exceptions for not substituting anything inside [[...]]
*
*/
public TemplatePreprocessingReader(final Reader in, final int bufferSize) {
this(in, bufferSize, true);
}
/**
*
* @since 2.0.11
*/
public TemplatePreprocessingReader(final Reader in, final int bufferSize, final boolean addSyntheticRootElement) {
super();
this.innerReader = in;
this.bufferedReader = new BufferedReader(this.innerReader, bufferSize);
this.buffer = new char[bufferSize + 1024];
this.overflow = new char[bufferSize + 2048];
this.overflowIndex = 0;
this.addSyntheticRootElement = addSyntheticRootElement;
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] CALLING read(char[], {}, {})",
new Object[] {TemplateEngine.threadIndex(),Integer.valueOf(off), Integer.valueOf(len)});
}
if ((len * 2) > this.overflow.length) {
// Resize buffer and overflow
this.buffer = new char[len + 1024];
final char[] newOverflow = new char[len + 2048];
System.arraycopy(this.overflow, 0, newOverflow, 0, this.overflowIndex);
this.overflow = newOverflow;
}
int bufferSize = 0;
if (this.overflowIndex > 0) {
final int copied =
copyToResult(
this.overflow, 0, this.overflowIndex,
this.buffer, 0, this.buffer.length);
bufferSize += copied;
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] READ FROM OVERFLOW BUFFER {} Some content from the overflow buffer has been copied into results.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(copied)});
}
}
char[] overflowOverflow = null;
if (this.overflowIndex > 0) {
// Overflow did not entirely fit into buffer, and some overflow
// had to be relocated. This overflow will have to be placed at the end of the
// overflow generated in the current call (if any).
overflowOverflow = new char[this.overflowIndex];
System.arraycopy(this.overflow, 0, overflowOverflow, 0, this.overflowIndex);
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RELLOCATED SOME OVERFLOW CONTENTS, WAITING TO BE ADDED TO RESULT/NEW OVERFLOW {} Some content was remaining at the overflow buffer and will have to be rellocated.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(this.overflowIndex)});
}
this.overflowIndex = 0;
}
if (!this.noMoreToRead && bufferSize < this.buffer.length) {
// Buffer was not filled up with content from overflow, so ask for more content
final int toBeRead = this.buffer.length - bufferSize;
int reallyRead = this.bufferedReader.read(this.buffer, bufferSize, toBeRead);
if (this.addSyntheticRootElement && !this.syntheticRootElementClosingSent && (reallyRead < 0)) {
// If there is no more content to be read from the source reader, close the synthetic
// root element and make it look like it was read from source.
final int closingSizeToInsert =
Math.min(
(SYNTHETIC_ROOT_ELEMENT_END_CHARS.length - this.rootElementClosingOffset),
(this.buffer.length - bufferSize));
reallyRead =
copyToResult(
SYNTHETIC_ROOT_ELEMENT_END_CHARS, this.rootElementClosingOffset, closingSizeToInsert,
this.buffer, bufferSize, this.buffer.length);
this.rootElementClosingOffset += reallyRead;
if (this.rootElementClosingOffset >= SYNTHETIC_ROOT_ELEMENT_END_CHARS.length) {
this.syntheticRootElementClosingSent = true;
}
}
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] READ FROM SOURCE {} A read operation was executed on the source reader (max chars requested: {}).",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(reallyRead), Integer.valueOf(toBeRead)});
}
if (reallyRead < 0) {
if (bufferSize == 0) {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN {} After trying to read from input: No input left, no buffer left.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(reallyRead)});
}
return reallyRead;
}
this.noMoreToRead = true;
} else {
bufferSize += reallyRead;
}
}
if (this.noMoreToRead && bufferSize == 0) {
// Nothing left to do. Just return -1
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN -1 Reader was already marked to be finished. No more input, no more buffer.",
new Object[] {TemplateEngine.threadIndex()});
}
return -1;
}
int totalRead = 0;
int cbufi = off;
int last = off + len;
int buffi = 0;
while (cbufi < last && buffi < bufferSize) {
/*
* Process DOCTYPE first (if needed)
*/
if (!this.docTypeClauseRead) {
final int matchedDocType =
match(DOCTYPE, 0, DOCTYPE.length, this.buffer, buffi, bufferSize);
if (matchedDocType > 0) {
this.docTypeClause = new String(this.buffer, buffi, matchedDocType);
this.docTypeClauseRead = true;
final char[] normalizedDocType =
normalizeDocTypeClause(this.buffer, buffi, matchedDocType);
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] Normalized DOCTYPE clause: {}",
new Object[] {TemplateEngine.threadIndex(), new String(normalizedDocType)});
}
int copied = -1;
if (this.addSyntheticRootElement && !this.syntheticRootElementOpeningProcessed) {
// If DOCTYPE is processed, we will inject the synthetic root
// element just after the DOCTYPE so that we avoid problems with
// DOCTYPE clause being bigger than 'len' argument in the first 'read()' call.
final char[] normalizedDocTypePlusSyntheticRootElement =
new char[normalizedDocType.length + SYNTHETIC_ROOT_ELEMENT_START_CHARS.length];
System.arraycopy(normalizedDocType, 0, normalizedDocTypePlusSyntheticRootElement, 0, normalizedDocType.length);
System.arraycopy(SYNTHETIC_ROOT_ELEMENT_START_CHARS, 0, normalizedDocTypePlusSyntheticRootElement, normalizedDocType.length, SYNTHETIC_ROOT_ELEMENT_START_CHARS.length);
copied =
copyToResult(
normalizedDocTypePlusSyntheticRootElement, 0, normalizedDocTypePlusSyntheticRootElement.length,
cbuf, cbufi, last);
this.syntheticRootElementOpeningProcessed = true;
} else {
copied =
copyToResult(
normalizedDocType, 0, normalizedDocType.length,
cbuf, cbufi, last);
}
cbufi += copied;
totalRead += copied;
buffi += matchedDocType;
continue;
}
}
final int matchedStartOfComment =
(this.inComment?
-2 : match(COMMENT_START, 0, COMMENT_START.length, this.buffer, buffi, bufferSize));
if (matchedStartOfComment > 0) {
this.inComment = true;
final int copied =
copyToResult(
this.buffer, buffi, matchedStartOfComment,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += matchedStartOfComment;
continue;
}
final int matchedEndOfComment =
(this.inComment?
match(COMMENT_END, 0, COMMENT_END.length, this.buffer, buffi, bufferSize) : -2);
if (matchedEndOfComment > 0) {
this.inComment = false;
final int copied =
copyToResult(
this.buffer, buffi, matchedEndOfComment,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += matchedEndOfComment;
continue;
}
final int matchedEntity =
(this.inComment?
-2 : match(ENTITY, 0, ENTITY.length, this.buffer, buffi, bufferSize));
if (matchedEntity > 0) {
final int copied =
copyToResult(
ENTITY_START_SUBSTITUTE_CHAR_ARRAY, 0, ENTITY_START_SUBSTITUTE_CHAR_ARRAY.length,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += 1; // Only one character is substituted (&)
continue;
}
- if (this.buffer[buffi] == '<' && this.addSyntheticRootElement && !this.syntheticRootElementOpeningProcessed && !this.inComment) {
+ if (!Character.isWhitespace(this.buffer[buffi]) && this.addSyntheticRootElement && !this.syntheticRootElementOpeningProcessed && !this.inComment) {
// This block will be reached if we did not have to process a
// DOCTYPE clause (because the DOCTYPE would have
// matched the previous block). And will not be affected by any whitespaces
- // or comments before DOCTYPE because of the this.buffer[buffi] == '<' check.
+ // or comments before DOCTYPE because of the !Character.isWhitespace condition.
final int copied =
copyToResult(
SYNTHETIC_ROOT_ELEMENT_START_CHARS, 0, SYNTHETIC_ROOT_ELEMENT_START_CHARS.length,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
this.syntheticRootElementOpeningProcessed = true;
continue;
}
cbuf[cbufi++] = this.buffer[buffi++];
totalRead++;
}
if (buffi < bufferSize) {
// Copy remaining buffer to overflow
final int toBeOverFlowed = bufferSize - buffi;
final int copied =
copyToResult(
this.buffer, buffi, toBeOverFlowed,
cbuf, cbufi, last);
// copied must be zero
if (copied != 0) {
throw new TemplateInputException("Overflow was not correctly computed!");
}
}
if (overflowOverflow != null) {
final int copied =
copyToResult(
overflowOverflow, 0, overflowOverflow.length,
cbuf, cbufi, last);
// copied must be zero
if (copied != 0) {
throw new TemplateInputException("Overflow-overflow was not correctly computed!");
}
}
if (readerLogger.isTraceEnabled()) {
final char[] result = new char[totalRead];
System.arraycopy(cbuf, off, result, 0, totalRead);
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN {} Input was read and processed. Returning content: [[{}]]",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(totalRead), new String(result)});
}
return totalRead;
}
@Override
public int read() throws IOException {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] CALLING read(). Will be delegated to read(char[], 0, 1).",
new Object[] {TemplateEngine.threadIndex()});
}
final char[] cbuf = new char[1];
final int res = read(cbuf, 0, 1);
if (res <= 0) {
return res;
}
return cbuf[0];
}
@Override
public int read(final CharBuffer target) throws IOException {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] CALLING read(CharBuffer). Will be delegated as several calls to read(char[], 0, 1024).",
new Object[] {TemplateEngine.threadIndex()});
}
final char[] cbuf = new char[1024];
int totalRead = -1;
int read;
while ((read = read(cbuf, 0, cbuf.length)) != -1) {
target.put(cbuf, 0, read);
if (totalRead == -1) {
totalRead = 0;
}
totalRead += read;
}
return totalRead;
}
@Override
public int read(final char[] cbuf) throws IOException {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] CALLING read(char[] cbuf). Will be delegated to read(cbuf, 0, cbuf.length).",
new Object[] {TemplateEngine.threadIndex()});
}
return read(cbuf, 0, cbuf.length);
}
@Override
public long skip(long n) throws IOException {
throw new IOException("Skip not supported in reader");
}
@Override
public boolean ready() throws IOException {
if (this.bufferedReader.ready()) {
return true;
}
return this.overflowIndex > 0;
}
@Override
public boolean markSupported() {
return false;
}
@Override
public void mark(int readAheadLimit) throws IOException {
throw new IOException("Mark not supported in reader");
}
@Override
public void reset() throws IOException {
throw new IOException("Reset not supported in reader");
}
@Override
public void close() throws IOException {
this.bufferedReader.close();
}
/*
* fragment: the char[] containing the fragment to be copied
* fragmentOff: the offset for the fragment char[]
* fragmentLen: the length of the fragment to be copied
* cbuf: the result buffer
* cbufi: the current position in the result buffer (offset)
* last: the last position (non-inclusive) that can be filled in cbuf
*
* RETURNS: the amount of chars that have been actually copied to the cbuf result array
*/
private int copyToResult(
final char[] fragment, final int fragmentOff, final int fragmentLen,
final char[] cbuf, final int cbufi, final int last) {
if (cbufi + fragmentLen < last) {
System.arraycopy(fragment, fragmentOff, cbuf, cbufi, fragmentLen);
if (fragment == this.overflow) {
// Overflow has been cleaned
this.overflowIndex = 0;
}
return fragmentLen;
}
// There is no space at the result buffer: we must overflow
final int toBeCopied = last - cbufi;
final int toBeOverflowed = fragmentLen - toBeCopied;
if (toBeCopied > 0) {
System.arraycopy(fragment, fragmentOff, cbuf, cbufi, toBeCopied);
}
if (fragment != this.overflow) {
System.arraycopy(fragment, (fragmentOff + toBeCopied), this.overflow, this.overflowIndex, toBeOverflowed);
this.overflowIndex += toBeOverflowed;
} else {
// Both source and target are the overflow array
System.arraycopy(fragment, (fragmentOff + toBeCopied), this.overflow, 0, toBeOverflowed);
this.overflowIndex = toBeOverflowed;
}
return toBeCopied;
}
/*
* RETURNS:
* <0 = does not start here
* 0 = maybe (not enough buffer to know)
* >0 = does start here
*/
private static int match(
final int[] fragment, final int fragmentOff, final int fragmentLen,
final char[] buffer, final int buffi, final int bufferLast) {
/*
* Trying to fail fast
*/
final char f0Lower = LOWER_CHARS[fragment[fragmentOff]];
final char f0Upper = UPPER_CHARS[fragment[fragmentOff]];
if (f0Lower != CHAR_WHITESPACE_WILDCARD && f0Lower != CHAR_ALPHANUMERIC_WILDCARD &&
f0Lower != buffer[buffi] && f0Upper != buffer[buffi]) {
return -1;
}
final int fragmentLast = fragmentOff + fragmentLen;
int buffj = buffi;
int fragmenti = fragmentOff;
while (buffj < bufferLast && fragmenti < fragmentLast) {
final int fragmentIndex = fragment[fragmenti];
// lower will be enough for most checks
final char fLower = LOWER_CHARS[fragmentIndex];
// For wildcards, checking against lowercase will be enough (wildcards are at the same
// position in lower and upper case).
if (fLower == CHAR_WHITESPACE_WILDCARD) {
if (buffer[buffj] != ' ' && buffer[buffj] != '\t') {
if (buffj > buffi && (buffer[buffj - 1] == ' ' || buffer[buffj - 1] == '\t')) {
fragmenti++;
} else {
// We did not find at least one whitespace
return -1;
}
} else {
buffj++;
}
} else if (fLower == CHAR_OPTIONAL_WHITESPACE_WILDCARD) {
if (buffer[buffj] != ' ' && buffer[buffj] != '\t') {
fragmenti++;
} else {
buffj++;
}
} else if (fLower == CHAR_ALPHANUMERIC_WILDCARD) {
final char c = buffer[buffj];
final boolean isUpper = (c >= 'A' && c <= 'Z');
final boolean isLower = (c >= 'a' && c <= 'z');
final boolean isDigit = (c >= '0' && c <= '9');
final boolean isHash = (c == '#');
if ((!isUpper && !isLower && !isDigit && !isHash) ||
(fragmenti + 1 < fragmentLast &&
(UPPER_CHARS[fragment[fragmenti + 1]] == buffer[buffj]) ||
(LOWER_CHARS[fragment[fragmenti + 1]] == buffer[buffj]))) {
// Either we found a non-alphanumeric, or we simply found
// a character that matches next one in fragment
fragmenti++;
} else {
buffj++;
}
} else if (fLower == CHAR_ANY_WILDCARD) {
if ((fragmenti + 1 < fragmentLast &&
(UPPER_CHARS[fragment[fragmenti + 1]] == buffer[buffj]) ||
(LOWER_CHARS[fragment[fragmenti + 1]] == buffer[buffj]))) {
// We found a character that matches next one in fragment!
fragmenti++;
} else {
buffj++;
}
} else {
final char bufferChar = buffer[buffj];
if (bufferChar != UPPER_CHARS[fragmentIndex] &&
bufferChar != fLower) {
return -1;
}
buffj++;
fragmenti++;
}
}
if (fragmenti == fragmentLast) {
// Matches! and we return the number of chars that matched
return buffj - buffi;
}
// Was matching OK, but then we hit the end of the buffer...
return 0;
}
private static char[] normalizeDocTypeClause(final char[] buffer, int offset, int len) {
try {
boolean afterQuote = false;
final char[] result = new char[len];
System.arraycopy(NORMALIZED_DOCTYPE_PREFIX, 0, result, 0, NORMALIZED_DOCTYPE_PREFIX.length);
for (int i = (offset + NORMALIZED_DOCTYPE_PREFIX.length); i < (offset + len); i++) {
final char c = buffer[i];
if (c == '\"') {
// Once we find a quote symbol, we stop worrying about normalizing and just copy verbatim
afterQuote = true;
result[i - offset] = c;
} else if (!afterQuote && (c == 'P' || c == 'p')) {
final char c2 = buffer[i + 1];
if (c2 == 'U' || c2 == 'u') {
final char c3 = buffer[i + 2];
final char c4 = buffer[i + 3];
final char c5 = buffer[i + 4];
final char c6 = buffer[i + 5];
final char c7 = buffer[i + 6];
if ((c3 == 'B' || c3 == 'b') &&
(c4 == 'L' || c4 == 'l') &&
(c5 == 'I' || c5 == 'i') &&
(c6 == 'C' || c6 == 'c') &&
(c7 == ' ' || c7 == '\t')) {
System.arraycopy(NORMALIZED_DOCTYPE_PUBLIC, 0, result, (i - offset), NORMALIZED_DOCTYPE_PUBLIC.length);
i += NORMALIZED_DOCTYPE_PUBLIC.length - 1;
continue;
}
}
result[i - offset] = c;
} else if (!afterQuote && (c == 'S' || c == 's')) {
final char c2 = buffer[i + 1];
if (c2 == 'Y' || c2 == 'y') {
final char c3 = buffer[i + 2];
final char c4 = buffer[i + 3];
final char c5 = buffer[i + 4];
final char c6 = buffer[i + 5];
final char c7 = buffer[i + 6];
if ((c3 == 'S' || c3 == 's') &&
(c4 == 'T' || c4 == 't') &&
(c5 == 'E' || c5 == 'e') &&
(c6 == 'M' || c6 == 'm') &&
(c7 == ' ' || c7 == '\t')) {
System.arraycopy(NORMALIZED_DOCTYPE_SYSTEM, 0, result, (i - offset), NORMALIZED_DOCTYPE_SYSTEM.length);
i += NORMALIZED_DOCTYPE_SYSTEM.length - 1;
continue;
}
}
result[i - offset] = c;
} else {
result[i - offset] = c;
}
}
return result;
} catch (final Exception e) {
throw new TemplateInputException("DOCTYPE clause has bad format: \"" + (new String(buffer, offset, len)) + "\"");
}
}
public String getDocTypeClause() {
return this.docTypeClause;
}
public static final String removeEntitySubstitutions(final String text) {
if (text == null) {
return null;
}
final int textLen = text.length();
for (int i = 0; i < textLen; i++) {
if (text.charAt(i) == TemplatePreprocessingReader.CHAR_ENTITY_START_SUBSTITUTE) {
final char[] textCharArray = text.toCharArray();
for (int j = 0; j < textLen; j++) {
if (textCharArray[j] == TemplatePreprocessingReader.CHAR_ENTITY_START_SUBSTITUTE) {
textCharArray[j] = '&';
}
}
return new String(textCharArray);
}
}
return text;
}
public static final void removeEntitySubstitutions(final char[] text, final int off, final int len) {
if (text == null) {
return;
}
final int finalPos = off + len;
for (int i = off; i < finalPos; i++) {
if (text[i] == TemplatePreprocessingReader.CHAR_ENTITY_START_SUBSTITUTE) {
text[i] = '&';
}
}
}
/**
* @since 2.0.11
*/
public Reader getInnerReader() {
return this.innerReader;
}
}
| false | true | public int read(char[] cbuf, int off, int len) throws IOException {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] CALLING read(char[], {}, {})",
new Object[] {TemplateEngine.threadIndex(),Integer.valueOf(off), Integer.valueOf(len)});
}
if ((len * 2) > this.overflow.length) {
// Resize buffer and overflow
this.buffer = new char[len + 1024];
final char[] newOverflow = new char[len + 2048];
System.arraycopy(this.overflow, 0, newOverflow, 0, this.overflowIndex);
this.overflow = newOverflow;
}
int bufferSize = 0;
if (this.overflowIndex > 0) {
final int copied =
copyToResult(
this.overflow, 0, this.overflowIndex,
this.buffer, 0, this.buffer.length);
bufferSize += copied;
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] READ FROM OVERFLOW BUFFER {} Some content from the overflow buffer has been copied into results.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(copied)});
}
}
char[] overflowOverflow = null;
if (this.overflowIndex > 0) {
// Overflow did not entirely fit into buffer, and some overflow
// had to be relocated. This overflow will have to be placed at the end of the
// overflow generated in the current call (if any).
overflowOverflow = new char[this.overflowIndex];
System.arraycopy(this.overflow, 0, overflowOverflow, 0, this.overflowIndex);
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RELLOCATED SOME OVERFLOW CONTENTS, WAITING TO BE ADDED TO RESULT/NEW OVERFLOW {} Some content was remaining at the overflow buffer and will have to be rellocated.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(this.overflowIndex)});
}
this.overflowIndex = 0;
}
if (!this.noMoreToRead && bufferSize < this.buffer.length) {
// Buffer was not filled up with content from overflow, so ask for more content
final int toBeRead = this.buffer.length - bufferSize;
int reallyRead = this.bufferedReader.read(this.buffer, bufferSize, toBeRead);
if (this.addSyntheticRootElement && !this.syntheticRootElementClosingSent && (reallyRead < 0)) {
// If there is no more content to be read from the source reader, close the synthetic
// root element and make it look like it was read from source.
final int closingSizeToInsert =
Math.min(
(SYNTHETIC_ROOT_ELEMENT_END_CHARS.length - this.rootElementClosingOffset),
(this.buffer.length - bufferSize));
reallyRead =
copyToResult(
SYNTHETIC_ROOT_ELEMENT_END_CHARS, this.rootElementClosingOffset, closingSizeToInsert,
this.buffer, bufferSize, this.buffer.length);
this.rootElementClosingOffset += reallyRead;
if (this.rootElementClosingOffset >= SYNTHETIC_ROOT_ELEMENT_END_CHARS.length) {
this.syntheticRootElementClosingSent = true;
}
}
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] READ FROM SOURCE {} A read operation was executed on the source reader (max chars requested: {}).",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(reallyRead), Integer.valueOf(toBeRead)});
}
if (reallyRead < 0) {
if (bufferSize == 0) {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN {} After trying to read from input: No input left, no buffer left.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(reallyRead)});
}
return reallyRead;
}
this.noMoreToRead = true;
} else {
bufferSize += reallyRead;
}
}
if (this.noMoreToRead && bufferSize == 0) {
// Nothing left to do. Just return -1
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN -1 Reader was already marked to be finished. No more input, no more buffer.",
new Object[] {TemplateEngine.threadIndex()});
}
return -1;
}
int totalRead = 0;
int cbufi = off;
int last = off + len;
int buffi = 0;
while (cbufi < last && buffi < bufferSize) {
/*
* Process DOCTYPE first (if needed)
*/
if (!this.docTypeClauseRead) {
final int matchedDocType =
match(DOCTYPE, 0, DOCTYPE.length, this.buffer, buffi, bufferSize);
if (matchedDocType > 0) {
this.docTypeClause = new String(this.buffer, buffi, matchedDocType);
this.docTypeClauseRead = true;
final char[] normalizedDocType =
normalizeDocTypeClause(this.buffer, buffi, matchedDocType);
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] Normalized DOCTYPE clause: {}",
new Object[] {TemplateEngine.threadIndex(), new String(normalizedDocType)});
}
int copied = -1;
if (this.addSyntheticRootElement && !this.syntheticRootElementOpeningProcessed) {
// If DOCTYPE is processed, we will inject the synthetic root
// element just after the DOCTYPE so that we avoid problems with
// DOCTYPE clause being bigger than 'len' argument in the first 'read()' call.
final char[] normalizedDocTypePlusSyntheticRootElement =
new char[normalizedDocType.length + SYNTHETIC_ROOT_ELEMENT_START_CHARS.length];
System.arraycopy(normalizedDocType, 0, normalizedDocTypePlusSyntheticRootElement, 0, normalizedDocType.length);
System.arraycopy(SYNTHETIC_ROOT_ELEMENT_START_CHARS, 0, normalizedDocTypePlusSyntheticRootElement, normalizedDocType.length, SYNTHETIC_ROOT_ELEMENT_START_CHARS.length);
copied =
copyToResult(
normalizedDocTypePlusSyntheticRootElement, 0, normalizedDocTypePlusSyntheticRootElement.length,
cbuf, cbufi, last);
this.syntheticRootElementOpeningProcessed = true;
} else {
copied =
copyToResult(
normalizedDocType, 0, normalizedDocType.length,
cbuf, cbufi, last);
}
cbufi += copied;
totalRead += copied;
buffi += matchedDocType;
continue;
}
}
final int matchedStartOfComment =
(this.inComment?
-2 : match(COMMENT_START, 0, COMMENT_START.length, this.buffer, buffi, bufferSize));
if (matchedStartOfComment > 0) {
this.inComment = true;
final int copied =
copyToResult(
this.buffer, buffi, matchedStartOfComment,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += matchedStartOfComment;
continue;
}
final int matchedEndOfComment =
(this.inComment?
match(COMMENT_END, 0, COMMENT_END.length, this.buffer, buffi, bufferSize) : -2);
if (matchedEndOfComment > 0) {
this.inComment = false;
final int copied =
copyToResult(
this.buffer, buffi, matchedEndOfComment,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += matchedEndOfComment;
continue;
}
final int matchedEntity =
(this.inComment?
-2 : match(ENTITY, 0, ENTITY.length, this.buffer, buffi, bufferSize));
if (matchedEntity > 0) {
final int copied =
copyToResult(
ENTITY_START_SUBSTITUTE_CHAR_ARRAY, 0, ENTITY_START_SUBSTITUTE_CHAR_ARRAY.length,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += 1; // Only one character is substituted (&)
continue;
}
if (this.buffer[buffi] == '<' && this.addSyntheticRootElement && !this.syntheticRootElementOpeningProcessed && !this.inComment) {
// This block will be reached if we did not have to process a
// DOCTYPE clause (because the DOCTYPE would have
// matched the previous block). And will not be affected by any whitespaces
// or comments before DOCTYPE because of the this.buffer[buffi] == '<' check.
final int copied =
copyToResult(
SYNTHETIC_ROOT_ELEMENT_START_CHARS, 0, SYNTHETIC_ROOT_ELEMENT_START_CHARS.length,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
this.syntheticRootElementOpeningProcessed = true;
continue;
}
cbuf[cbufi++] = this.buffer[buffi++];
totalRead++;
}
if (buffi < bufferSize) {
// Copy remaining buffer to overflow
final int toBeOverFlowed = bufferSize - buffi;
final int copied =
copyToResult(
this.buffer, buffi, toBeOverFlowed,
cbuf, cbufi, last);
// copied must be zero
if (copied != 0) {
throw new TemplateInputException("Overflow was not correctly computed!");
}
}
if (overflowOverflow != null) {
final int copied =
copyToResult(
overflowOverflow, 0, overflowOverflow.length,
cbuf, cbufi, last);
// copied must be zero
if (copied != 0) {
throw new TemplateInputException("Overflow-overflow was not correctly computed!");
}
}
if (readerLogger.isTraceEnabled()) {
final char[] result = new char[totalRead];
System.arraycopy(cbuf, off, result, 0, totalRead);
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN {} Input was read and processed. Returning content: [[{}]]",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(totalRead), new String(result)});
}
return totalRead;
}
| public int read(char[] cbuf, int off, int len) throws IOException {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] CALLING read(char[], {}, {})",
new Object[] {TemplateEngine.threadIndex(),Integer.valueOf(off), Integer.valueOf(len)});
}
if ((len * 2) > this.overflow.length) {
// Resize buffer and overflow
this.buffer = new char[len + 1024];
final char[] newOverflow = new char[len + 2048];
System.arraycopy(this.overflow, 0, newOverflow, 0, this.overflowIndex);
this.overflow = newOverflow;
}
int bufferSize = 0;
if (this.overflowIndex > 0) {
final int copied =
copyToResult(
this.overflow, 0, this.overflowIndex,
this.buffer, 0, this.buffer.length);
bufferSize += copied;
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] READ FROM OVERFLOW BUFFER {} Some content from the overflow buffer has been copied into results.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(copied)});
}
}
char[] overflowOverflow = null;
if (this.overflowIndex > 0) {
// Overflow did not entirely fit into buffer, and some overflow
// had to be relocated. This overflow will have to be placed at the end of the
// overflow generated in the current call (if any).
overflowOverflow = new char[this.overflowIndex];
System.arraycopy(this.overflow, 0, overflowOverflow, 0, this.overflowIndex);
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RELLOCATED SOME OVERFLOW CONTENTS, WAITING TO BE ADDED TO RESULT/NEW OVERFLOW {} Some content was remaining at the overflow buffer and will have to be rellocated.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(this.overflowIndex)});
}
this.overflowIndex = 0;
}
if (!this.noMoreToRead && bufferSize < this.buffer.length) {
// Buffer was not filled up with content from overflow, so ask for more content
final int toBeRead = this.buffer.length - bufferSize;
int reallyRead = this.bufferedReader.read(this.buffer, bufferSize, toBeRead);
if (this.addSyntheticRootElement && !this.syntheticRootElementClosingSent && (reallyRead < 0)) {
// If there is no more content to be read from the source reader, close the synthetic
// root element and make it look like it was read from source.
final int closingSizeToInsert =
Math.min(
(SYNTHETIC_ROOT_ELEMENT_END_CHARS.length - this.rootElementClosingOffset),
(this.buffer.length - bufferSize));
reallyRead =
copyToResult(
SYNTHETIC_ROOT_ELEMENT_END_CHARS, this.rootElementClosingOffset, closingSizeToInsert,
this.buffer, bufferSize, this.buffer.length);
this.rootElementClosingOffset += reallyRead;
if (this.rootElementClosingOffset >= SYNTHETIC_ROOT_ELEMENT_END_CHARS.length) {
this.syntheticRootElementClosingSent = true;
}
}
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] READ FROM SOURCE {} A read operation was executed on the source reader (max chars requested: {}).",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(reallyRead), Integer.valueOf(toBeRead)});
}
if (reallyRead < 0) {
if (bufferSize == 0) {
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN {} After trying to read from input: No input left, no buffer left.",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(reallyRead)});
}
return reallyRead;
}
this.noMoreToRead = true;
} else {
bufferSize += reallyRead;
}
}
if (this.noMoreToRead && bufferSize == 0) {
// Nothing left to do. Just return -1
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN -1 Reader was already marked to be finished. No more input, no more buffer.",
new Object[] {TemplateEngine.threadIndex()});
}
return -1;
}
int totalRead = 0;
int cbufi = off;
int last = off + len;
int buffi = 0;
while (cbufi < last && buffi < bufferSize) {
/*
* Process DOCTYPE first (if needed)
*/
if (!this.docTypeClauseRead) {
final int matchedDocType =
match(DOCTYPE, 0, DOCTYPE.length, this.buffer, buffi, bufferSize);
if (matchedDocType > 0) {
this.docTypeClause = new String(this.buffer, buffi, matchedDocType);
this.docTypeClauseRead = true;
final char[] normalizedDocType =
normalizeDocTypeClause(this.buffer, buffi, matchedDocType);
if (readerLogger.isTraceEnabled()) {
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] Normalized DOCTYPE clause: {}",
new Object[] {TemplateEngine.threadIndex(), new String(normalizedDocType)});
}
int copied = -1;
if (this.addSyntheticRootElement && !this.syntheticRootElementOpeningProcessed) {
// If DOCTYPE is processed, we will inject the synthetic root
// element just after the DOCTYPE so that we avoid problems with
// DOCTYPE clause being bigger than 'len' argument in the first 'read()' call.
final char[] normalizedDocTypePlusSyntheticRootElement =
new char[normalizedDocType.length + SYNTHETIC_ROOT_ELEMENT_START_CHARS.length];
System.arraycopy(normalizedDocType, 0, normalizedDocTypePlusSyntheticRootElement, 0, normalizedDocType.length);
System.arraycopy(SYNTHETIC_ROOT_ELEMENT_START_CHARS, 0, normalizedDocTypePlusSyntheticRootElement, normalizedDocType.length, SYNTHETIC_ROOT_ELEMENT_START_CHARS.length);
copied =
copyToResult(
normalizedDocTypePlusSyntheticRootElement, 0, normalizedDocTypePlusSyntheticRootElement.length,
cbuf, cbufi, last);
this.syntheticRootElementOpeningProcessed = true;
} else {
copied =
copyToResult(
normalizedDocType, 0, normalizedDocType.length,
cbuf, cbufi, last);
}
cbufi += copied;
totalRead += copied;
buffi += matchedDocType;
continue;
}
}
final int matchedStartOfComment =
(this.inComment?
-2 : match(COMMENT_START, 0, COMMENT_START.length, this.buffer, buffi, bufferSize));
if (matchedStartOfComment > 0) {
this.inComment = true;
final int copied =
copyToResult(
this.buffer, buffi, matchedStartOfComment,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += matchedStartOfComment;
continue;
}
final int matchedEndOfComment =
(this.inComment?
match(COMMENT_END, 0, COMMENT_END.length, this.buffer, buffi, bufferSize) : -2);
if (matchedEndOfComment > 0) {
this.inComment = false;
final int copied =
copyToResult(
this.buffer, buffi, matchedEndOfComment,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += matchedEndOfComment;
continue;
}
final int matchedEntity =
(this.inComment?
-2 : match(ENTITY, 0, ENTITY.length, this.buffer, buffi, bufferSize));
if (matchedEntity > 0) {
final int copied =
copyToResult(
ENTITY_START_SUBSTITUTE_CHAR_ARRAY, 0, ENTITY_START_SUBSTITUTE_CHAR_ARRAY.length,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
buffi += 1; // Only one character is substituted (&)
continue;
}
if (!Character.isWhitespace(this.buffer[buffi]) && this.addSyntheticRootElement && !this.syntheticRootElementOpeningProcessed && !this.inComment) {
// This block will be reached if we did not have to process a
// DOCTYPE clause (because the DOCTYPE would have
// matched the previous block). And will not be affected by any whitespaces
// or comments before DOCTYPE because of the !Character.isWhitespace condition.
final int copied =
copyToResult(
SYNTHETIC_ROOT_ELEMENT_START_CHARS, 0, SYNTHETIC_ROOT_ELEMENT_START_CHARS.length,
cbuf, cbufi, last);
cbufi += copied;
totalRead += copied;
this.syntheticRootElementOpeningProcessed = true;
continue;
}
cbuf[cbufi++] = this.buffer[buffi++];
totalRead++;
}
if (buffi < bufferSize) {
// Copy remaining buffer to overflow
final int toBeOverFlowed = bufferSize - buffi;
final int copied =
copyToResult(
this.buffer, buffi, toBeOverFlowed,
cbuf, cbufi, last);
// copied must be zero
if (copied != 0) {
throw new TemplateInputException("Overflow was not correctly computed!");
}
}
if (overflowOverflow != null) {
final int copied =
copyToResult(
overflowOverflow, 0, overflowOverflow.length,
cbuf, cbufi, last);
// copied must be zero
if (copied != 0) {
throw new TemplateInputException("Overflow-overflow was not correctly computed!");
}
}
if (readerLogger.isTraceEnabled()) {
final char[] result = new char[totalRead];
System.arraycopy(cbuf, off, result, 0, totalRead);
readerLogger.trace("[THYMELEAF][TEMPLATEPREPROCESSINGREADER][{}] RETURN {} Input was read and processed. Returning content: [[{}]]",
new Object[] {TemplateEngine.threadIndex(), Integer.valueOf(totalRead), new String(result)});
}
return totalRead;
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/TransitBoardAlight.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/TransitBoardAlight.java
index 8865ca266..dc72ec368 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/TransitBoardAlight.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/edgetype/TransitBoardAlight.java
@@ -1,396 +1,397 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.edgetype;
import org.onebusaway.gtfs.model.Route;
import org.onebusaway.gtfs.model.Trip;
import org.opentripplanner.gtfs.GtfsLibrary;
import org.opentripplanner.routing.core.EdgeNarrative;
import org.opentripplanner.routing.core.RouteSpec;
import org.opentripplanner.routing.core.RoutingContext;
import org.opentripplanner.routing.core.ServiceDay;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.core.StateEditor;
import org.opentripplanner.routing.core.TraverseMode;
import org.opentripplanner.routing.core.TraverseModeSet;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.trippattern.TripTimes;
import org.opentripplanner.routing.vertextype.PatternStopVertex;
import org.opentripplanner.routing.vertextype.TransitStopArrive;
import org.opentripplanner.routing.vertextype.TransitStopDepart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import lombok.Getter;
import com.vividsolutions.jts.geom.Geometry;
/**
* Models boarding or alighting a vehicle - that is to say, traveling from a state off
* vehicle to a state on vehicle. When traversed forward on a boarding or backwards on an
* alighting, the the resultant state has the time of the next departure, in addition the pattern
* that was boarded. When traversed backward on a boarding or forward on an alighting, the result
* state is unchanged. A boarding penalty can also be applied to discourage transfers. In an on
* the fly reverse-optimization search, the overloaded traverse method can be used to give an
* initial wait time. Also, in reverse-opimization, board costs are correctly applied.
*
* This is the result of combining the classes formerly known as PatternBoard and PatternAlight.
*
* @author mattwigway
*/
public class TransitBoardAlight extends PatternEdge implements OnBoardForwardEdge {
private static final long serialVersionUID = 1042740795612978747L;
private static final Logger _log = LoggerFactory.getLogger(TransitBoardAlight.class);
private int stopIndex;
private int modeMask;
@Getter
private boolean boarding;
public TransitBoardAlight (TransitStopDepart fromStopVertex, PatternStopVertex toPatternVertex,
TableTripPattern pattern, int stopIndex, TraverseMode mode) {
super(fromStopVertex, toPatternVertex);
this.stopIndex = stopIndex;
this.modeMask = new TraverseModeSet(mode).getMask();
this.boarding = true;
}
public TransitBoardAlight (PatternStopVertex fromPatternStop, TransitStopArrive toStationVertex,
TableTripPattern pattern, int stopIndex, TraverseMode mode) {
super(fromPatternStop, toStationVertex);
this.stopIndex = stopIndex;
this.modeMask = new TraverseModeSet(mode).getMask();
this.boarding = false;
}
/** look for pattern in tov (instead of fromv as is done for all other pattern edges) */
@Override
public TableTripPattern getPattern() {
if (boarding)
return ((PatternStopVertex) tov).getTripPattern();
else
return ((PatternStopVertex) fromv).getTripPattern();
}
public String getDirection() {
return null;
}
public double getDistance() {
return 0;
}
public Geometry getGeometry() {
return null;
}
public TraverseMode getMode() {
return boarding ? TraverseMode.BOARDING : TraverseMode.ALIGHTING;
}
public String getName() {
return boarding ? "leave street network for transit network" :
"leave transit network for street network";
}
@Override
public State traverse(State state0) {
return traverse(state0, 0);
}
public State traverse(State state0, long arrivalTimeAtStop) {
RoutingContext rctx = state0.getContext();
RoutingRequest options = state0.getOptions();
// this method is on State not RoutingRequest because we care whether the user is in
// possession of a rented bike.
TraverseMode mode = state0.getNonTransitMode(options);
// figure out the direction
- // XOR: http://stackoverflow.com/questions/726652
- boolean offTransit = !((boarding || options.isArriveBy()) &&
- !(boarding && options.isArriveBy()));
+ // it's leaving transit iff it's a boarding and is arrive by, or it's not a boarding and
+ // is not arrive by
+ boolean offTransit = (boarding && options.isArriveBy()) ||
+ (!boarding && !options.isArriveBy());
if (offTransit) {
int type;
/* leaving transit, not so much to do */
// do not alight immediately when arrive-depart dwell has been eliminated
// this affects multi-itinerary searches
if (state0.getBackEdge() instanceof TransitBoardAlight) {
return null;
}
EdgeNarrative en = new TransitNarrative(state0.getTripTimes().trip, this);
StateEditor s1 = state0.edit(this, en);
if (boarding)
type = getPattern().getBoardType(stopIndex);
else
type = getPattern().getAlightType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTripId(null);
s1.setLastAlightedTime(state0.getTime());
s1.setPreviousStop(fromv);
s1.setLastPattern(this.getPattern());
// determine the wait
if (arrivalTimeAtStop > 0) {
int wait = (int) Math.abs(state0.getTime() - arrivalTimeAtStop);
s1.incrementTimeInSeconds(wait);
// this should only occur at the beginning
s1.incrementWeight(wait * options.waitAtBeginningFactor);
s1.setInitialWaitTime(wait);
//_log.debug("Initial wait time set to {} in PatternBoard", wait);
}
// during reverse optimization, board costs should be applied to PatternBoards
// so that comparable trip plans result (comparable to non-optimized plans)
if (options.isReverseOptimizing())
s1.incrementWeight(options.getBoardCost(mode));
if (options.isReverseOptimizeOnTheFly()) {
int thisDeparture = state0.getTripTimes().getDepartureTime(stopIndex);
int numTrips = getPattern().getNumTrips();
int nextDeparture;
s1.setLastNextArrivalDelta(Integer.MAX_VALUE);
for (int tripIndex = 0; tripIndex < numTrips; tripIndex++) {
nextDeparture = getPattern().getDepartureTime(stopIndex, tripIndex);
if (nextDeparture > thisDeparture) {
s1.setLastNextArrivalDelta(nextDeparture - thisDeparture);
break;
}
}
}
return s1.makeState();
} else {
/* onto transit: look for a transit trip on this pattern */
int wait, type;
TripTimes tripTimes;
if (state0.getLastPattern() == this.getPattern()) {
return null;
}
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding/alighting time
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to
* initial state) if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long current_time = state0.getTime();
int bestWait = -1;
TripTimes bestTripTimes = null;
int serviceId = getPattern().getServiceId();
for (ServiceDay sd : rctx.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(current_time);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
// Removed by mattwigway 2012-08-06 following discussion with novalis_dt.
// Imagine a state at 23:59 Sunday, that should take a bus departing at 00:01
// Monday (and coded on Monday in the GTFS); disallowing Monday's departures would
// produce a strange plan. This proved to be a problem when reverse-optimizing
// arrive-by trips; trips would get moved earlier for transfer purposes and then
// the future days would not be considered.
// We also can't break off the search after we find trips today, because imagine
// a trip on a pattern at 25:00 today and another trip on the same pattern at
// 00:30 tommorrow. The 00:30 trip should be taken, but if we stopped the search
// after finding today's 25:00 trip we would never find tomorrow's 00:30 trip.
//if (secondsSinceMidnight < 0)
// continue;
if (sd.serviceIdRunning(serviceId)) {
// make sure we search for boards on board and alights on alight
if (boarding)
tripTimes = getPattern().getNextTrip(stopIndex,
secondsSinceMidnight, mode == TraverseMode.BICYCLE, options);
else
tripTimes = getPattern().getPreviousTrip(stopIndex,
secondsSinceMidnight, mode == TraverseMode.BICYCLE, options);
if (tripTimes != null) {
// a trip was found, index is valid, wait will be non-negative
// we care about departures on board and arrivals on alight
if (boarding)
wait = (int)
(sd.time(tripTimes.getDepartureTime(stopIndex)) - current_time);
else
wait = (int)
(current_time - sd.time(tripTimes.getArrivalTime(stopIndex)));
if (wait < 0)
_log.error("negative wait time on board");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
bestTripTimes = tripTimes;
}
}
}
}
if (bestWait < 0) {
return null;
}
Trip trip = bestTripTimes.getTrip();
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan */
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
if (boarding)
type = getPattern().getBoardType(stopIndex);
else
type = getPattern().getAlightType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
// save the trip times to ensure that router has a consistent view of them
s1.setTripTimes(bestTripTimes);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(getPattern().getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
double wait_cost = bestWait;
if (state0.getNumBoardings() == 0 && !options.isReverseOptimizing()) {
wait_cost *= options.waitAtBeginningFactor;
// this is subtracted out in Analyst searches in lieu of reverse optimization
s1.setInitialWaitTime(bestWait);
} else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
// when reverse optimizing, the board cost needs to be applied on
// alight to prevent state domination due to free alights
if (options.isReverseOptimizing())
s1.incrementWeight(wait_cost);
else
s1.incrementWeight(wait_cost + options.getBoardCost(mode));
// On-the-fly reverse optimization
// determine if this needs to be reverse-optimized.
// The last alight can be moved forward by bestWait (but no further) without
// impacting the possibility of this trip
if (options.isReverseOptimizeOnTheFly() && !options.isReverseOptimizing() &&
state0.getNumBoardings() > 0 && state0.getLastNextArrivalDelta() <= bestWait &&
state0.getLastNextArrivalDelta() > -1) {
// it is re-reversed by optimize, so this still yields a forward tree
State optimized = s1.makeState().optimizeOrReverse(true, true);
if (optimized == null)
_log.error("Null optimized state. This shouldn't happen");
return optimized;
}
// if we didn't return an optimized path, return an unoptimized one
return s1.makeState();
}
}
public State optimisticTraverse(State state0) {
StateEditor s1 = state0.edit(this);
// no cost (see patternalight)
return s1.makeState();
}
/* See weightLowerBound comment. */
public double timeLowerBound(RoutingContext rctx) {
if ((rctx.opt.isArriveBy() && boarding) || (!rctx.opt.isArriveBy() && !boarding)) {
if (!rctx.opt.getModes().get(modeMask)) {
return Double.POSITIVE_INFINITY;
}
int serviceId = getPattern().getServiceId();
for (ServiceDay sd : rctx.serviceDays)
if (sd.serviceIdRunning(serviceId))
return 0;
return Double.POSITIVE_INFINITY;
} else {
return 0;
}
}
/*
* If the main search is proceeding backward, the lower bound search is proceeding forward.
* Check the mode or serviceIds of this pattern at board time to see whether this pattern is
* worth exploring. If the main search is proceeding forward, board cost is added at board
* edges. The lower bound search is proceeding backward, and if it has reached a board edge the
* pattern was already deemed useful.
*/
public double weightLowerBound(RoutingRequest options) {
if ((options.isArriveBy() && boarding) || (!options.isArriveBy() && !boarding))
return timeLowerBound(options);
else
return options.getBoardCostLowerBound();
}
public int getStopIndex() {
return stopIndex;
}
public String toString() {
return "TransitBoardAlight(" +
(boarding ? "boarding " : "alighting ") +
getFromVertex() + " to " + getToVertex() + ")";
}
}
| true | true | public State traverse(State state0, long arrivalTimeAtStop) {
RoutingContext rctx = state0.getContext();
RoutingRequest options = state0.getOptions();
// this method is on State not RoutingRequest because we care whether the user is in
// possession of a rented bike.
TraverseMode mode = state0.getNonTransitMode(options);
// figure out the direction
// XOR: http://stackoverflow.com/questions/726652
boolean offTransit = !((boarding || options.isArriveBy()) &&
!(boarding && options.isArriveBy()));
if (offTransit) {
int type;
/* leaving transit, not so much to do */
// do not alight immediately when arrive-depart dwell has been eliminated
// this affects multi-itinerary searches
if (state0.getBackEdge() instanceof TransitBoardAlight) {
return null;
}
EdgeNarrative en = new TransitNarrative(state0.getTripTimes().trip, this);
StateEditor s1 = state0.edit(this, en);
if (boarding)
type = getPattern().getBoardType(stopIndex);
else
type = getPattern().getAlightType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTripId(null);
s1.setLastAlightedTime(state0.getTime());
s1.setPreviousStop(fromv);
s1.setLastPattern(this.getPattern());
// determine the wait
if (arrivalTimeAtStop > 0) {
int wait = (int) Math.abs(state0.getTime() - arrivalTimeAtStop);
s1.incrementTimeInSeconds(wait);
// this should only occur at the beginning
s1.incrementWeight(wait * options.waitAtBeginningFactor);
s1.setInitialWaitTime(wait);
//_log.debug("Initial wait time set to {} in PatternBoard", wait);
}
// during reverse optimization, board costs should be applied to PatternBoards
// so that comparable trip plans result (comparable to non-optimized plans)
if (options.isReverseOptimizing())
s1.incrementWeight(options.getBoardCost(mode));
if (options.isReverseOptimizeOnTheFly()) {
int thisDeparture = state0.getTripTimes().getDepartureTime(stopIndex);
int numTrips = getPattern().getNumTrips();
int nextDeparture;
s1.setLastNextArrivalDelta(Integer.MAX_VALUE);
for (int tripIndex = 0; tripIndex < numTrips; tripIndex++) {
nextDeparture = getPattern().getDepartureTime(stopIndex, tripIndex);
if (nextDeparture > thisDeparture) {
s1.setLastNextArrivalDelta(nextDeparture - thisDeparture);
break;
}
}
}
return s1.makeState();
} else {
/* onto transit: look for a transit trip on this pattern */
int wait, type;
TripTimes tripTimes;
if (state0.getLastPattern() == this.getPattern()) {
return null;
}
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding/alighting time
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to
* initial state) if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long current_time = state0.getTime();
int bestWait = -1;
TripTimes bestTripTimes = null;
int serviceId = getPattern().getServiceId();
for (ServiceDay sd : rctx.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(current_time);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
// Removed by mattwigway 2012-08-06 following discussion with novalis_dt.
// Imagine a state at 23:59 Sunday, that should take a bus departing at 00:01
// Monday (and coded on Monday in the GTFS); disallowing Monday's departures would
// produce a strange plan. This proved to be a problem when reverse-optimizing
// arrive-by trips; trips would get moved earlier for transfer purposes and then
// the future days would not be considered.
// We also can't break off the search after we find trips today, because imagine
// a trip on a pattern at 25:00 today and another trip on the same pattern at
// 00:30 tommorrow. The 00:30 trip should be taken, but if we stopped the search
// after finding today's 25:00 trip we would never find tomorrow's 00:30 trip.
//if (secondsSinceMidnight < 0)
// continue;
if (sd.serviceIdRunning(serviceId)) {
// make sure we search for boards on board and alights on alight
if (boarding)
tripTimes = getPattern().getNextTrip(stopIndex,
secondsSinceMidnight, mode == TraverseMode.BICYCLE, options);
else
tripTimes = getPattern().getPreviousTrip(stopIndex,
secondsSinceMidnight, mode == TraverseMode.BICYCLE, options);
if (tripTimes != null) {
// a trip was found, index is valid, wait will be non-negative
// we care about departures on board and arrivals on alight
if (boarding)
wait = (int)
(sd.time(tripTimes.getDepartureTime(stopIndex)) - current_time);
else
wait = (int)
(current_time - sd.time(tripTimes.getArrivalTime(stopIndex)));
if (wait < 0)
_log.error("negative wait time on board");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
bestTripTimes = tripTimes;
}
}
}
}
if (bestWait < 0) {
return null;
}
Trip trip = bestTripTimes.getTrip();
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan */
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
if (boarding)
type = getPattern().getBoardType(stopIndex);
else
type = getPattern().getAlightType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
// save the trip times to ensure that router has a consistent view of them
s1.setTripTimes(bestTripTimes);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(getPattern().getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
double wait_cost = bestWait;
if (state0.getNumBoardings() == 0 && !options.isReverseOptimizing()) {
wait_cost *= options.waitAtBeginningFactor;
// this is subtracted out in Analyst searches in lieu of reverse optimization
s1.setInitialWaitTime(bestWait);
} else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
// when reverse optimizing, the board cost needs to be applied on
// alight to prevent state domination due to free alights
if (options.isReverseOptimizing())
s1.incrementWeight(wait_cost);
else
s1.incrementWeight(wait_cost + options.getBoardCost(mode));
// On-the-fly reverse optimization
// determine if this needs to be reverse-optimized.
// The last alight can be moved forward by bestWait (but no further) without
// impacting the possibility of this trip
if (options.isReverseOptimizeOnTheFly() && !options.isReverseOptimizing() &&
state0.getNumBoardings() > 0 && state0.getLastNextArrivalDelta() <= bestWait &&
state0.getLastNextArrivalDelta() > -1) {
// it is re-reversed by optimize, so this still yields a forward tree
State optimized = s1.makeState().optimizeOrReverse(true, true);
if (optimized == null)
_log.error("Null optimized state. This shouldn't happen");
return optimized;
}
// if we didn't return an optimized path, return an unoptimized one
return s1.makeState();
}
}
| public State traverse(State state0, long arrivalTimeAtStop) {
RoutingContext rctx = state0.getContext();
RoutingRequest options = state0.getOptions();
// this method is on State not RoutingRequest because we care whether the user is in
// possession of a rented bike.
TraverseMode mode = state0.getNonTransitMode(options);
// figure out the direction
// it's leaving transit iff it's a boarding and is arrive by, or it's not a boarding and
// is not arrive by
boolean offTransit = (boarding && options.isArriveBy()) ||
(!boarding && !options.isArriveBy());
if (offTransit) {
int type;
/* leaving transit, not so much to do */
// do not alight immediately when arrive-depart dwell has been eliminated
// this affects multi-itinerary searches
if (state0.getBackEdge() instanceof TransitBoardAlight) {
return null;
}
EdgeNarrative en = new TransitNarrative(state0.getTripTimes().trip, this);
StateEditor s1 = state0.edit(this, en);
if (boarding)
type = getPattern().getBoardType(stopIndex);
else
type = getPattern().getAlightType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
s1.setTripId(null);
s1.setLastAlightedTime(state0.getTime());
s1.setPreviousStop(fromv);
s1.setLastPattern(this.getPattern());
// determine the wait
if (arrivalTimeAtStop > 0) {
int wait = (int) Math.abs(state0.getTime() - arrivalTimeAtStop);
s1.incrementTimeInSeconds(wait);
// this should only occur at the beginning
s1.incrementWeight(wait * options.waitAtBeginningFactor);
s1.setInitialWaitTime(wait);
//_log.debug("Initial wait time set to {} in PatternBoard", wait);
}
// during reverse optimization, board costs should be applied to PatternBoards
// so that comparable trip plans result (comparable to non-optimized plans)
if (options.isReverseOptimizing())
s1.incrementWeight(options.getBoardCost(mode));
if (options.isReverseOptimizeOnTheFly()) {
int thisDeparture = state0.getTripTimes().getDepartureTime(stopIndex);
int numTrips = getPattern().getNumTrips();
int nextDeparture;
s1.setLastNextArrivalDelta(Integer.MAX_VALUE);
for (int tripIndex = 0; tripIndex < numTrips; tripIndex++) {
nextDeparture = getPattern().getDepartureTime(stopIndex, tripIndex);
if (nextDeparture > thisDeparture) {
s1.setLastNextArrivalDelta(nextDeparture - thisDeparture);
break;
}
}
}
return s1.makeState();
} else {
/* onto transit: look for a transit trip on this pattern */
int wait, type;
TripTimes tripTimes;
if (state0.getLastPattern() == this.getPattern()) {
return null;
}
if (!options.getModes().get(modeMask)) {
return null;
}
/* find next boarding/alighting time
* check lists of transit serviceIds running yesterday, today, and tomorrow (relative to
* initial state) if this pattern's serviceId is running look for the next boarding time
* choose the soonest boarding time among trips starting yesterday, today, or tomorrow
*/
long current_time = state0.getTime();
int bestWait = -1;
TripTimes bestTripTimes = null;
int serviceId = getPattern().getServiceId();
for (ServiceDay sd : rctx.serviceDays) {
int secondsSinceMidnight = sd.secondsSinceMidnight(current_time);
// only check for service on days that are not in the future
// this avoids unnecessarily examining tomorrow's services
// Removed by mattwigway 2012-08-06 following discussion with novalis_dt.
// Imagine a state at 23:59 Sunday, that should take a bus departing at 00:01
// Monday (and coded on Monday in the GTFS); disallowing Monday's departures would
// produce a strange plan. This proved to be a problem when reverse-optimizing
// arrive-by trips; trips would get moved earlier for transfer purposes and then
// the future days would not be considered.
// We also can't break off the search after we find trips today, because imagine
// a trip on a pattern at 25:00 today and another trip on the same pattern at
// 00:30 tommorrow. The 00:30 trip should be taken, but if we stopped the search
// after finding today's 25:00 trip we would never find tomorrow's 00:30 trip.
//if (secondsSinceMidnight < 0)
// continue;
if (sd.serviceIdRunning(serviceId)) {
// make sure we search for boards on board and alights on alight
if (boarding)
tripTimes = getPattern().getNextTrip(stopIndex,
secondsSinceMidnight, mode == TraverseMode.BICYCLE, options);
else
tripTimes = getPattern().getPreviousTrip(stopIndex,
secondsSinceMidnight, mode == TraverseMode.BICYCLE, options);
if (tripTimes != null) {
// a trip was found, index is valid, wait will be non-negative
// we care about departures on board and arrivals on alight
if (boarding)
wait = (int)
(sd.time(tripTimes.getDepartureTime(stopIndex)) - current_time);
else
wait = (int)
(current_time - sd.time(tripTimes.getArrivalTime(stopIndex)));
if (wait < 0)
_log.error("negative wait time on board");
if (bestWait < 0 || wait < bestWait) {
// track the soonest departure over all relevant schedules
bestWait = wait;
bestTripTimes = tripTimes;
}
}
}
}
if (bestWait < 0) {
return null;
}
Trip trip = bestTripTimes.getTrip();
/* check if route banned for this plan */
if (options.bannedRoutes != null) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.bannedRoutes.contains(spec)) {
return null;
}
}
/* check if route is preferred for this plan */
long preferences_penalty = 0;
if (options.preferredRoutes != null && options.preferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (!options.preferredRoutes.contains(spec)) {
preferences_penalty += options.useAnotherThanPreferredRoutesPenalty;
}
}
/* check if route is unpreferred for this plan */
if (options.unpreferredRoutes != null && options.unpreferredRoutes.size() > 0) {
Route route = trip.getRoute();
RouteSpec spec = new RouteSpec(route.getId().getAgencyId(),
GtfsLibrary.getRouteName(route));
if (options.unpreferredRoutes.contains(spec)) {
preferences_penalty += options.useUnpreferredRoutesPenalty;
}
}
EdgeNarrative en = new TransitNarrative(trip, this);
StateEditor s1 = state0.edit(this, en);
if (boarding)
type = getPattern().getBoardType(stopIndex);
else
type = getPattern().getAlightType(stopIndex);
if (TransitUtils.handleBoardAlightType(s1, type)) {
return null;
}
// save the trip times to ensure that router has a consistent view of them
s1.setTripTimes(bestTripTimes);
s1.incrementTimeInSeconds(bestWait);
s1.incrementNumBoardings();
s1.setTripId(trip.getId());
s1.setZone(getPattern().getZone(stopIndex));
s1.setRoute(trip.getRoute().getId());
double wait_cost = bestWait;
if (state0.getNumBoardings() == 0 && !options.isReverseOptimizing()) {
wait_cost *= options.waitAtBeginningFactor;
// this is subtracted out in Analyst searches in lieu of reverse optimization
s1.setInitialWaitTime(bestWait);
} else {
wait_cost *= options.waitReluctance;
}
s1.incrementWeight(preferences_penalty);
// when reverse optimizing, the board cost needs to be applied on
// alight to prevent state domination due to free alights
if (options.isReverseOptimizing())
s1.incrementWeight(wait_cost);
else
s1.incrementWeight(wait_cost + options.getBoardCost(mode));
// On-the-fly reverse optimization
// determine if this needs to be reverse-optimized.
// The last alight can be moved forward by bestWait (but no further) without
// impacting the possibility of this trip
if (options.isReverseOptimizeOnTheFly() && !options.isReverseOptimizing() &&
state0.getNumBoardings() > 0 && state0.getLastNextArrivalDelta() <= bestWait &&
state0.getLastNextArrivalDelta() > -1) {
// it is re-reversed by optimize, so this still yields a forward tree
State optimized = s1.makeState().optimizeOrReverse(true, true);
if (optimized == null)
_log.error("Null optimized state. This shouldn't happen");
return optimized;
}
// if we didn't return an optimized path, return an unoptimized one
return s1.makeState();
}
}
|
diff --git a/src/main/java/com/happyelements/hive/web/HadoopClient.java b/src/main/java/com/happyelements/hive/web/HadoopClient.java
index 0e97340..6abf8c8 100755
--- a/src/main/java/com/happyelements/hive/web/HadoopClient.java
+++ b/src/main/java/com/happyelements/hive/web/HadoopClient.java
@@ -1,271 +1,276 @@
/*
* Copyright (c) 2012, someone All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1.Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer. 2.Redistributions in binary
* form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided
* with the distribution. 3.Neither the name of the Happyelements Ltd. nor the
* names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.happyelements.hive.web;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.JobStatus;
import org.apache.hadoop.mapred.JobTracker;
import org.apache.hadoop.mapred.RunningJob;
/**
* wrapper for some hadoop api
* @author <a href="mailto:[email protected]">kevin</a>
*/
public class HadoopClient {
private static final Log LOGGER = LogFactory.getLog(HadoopClient.class);
/**
* query info,include job status and query/user
* @author <a href="mailto:[email protected]">kevin</a>
*/
public static class QueryInfo {
public final String user;
public final String query_id;
public final String query;
public final String job_id;
public final Configuration configuration;
public long access;
public JobStatus status;
/**
* constructor
* @param user
* the user name
* @param query_id
* the query id
* @param query
* the query string
* @param job_id
* the job id
*/
public QueryInfo(String user, String query_id, String query,
String job_id, Configuration configuration) {
this.user = user;
this.query_id = query_id;
this.query = query.replace("\n", " ").replace("\r", " ")
.replace("\"", "'");
this.job_id = job_id;
this.configuration = configuration;
}
/**
* {@inheritDoc}}
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "user:" + this.user + " query_id:" + this.query_id
+ " job_id:" + this.job_id + " query:" + this.query;
}
}
private static int refresh_request_count = 0;
private static long now = System.currentTimeMillis();
private static final org.apache.hadoop.mapred.JobClient CLIENT;
private static final ConcurrentHashMap<String, Map<String, QueryInfo>> USER_JOB_CACHE;
private static final ConcurrentHashMap<String, QueryInfo> JOB_CACHE;
static {
try {
CLIENT = new org.apache.hadoop.mapred.JobClient(new JobConf(
new HiveConf()));
} catch (Exception e) {
throw new RuntimeException(e);
}
// create user job cache
JOB_CACHE = new ConcurrentHashMap<String, HadoopClient.QueryInfo>();
USER_JOB_CACHE = new ConcurrentHashMap<String, Map<String, QueryInfo>>();
Timer timer = Central.getTimer();
// schedule user cache update
timer.schedule(new TimerTask() {
@Override
public void run() {
if (HadoopClient.refresh_request_count <= 0) {
return;
}
HadoopClient.now = System.currentTimeMillis();
try {
LOGGER.debug("trigger refresh jobs");
for (JobStatus status : HadoopClient.CLIENT.getAllJobs()) {
// save job id
String job_id = status.getJobID().getJtIdentifier();
// update info
QueryInfo info = JOB_CACHE.get(job_id);
if (info == null) {
JobConf conf = new JobConf(JobTracker
.getLocalJobFilePath(status.getJobID()));
String query = conf.get("hive.query.string");
String query_id = conf.get("rest.query.id");
String user = conf.get("he.user.name");
info = new QueryInfo(user == null ? "" : user, //
query_id == null ? "" : query_id, //
query == null ? "" : query, //
job_id, conf);
info.access = HadoopClient.now;
JOB_CACHE.put(job_id, info);
}
// update status
info.status = status;
- // find user cache
- Map<String, QueryInfo> user_infos = USER_JOB_CACHE
- .get(info.user);
- if (user_infos == null) {
- user_infos = new ConcurrentHashMap<String, HadoopClient.QueryInfo>();
- USER_JOB_CACHE.put(info.user, user_infos);
+ // tricky way to update user cache,as a none App,user
+ // will be empty
+ if (!info.user.isEmpty()) {
+ // find user cache
+ Map<String, QueryInfo> user_infos = USER_JOB_CACHE
+ .get(info.user);
+ if (user_infos == null) {
+ user_infos = new ConcurrentHashMap<String, HadoopClient.QueryInfo>();
+ USER_JOB_CACHE.put(info.user, user_infos);
+ }
+ user_infos.put(job_id, info);
+ user_infos.put(
+ info.configuration.get("rest.query.id"),
+ info);
}
- user_infos.put(job_id, info);
- user_infos.put(info.configuration.get("rest.query.id"),
- info);
}
// reset flag
HadoopClient.refresh_request_count = 0;
} catch (IOException e) {
HadoopClient.LOGGER.error("fail to refresh old job", e);
}
}
}, 0, 1000);
// schedule query info cache clean up
timer.schedule(new TimerTask() {
@Override
public void run() {
HadoopClient.now = System.currentTimeMillis();
// clear user jobs
for (Entry<String, Map<String, QueryInfo>> entry : HadoopClient.USER_JOB_CACHE
.entrySet()) {
// optimize cache size
boolean empty = true;
// find eviction
Map<String, QueryInfo> user_querys = entry.getValue();
for (Entry<String, QueryInfo> query_info_entry : user_querys
.entrySet()) {
empty = false;
QueryInfo info = query_info_entry.getValue();
if (info == null
|| HadoopClient.now - info.access >= 3600000) {
user_querys.remove(entry.getKey());
}
}
// no entry in map ,remove it
if (empty) {
// it *MAY* help GC
new SoftReference<Map<String, QueryInfo>>(
HadoopClient.USER_JOB_CACHE.remove(entry
.getKey()));
}
}
// clear jobs
for (Entry<String, QueryInfo> entry : JOB_CACHE.entrySet()) {
QueryInfo info = entry.getValue();
if (info == null
|| HadoopClient.now - info.access >= 3600000) {
JOB_CACHE.remove(entry.getKey());
}
}
}
}, 0, 60000);
}
/**
* find query info by either job id or query id
* @param id
* either job id or query id
* @return
* the query info
*/
public static QueryInfo getQueryInfo(String id) {
// trigger refresh
HadoopClient.refresh_request_count++;
QueryInfo info;
// lucky case
if ((info = JOB_CACHE.get(id)) != null) {
return info;
}
// may be a query id loop it
for (Entry<String, Map<String, QueryInfo>> entry : HadoopClient.USER_JOB_CACHE
.entrySet()) {
// find match
if ((info = entry.getValue().get(id)) != null) {
break;
}
}
return info;
}
/**
* get running job status
* @param id
* the JobID of job
* @return
* the running job if exist
* @throws IOException
* thrown when communicate to jobtracker fail
*/
public static RunningJob getJob(JobID id) throws IOException {
return HadoopClient.CLIENT.getJob(id);
}
/**
* get the user query
* @param user
* the user name
* @return
* the users name
*/
public static Map<String, QueryInfo> getUserQuerys(String user) {
// trigger refresh
HadoopClient.refresh_request_count++;
return HadoopClient.USER_JOB_CACHE.get(user);
}
}
| false | true | public void run() {
if (HadoopClient.refresh_request_count <= 0) {
return;
}
HadoopClient.now = System.currentTimeMillis();
try {
LOGGER.debug("trigger refresh jobs");
for (JobStatus status : HadoopClient.CLIENT.getAllJobs()) {
// save job id
String job_id = status.getJobID().getJtIdentifier();
// update info
QueryInfo info = JOB_CACHE.get(job_id);
if (info == null) {
JobConf conf = new JobConf(JobTracker
.getLocalJobFilePath(status.getJobID()));
String query = conf.get("hive.query.string");
String query_id = conf.get("rest.query.id");
String user = conf.get("he.user.name");
info = new QueryInfo(user == null ? "" : user, //
query_id == null ? "" : query_id, //
query == null ? "" : query, //
job_id, conf);
info.access = HadoopClient.now;
JOB_CACHE.put(job_id, info);
}
// update status
info.status = status;
// find user cache
Map<String, QueryInfo> user_infos = USER_JOB_CACHE
.get(info.user);
if (user_infos == null) {
user_infos = new ConcurrentHashMap<String, HadoopClient.QueryInfo>();
USER_JOB_CACHE.put(info.user, user_infos);
}
user_infos.put(job_id, info);
user_infos.put(info.configuration.get("rest.query.id"),
info);
}
// reset flag
HadoopClient.refresh_request_count = 0;
} catch (IOException e) {
HadoopClient.LOGGER.error("fail to refresh old job", e);
}
}
| public void run() {
if (HadoopClient.refresh_request_count <= 0) {
return;
}
HadoopClient.now = System.currentTimeMillis();
try {
LOGGER.debug("trigger refresh jobs");
for (JobStatus status : HadoopClient.CLIENT.getAllJobs()) {
// save job id
String job_id = status.getJobID().getJtIdentifier();
// update info
QueryInfo info = JOB_CACHE.get(job_id);
if (info == null) {
JobConf conf = new JobConf(JobTracker
.getLocalJobFilePath(status.getJobID()));
String query = conf.get("hive.query.string");
String query_id = conf.get("rest.query.id");
String user = conf.get("he.user.name");
info = new QueryInfo(user == null ? "" : user, //
query_id == null ? "" : query_id, //
query == null ? "" : query, //
job_id, conf);
info.access = HadoopClient.now;
JOB_CACHE.put(job_id, info);
}
// update status
info.status = status;
// tricky way to update user cache,as a none App,user
// will be empty
if (!info.user.isEmpty()) {
// find user cache
Map<String, QueryInfo> user_infos = USER_JOB_CACHE
.get(info.user);
if (user_infos == null) {
user_infos = new ConcurrentHashMap<String, HadoopClient.QueryInfo>();
USER_JOB_CACHE.put(info.user, user_infos);
}
user_infos.put(job_id, info);
user_infos.put(
info.configuration.get("rest.query.id"),
info);
}
}
// reset flag
HadoopClient.refresh_request_count = 0;
} catch (IOException e) {
HadoopClient.LOGGER.error("fail to refresh old job", e);
}
}
|
diff --git a/src/js/incomplete/JSPopover.java b/src/js/incomplete/JSPopover.java
index b9440cf..130897c 100644
--- a/src/js/incomplete/JSPopover.java
+++ b/src/js/incomplete/JSPopover.java
@@ -1,130 +1,131 @@
package js.incomplete;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Polygon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class JSPopover extends JFrame {
public static final int TOP = 0;
public static final int LEFT = 1;
private Color strokeColor = Color.black;
private JPanel panel;
private int direction;
public JSPopover() {
direction = TOP;
setLayout(null);
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
setAlwaysOnTop(true);
setFocusableWindowState(false);
panel = new JPanel();
panel.setBounds(10, 30, getWidth() - 20, getHeight() - 20);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
add(panel);
}
public JSPopover(int direction) {
setDirection(direction);
setLayout(null);
setUndecorated(true);
setBackground(new Color(0, 0, 0, 0));
setAlwaysOnTop(true);
setFocusableWindowState(false);
panel = new JPanel();
if (direction == LEFT)
panel.setBounds(30, 10, getWidth() - 40, getHeight() - 20);
else
panel.setBounds(10, 30, getWidth() - 20, getHeight() - 40);
panel.setBackground(Color.WHITE);
panel.setLayout(null);
add(panel);
}
public void setStrokeColor(Color c) {
strokeColor = c;
repaint();
}
public void setContentBackground(Color c) {
panel.setBackground(c);
}
public void paint(Graphics g) {
+ g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(strokeColor);
int width = getWidth();
int height = getHeight();
int middleH = height / 2;
int middleW = width / 2;
if (direction == LEFT) {
int[] xPoints = {0, 20, 20, 0};
int[] yPoints = {middleH, middleH - 20, middleH + 20, middleH};
int nPoints = xPoints.length;
Polygon p = new Polygon(xPoints, yPoints, nPoints);
g.fillPolygon(p);
g.fillRoundRect(20, 0, width - 21, height - 1, 20, 20);
} else {
int[] xPoints = {middleW, middleW + 20, middleW - 20, middleW};
int[] yPoints = {0, 20, 20, 0};
int nPoints = xPoints.length;
Polygon p = new Polygon(xPoints, yPoints, nPoints);
g.fillPolygon(p);
g.fillRoundRect(0, 20, width - 1, height - 21, 20, 20);
}
if (direction == LEFT)
panel.setBounds(30, 10, getWidth() - 40, getHeight() - 20);
else
panel.setBounds(10, 30, getWidth() - 20, getHeight() - 40);
super.paint(g);
}
public void setLocation(int x, int y) {
int width = getWidth();
int height = getHeight();
int middleH = height / 2;
int middleW = width / 2;
if (direction == LEFT)
super.setLocation(x, y - middleH);
else
super.setLocation(x - middleW, y);
}
public Component add(Component comp) {
if (comp != panel) {
return panel.add(comp);
} else {
return super.add(comp);
}
}
public void setSize(int width, int height) {
remove(panel);
if (direction == LEFT) {
panel.setBounds(30, 10, width - 40, height - 20);
super.setSize(width + 20, height);
} else {
panel.setBounds(10, 30, getWidth() - 20, getHeight() - 40);
super.setSize(width, height + 20);
}
add(panel);
}
public void setDirection(int direction) {
this.direction = direction;
repaint();
}
}
| true | true | public void paint(Graphics g) {
g.setColor(strokeColor);
int width = getWidth();
int height = getHeight();
int middleH = height / 2;
int middleW = width / 2;
if (direction == LEFT) {
int[] xPoints = {0, 20, 20, 0};
int[] yPoints = {middleH, middleH - 20, middleH + 20, middleH};
int nPoints = xPoints.length;
Polygon p = new Polygon(xPoints, yPoints, nPoints);
g.fillPolygon(p);
g.fillRoundRect(20, 0, width - 21, height - 1, 20, 20);
} else {
int[] xPoints = {middleW, middleW + 20, middleW - 20, middleW};
int[] yPoints = {0, 20, 20, 0};
int nPoints = xPoints.length;
Polygon p = new Polygon(xPoints, yPoints, nPoints);
g.fillPolygon(p);
g.fillRoundRect(0, 20, width - 1, height - 21, 20, 20);
}
if (direction == LEFT)
panel.setBounds(30, 10, getWidth() - 40, getHeight() - 20);
else
panel.setBounds(10, 30, getWidth() - 20, getHeight() - 40);
super.paint(g);
}
| public void paint(Graphics g) {
g.clearRect(0, 0, getWidth(), getHeight());
g.setColor(strokeColor);
int width = getWidth();
int height = getHeight();
int middleH = height / 2;
int middleW = width / 2;
if (direction == LEFT) {
int[] xPoints = {0, 20, 20, 0};
int[] yPoints = {middleH, middleH - 20, middleH + 20, middleH};
int nPoints = xPoints.length;
Polygon p = new Polygon(xPoints, yPoints, nPoints);
g.fillPolygon(p);
g.fillRoundRect(20, 0, width - 21, height - 1, 20, 20);
} else {
int[] xPoints = {middleW, middleW + 20, middleW - 20, middleW};
int[] yPoints = {0, 20, 20, 0};
int nPoints = xPoints.length;
Polygon p = new Polygon(xPoints, yPoints, nPoints);
g.fillPolygon(p);
g.fillRoundRect(0, 20, width - 1, height - 21, 20, 20);
}
if (direction == LEFT)
panel.setBounds(30, 10, getWidth() - 40, getHeight() - 20);
else
panel.setBounds(10, 30, getWidth() - 20, getHeight() - 40);
super.paint(g);
}
|
diff --git a/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java b/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java
index 67476ed7..25512ce7 100644
--- a/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java
+++ b/src/main/java/com/googlecode/mgwt/linker/client/cache/html5/Html5ApplicationCache.java
@@ -1,180 +1,180 @@
package com.googlecode.mgwt.linker.client.cache.html5;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.google.web.bindery.event.shared.SimpleEventBus;
import com.googlecode.mgwt.linker.client.cache.ApplicationCache;
import com.googlecode.mgwt.linker.client.cache.ApplicationCacheStatus;
import com.googlecode.mgwt.linker.client.cache.event.CachedEvent;
import com.googlecode.mgwt.linker.client.cache.event.CheckingEvent;
import com.googlecode.mgwt.linker.client.cache.event.CheckingEvent.Handler;
import com.googlecode.mgwt.linker.client.cache.event.DownloadingEvent;
import com.googlecode.mgwt.linker.client.cache.event.ErrorEvent;
import com.googlecode.mgwt.linker.client.cache.event.NoUpdateEvent;
import com.googlecode.mgwt.linker.client.cache.event.ObsoleteEvent;
import com.googlecode.mgwt.linker.client.cache.event.ProgressEvent;
import com.googlecode.mgwt.linker.client.cache.event.UpdateReadyEvent;
public class Html5ApplicationCache implements ApplicationCache {
private static final ApplicationCacheStatus[] STATUS_MAPPING = new ApplicationCacheStatus[] {
ApplicationCacheStatus.UNCACHED, ApplicationCacheStatus.IDLE, ApplicationCacheStatus.CHECKING, ApplicationCacheStatus.DOWNLOADING, ApplicationCacheStatus.UPDATEREADY,
ApplicationCacheStatus.OBSOLETE};
public static Html5ApplicationCache createIfSupported() {
if (!isSupported()) {
return null;
}
return new Html5ApplicationCache();
}
protected static native boolean isSupported()/*-{
return typeof ($wnd.applicationCache) == "object";
}-*/;
protected EventBus eventBus = new SimpleEventBus();
protected Html5ApplicationCache() {
initialize();
}
@Override
public ApplicationCacheStatus getStatus() {
int status0 = getStatus0();
return STATUS_MAPPING[status0];
}
@Override
public HandlerRegistration addCheckingHandler(Handler handler) {
return eventBus.addHandler(CheckingEvent.getType(), handler);
}
@Override
public HandlerRegistration addCachedHandler(com.googlecode.mgwt.linker.client.cache.event.CachedEvent.Handler handler) {
return eventBus.addHandler(CachedEvent.getType(), handler);
}
@Override
public HandlerRegistration addDownloadingHandler(com.googlecode.mgwt.linker.client.cache.event.DownloadingEvent.Handler handler) {
return eventBus.addHandler(DownloadingEvent.getType(), handler);
}
@Override
public HandlerRegistration addErrorHandler(com.googlecode.mgwt.linker.client.cache.event.ErrorEvent.Handler handler) {
return eventBus.addHandler(ErrorEvent.getType(), handler);
}
@Override
public HandlerRegistration addNoUpdateHandler(com.googlecode.mgwt.linker.client.cache.event.NoUpdateEvent.Handler handler) {
return eventBus.addHandler(NoUpdateEvent.getType(), handler);
}
@Override
public HandlerRegistration addObsoleteHandler(com.googlecode.mgwt.linker.client.cache.event.ObsoleteEvent.Handler handler) {
return eventBus.addHandler(ObsoleteEvent.getType(), handler);
}
@Override
public HandlerRegistration addProgressHandler(com.googlecode.mgwt.linker.client.cache.event.ProgressEvent.Handler handler) {
return eventBus.addHandler(ProgressEvent.getType(), handler);
}
@Override
public HandlerRegistration addUpdateReadyHandler(com.googlecode.mgwt.linker.client.cache.event.UpdateReadyEvent.Handler handler) {
return eventBus.addHandler(UpdateReadyEvent.getType(), handler);
}
protected native int getStatus0()/*-{
return $wnd.applicationCache.status;
}-*/;
protected void onChecking() {
eventBus.fireEventFromSource(new CheckingEvent(), this);
}
protected void onError() {
eventBus.fireEventFromSource(new ErrorEvent(), this);
}
protected void onNoUpdate() {
eventBus.fireEventFromSource(new NoUpdateEvent(), this);
}
protected void onDownloading() {
eventBus.fireEventFromSource(new DownloadingEvent(), this);
}
protected void onProgress() {
eventBus.fireEventFromSource(new ProgressEvent(), this);
}
protected void onUpdateReady() {
eventBus.fireEventFromSource(new UpdateReadyEvent(), this);
}
protected void onCached() {
eventBus.fireEventFromSource(new CachedEvent(), this);
}
protected void onObsolete() {
eventBus.fireEventFromSource(new ObsoleteEvent(), this);
}
protected native void initialize() /*-{
var that = this;
var check = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onChecking()();
});
$wnd.applicationCache.addEventListener("checking", check);
var onError = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onError()();
});
- $wnd.applicationCache.addEventListener("onerror", onError);
+ $wnd.applicationCache.addEventListener("error", onError);
var onUpdate = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onNoUpdate()();
});
- $wnd.applicationCache.addEventListener("onnoupdate", onUpdate);
+ $wnd.applicationCache.addEventListener("noupdate", onUpdate);
var ondownloading = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onDownloading()();
});
- $wnd.applicationCache.addEventListener("ondownloading", ondownloading);
+ $wnd.applicationCache.addEventListener("downloading", ondownloading);
var onprogress = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onProgress()();
});
- $wnd.applicationCache.addEventListener("onprogress", onprogress);
+ $wnd.applicationCache.addEventListener("progress", onprogress);
var onupdateReady = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onUpdateReady()();
});
- $wnd.applicationCache.addEventListener("onupdateready", onupdateReady);
+ $wnd.applicationCache.addEventListener("updateready", onupdateReady);
var oncached = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onCached()();
});
- $wnd.applicationCache.addEventListener("oncached", oncached);
+ $wnd.applicationCache.addEventListener("cached", oncached);
var onobsolete = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onObsolete()();
});
- $wnd.applicationCache.addEventListener("onobsolete", onobsolete);
+ $wnd.applicationCache.addEventListener("obsolete", onobsolete);
}-*/;
@Override
public native void swapCache() /*-{
$wnd.applicationCache.swapCache();
}-*/;
@Override
public native void update() /*-{
$wnd.applicationCache.update();
}-*/;
}
| false | true | protected native void initialize() /*-{
var that = this;
var check = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onChecking()();
});
$wnd.applicationCache.addEventListener("checking", check);
var onError = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onError()();
});
$wnd.applicationCache.addEventListener("onerror", onError);
var onUpdate = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onNoUpdate()();
});
$wnd.applicationCache.addEventListener("onnoupdate", onUpdate);
var ondownloading = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onDownloading()();
});
$wnd.applicationCache.addEventListener("ondownloading", ondownloading);
var onprogress = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onProgress()();
});
$wnd.applicationCache.addEventListener("onprogress", onprogress);
var onupdateReady = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onUpdateReady()();
});
$wnd.applicationCache.addEventListener("onupdateready", onupdateReady);
var oncached = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onCached()();
});
$wnd.applicationCache.addEventListener("oncached", oncached);
var onobsolete = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onObsolete()();
});
$wnd.applicationCache.addEventListener("onobsolete", onobsolete);
}-*/;
| protected native void initialize() /*-{
var that = this;
var check = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onChecking()();
});
$wnd.applicationCache.addEventListener("checking", check);
var onError = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onError()();
});
$wnd.applicationCache.addEventListener("error", onError);
var onUpdate = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onNoUpdate()();
});
$wnd.applicationCache.addEventListener("noupdate", onUpdate);
var ondownloading = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onDownloading()();
});
$wnd.applicationCache.addEventListener("downloading", ondownloading);
var onprogress = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onProgress()();
});
$wnd.applicationCache.addEventListener("progress", onprogress);
var onupdateReady = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onUpdateReady()();
});
$wnd.applicationCache.addEventListener("updateready", onupdateReady);
var oncached = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onCached()();
});
$wnd.applicationCache.addEventListener("cached", oncached);
var onobsolete = $entry(function() {
that.@com.googlecode.mgwt.linker.client.cache.html5.Html5ApplicationCache::onObsolete()();
});
$wnd.applicationCache.addEventListener("obsolete", onobsolete);
}-*/;
|
diff --git a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java
index b6dfdfc8..15af667c 100644
--- a/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java
+++ b/plugins/org.eclipse.dltk.javascript.core/src/org/eclipse/dltk/internal/javascript/ti/TypeInferencerVisitor.java
@@ -1,927 +1,944 @@
/*******************************************************************************
* Copyright (c) 2010 xored software, Inc.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* xored software, Inc. - initial API and Implementation (Alex Panchenko)
*******************************************************************************/
package org.eclipse.dltk.internal.javascript.ti;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.eclipse.dltk.ast.ASTNode;
import org.eclipse.dltk.internal.javascript.validation.JavaScriptValidations;
import org.eclipse.dltk.javascript.ast.Argument;
import org.eclipse.dltk.javascript.ast.ArrayInitializer;
import org.eclipse.dltk.javascript.ast.AsteriskExpression;
import org.eclipse.dltk.javascript.ast.BinaryOperation;
import org.eclipse.dltk.javascript.ast.BooleanLiteral;
import org.eclipse.dltk.javascript.ast.BreakStatement;
import org.eclipse.dltk.javascript.ast.CallExpression;
import org.eclipse.dltk.javascript.ast.CaseClause;
import org.eclipse.dltk.javascript.ast.CatchClause;
import org.eclipse.dltk.javascript.ast.CommaExpression;
import org.eclipse.dltk.javascript.ast.ConditionalOperator;
import org.eclipse.dltk.javascript.ast.ConstStatement;
import org.eclipse.dltk.javascript.ast.ContinueStatement;
import org.eclipse.dltk.javascript.ast.DecimalLiteral;
import org.eclipse.dltk.javascript.ast.DefaultXmlNamespaceStatement;
import org.eclipse.dltk.javascript.ast.DeleteStatement;
import org.eclipse.dltk.javascript.ast.DoWhileStatement;
import org.eclipse.dltk.javascript.ast.EmptyExpression;
import org.eclipse.dltk.javascript.ast.EmptyStatement;
import org.eclipse.dltk.javascript.ast.Expression;
import org.eclipse.dltk.javascript.ast.ForEachInStatement;
import org.eclipse.dltk.javascript.ast.ForInStatement;
import org.eclipse.dltk.javascript.ast.ForStatement;
import org.eclipse.dltk.javascript.ast.FunctionStatement;
import org.eclipse.dltk.javascript.ast.GetAllChildrenExpression;
import org.eclipse.dltk.javascript.ast.GetArrayItemExpression;
import org.eclipse.dltk.javascript.ast.GetLocalNameExpression;
import org.eclipse.dltk.javascript.ast.Identifier;
import org.eclipse.dltk.javascript.ast.IfStatement;
import org.eclipse.dltk.javascript.ast.Keyword;
import org.eclipse.dltk.javascript.ast.LabelledStatement;
import org.eclipse.dltk.javascript.ast.NewExpression;
import org.eclipse.dltk.javascript.ast.NullExpression;
import org.eclipse.dltk.javascript.ast.ObjectInitializer;
import org.eclipse.dltk.javascript.ast.ObjectInitializerPart;
import org.eclipse.dltk.javascript.ast.ParenthesizedExpression;
import org.eclipse.dltk.javascript.ast.PropertyExpression;
import org.eclipse.dltk.javascript.ast.PropertyInitializer;
import org.eclipse.dltk.javascript.ast.RegExpLiteral;
import org.eclipse.dltk.javascript.ast.ReturnStatement;
import org.eclipse.dltk.javascript.ast.Script;
import org.eclipse.dltk.javascript.ast.SimpleType;
import org.eclipse.dltk.javascript.ast.Statement;
import org.eclipse.dltk.javascript.ast.StatementBlock;
import org.eclipse.dltk.javascript.ast.StringLiteral;
import org.eclipse.dltk.javascript.ast.SwitchComponent;
import org.eclipse.dltk.javascript.ast.SwitchStatement;
import org.eclipse.dltk.javascript.ast.ThisExpression;
import org.eclipse.dltk.javascript.ast.ThrowStatement;
import org.eclipse.dltk.javascript.ast.TryStatement;
import org.eclipse.dltk.javascript.ast.TypeOfExpression;
import org.eclipse.dltk.javascript.ast.UnaryOperation;
import org.eclipse.dltk.javascript.ast.VariableDeclaration;
import org.eclipse.dltk.javascript.ast.VariableStatement;
import org.eclipse.dltk.javascript.ast.VoidExpression;
import org.eclipse.dltk.javascript.ast.VoidOperator;
import org.eclipse.dltk.javascript.ast.WhileStatement;
import org.eclipse.dltk.javascript.ast.WithStatement;
import org.eclipse.dltk.javascript.ast.XmlAttributeIdentifier;
import org.eclipse.dltk.javascript.ast.XmlExpressionFragment;
import org.eclipse.dltk.javascript.ast.XmlFragment;
import org.eclipse.dltk.javascript.ast.XmlLiteral;
import org.eclipse.dltk.javascript.ast.XmlTextFragment;
import org.eclipse.dltk.javascript.ast.YieldOperator;
import org.eclipse.dltk.javascript.parser.JSParser;
import org.eclipse.dltk.javascript.parser.PropertyExpressionUtils;
import org.eclipse.dltk.javascript.typeinference.IValueCollection;
import org.eclipse.dltk.javascript.typeinference.IValueReference;
import org.eclipse.dltk.javascript.typeinference.ReferenceKind;
import org.eclipse.dltk.javascript.typeinference.ReferenceLocation;
import org.eclipse.dltk.javascript.typeinfo.IModelBuilder;
import org.eclipse.dltk.javascript.typeinfo.IModelBuilder.IParameter;
import org.eclipse.dltk.javascript.typeinfo.ITypeNames;
import org.eclipse.dltk.javascript.typeinfo.ReferenceSource;
import org.eclipse.dltk.javascript.typeinfo.TypeInfoManager;
import org.eclipse.dltk.javascript.typeinfo.model.Member;
import org.eclipse.dltk.javascript.typeinfo.model.Method;
import org.eclipse.dltk.javascript.typeinfo.model.Parameter;
import org.eclipse.dltk.javascript.typeinfo.model.ParameterKind;
import org.eclipse.dltk.javascript.typeinfo.model.Property;
import org.eclipse.dltk.javascript.typeinfo.model.Type;
import org.eclipse.dltk.javascript.typeinfo.model.TypeInfoModelFactory;
import org.eclipse.dltk.javascript.typeinfo.model.TypeKind;
import org.eclipse.emf.common.util.EList;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class TypeInferencerVisitor extends TypeInferencerVisitorBase {
public TypeInferencerVisitor(ITypeInferenceContext context) {
super(context);
}
private final Stack<Branching> branchings = new Stack<Branching>();
private class Branching {
public void end() {
branchings.remove(this);
}
}
protected Branching branching() {
final Branching branching = new Branching();
branchings.add(branching);
return branching;
}
private ReferenceSource getSource() {
final ReferenceSource source = context.getSource();
return source != null ? source : ReferenceSource.UNKNOWN;
}
protected void assign(IValueReference dest, IValueReference src) {
if (branchings.isEmpty()) {
dest.setValue(src);
} else {
dest.addValue(src, false);
}
}
@Override
public IValueReference visitArrayInitializer(ArrayInitializer node) {
return context.getFactory().createArray(peekContext());
}
@Override
public IValueReference visitAsteriskExpression(AsteriskExpression node) {
return context.getFactory().createXML(peekContext());
}
@Override
public IValueReference visitBinaryOperation(BinaryOperation node) {
final IValueReference left = visit(node.getLeftExpression());
final IValueReference right = visit(node.getRightExpression());
if (JSParser.ASSIGN == node.getOperation()) {
return visitAssign(left, right);
} else if (left == null && right instanceof ConstantValue) {
return right;
} else {
// TODO handle other operations
return null;
}
}
protected IValueReference visitAssign(IValueReference left,
IValueReference right) {
if (left != null)
assign(left, right);
return right;
}
@Override
public IValueReference visitBooleanLiteral(BooleanLiteral node) {
return context.getFactory().createBoolean(peekContext());
}
@Override
public IValueReference visitBreakStatement(BreakStatement node) {
return null;
}
@Override
public IValueReference visitCallExpression(CallExpression node) {
final IValueReference reference = visit(node.getExpression());
for (ASTNode argument : node.getArguments()) {
visit(argument);
}
if (reference != null) {
return reference.getChild(IValueReference.FUNCTION_OP);
} else {
return null;
}
}
@Override
public IValueReference visitCommaExpression(CommaExpression node) {
return visit(node.getItems());
}
@Override
public IValueReference visitConditionalOperator(ConditionalOperator node) {
visit(node.getCondition());
return merge(visit(node.getTrueValue()), visit(node.getFalseValue()));
}
@Override
public IValueReference visitConstDeclaration(ConstStatement node) {
final IValueCollection context = peekContext();
for (VariableDeclaration declaration : node.getVariables()) {
createVariable(context, declaration);
}
return null;
}
protected IValueReference createVariable(IValueCollection context,
VariableDeclaration declaration) {
final Identifier identifier = declaration.getIdentifier();
final String varName = identifier.getName();
final IValueReference reference = context.createChild(varName);
final org.eclipse.dltk.javascript.ast.Type varType = declaration
.getType();
if (varType != null) {
reference.setDeclaredType(resolveType(varType));
}
reference.setKind(ReferenceKind.LOCAL);
reference.setLocation(ReferenceLocation.create(getSource(),
declaration.sourceStart(), declaration.sourceEnd(),
identifier.sourceStart(), identifier.sourceEnd()));
if (declaration.getInitializer() != null) {
assign(reference, visit(declaration.getInitializer()));
}
return reference;
}
@Override
public IValueReference visitContinueStatement(ContinueStatement node) {
return null;
}
@Override
public IValueReference visitDecimalLiteral(DecimalLiteral node) {
return context.getFactory().createNumber(peekContext());
}
@Override
public IValueReference visitDefaultXmlNamespace(
DefaultXmlNamespaceStatement node) {
visit(node.getValue());
return null;
}
@Override
public IValueReference visitDeleteStatement(DeleteStatement node) {
IValueReference value = visit(node.getExpression());
if (value != null) {
value.delete();
}
return context.getFactory().createBoolean(peekContext());
}
@Override
public IValueReference visitDoWhileStatement(DoWhileStatement node) {
visit(node.getCondition());
visit(node.getBody());
return null;
}
@Override
public IValueReference visitEmptyExpression(EmptyExpression node) {
return null;
}
@Override
public IValueReference visitEmptyStatement(EmptyStatement node) {
return null;
}
@Override
public IValueReference visitForEachInStatement(ForEachInStatement node) {
visit(node.getItem());
visit(node.getIterator());
visit(node.getBody());
return null;
}
@Override
public IValueReference visitForInStatement(ForInStatement node) {
final IValueReference item = visit(node.getItem());
if (item != null) {
assign(item, context.getFactory().createString(peekContext()));
}
visit(node.getIterator());
visit(node.getBody());
return null;
}
@Override
public IValueReference visitForStatement(ForStatement node) {
if (node.getInitial() != null)
visit(node.getInitial());
if (node.getCondition() != null)
visit(node.getCondition());
if (node.getStep() != null)
visit(node.getStep());
if (node.getBody() != null)
visit(node.getBody());
return null;
}
@Override
public IValueReference visitFunctionStatement(FunctionStatement node) {
final JSMethod method = new JSMethod();
final Identifier methodName = node.getName();
if (methodName != null) {
method.setName(methodName.getName());
}
org.eclipse.dltk.javascript.ast.Type funcType = node.getReturnType();
if (funcType != null) {
method.setType(resolveType(funcType));
}
for (Argument argument : node.getArguments()) {
final IParameter parameter = method.createParameter();
parameter.setName(argument.getIdentifier().getName());
org.eclipse.dltk.javascript.ast.Type paramType = argument.getType();
if (paramType != null) {
parameter.setType(resolveType(paramType));
parameter.setLocation(ReferenceLocation.create(getSource(),
argument.sourceStart(), paramType.sourceEnd(),
argument.sourceStart(), argument.sourceEnd()));
} else {
parameter.setLocation(ReferenceLocation.create(getSource(),
argument.sourceStart(), argument.sourceEnd()));
}
method.getParameters().add(parameter);
}
if (methodName != null) {
for (IModelBuilder extension : TypeInfoManager.getModelBuilders()) {
extension.processMethod(context, node, method);
}
}
final IValueCollection function = new FunctionValueCollection(
peekContext(), method.getName());
for (IParameter parameter : method.getParameters()) {
final IValueReference refArg = function.createChild(parameter
.getName());
refArg.setKind(ReferenceKind.ARGUMENT);
refArg.setDeclaredType(parameter.getType());
refArg.setLocation(parameter.getLocation());
}
enterContext(function);
try {
visitFunctionBody(node);
} finally {
leaveContext();
}
final IValueReference result;
if (methodName != null) {
result = peekContext().createChild(method.getName());
result.setLocation(ReferenceLocation.create(getSource(),
node.sourceStart(), node.sourceEnd(),
methodName.sourceStart(), methodName.sourceEnd()));
} else {
result = new AnonymousValue();
final Keyword kw = node.getFunctionKeyword();
result.setLocation(ReferenceLocation.create(getSource(),
node.sourceStart(), node.sourceEnd(), kw.sourceStart(),
kw.sourceEnd()));
}
result.setKind(ReferenceKind.FUNCTION);
result.setDeclaredType(context.getKnownType(ITypeNames.FUNCTION));
result.setAttribute(IReferenceAttributes.PARAMETERS, method);
result.setAttribute(IReferenceAttributes.FUNCTION_SCOPE, function);
final IValueReference returnValue = result
.getChild(IValueReference.FUNCTION_OP);
returnValue.setDeclaredType(method.getType());
returnValue.setValue(function.getReturnValue());
return result;
}
protected void visitFunctionBody(FunctionStatement node) {
visit(node.getBody());
}
protected Type resolveType(org.eclipse.dltk.javascript.ast.Type type) {
return context.getType(type.getName());
}
@Override
public IValueReference visitGetAllChildrenExpression(
GetAllChildrenExpression node) {
return context.getFactory().createXML(peekContext());
}
@Override
public IValueReference visitGetArrayItemExpression(
GetArrayItemExpression node) {
final IValueReference array = visit(node.getArray());
visit(node.getIndex());
if (array != null) {
// always just create the ARRAY_OP child (for code completion)
IValueReference child = array.getChild(IValueReference.ARRAY_OP);
String arrayType = null;
if (array.getDeclaredType() != null) {
arrayType = (String) array.getDeclaredType().getAttribute(
ITypeInferenceContext.GENERIC_ARRAY_TYPE);
}
else
{
Set<Type> types = array.getTypes();
if (types.size() > 0)
arrayType = (String) types.iterator().next()
.getAttribute(
ITypeInferenceContext.GENERIC_ARRAY_TYPE);
}
if (arrayType != null && child.getDeclaredType() == null) {
child.setDeclaredType(context.getType(arrayType));
}
if (node.getIndex() instanceof StringLiteral) {
child = extractNamedChild(array, node.getIndex());
if (arrayType != null && child.getDeclaredType() == null) {
child.setDeclaredType(context.getType(arrayType));
}
}
return child;
}
return null;
}
@Override
public IValueReference visitGetLocalNameExpression(
GetLocalNameExpression node) {
return null;
}
@Override
public IValueReference visitIdentifier(Identifier node) {
return peekContext().getChild(node.getName());
}
private Boolean evaluateCondition(Expression condition) {
if (condition instanceof BooleanLiteral) {
return Boolean.valueOf(((BooleanLiteral) condition).getText());
} else {
return null;
}
}
@Override
public IValueReference visitIfStatement(IfStatement node) {
visit(node.getCondition());
final List<Statement> statements = new ArrayList<Statement>(2);
Statement onlyBranch = null;
final Boolean condition = evaluateCondition(node.getCondition());
if ((condition == null || condition.booleanValue())
&& node.getThenStatement() != null) {
statements.add(node.getThenStatement());
if (condition != null && condition.booleanValue()) {
onlyBranch = node.getThenStatement();
}
}
if ((condition == null || !condition.booleanValue())
&& node.getElseStatement() != null) {
statements.add(node.getElseStatement());
if (condition != null && !condition.booleanValue()) {
onlyBranch = node.getElseStatement();
}
}
if (!statements.isEmpty()) {
if (statements.size() == 1) {
if (statements.get(0) == onlyBranch) {
visit(statements.get(0));
} else {
final Branching branching = branching();
visit(statements.get(0));
branching.end();
}
} else {
final Branching branching = branching();
final List<NestedValueCollection> collections = new ArrayList<NestedValueCollection>(
statements.size());
for (Statement statement : statements) {
final NestedValueCollection nestedCollection = new NestedValueCollection(
peekContext());
enterContext(nestedCollection);
visit(statement);
leaveContext();
collections.add(nestedCollection);
}
NestedValueCollection.mergeTo(peekContext(), collections);
branching.end();
}
}
return null;
}
@Override
public IValueReference visitLabelledStatement(LabelledStatement node) {
if (node.getStatement() != null)
visit(node.getStatement());
return null;
}
@Override
public IValueReference visitNewExpression(NewExpression node) {
final IValueReference result = new AnonymousValue() {
public IValueReference getChild(String name) {
if (name.equals(IValueReference.FUNCTION_OP))
return this;
return super.getChild(name);
}
};
final Expression objectClass = node.getObjectClass();
visit(objectClass);
final String className = PropertyExpressionUtils.getPath(objectClass);
if (className != null) {
final Type type = resolveJavaScriptType(context, className,
peekContext());
if (type.getKind() != TypeKind.UNKNOWN) {
result.setValue(context.getFactory()
.create(peekContext(),
type));
} else {
result.setValue(new LazyReference(context, className,
peekContext()));
}
return result;
}
result.setValue(context.getFactory().createObject(peekContext()));
return result;
}
public static Type resolveJavaScriptType(ITypeInferenceContext context,
String className, IValueCollection collection) {
if (className == null)
return null;
Type type = context.getType(className);
if (type.getKind() == TypeKind.UNKNOWN) {
String[] scopes = className.split("\\.");
IValueReference functionType = null;
for (String scope : scopes) {
if (functionType == null) {
functionType = collection.getChild(scope);
} else {
functionType = functionType.getChild(scope);
}
}
if (functionType != null && functionType.exists()) {
// test first if it could be a Java type (Packages.xx support)
Type javaType = (Type) functionType.getAttribute(
IReferenceAttributes.JAVA_OBJECT_TYPE, true);
if (javaType != null) {
return javaType;
}
type.setKind(TypeKind.JAVASCRIPT);
EList<Member> members = type.getMembers();
FunctionValueCollection functionCollection = (FunctionValueCollection) functionType
.getAttribute(IReferenceAttributes.FUNCTION_SCOPE, true);
IValueReference functionCallChild = null;
if (functionCollection != null) {
functionCallChild = functionCollection.getThis();
} else {
functionCallChild = functionType
.getChild(IValueReference.FUNCTION_OP);
}
Set<String> functionFields = functionCallChild
.getDirectChildren();
for (String fieldName : functionFields) {
if (fieldName.equals(IValueReference.FUNCTION_OP))
continue;
IValueReference child = functionCallChild
.getChild(fieldName);
// test if it is a function.
if (child.hasChild(IValueReference.FUNCTION_OP)) {
Method method = TypeInfoModelFactory.eINSTANCE
.createMethod();
- method.setAttribute(IReferenceAttributes.LOCATION,
- child.getLocation());
+ if (child.getKind() == ReferenceKind.LOCAL)
+ {
+ Set<Value> references = ((Value)((IValueProvider)child).getValue()).getReferences();
+ if (references.isEmpty())
+ {
+ method.setAttribute(IReferenceAttributes.LOCATION,
+ child.getLocation());
+ }
+ else
+ {
+ method.setAttribute(IReferenceAttributes.LOCATION,references.iterator().next().getLocation());
+ }
+ }
+ else
+ {
+ method.setAttribute(IReferenceAttributes.LOCATION,
+ child.getLocation());
+ }
method.setName(fieldName);
- method.setType(JavaScriptValidations.typeOf(child));
+ method.setType(JavaScriptValidations.typeOf(child
+ .getChild(IValueReference.FUNCTION_OP)));
JSMethod jsmethod = (JSMethod) child.getAttribute(
IReferenceAttributes.PARAMETERS, true);
if (jsmethod != null
&& jsmethod.getParameterCount() > 0) {
EList<Parameter> parameters = method
.getParameters();
List<IParameter> jsParameters = jsmethod
.getParameters();
for (IParameter jsParameter : jsParameters) {
Parameter parameter = TypeInfoModelFactory.eINSTANCE
.createParameter();
parameter.setKind(ParameterKind.OPTIONAL);
parameter.setType(jsParameter.getType());
parameter.setName(jsParameter.getName());
parameters.add(parameter);
}
}
members.add(method);
} else {
Property property = TypeInfoModelFactory.eINSTANCE
.createProperty();
property.setAttribute(IReferenceAttributes.LOCATION,
child.getLocation());
property.setName(fieldName);
property.setType(JavaScriptValidations.typeOf(child));
members.add(property);
}
}
return type;
}
}
return type;
}
@Override
public IValueReference visitNullExpression(NullExpression node) {
return null;
}
@Override
public IValueReference visitObjectInitializer(ObjectInitializer node) {
final IValueReference result = new AnonymousValue();
for (ObjectInitializerPart part : node.getInitializers()) {
if (part instanceof PropertyInitializer) {
final PropertyInitializer pi = (PropertyInitializer) part;
final IValueReference child = extractNamedChild(result,
pi.getName());
final IValueReference value = visit(pi.getValue());
if (child != null) {
child.setValue(value);
child.setLocation(ReferenceLocation.create(getSource(), pi
.getName().sourceStart(), pi.getName().sourceEnd()));
if (child.getKind() == ReferenceKind.UNKNOWN) {
child.setKind(ReferenceKind.LOCAL);
}
}
} else {
// TODO handle get/set methods
}
}
return result;
}
@Override
public IValueReference visitParenthesizedExpression(
ParenthesizedExpression node) {
return visit(node.getExpression());
}
@Override
public IValueReference visitPropertyExpression(PropertyExpression node) {
final IValueReference object = visit(node.getObject());
Expression property = node.getProperty();
IValueReference child = extractNamedChild(object, property);
if (child != null && node.getObject() instanceof ThisExpression) {
// TODO check is this also a local reference kind or should this be
// a special one?
child.setKind(ReferenceKind.LOCAL);
child.setLocation(ReferenceLocation.create(getSource(),
node.sourceStart(), node.sourceEnd(),
property.sourceStart(), property.sourceEnd()));
}
return child;
}
protected IValueReference extractNamedChild(IValueReference parent,
Expression name) {
if (parent != null) {
final String nameStr;
if (name instanceof Identifier) {
nameStr = ((Identifier) name).getName();
} else if (name instanceof StringLiteral) {
nameStr = ((StringLiteral) name).getValue();
} else if (name instanceof XmlAttributeIdentifier) {
nameStr = ((XmlAttributeIdentifier) name).getAttributeName();
} else {
return null;
}
return parent.getChild(nameStr);
}
return null;
}
@Override
public IValueReference visitRegExpLiteral(RegExpLiteral node) {
return context.getFactory().createRegExp(peekContext());
}
@Override
public IValueReference visitReturnStatement(ReturnStatement node) {
if (node.getValue() != null) {
final IValueReference value = visit(node.getValue());
if (value != null) {
final IValueReference returnValue = peekContext()
.getReturnValue();
if (returnValue != null) {
returnValue.addValue(value, true);
}
}
}
return null;
}
@Override
public IValueReference visitScript(Script node) {
return visit(node.getStatements());
}
@Override
public IValueReference visitSimpleType(SimpleType node) {
// TODO Auto-generated method stub
return null;
}
@Override
public IValueReference visitStatementBlock(StatementBlock node) {
for (Statement statement : node.getStatements()) {
visit(statement);
}
return null;
}
@Override
public IValueReference visitStringLiteral(StringLiteral node) {
return context.getFactory().createString(peekContext());
}
@Override
public IValueReference visitSwitchStatement(SwitchStatement node) {
if (node.getCondition() != null)
visit(node.getCondition());
for (SwitchComponent component : node.getCaseClauses()) {
if (component instanceof CaseClause) {
visit(((CaseClause) component).getCondition());
}
visit(component.getStatements());
}
return null;
}
@Override
public IValueReference visitThisExpression(ThisExpression node) {
return peekContext().getThis();
}
@Override
public IValueReference visitThrowStatement(ThrowStatement node) {
visit(node.getException());
return null;
}
@Override
public IValueReference visitTryStatement(TryStatement node) {
visit(node.getBody());
for (CatchClause catchClause : node.getCatches()) {
final NestedValueCollection collection = new NestedValueCollection(
peekContext());
collection.createChild(catchClause.getException().getName());
enterContext(collection);
visit(catchClause.getStatement());
leaveContext();
}
if (node.getFinally() != null) {
visit(node.getFinally().getStatement());
}
return null;
}
@Override
public IValueReference visitTypeOfExpression(TypeOfExpression node) {
return context.getFactory().createString(peekContext());
}
@Override
public IValueReference visitUnaryOperation(UnaryOperation node) {
return visit(node.getExpression());
}
@Override
public IValueReference visitVariableStatment(VariableStatement node) {
final IValueCollection context = peekContext();
IValueReference result = null;
for (VariableDeclaration declaration : node.getVariables()) {
result = createVariable(context, declaration);
}
return result;
}
@Override
public IValueReference visitVoidExpression(VoidExpression node) {
visit(node.getExpression());
return null;
}
@Override
public IValueReference visitVoidOperator(VoidOperator node) {
visit(node.getExpression());
return null;
}
@Override
public IValueReference visitWhileStatement(WhileStatement node) {
if (node.getCondition() != null)
visit(node.getCondition());
if (node.getBody() != null)
visit(node.getBody());
return null;
}
@Override
public IValueReference visitWithStatement(WithStatement node) {
final IValueReference with = visit(node.getExpression());
if (with != null) {
final WithValueCollection withCollection = new WithValueCollection(
peekContext(), with);
enterContext(withCollection);
visit(node.getStatement());
leaveContext();
} else {
visit(node.getStatement());
}
return null;
}
@Override
public IValueReference visitXmlLiteral(XmlLiteral node) {
IValueReference xmlValueReference = context.getFactory().createXML(
peekContext());
if (xmlValueReference instanceof IValueProvider) {
Type xmlType = context.getKnownType(ITypeNames.XML);
IValue xmlValue = ((IValueProvider) xmlValueReference).getValue();
List<XmlFragment> fragments = node.getFragments();
StringBuilder xml = new StringBuilder();
for (XmlFragment xmlFragment : fragments) {
if (xmlFragment instanceof XmlTextFragment
&& !((XmlTextFragment) xmlFragment).getXml().equals(
"<></>")) {
xml.append(((XmlTextFragment) xmlFragment).getXml());
} else if (xmlFragment instanceof XmlExpressionFragment) {
xml.append("\"\"");
}
}
if (xml.length() > 0) {
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
try {
DocumentBuilder docBuilder = docBuilderFactory
.newDocumentBuilder();
Document doc = docBuilder.parse(new InputSource(
new StringReader(xml.toString())));
NodeList nl = doc.getChildNodes();
if (nl.getLength() == 1) {
Node item = nl.item(0);
NamedNodeMap attributes = item.getAttributes();
for (int a = 0; a < attributes.getLength(); a++) {
Node attribute = attributes.item(a);
xmlValue.createChild("@" + attribute.getNodeName());
}
createXmlChilds(xmlType, xmlValue, item.getChildNodes());
} else {
System.err.println("root should be 1 child?? " + xml);
}
} catch (Exception e) {
}
}
}
return xmlValueReference;
}
/**
* @param xmlType
* @param xmlValue
* @param nl
*/
private void createXmlChilds(Type xmlType, IValue xmlValue, NodeList nl) {
for (int i = 0; i < nl.getLength(); i++) {
Node item = nl.item(i);
if (item.getNodeType() == Node.TEXT_NODE) {
String value = item.getNodeValue();
if (value == null || "".equals(value.trim())) {
continue;
}
}
IValue nodeValue = xmlValue.createChild(item.getNodeName());
nodeValue.setDeclaredType(xmlType);
NamedNodeMap attributes = item.getAttributes();
for (int a = 0; a < attributes.getLength(); a++) {
Node attribute = attributes.item(a);
nodeValue.createChild("@" + attribute.getNodeName());
}
createXmlChilds(xmlType, nodeValue, item.getChildNodes());
}
}
@Override
public IValueReference visitXmlPropertyIdentifier(
XmlAttributeIdentifier node) {
return context.getFactory().createXML(peekContext());
}
@Override
public IValueReference visitYieldOperator(YieldOperator node) {
final IValueReference value = visit(node.getExpression());
if (value != null) {
final IValueReference reference = peekContext().getReturnValue();
if (reference != null) {
reference.addValue(value, true);
}
}
return null;
}
}
| false | true | public static Type resolveJavaScriptType(ITypeInferenceContext context,
String className, IValueCollection collection) {
if (className == null)
return null;
Type type = context.getType(className);
if (type.getKind() == TypeKind.UNKNOWN) {
String[] scopes = className.split("\\.");
IValueReference functionType = null;
for (String scope : scopes) {
if (functionType == null) {
functionType = collection.getChild(scope);
} else {
functionType = functionType.getChild(scope);
}
}
if (functionType != null && functionType.exists()) {
// test first if it could be a Java type (Packages.xx support)
Type javaType = (Type) functionType.getAttribute(
IReferenceAttributes.JAVA_OBJECT_TYPE, true);
if (javaType != null) {
return javaType;
}
type.setKind(TypeKind.JAVASCRIPT);
EList<Member> members = type.getMembers();
FunctionValueCollection functionCollection = (FunctionValueCollection) functionType
.getAttribute(IReferenceAttributes.FUNCTION_SCOPE, true);
IValueReference functionCallChild = null;
if (functionCollection != null) {
functionCallChild = functionCollection.getThis();
} else {
functionCallChild = functionType
.getChild(IValueReference.FUNCTION_OP);
}
Set<String> functionFields = functionCallChild
.getDirectChildren();
for (String fieldName : functionFields) {
if (fieldName.equals(IValueReference.FUNCTION_OP))
continue;
IValueReference child = functionCallChild
.getChild(fieldName);
// test if it is a function.
if (child.hasChild(IValueReference.FUNCTION_OP)) {
Method method = TypeInfoModelFactory.eINSTANCE
.createMethod();
method.setAttribute(IReferenceAttributes.LOCATION,
child.getLocation());
method.setName(fieldName);
method.setType(JavaScriptValidations.typeOf(child));
JSMethod jsmethod = (JSMethod) child.getAttribute(
IReferenceAttributes.PARAMETERS, true);
if (jsmethod != null
&& jsmethod.getParameterCount() > 0) {
EList<Parameter> parameters = method
.getParameters();
List<IParameter> jsParameters = jsmethod
.getParameters();
for (IParameter jsParameter : jsParameters) {
Parameter parameter = TypeInfoModelFactory.eINSTANCE
.createParameter();
parameter.setKind(ParameterKind.OPTIONAL);
parameter.setType(jsParameter.getType());
parameter.setName(jsParameter.getName());
parameters.add(parameter);
}
}
members.add(method);
} else {
Property property = TypeInfoModelFactory.eINSTANCE
.createProperty();
property.setAttribute(IReferenceAttributes.LOCATION,
child.getLocation());
property.setName(fieldName);
property.setType(JavaScriptValidations.typeOf(child));
members.add(property);
}
}
return type;
}
}
return type;
}
| public static Type resolveJavaScriptType(ITypeInferenceContext context,
String className, IValueCollection collection) {
if (className == null)
return null;
Type type = context.getType(className);
if (type.getKind() == TypeKind.UNKNOWN) {
String[] scopes = className.split("\\.");
IValueReference functionType = null;
for (String scope : scopes) {
if (functionType == null) {
functionType = collection.getChild(scope);
} else {
functionType = functionType.getChild(scope);
}
}
if (functionType != null && functionType.exists()) {
// test first if it could be a Java type (Packages.xx support)
Type javaType = (Type) functionType.getAttribute(
IReferenceAttributes.JAVA_OBJECT_TYPE, true);
if (javaType != null) {
return javaType;
}
type.setKind(TypeKind.JAVASCRIPT);
EList<Member> members = type.getMembers();
FunctionValueCollection functionCollection = (FunctionValueCollection) functionType
.getAttribute(IReferenceAttributes.FUNCTION_SCOPE, true);
IValueReference functionCallChild = null;
if (functionCollection != null) {
functionCallChild = functionCollection.getThis();
} else {
functionCallChild = functionType
.getChild(IValueReference.FUNCTION_OP);
}
Set<String> functionFields = functionCallChild
.getDirectChildren();
for (String fieldName : functionFields) {
if (fieldName.equals(IValueReference.FUNCTION_OP))
continue;
IValueReference child = functionCallChild
.getChild(fieldName);
// test if it is a function.
if (child.hasChild(IValueReference.FUNCTION_OP)) {
Method method = TypeInfoModelFactory.eINSTANCE
.createMethod();
if (child.getKind() == ReferenceKind.LOCAL)
{
Set<Value> references = ((Value)((IValueProvider)child).getValue()).getReferences();
if (references.isEmpty())
{
method.setAttribute(IReferenceAttributes.LOCATION,
child.getLocation());
}
else
{
method.setAttribute(IReferenceAttributes.LOCATION,references.iterator().next().getLocation());
}
}
else
{
method.setAttribute(IReferenceAttributes.LOCATION,
child.getLocation());
}
method.setName(fieldName);
method.setType(JavaScriptValidations.typeOf(child
.getChild(IValueReference.FUNCTION_OP)));
JSMethod jsmethod = (JSMethod) child.getAttribute(
IReferenceAttributes.PARAMETERS, true);
if (jsmethod != null
&& jsmethod.getParameterCount() > 0) {
EList<Parameter> parameters = method
.getParameters();
List<IParameter> jsParameters = jsmethod
.getParameters();
for (IParameter jsParameter : jsParameters) {
Parameter parameter = TypeInfoModelFactory.eINSTANCE
.createParameter();
parameter.setKind(ParameterKind.OPTIONAL);
parameter.setType(jsParameter.getType());
parameter.setName(jsParameter.getName());
parameters.add(parameter);
}
}
members.add(method);
} else {
Property property = TypeInfoModelFactory.eINSTANCE
.createProperty();
property.setAttribute(IReferenceAttributes.LOCATION,
child.getLocation());
property.setName(fieldName);
property.setType(JavaScriptValidations.typeOf(child));
members.add(property);
}
}
return type;
}
}
return type;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.