answer stringlengths 17 10.2M |
|---|
package nl.mpi.arbil;
import java.awt.Component;
import java.awt.Desktop;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.ButtonGroup;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import javax.swing.tree.DefaultMutableTreeNode;
public class GuiHelper {
static ArbilDragDrop arbilDragDrop = new ArbilDragDrop();
static ImdiSchema imdiSchema = new ImdiSchema();
static LinorgBugCatcher linorgBugCatcher = new LinorgBugCatcher();
static ImdiLoader imdiLoader = new ImdiLoader();
// private JPanel selectedFilesPanel;
//static LinorgWindowManager linorgWindowManager = new LinorgWindowManager();
// create a clip board owner for copy and paste actions
static ClipboardOwner clipboardOwner = new ClipboardOwner() {
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("lost clipboard ownership");
//throw new UnsupportedOperationException("Not supported yet.");
}
};
static private GuiHelper singleInstance = null;
static synchronized public GuiHelper getSingleInstance() {
System.out.println("GuiHelper getSingleInstance");
if (singleInstance == null) {
singleInstance = new GuiHelper();
}
return singleInstance;
}
private GuiHelper() {
LinorgFavourites.getSingleInstance(); // cause the favourites imdi nodes to be loaded
}
public void saveState(boolean saveWindows) {
ImdiFieldViews.getSingleInstance().saveViewsToFile();
// linorgFavourites.saveSelectedFavourites(); // no need to do here because the list is saved when favourites are changed
TreeHelper.getSingleInstance().saveLocations();
if (saveWindows) {
LinorgWindowManager.getSingleInstance().saveWindowStates();
}
}
public void initViewMenu(javax.swing.JMenu viewMenu) {
viewMenu.removeAll();
ButtonGroup viewMenuButtonGroup = new javax.swing.ButtonGroup();
//String[] viewLabels = guiHelper.imdiFieldViews.getSavedFieldViewLables();
for (Enumeration menuItemName = ImdiFieldViews.getSingleInstance().getSavedFieldViewLables(); menuItemName.hasMoreElements();) {
String currentMenuName = menuItemName.nextElement().toString();
javax.swing.JRadioButtonMenuItem viewLabelRadioButtonMenuItem;
viewLabelRadioButtonMenuItem = new javax.swing.JRadioButtonMenuItem();
viewMenuButtonGroup.add(viewLabelRadioButtonMenuItem);
viewLabelRadioButtonMenuItem.setSelected(ImdiFieldViews.getSingleInstance().getCurrentGlobalViewName().equals(currentMenuName));
viewLabelRadioButtonMenuItem.setText(currentMenuName);
viewLabelRadioButtonMenuItem.setName(currentMenuName);
viewLabelRadioButtonMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
try {
ImdiFieldViews.getSingleInstance().setCurrentGlobalViewName(((Component) evt.getSource()).getName());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
}
}
});
viewMenu.add(viewLabelRadioButtonMenuItem);
}
}
//// date filter code
// public void updateDateSlider(JSlider dateSlider) {
// if (imdiHelper.minNodeDate == null) {
// System.out.println("global node date is null");
// return;
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(imdiHelper.minNodeDate);
// int startYear = calendar.get(Calendar.YEAR);
// dateSlider.setMinimum(startYear);
// calendar.setTime(imdiHelper.maxNodeDate);
// int endYear = calendar.get(Calendar.YEAR);
// dateSlider.setMaximum(endYear);
// public void filterByDate(DefaultMutableTreeNode itemNode, int sliderValue) {
// Calendar calendar = Calendar.getInstance();
// calendar.set(Calendar.YEAR, sliderValue);
// Enumeration childNodes = itemNode.children();
// while (childNodes.hasMoreElements()) {
// Object tempNodeObject = ((DefaultMutableTreeNode) childNodes.nextElement()).getUserObject();
// if (imdiHelper.isImdiNode(tempNodeObject)) {
// ((ImdiHelper.ImdiTreeObject) tempNodeObject).setMinDate(calendar.getTime());
// } else {
// System.out.println("not an imdi node: " + tempNodeObject.toString());
//// end date filter code
public void openImdiXmlWindow(Object userObject, boolean formatXml, boolean launchInBrowser) {
if (userObject instanceof ImdiTreeObject) {
if (((ImdiTreeObject) (userObject)).needsSaveToDisk) {
if (JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(LinorgWindowManager.getSingleInstance().linorgFrame, "The node must be saved first.\nSave now?", "View IMDI XML", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) {
((ImdiTreeObject) (userObject)).saveChangesToCache(true);
} else {
return;
}
}
File nodeFile = ((ImdiTreeObject) (userObject)).getFile();
System.out.println("openImdiXmlWindow: " + nodeFile);
String nodeName = ((ImdiTreeObject) (userObject)).toString();
if (formatXml) {
try {
// 1. Instantiate a TransformerFactory.
javax.xml.transform.TransformerFactory tFactory = javax.xml.transform.TransformerFactory.newInstance();
// 2. Use the TransformerFactory to process the stylesheet Source and generate a Transformer.
URL xslUrl = this.getClass().getResource("/nl/mpi/arbil/resources/xsl/imdi-viewer.xsl");
File tempHtmlFile;
File xslFile = null;
if (imdiSchema.selectedTemplateDirectory != null) {
xslFile = new File(imdiSchema.selectedTemplateDirectory.toString() + File.separatorChar + "format.xsl");
}
if (xslFile != null && xslFile.exists()) {
xslUrl = xslFile.toURL();
tempHtmlFile = File.createTempFile("tmp", ".html", xslFile.getParentFile());
tempHtmlFile.deleteOnExit();
} else {
// copy any dependent files from the jar
String[] dependentFiles = {"imdi-viewer-open.gif", "imdi-viewer-closed.gif", "imdi-viewer.js", "additTooltip.js", "additPopup.js", "imdi-viewer.css", "additTooltip.css"};
tempHtmlFile = File.createTempFile("tmp", ".html");
tempHtmlFile.deleteOnExit();
for (String dependantFileString : dependentFiles) {
File tempDependantFile = new File(tempHtmlFile.getParent() + File.separatorChar + dependantFileString);
tempDependantFile.deleteOnExit();
// File tempDependantFile = File.createTempFile(dependantFileString, "");
FileOutputStream outFile = new FileOutputStream(tempDependantFile);
//InputStream inputStream = this.getClass().getResourceAsStream("html/imdi-viewer/" + dependantFileString);
InputStream inputStream = this.getClass().getResourceAsStream("/nl/mpi/arbil/resources/xsl/" + dependantFileString);
int bufferLength = 1024 * 4;
byte[] buffer = new byte[bufferLength]; // make htis 1024*4 or something and read chunks not the whole file
int bytesread = 0;
while (bytesread >= 0) {
bytesread = inputStream.read(buffer);
if (bytesread == -1) {
break;
}
outFile.write(buffer, 0, bytesread);
}
outFile.close();
}
}
javax.xml.transform.Transformer transformer = tFactory.newTransformer(new javax.xml.transform.stream.StreamSource(xslUrl.toString()));
// 3. Use the Transformer to transform an XML Source and send the output to a Result object.
transformer.transform(new javax.xml.transform.stream.StreamSource(nodeFile), new javax.xml.transform.stream.StreamResult(new java.io.FileOutputStream(tempHtmlFile.getCanonicalPath())));
if (!launchInBrowser) {
LinorgWindowManager.getSingleInstance().openUrlWindowOnce(nodeName + " formatted", tempHtmlFile.toURL());
} else {
openFileInExternalApplication(tempHtmlFile.toURI());
}
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
//System.out.println(ex.getMessage());
//LinorgWindowManager.getSingleInstance().openUrlWindow(nodeName, nodeUrl);
}
} else {
try {
LinorgWindowManager.getSingleInstance().openUrlWindowOnce(nodeName + "-xml", nodeFile.toURL());
} catch (Exception ex) {
GuiHelper.linorgBugCatcher.logError(ex);
//System.out.println(ex.getMessage());
//LinorgWindowManager.getSingleInstance().openUrlWindow(nodeName, nodeUrl);
}
}
}
}
// TODO: this could be merged witht the add row function
public AbstractTableModel getImdiTableModel(Hashtable rowNodes) {
ImdiTableModel searchTableModel = new ImdiTableModel();
searchTableModel.setShowIcons(true);
searchTableModel.addImdiObjects(rowNodes.elements());
//Enumeration rowNodeEnum = rowNodes.elements();
//while (rowNodeEnum.hasMoreElements()) {
//searchTableModel.addImdiObject((ImdiHelper.ImdiTreeObject) rowNodeEnum.nextElement());
return searchTableModel;
}
public AbstractTableModel getImdiTableModel() {
ImdiTableModel tempModel = new ImdiTableModel();
tempModel.setShowIcons(true);
return tempModel;
}
public boolean openFileInExternalApplication(URI targetUri) {
boolean result = false;
boolean awtDesktopFound = false;
try {
Class.forName("java.awt.Desktop");
awtDesktopFound = true;
} catch (ClassNotFoundException cnfE) {
awtDesktopFound = false;
System.out.println("java.awt.Desktop class not found");
}
if (awtDesktopFound) {
try {
Desktop.getDesktop().browse(targetUri);
result = true;
} catch (MalformedURLException muE) {
muE.printStackTrace();
} catch (IOException ioE) {
ioE.printStackTrace();
}
} else {
try {
String osNameString = System.getProperty("os.name").toLowerCase();
String openCommand = "";
if (osNameString.indexOf("windows") != -1 || osNameString.indexOf("nt") != -1) {
openCommand = "cmd /c start ";
}
if (osNameString.equals("windows 95") || osNameString.equals("windows 98")) {
openCommand = "command.com /C start ";
}
if (osNameString.indexOf("mac") != -1) {
openCommand = "open ";
}
if (osNameString.indexOf("linux") != -1) {
openCommand = "gnome-open ";
}
String execString = openCommand + targetUri;
System.out.println(execString);
Process launchedProcess = Runtime.getRuntime().exec(execString);
BufferedReader errorStreamReader = new BufferedReader(new InputStreamReader(launchedProcess.getErrorStream()));
String line;
while ((line = errorStreamReader.readLine()) != null) {
LinorgWindowManager.getSingleInstance().addMessageDialogToQueue(line, "Open In External Application");
System.out.println("Launched process error stream: \"" + line + "\"");
}
result = true;
} catch (Exception e) {
e.printStackTrace();
}
}
return result;
}
public void removeFromGridData(TableModel tableModel, Vector nodesToRemove) {
// remove the supplied nodes from the grid
((ImdiTableModel) tableModel).removeImdiObjects(nodesToRemove.elements());
for (Enumeration nodesToRemoveEnum = nodesToRemove.elements(); nodesToRemoveEnum.hasMoreElements();) {
// iterate over the supplied nodes
Object currentObject = nodesToRemoveEnum.nextElement();
if (ImdiTreeObject.isImdiNode(currentObject)) {
String hashKey = ((ImdiTreeObject) currentObject).getUrlString();
}
}
}
} |
package org.openscience.cdk.app;
import org.openscience.cdk.config.Elements;
import org.openscience.cdk.interfaces.IAtom;
import org.openscience.cdk.interfaces.IAtomContainer;
import org.openscience.cdk.interfaces.IBond;
public class MolOp {
private static int calcValence(IAtom atom) {
int v = atom.getImplicitHydrogenCount();
for (IBond bond : atom.bonds()) {
IBond.Order order = bond.getOrder();
if (order != null && order != IBond.Order.UNSET)
v += order.numeric();
}
return v;
}
private static boolean isDativeDonor(IAtom a) {
switch (a.getAtomicNumber()) {
case 7:
case 15:
return a.getFormalCharge() == 0 && calcValence(a) == 4;
case 8:
return a.getFormalCharge() == 0 && calcValence(a) == 3;
default:
return false;
}
}
private static boolean isDativeAcceptor(IAtom a) {
if (Elements.isMetal(a))
return true;
switch (a.getAtomicNumber()) {
case 5:
return a.getFormalCharge() == 0 && calcValence(a) == 4;
case 8:
return a.getFormalCharge() == 0 && calcValence(a) == 1;
default:
return false;
}
}
private static boolean isPosDativeDonor(IAtom a) {
switch (a.getAtomicNumber()) {
case 7:
case 15:
return a.getFormalCharge() == +1 && calcValence(a) == 4;
case 8:
return a.getFormalCharge() == +1 && calcValence(a) == 3;
default:
return false;
}
}
private static boolean isNegDativeAcceptor(IAtom a) {
if (a.getFormalCharge() != -1)
return false;
if (Elements.isMetal(a))
return true;
switch (a.getAtomicNumber()) {
case 5:
return calcValence(a) == 4;
case 8:
return calcValence(a) == 1;
default:
return false;
}
}
public static void perceiveRadicals(IAtomContainer mol) {
for (IAtom atom : mol.atoms()) {
int v;
Integer q = atom.getFormalCharge();
if (q == null) q = 0;
switch (atom.getAtomicNumber()) {
case 6:
if (q == 0) {
v = calcValence(atom);
if (v == 2)
mol.addSingleElectron(mol.indexOf(atom));
if (v < 4)
mol.addSingleElectron(mol.indexOf(atom));
}
break;
case 7:
if (q == 0) {
v = calcValence(atom);
if (v < 3)
mol.addSingleElectron(mol.indexOf(atom));
}
break;
case 8:
if (q == 0) {
v = calcValence(atom);
if (v < 2)
mol.addSingleElectron(mol.indexOf(atom));
if (v < 1)
mol.addSingleElectron(mol.indexOf(atom));
}
break;
}
}
}
public static void perceiveDativeBonds(IAtomContainer mol) {
for (IBond bond : mol.bonds()) {
IAtom beg = bond.getBegin();
IAtom end = bond.getEnd();
if (isDativeDonor(end) && isDativeAcceptor(beg)) {
bond.setDisplay(IBond.Display.ArrowBeg);
} else if (isDativeDonor(beg) && isDativeAcceptor(end)) {
bond.setDisplay(IBond.Display.ArrowEnd);
} else if (isPosDativeDonor(end) && isNegDativeAcceptor(beg)) {
bond.setDisplay(IBond.Display.ArrowBeg);
beg.setFormalCharge(beg.getFormalCharge()+1);
end.setFormalCharge(end.getFormalCharge()-1);
} else if (isPosDativeDonor(beg) && isNegDativeAcceptor(end)) {
bond.setDisplay(IBond.Display.ArrowEnd);
beg.setFormalCharge(beg.getFormalCharge()+1);
end.setFormalCharge(end.getFormalCharge()-1);
}
}
}
} |
package org.jboss.as.cli.handlers;
import java.io.File;
import java.io.FileInputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.jboss.as.cli.CommandContext;
import org.jboss.as.cli.CommandFormatException;
import org.jboss.as.cli.CommandLineCompleter;
import org.jboss.as.cli.Util;
import org.jboss.as.cli.impl.ArgumentWithValue;
import org.jboss.as.cli.impl.ArgumentWithoutValue;
import org.jboss.as.cli.operation.OperationFormatException;
import org.jboss.as.cli.operation.ParsedCommandLine;
import org.jboss.as.cli.operation.impl.DefaultOperationRequestAddress;
import org.jboss.as.controller.client.ModelControllerClient;
import org.jboss.as.controller.client.OperationBuilder;
import org.jboss.as.protocol.StreamUtils;
import org.jboss.dmr.ModelNode;
/**
*
* @author Alexey Loubyansky
*/
public class DeployHandler extends BatchModeCommandHandler {
private final ArgumentWithoutValue force;
private final ArgumentWithoutValue l;
private final ArgumentWithoutValue path;
private final ArgumentWithoutValue name;
private final ArgumentWithoutValue rtName;
private final ArgumentWithValue serverGroups;
private final ArgumentWithoutValue allServerGroups;
private final ArgumentWithoutValue disabled;
public DeployHandler(CommandContext ctx) {
super(ctx, "deploy", true);
final DefaultOperationRequestAddress requiredAddress = new DefaultOperationRequestAddress();
requiredAddress.toNodeType(Util.DEPLOYMENT);
addRequiredPath(requiredAddress);
l = new ArgumentWithoutValue(this, "-l");
l.setExclusive(true);
final FilenameTabCompleter pathCompleter = Util.isWindows() ? WindowsFilenameTabCompleter.INSTANCE : DefaultFilenameTabCompleter.INSTANCE;
path = new ArgumentWithValue(this, pathCompleter, 0, "--path") {
@Override
public String getValue(ParsedCommandLine args) {
String value = super.getValue(args);
if(value != null) {
if(value.length() >= 0 && value.charAt(0) == '"' && value.charAt(value.length() - 1) == '"') {
value = value.substring(1, value.length() - 1);
}
value = pathCompleter.translatePath(value);
}
return value;
}
};
path.addCantAppearAfter(l);
force = new ArgumentWithoutValue(this, "--force", "-f");
force.addRequiredPreceding(path);
name = new ArgumentWithValue(this, new CommandLineCompleter() {
@Override
public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) {
ParsedCommandLine args = ctx.getParsedCommandLine();
try {
if(path.isPresent(args)) {
return -1;
}
} catch (CommandFormatException e) {
return -1;
}
int nextCharIndex = 0;
while (nextCharIndex < buffer.length()) {
if (!Character.isWhitespace(buffer.charAt(nextCharIndex))) {
break;
}
++nextCharIndex;
}
if(ctx.getModelControllerClient() != null) {
List<String> deployments = Util.getDeployments(ctx.getModelControllerClient());
if(deployments.isEmpty()) {
return -1;
}
String opBuffer = buffer.substring(nextCharIndex).trim();
if (opBuffer.isEmpty()) {
candidates.addAll(deployments);
} else {
for(String name : deployments) {
if(name.startsWith(opBuffer)) {
candidates.add(name);
}
}
Collections.sort(candidates);
}
return nextCharIndex;
} else {
return -1;
}
}}, "--name");
name.addCantAppearAfter(l);
path.addCantAppearAfter(name);
rtName = new ArgumentWithValue(this, "--runtime-name");
rtName.addRequiredPreceding(path);
allServerGroups = new ArgumentWithoutValue(this, "--all-server-groups") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if(!ctx.isDomainMode()) {
return false;
}
return super.canAppearNext(ctx);
}
};
allServerGroups.addRequiredPreceding(path);
allServerGroups.addRequiredPreceding(name);
allServerGroups.addCantAppearAfter(force);
force.addCantAppearAfter(allServerGroups);
serverGroups = new ArgumentWithValue(this, new CommandLineCompleter() {
@Override
public int complete(CommandContext ctx, String buffer, int cursor, List<String> candidates) {
List<String> allGroups = Util.getServerGroups(ctx.getModelControllerClient());
if(buffer.isEmpty()) {
candidates.addAll(allGroups);
Collections.sort(candidates);
return 0;
}
final String[] groups = buffer.split(",+");
final String chunk;
final int lastGroupIndex;
if(buffer.charAt(buffer.length() - 1) == ',') {
lastGroupIndex = groups.length;
chunk = null;
} else {
lastGroupIndex = groups.length - 1;
chunk = groups[groups.length - 1];
}
for(int i = 0; i < lastGroupIndex; ++i) {
allGroups.remove(groups[i]);
}
final int result;
if(chunk == null) {
candidates.addAll(allGroups);
result = buffer.length();
} else {
for(String group : allGroups) {
if(group.startsWith(chunk)) {
candidates.add(group);
}
}
result = buffer.lastIndexOf(',') + 1;
}
Collections.sort(candidates);
return result;
}}, "--server-groups") {
@Override
public boolean canAppearNext(CommandContext ctx) throws CommandFormatException {
if(!ctx.isDomainMode()) {
return false;
}
return super.canAppearNext(ctx);
}
};
serverGroups.addRequiredPreceding(path);
serverGroups.addRequiredPreceding(name);
serverGroups.addCantAppearAfter(force);
force.addCantAppearAfter(serverGroups);
serverGroups.addCantAppearAfter(allServerGroups);
allServerGroups.addCantAppearAfter(serverGroups);
disabled = new ArgumentWithoutValue(this, "--disabled");
disabled.addRequiredPreceding(path);
disabled.addCantAppearAfter(serverGroups);
disabled.addCantAppearAfter(allServerGroups);
disabled.addCantAppearAfter(force);
force.addCantAppearAfter(disabled);
}
@Override
protected void doHandle(CommandContext ctx) throws CommandFormatException {
final ModelControllerClient client = ctx.getModelControllerClient();
ParsedCommandLine args = ctx.getParsedCommandLine();
boolean l = this.l.isPresent(args);
if (!args.hasProperties() || l) {
printList(ctx, Util.getDeployments(client), l);
return;
}
final String path = this.path.getValue(args);
final File f;
if(path != null) {
f = new File(path);
if(!f.exists()) {
ctx.printLine("Path " + f.getAbsolutePath() + " doesn't exist.");
return;
}
if(f.isDirectory()) {
ctx.printLine(f.getAbsolutePath() + " is a directory.");
return;
}
} else {
f = null;
}
String name = this.name.getValue(args);
if(name == null) {
if(f == null) {
ctx.printLine("Either path or --name is requied.");
return;
}
name = f.getName();
}
final String runtimeName = rtName.getValue(args);
final boolean force = this.force.isPresent(args);
final boolean disabled = this.disabled.isPresent(args);
final String serverGroups = this.serverGroups.getValue(args);
final boolean allServerGroups = this.allServerGroups.isPresent(args);
if(force) {
if(f == null) {
ctx.printLine(this.force.getFullName() + " requires a filesystem path of the deployment to be added to the deployment repository.");
return;
}
if(disabled || serverGroups != null || allServerGroups) {
ctx.printLine(this.force.getFullName() +
" only replaces the content in the deployment repository and can't be used in combination with any of " +
this.disabled.getFullName() + ", " + this.serverGroups.getFullName() + " or " + this.allServerGroups.getFullName() + '.');
return;
}
if(Util.isDeploymentInRepository(name, client)) {
replaceDeployment(ctx, f, name, runtimeName);
return;
} else if(ctx.isDomainMode()) {
// add deployment to the repository (enabled in standalone, disabled in domain (i.e. not associated with any sg))
final ModelNode request = buildAddRequest(ctx, f, name, runtimeName);
execute(ctx, request, f);
return;
}
// standalone mode will add and deploy
}
if(disabled) {
if(f == null) {
ctx.printLine(this.disabled.getFullName() + " requires a filesystem path of the deployment to be added to the deployment repository.");
return;
}
if(serverGroups != null || allServerGroups) {
ctx.printLine(this.serverGroups.getFullName() + " and " + this.allServerGroups.getFullName() +
" can't be used in combination with " + this.disabled.getFullName() + '.');
return;
}
if(Util.isDeploymentInRepository(name, client)) {
ctx.printLine("'" + name + "' already exists in the deployment repository (use " +
this.force.getFullName() + " to replace the existing content in the repository).");
return;
}
// add deployment to the repository disabled
final ModelNode request = buildAddRequest(ctx, f, name, runtimeName);
execute(ctx, request, f);
return;
}
// actually, the deployment is added before it is deployed
// but this code here is to validate arguments and not to add deployment if something is wrong
final ModelNode deployRequest;
if(ctx.isDomainMode()) {
final List<String> sgList;
if(allServerGroups) {
if(serverGroups != null) {
ctx.printLine(this.serverGroups.getFullName() + " can't appear in the same command with " + this.allServerGroups.getFullName());
return;
}
sgList = Util.getServerGroups(client);
if(sgList.isEmpty()) {
ctx.printLine("No server group is available.");
return;
}
} else if(serverGroups == null) {
final StringBuilder buf = new StringBuilder();
buf.append("One of ");
if(f != null) {
buf.append(this.disabled.getFullName()).append(", ");
}
buf.append(this.allServerGroups.getFullName() + " or " + this.serverGroups.getFullName() + " is missing.");
ctx.printLine(buf.toString());
return;
} else {
sgList = Arrays.asList(serverGroups.split(","));
if(sgList.isEmpty()) {
ctx.printLine("Couldn't locate server group name in '" + this.serverGroups.getFullName() + "=" + serverGroups + "'.");
return;
}
}
deployRequest = new ModelNode();
deployRequest.get(Util.OPERATION).set(Util.COMPOSITE);
deployRequest.get(Util.ADDRESS).setEmptyList();
ModelNode steps = deployRequest.get(Util.STEPS);
for (String serverGroup : sgList) {
steps.add(Util.configureDeploymentOperation(Util.ADD, name, serverGroup));
}
for (String serverGroup : sgList) {
steps.add(Util.configureDeploymentOperation(Util.DEPLOY, name, serverGroup));
}
} else {
if(serverGroups != null || allServerGroups) {
ctx.printLine(this.serverGroups.getFullName() + " and " + this.allServerGroups.getFullName() +
" can't appear in standalone mode.");
return;
}
deployRequest = new ModelNode();
deployRequest.get(Util.OPERATION).set(Util.DEPLOY);
deployRequest.get(Util.ADDRESS, Util.DEPLOYMENT).set(name);
}
if(f != null) {
if(Util.isDeploymentInRepository(name, client)) {
ctx.printLine("'" + name + "' already exists in the deployment repository (use " +
this.force.getFullName() + " to replace the existing content in the repository).");
return;
}
final ModelNode request = new ModelNode();
request.get(Util.OPERATION).set(Util.COMPOSITE);
request.get(Util.ADDRESS).setEmptyList();
final ModelNode steps = request.get(Util.STEPS);
steps.add(buildAddRequest(ctx, f, name, runtimeName));
steps.add(deployRequest);
execute(ctx, request, f);
return;
} else if(!Util.isDeploymentInRepository(name, client)) {
ctx.printLine("'" + name + "' is not found among the registered deployments.");
return;
}
try {
final ModelNode result = client.execute(deployRequest);
if (!Util.isSuccess(result)) {
ctx.printLine(Util.getFailureDescription(result));
return;
}
} catch (Exception e) {
ctx.printLine("Failed to deploy: " + e.getLocalizedMessage());
return;
}
}
@Override
public ModelNode buildRequest(CommandContext ctx) throws CommandFormatException {
final ModelControllerClient client = ctx.getModelControllerClient();
ParsedCommandLine args = ctx.getParsedCommandLine();
boolean l = this.l.isPresent(args);
if (!args.hasProperties() || l) {
throw new OperationFormatException("Command is missing arguments for non-interactive mode: '" + args.getOriginalLine() + "'.");
}
final String path = this.path.getValue(args);
final File f;
if(path != null) {
f = new File(path);
if(!f.exists()) {
throw new OperationFormatException("Path " + f.getAbsolutePath() + " doesn't exist.");
}
if(f.isDirectory()) {
throw new OperationFormatException(f.getAbsolutePath() + " is a directory.");
}
} else {
f = null;
}
String name = this.name.getValue(args);
if(name == null) {
if(f == null) {
throw new OperationFormatException("Either path or --name is requied.");
}
name = f.getName();
}
final String runtimeName = rtName.getValue(args);
final boolean force = this.force.isPresent(args);
final boolean disabled = this.disabled.isPresent(args);
final String serverGroups = this.serverGroups.getValue(args);
final boolean allServerGroups = this.allServerGroups.isPresent(args);
if(force) {
if(f == null) {
throw new OperationFormatException(this.force.getFullName() + " requires a filesystem path of the deployment to be added to the deployment repository.");
}
if(disabled || serverGroups != null || allServerGroups) {
throw new OperationFormatException(this.force.getFullName() +
" only replaces the content in the deployment repository and can't be used in combination with any of " +
this.disabled.getFullName() + ", " + this.serverGroups.getFullName() + " or " + this.allServerGroups.getFullName() + '.');
}
if(Util.isDeploymentInRepository(name, client)) {
return buildDeploymentReplace(f, name, runtimeName);
} else {
// add deployment to the repository (enabled in standalone, disabled in domain (i.e. not associated with any sg))
return buildDeploymentAdd(f, name, runtimeName);
}
}
if(disabled) {
if(f == null) {
throw new OperationFormatException(this.disabled.getFullName() +
" requires a filesystem path of the deployment to be added to the deployment repository.");
}
if(serverGroups != null || allServerGroups) {
throw new OperationFormatException(this.serverGroups.getFullName() + " and " + this.allServerGroups.getFullName() +
" can't be used in combination with " + this.disabled.getFullName() + '.');
}
if(Util.isDeploymentInRepository(name, client)) {
throw new OperationFormatException("'" + name + "' already exists in the deployment repository (use " +
this.force.getFullName() + " to replace the existing content in the repository).");
}
// add deployment to the repository disabled
return buildDeploymentAdd(f, name, runtimeName);
}
// actually, the deployment is added before it is deployed
// but this code here is to validate arguments and not to add deployment if something is wrong
final ModelNode deployRequest;
if(ctx.isDomainMode()) {
final List<String> sgList;
if(allServerGroups) {
if(serverGroups != null) {
throw new OperationFormatException(this.serverGroups.getFullName() + " can't appear in the same command with " + this.allServerGroups.getFullName());
}
sgList = Util.getServerGroups(client);
if(sgList.isEmpty()) {
throw new OperationFormatException("No server group is available.");
}
} else if(serverGroups == null) {
final StringBuilder buf = new StringBuilder();
buf.append("One of ");
if(f != null) {
buf.append(this.disabled.getFullName()).append(", ");
}
buf.append(this.allServerGroups.getFullName() + " or " + this.serverGroups.getFullName() + " is missing.");
throw new OperationFormatException(buf.toString());
} else {
sgList = Arrays.asList(serverGroups.split(","));
if(sgList.isEmpty()) {
throw new OperationFormatException("Couldn't locate server group name in '" + this.serverGroups.getFullName() + "=" + serverGroups + "'.");
}
}
deployRequest = new ModelNode();
deployRequest.get(Util.OPERATION).set(Util.COMPOSITE);
deployRequest.get(Util.ADDRESS).setEmptyList();
ModelNode steps = deployRequest.get(Util.STEPS);
for (String serverGroup : sgList) {
steps.add(Util.configureDeploymentOperation(Util.ADD, name, serverGroup));
}
for (String serverGroup : sgList) {
steps.add(Util.configureDeploymentOperation(Util.DEPLOY, name, serverGroup));
}
} else {
if(serverGroups != null || allServerGroups) {
throw new OperationFormatException(this.serverGroups.getFullName() + " and " + this.allServerGroups.getFullName() +
" can't appear in standalone mode.");
}
deployRequest = new ModelNode();
deployRequest.get(Util.OPERATION).set(Util.DEPLOY);
deployRequest.get(Util.ADDRESS, Util.DEPLOYMENT).set(name);
}
final ModelNode addRequest;
if(f != null) {
if(Util.isDeploymentInRepository(name, client)) {
throw new OperationFormatException("'" + name + "' already exists in the deployment repository (use " +
this.force.getFullName() + " to replace the existing content in the repository).");
}
addRequest = this.buildDeploymentAdd(f, name, runtimeName);
} else if(!Util.isDeploymentInRepository(name, client)) {
throw new OperationFormatException("'" + name + "' is not found among the registered deployments.");
} else {
addRequest = null;
}
if(addRequest != null) {
final ModelNode composite = new ModelNode();
composite.get(Util.OPERATION).set(Util.COMPOSITE);
composite.get(Util.ADDRESS).setEmptyList();
final ModelNode steps = composite.get(Util.STEPS);
steps.add(addRequest);
steps.add(deployRequest);
return composite;
}
return deployRequest;
}
protected ModelNode buildDeploymentReplace(final File f, String name, String runtimeName) throws OperationFormatException {
final ModelNode request = new ModelNode();
request.get(Util.OPERATION).set(Util.FULL_REPLACE_DEPLOYMENT);
request.get(Util.NAME).set(name);
if(runtimeName != null) {
request.get(Util.RUNTIME_NAME).set(runtimeName);
}
byte[] bytes = readBytes(f);
request.get(Util.CONTENT).get(0).get(Util.BYTES).set(bytes);
return request;
}
protected ModelNode buildDeploymentAdd(final File f, String name, String runtimeName) throws OperationFormatException {
final ModelNode request = new ModelNode();
request.get(Util.OPERATION).set(Util.ADD);
request.get(Util.ADDRESS, Util.DEPLOYMENT).set(name);
if (runtimeName != null) {
request.get(Util.RUNTIME_NAME).set(runtimeName);
}
byte[] bytes = readBytes(f);
request.get(Util.CONTENT).get(0).get(Util.BYTES).set(bytes);
return request;
}
protected void execute(CommandContext ctx, ModelNode request, File f) {
ModelNode result;
FileInputStream is = null;
try {
is = new FileInputStream(f);
OperationBuilder op = new OperationBuilder(request);
op.addInputStream(is);
request.get(Util.CONTENT).get(0).get(Util.INPUT_STREAM_INDEX).set(0);
result = ctx.getModelControllerClient().execute(op.build());
} catch (Exception e) {
ctx.printLine("Failed to add the deployment content to the repository: " + e.getLocalizedMessage());
return;
} finally {
StreamUtils.safeClose(is);
}
if (!Util.isSuccess(result)) {
ctx.printLine(Util.getFailureDescription(result));
return;
}
}
protected ModelNode buildAddRequest(CommandContext ctx, final File f, String name, final String runtimeName) {
final ModelNode request = new ModelNode();
request.get(Util.OPERATION).set(Util.ADD);
request.get(Util.ADDRESS, Util.DEPLOYMENT).set(name);
if (runtimeName != null) {
request.get(Util.RUNTIME_NAME).set(runtimeName);
}
request.get(Util.CONTENT).get(0).get(Util.INPUT_STREAM_INDEX).set(0);
return request;
}
protected void replaceDeployment(CommandContext ctx, final File f, String name, final String runtimeName) {
ModelNode result;
// replace
final ModelNode request = new ModelNode();
request.get(Util.OPERATION).set(Util.FULL_REPLACE_DEPLOYMENT);
request.get(Util.NAME).set(name);
if(runtimeName != null) {
request.get(Util.RUNTIME_NAME).set(runtimeName);
}
FileInputStream is = null;
try {
is = new FileInputStream(f);
OperationBuilder op = new OperationBuilder(request);
op.addInputStream(is);
request.get(Util.CONTENT).get(0).get(Util.INPUT_STREAM_INDEX).set(0);
result = ctx.getModelControllerClient().execute(op.build());
} catch(Exception e) {
ctx.printLine("Failed to replace the deployment: " + e.getLocalizedMessage());
return;
} finally {
StreamUtils.safeClose(is);
}
if(!Util.isSuccess(result)) {
ctx.printLine(Util.getFailureDescription(result));
return;
}
}
protected byte[] readBytes(File f) throws OperationFormatException {
byte[] bytes;
FileInputStream is = null;
try {
is = new FileInputStream(f);
bytes = new byte[(int) f.length()];
int read = is.read(bytes);
if(read != bytes.length) {
throw new OperationFormatException("Failed to read bytes from " + f.getAbsolutePath() + ": " + read + " from " + f.length());
}
} catch (Exception e) {
throw new OperationFormatException("Failed to read file " + f.getAbsolutePath(), e);
} finally {
StreamUtils.safeClose(is);
}
return bytes;
}
} |
package lighthouse.subwindows;
import com.google.common.util.concurrent.Futures;
import com.vinumeris.updatefx.UFXProtocol;
import com.vinumeris.updatefx.UpdateFX;
import com.vinumeris.updatefx.UpdateSummary;
import com.vinumeris.updatefx.Updater;
import de.jensd.fx.fontawesome.AwesomeIcon;
import de.jensd.fx.fontawesome.Icon;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.text.Text;
import lighthouse.Main;
import lighthouse.files.AppDirectory;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import static java.nio.file.Files.exists;
import static lighthouse.utils.GuiUtils.informationalAlert;
/**
* Lets the user select a version to pin themselves to.
*/
public class UpdateFXWindow {
public Main.OverlayUI<UpdateFXWindow> overlayUI;
@FXML Text descriptionLabel;
@FXML ListView<UFXProtocol.Update> updatesList;
@FXML Button pinBtn;
private ObservableList<UFXProtocol.Update> updates = FXCollections.observableArrayList();
private SimpleIntegerProperty currentPin = new SimpleIntegerProperty();
private UpdateSummary summary;
public void initialize() {
currentPin.set(UpdateFX.getVersionPin(AppDirectory.dir()));
updatesList.setCellFactory(param -> new ListCell<UFXProtocol.Update>() {
@Override
protected void updateItem(@Nullable UFXProtocol.Update item, boolean empty) {
super.updateItem(item, empty);
if (empty || summary == null) {
setText("");
setGraphic(null);
setStyle("");
} else {
setStyle("");
setText(item == null ? "Latest version" : item.getDescription(0).getOneLiner());
Icon icon = Icon.create().icon(AwesomeIcon.THUMB_TACK);
icon.setStyle("-fx-font-family: FontAwesome; -fx-font-size: 1.5em");
icon.visibleProperty().bind(currentPin.isEqualTo(item != null ? item.getVersion() : 0));
setGraphic(icon);
// Bold the current version that's running, or latest if we're up to date.
if ((item == null && Main.VERSION == summary.newVersion) ||
(item != null && item.getVersion() == Main.VERSION && item.getVersion() != summary.newVersion))
setStyle("-fx-font-weight: bold");
else
setStyle("");
}
}
});
updatesList.setItems(updates);
updatesList.getSelectionModel().selectFirst();
updatesList.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
updatesList.getSelectionModel().selectedIndexProperty().addListener((x, prev, cur) -> {
if (cur.intValue() > 0)
descriptionLabel.setText(updates.get(cur.intValue()).getDescription(0).getDescription());
else
descriptionLabel.setText("");
});
}
public static Main.OverlayUI<UpdateFXWindow> open(Updater updater) {
Main.OverlayUI<UpdateFXWindow> result = Main.instance.<UpdateFXWindow>overlayUI("subwindows/updatefx.fxml", "Application updates");
result.controller.setUpdater(checkNotNull(updater));
return result;
}
@FXML
public void pinClicked(ActionEvent event) {
UFXProtocol.Update selected = updatesList.getSelectionModel().getSelectedItem();
if (selected == null) {
UpdateFX.unpin(AppDirectory.dir());
currentPin.set(0);
informationalAlert("Version change",
"You will be switched to always track the latest version. The app will now restart.");
Main.restart();
} else {
int ver = selected.getVersion();
UpdateFX.pinToVersion(AppDirectory.dir(), ver);
currentPin.set(ver);
informationalAlert("Version change",
"You will be switched to always use version %d. The app will now restart.", ver);
Main.restart();
}
}
@FXML
public void closeClicked(ActionEvent event) {
overlayUI.done();
}
public void setUpdater(Updater updater) {
if (updater.isDone())
processUpdater(updater);
else
updater.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, event -> {
processUpdater(updater);
});
}
private void processUpdater(Updater updater) {
summary = Futures.getUnchecked(updater);
updates.clear();
updates.add(null); // Sentinel for "latest"
List<UFXProtocol.Update> list = new ArrayList<>(summary.updates.getUpdatesList());
Collections.reverse(list);
for (UFXProtocol.Update update : list) {
// For each update in the index, check if we have it on disk (the index can contain updates older than
// what we can roll back to).
if (exists(AppDirectory.dir().resolve(format("%d.jar", update.getVersion())))) {
if (update.getDescriptionCount() > 0)
updates.add(update);
}
}
}
} |
package org.jetel.component;
//import org.w3c.dom.Node;
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Method;
import org.jetel.graph.Node;
/**
* Description of the Class
*
* @author dpavlis
* @since May 27, 2002
* @revision $Revision$
*/
public class ComponentFactory {
private final static String NAME_OF_STATIC_LOAD_FROM_XML = "fromXML";
private final static Class[] PARAMETERS_FOR_METHOD = new Class[] { org.w3c.dom.Node.class };
private final static Map componentMap = new HashMap();
public static void init() {
ComponentDescription[] components = new ComponentDescriptionReader().getComponentDescriptions();
for(int i = 0; i < components.length; i++) {
registerComponent(components[i].getType(), components[i].getClassName());
}
// register known components
// parameters <component type>,<full class name including package>
// registerComponent(SimpleCopy.COMPONENT_TYPE,"org.jetel.component.SimpleCopy");
// registerComponent(Concatenate.COMPONENT_TYPE,"org.jetel.component.Concatenate");
// registerComponent(DelimitedDataReader.COMPONENT_TYPE,"org.jetel.component.DelimitedDataReader");
// registerComponent(DelimitedDataWriter.COMPONENT_TYPE,"org.jetel.component.DelimitedDataWriter");
// registerComponent(SimpleGather.COMPONENT_TYPE,"org.jetel.component.SimpleGather");
// registerComponent(DelimitedDataWriterNIO.COMPONENT_TYPE,"org.jetel.component.DelimitedDataWriterNIO");
// registerComponent(DelimitedDataReaderNIO.COMPONENT_TYPE,"org.jetel.component.DelimitedDataReaderNIO");
// registerComponent(Reformat.COMPONENT_TYPE,"org.jetel.component.Reformat");
// registerComponent(DBInputTable.COMPONENT_TYPE,"org.jetel.component.DBInputTable");
// registerComponent(Sort.COMPONENT_TYPE,"org.jetel.component.Sort");
// registerComponent(DBOutputTable.COMPONENT_TYPE,"org.jetel.component.DBOutputTable");
// registerComponent(FixLenDataWriterNIO.COMPONENT_TYPE,"org.jetel.component.FixLenDataWriterNIO");
// registerComponent(Dedup.COMPONENT_TYPE,"org.jetel.component.Dedup");
// registerComponent(FixLenDataReaderNIO.COMPONENT_TYPE,"org.jetel.component.FixLenDataReaderNIO");
// registerComponent("FIXED_DATA_READER_NIO","org.jetel.component.FixLenDataReaderNIO");
// registerComponent(Merge.COMPONENT_TYPE,"org.jetel.component.Merge");
// registerComponent(MergeJoin.COMPONENT_TYPE,"org.jetel.component.MergeJoin");
// registerComponent("SORTED_JOIN","org.jetel.component.MergeJoin"); // synonym for MergeJoin (former name)
// registerComponent(Trash.COMPONENT_TYPE,"org.jetel.component.Trash");
// registerComponent(Filter.COMPONENT_TYPE,"org.jetel.component.Filter");
// registerComponent(DBExecute.COMPONENT_TYPE,"org.jetel.component.DBExecute");
// registerComponent(HashJoin.COMPONENT_TYPE,"org.jetel.component.HashJoin");
// registerComponent(CheckForeignKey.COMPONENT_TYPE,"org.jetel.component.CheckForeignKey");
// registerComponent(DBFDataReader.COMPONENT_TYPE,"org.jetel.component.DBFDataReader");
// registerComponent(ExtFilter.COMPONENT_TYPE,"org.jetel.component.ExtFilter");
// registerComponent(ExtSort.COMPONENT_TYPE,"org.jetel.component.ExtSort");
// registerComponent(Partition.COMPONENT_TYPE,"org.jetel.component.Partition");
// registerComponent(DataIntersection.COMPONENT_TYPE,"org.jetel.component.DataIntersection");
// registerComponent(Aggregate.COMPONENT_TYPE,"org.jetel.component.Aggregate");
// registerComponent(XMLExtract.COMPONENT_TYPE,"org.jetel.component.XMLExtract");
}
public final static void registerComponent(Node component){
componentMap.put(component.getType(),component.getName());
}
public final static void registerComponent(String componentType,String className){
componentMap.put(componentType,className);
}
/**
* Method for creating various types of Components based on component type & XML parameter definition.<br>
* If component type is not registered, it tries to use componentType parameter directly as a class name.
* This way new components can be added withou modifying ComponentFactory code.
*
* @param componentType Type of the component (e.g. SimpleCopy, Gather, Join ...)
* @param xmlNode XML element containing appropriate Node parameters
* @return requested Component (Node) object or null if creation failed
* @since May 27, 2002
*/
public final static Node createComponent(String componentType, org.w3c.dom.Node nodeXML) {
// try to load the component (use type as a full name)
Class tClass;
Method method;
String className=null;
try{
className=(String)componentMap.get(componentType);
if (className==null){
// if it cannot be translated into class name, try to use the component
// type as fully qualified component name
className=componentType;
}
tClass = Class.forName(className);
}catch(ClassNotFoundException ex){
throw new RuntimeException("Unknown component: " + componentType + " class: "+className);
}catch(Exception ex){
throw new RuntimeException("Unknown exception: " + ex);
}
try{
Object[] args={nodeXML};
//Class.forName("org.w3c.dom.Node")
method=tClass.getMethod(NAME_OF_STATIC_LOAD_FROM_XML, PARAMETERS_FOR_METHOD);
//return newNode.fromXML(nodeXML);
return (org.jetel.graph.Node)method.invoke(null,args);
}catch(Exception ex){
throw new RuntimeException("Can't create object of : " + componentType + " exception: "+ex);
}
}
} |
package com.badlogic.gdx.ingenuity.screen;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.ingenuity.Asset;
import com.badlogic.gdx.ingenuity.GdxData;
import com.badlogic.gdx.ingenuity.screen.LoadingScreen.ILoadingComplete;
import com.badlogic.gdx.ingenuity.utils.helper.PixmapHelper;
import com.badlogic.gdx.ingenuity.utils.scene2d.SimpleScreen;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.ButtonGroup;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Align;
import net.mwplay.nativefont.NativeButton;
/**
* @ mitkey
* @ 2017520 12:14:45
* @ BaseTestScreen.java <br/>
* @ 0.0.1
*/
public abstract class BaseTestScreen extends SimpleScreen {
public static final List<Class<? extends SimpleScreen>> tests = new ArrayList<Class<? extends SimpleScreen>>(
Arrays.asList(LoginScreen.class, HallScreen.class, RoomScreen.class));
@Override
public void show() {
super.show();
Drawable up = changeSpace(PixmapHelper.getInstance().newRectangleDrawable(Color.DARK_GRAY, 20, 20));
Drawable down = changeSpace(PixmapHelper.getInstance().newRectangleDrawable(Color.GRAY, 20, 20));
Drawable checked = changeSpace(PixmapHelper.getInstance().newRectangleDrawable(Color.LIGHT_GRAY, 20, 20));
final ButtonGroup<NativeButton> buttonGroup = new ButtonGroup<NativeButton>();
Table table = new Table();
table.pad(10).center().defaults().align(Align.center).top().space(10);
for (final Class<? extends SimpleScreen> clazz : tests) {
NativeButton button = newNativeButton(clazz.getSimpleName(), up, down, checked, 20);
table.add(button).size(150, 50).row();
boolean checkCurChecked = checkCurChecked(button);
if (checkCurChecked) {
button.setDisabled(true);
button.setTouchable(Touchable.disabled);
}
buttonGroup.add(button);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
super.clicked(event, x, y);
game().updateScreen(new LoadingScreen(new ILoadingComplete() {
@Override
public boolean complete() {
try {
game().updateScreen(clazz.newInstance());
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return true;
}
}, Asset.none));
}
});
}
table.pack();
table.setPosition(0, GdxData.HEIGHT - table.getHeight());
stage().addActor(table);
buttonGroup.uncheckAll();
for (NativeButton temp : buttonGroup.getButtons()) {
if (checkCurChecked(temp)) {
temp.setChecked(true);
}
}
}
@Override
public void dispose() {
super.dispose();
}
public Class<? extends SimpleScreen> getCurScreenClazz() {
return getClass();
}
private boolean checkCurChecked(NativeButton temp) {
return getCurScreenClazz().getSimpleName().equals(temp.getText().toString());
}
private Drawable changeSpace(Drawable drawable) {
drawable.setTopHeight(20);
drawable.setRightWidth(20);
drawable.setBottomHeight(20);
drawable.setLeftWidth(20);
return drawable;
}
} |
package org.mwg.core.chunk.heap;
import org.mwg.Constants;
import org.mwg.Type;
import org.mwg.core.CoreConstants;
import org.mwg.chunk.ChunkListener;
import org.mwg.chunk.StateChunk;
import org.mwg.utility.HashHelper;
import org.mwg.utility.Base64;
import org.mwg.chunk.ChunkType;
import org.mwg.plugin.NodeStateCallback;
import org.mwg.struct.*;
import java.util.Arrays;
class HeapStateChunk implements StateChunk, ChunkListener {
private final long _index;
private final HeapChunkSpace _space;
private int _capacity;
private volatile int _size;
private long[] _k;
private Object[] _v;
private int[] _next;
private int[] _hash;
private byte[] _type;
private boolean unaligned = false;
private boolean _dirty;
HeapStateChunk(final HeapChunkSpace p_space, final long p_index) {
_space = p_space;
_index = p_index;
//null hash function
_next = null;
_hash = null;
_type = null;
//init to empty size
_size = 0;
_capacity = 0;
_dirty = false;
}
@Override
public final long world() {
return _space.worldByIndex(_index);
}
@Override
public final long time() {
return _space.timeByIndex(_index);
}
@Override
public final long id() {
return _space.idByIndex(_index);
}
@Override
public final byte chunkType() {
return ChunkType.STATE_CHUNK;
}
@Override
public final long index() {
return _index;
}
@Override
public synchronized final Object get(final long p_key) {
return internal_get(p_key);
}
private int internal_find(final long p_key) {
if (_size == 0) {
return -1;
} else if (_hash == null) {
for (int i = 0; i < _size; i++) {
if (_k[i] == p_key) {
return i;
}
}
return -1;
} else {
final int hashIndex = (int) HashHelper.longHash(p_key, _capacity * 2);
int m = _hash[hashIndex];
while (m >= 0) {
if (p_key == _k[m]) {
return m;
} else {
m = _next[m];
}
}
return -1;
}
}
private Object internal_get(final long p_key) {
//empty chunk, we return immediately
if (_size == 0) {
return null;
}
int found = internal_find(p_key);
Object result;
if(found != -1) {
result = _v[found];
//TODO optimize this
if (result != null) {
switch (_type[found]) {
case Type.DOUBLE_ARRAY:
double[] castedResultD = (double[]) result;
double[] copyD = new double[castedResultD.length];
System.arraycopy(castedResultD, 0, copyD, 0, castedResultD.length);
return copyD;
case Type.LONG_ARRAY:
long[] castedResultL = (long[]) result;
long[] copyL = new long[castedResultL.length];
System.arraycopy(castedResultL, 0, copyL, 0, castedResultL.length);
return copyL;
case Type.INT_ARRAY:
int[] castedResultI = (int[]) result;
int[] copyI = new int[castedResultI.length];
System.arraycopy(castedResultI, 0, copyI, 0, castedResultI.length);
return copyI;
default:
return result;
}
}
}
return null;
}
@Override
public synchronized final void set(final long p_elementIndex, final byte p_elemType, final Object p_unsafe_elem) {
internal_set(p_elementIndex, p_elemType, p_unsafe_elem, true, false);
}
@Override
public synchronized final void setFromKey(final String key, final byte p_elemType, final Object p_unsafe_elem) {
internal_set(_space.graph().resolver().stringToHash(key, true), p_elemType, p_unsafe_elem, true, false);
}
@Override
public synchronized final Object getFromKey(final String key) {
return internal_get(_space.graph().resolver().stringToHash(key, false));
}
@Override
public final <A> A getFromKeyWithDefault(final String key, final A defaultValue) {
final Object result = getFromKey(key);
if (result == null) {
return defaultValue;
} else {
return (A) result;
}
}
@Override
public synchronized final byte getType(final long p_key) {
if (_size == 0) {
return -1;
}
if (_hash == null) {
for (int i = 0; i < _capacity; i++) {
if (_k[i] == p_key) {
return _type[i];
}
}
} else {
int hashIndex = (int) HashHelper.longHash(p_key, _capacity * 2);
int m = _hash[hashIndex];
while (m >= 0) {
if (p_key == _k[m]) {
return _type[m];
} else {
m = _next[m];
}
}
}
return -1;
}
@Override
public byte getTypeFromKey(final String key) {
return getType(_space.graph().resolver().stringToHash(key, false));
}
@Override
public synchronized final Object getOrCreate(final long p_key, final byte p_type) {
final int found = internal_find(p_key);
if (found != -1) {
if (_type[found] == p_type) {
return _v[found];
}
}
Object toSet = null;
switch (p_type) {
case Type.RELATION:
toSet = new HeapRelationship(this, null);
break;
case Type.STRING_TO_LONG_MAP:
toSet = new HeapStringLongMap(this, CoreConstants.MAP_INITIAL_CAPACITY, null);
break;
case Type.LONG_TO_LONG_MAP:
toSet = new HeapLongLongMap(this, CoreConstants.MAP_INITIAL_CAPACITY, null);
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
toSet = new HeapLongLongArrayMap(this, CoreConstants.MAP_INITIAL_CAPACITY, null);
break;
}
internal_set(p_key, p_type, toSet, true, false);
return toSet;
}
@Override
public final Object getOrCreateFromKey(final String key, final byte elemType) {
return getOrCreate(_space.graph().resolver().stringToHash(key, true), elemType);
}
@Override
public final void declareDirty() {
if (_space != null && !_dirty) {
_dirty = true;
_space.notifyUpdate(_index);
}
}
@Override
public synchronized final void save(final Buffer buffer) {
Base64.encodeIntToBuffer(_size, buffer);
for (int i = 0; i < _size; i++) {
if (_v[i] != null) { //there is a real value
final Object loopValue = _v[i];
if (loopValue != null) {
buffer.write(CoreConstants.CHUNK_SEP);
Base64.encodeLongToBuffer(_k[i], buffer);
buffer.write(CoreConstants.CHUNK_SUB_SEP);
/** Encode to type of elem, for unSerialization */
Base64.encodeIntToBuffer(_type[i], buffer);
buffer.write(CoreConstants.CHUNK_SUB_SEP);
switch (_type[i]) {
case Type.STRING:
Base64.encodeStringToBuffer((String) loopValue, buffer);
break;
case Type.BOOL:
if ((Boolean) _v[i]) {
buffer.write(CoreConstants.BOOL_TRUE);
} else {
buffer.write(CoreConstants.BOOL_FALSE);
}
break;
case Type.LONG:
Base64.encodeLongToBuffer((Long) loopValue, buffer);
break;
case Type.DOUBLE:
Base64.encodeDoubleToBuffer((Double) loopValue, buffer);
break;
case Type.INT:
Base64.encodeIntToBuffer((Integer) loopValue, buffer);
break;
case Type.DOUBLE_ARRAY:
double[] castedDoubleArr = (double[]) loopValue;
Base64.encodeIntToBuffer(castedDoubleArr.length, buffer);
for (int j = 0; j < castedDoubleArr.length; j++) {
buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP);
Base64.encodeDoubleToBuffer(castedDoubleArr[j], buffer);
}
break;
case Type.RELATION:
Relationship castedLongArrRel = (Relationship) loopValue;
Base64.encodeIntToBuffer(castedLongArrRel.size(), buffer);
for (int j = 0; j < castedLongArrRel.size(); j++) {
buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP);
Base64.encodeLongToBuffer(castedLongArrRel.get(j), buffer);
}
break;
case Type.LONG_ARRAY:
long[] castedLongArr = (long[]) loopValue;
Base64.encodeIntToBuffer(castedLongArr.length, buffer);
for (int j = 0; j < castedLongArr.length; j++) {
buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP);
Base64.encodeLongToBuffer(castedLongArr[j], buffer);
}
break;
case Type.INT_ARRAY:
int[] castedIntArr = (int[]) loopValue;
Base64.encodeIntToBuffer(castedIntArr.length, buffer);
for (int j = 0; j < castedIntArr.length; j++) {
buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP);
Base64.encodeIntToBuffer(castedIntArr[j], buffer);
}
break;
case Type.STRING_TO_LONG_MAP:
StringLongMap castedStringLongMap = (StringLongMap) loopValue;
Base64.encodeLongToBuffer(castedStringLongMap.size(), buffer);
castedStringLongMap.each(new StringLongMapCallBack() {
@Override
public void on(final String key, final long value) {
buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP);
Base64.encodeStringToBuffer(key, buffer);
buffer.write(CoreConstants.CHUNK_SUB_SUB_SUB_SEP);
Base64.encodeLongToBuffer(value, buffer);
}
});
break;
case Type.LONG_TO_LONG_MAP:
LongLongMap castedLongLongMap = (LongLongMap) loopValue;
Base64.encodeLongToBuffer(castedLongLongMap.size(), buffer);
castedLongLongMap.each(new LongLongMapCallBack() {
@Override
public void on(final long key, final long value) {
buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP);
Base64.encodeLongToBuffer(key, buffer);
buffer.write(CoreConstants.CHUNK_SUB_SUB_SUB_SEP);
Base64.encodeLongToBuffer(value, buffer);
}
});
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
LongLongArrayMap castedLongLongArrayMap = (LongLongArrayMap) loopValue;
Base64.encodeLongToBuffer(castedLongLongArrayMap.size(), buffer);
castedLongLongArrayMap.each(new LongLongArrayMapCallBack() {
@Override
public void on(final long key, final long value) {
buffer.write(CoreConstants.CHUNK_SUB_SUB_SEP);
Base64.encodeLongToBuffer(key, buffer);
buffer.write(CoreConstants.CHUNK_SUB_SUB_SUB_SEP);
Base64.encodeLongToBuffer(value, buffer);
}
});
break;
default:
break;
}
}
}
}
}
@Override
public synchronized final void each(final NodeStateCallback callBack) {
for (int i = 0; i < _size; i++) {
if (_v[i] != null) {
callBack.on(_k[i], _type[i], _v[i]);
}
}
}
@Override
public synchronized void loadFrom(final StateChunk origin) {
if (origin == null) {
return;
}
HeapStateChunk casted = (HeapStateChunk) origin;
_k = casted._k;
_type = casted._type;
_capacity = casted._capacity;
_size = casted._size;
_hash = casted._hash;
_next = casted._next;
unaligned = true;
_v = new Object[_capacity];
for (int i = 0; i < casted._capacity; i++) {
switch (casted._type[i]) {
case Type.LONG_TO_LONG_MAP:
if (casted._v[i] != null) {
_v[i] = new HeapLongLongMap(this, -1, (HeapLongLongMap) casted._v[i]);
}
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
if (casted._v[i] != null) {
_v[i] = new HeapLongLongArrayMap(this, -1, (HeapLongLongArrayMap) casted._v[i]);
}
break;
case Type.STRING_TO_LONG_MAP:
if (casted._v[i] != null) {
_v[i] = new HeapStringLongMap(this, -1, (HeapStringLongMap) casted._v[i]);
}
break;
case Type.RELATION:
if (casted._v[i] != null) {
_v[i] = new HeapRelationship(this, (HeapRelationship) casted._v[i]);
}
break;
default:
_v[i] = casted._v[i];
break;
}
}
}
private synchronized void internal_set(final long p_key, final byte p_type, final Object p_unsafe_elem, boolean replaceIfPresent, boolean initial) {
Object param_elem = null;
//check the param type
if (p_unsafe_elem != null) {
try {
switch (p_type) {
/** Primitives */
case Type.BOOL:
param_elem = (boolean) p_unsafe_elem;
break;
case Type.DOUBLE:
param_elem = (double) p_unsafe_elem;
break;
case Type.LONG:
if (p_unsafe_elem instanceof Integer) {
int preCasting = (Integer) p_unsafe_elem;
param_elem = (long) preCasting;
} else {
param_elem = (long) p_unsafe_elem;
}
break;
case Type.INT:
param_elem = (int) p_unsafe_elem;
break;
case Type.STRING:
param_elem = (String) p_unsafe_elem;
break;
/** Arrays */
case Type.RELATION:
param_elem = (Relationship) p_unsafe_elem;
break;
case Type.DOUBLE_ARRAY:
double[] castedParamDouble = (double[]) p_unsafe_elem;
double[] clonedDoubleArray = new double[castedParamDouble.length];
System.arraycopy(castedParamDouble, 0, clonedDoubleArray, 0, castedParamDouble.length);
param_elem = clonedDoubleArray;
break;
case Type.LONG_ARRAY:
long[] castedParamLong = (long[]) p_unsafe_elem;
long[] clonedLongArray = new long[castedParamLong.length];
System.arraycopy(castedParamLong, 0, clonedLongArray, 0, castedParamLong.length);
param_elem = clonedLongArray;
break;
case Type.INT_ARRAY:
int[] castedParamInt = (int[]) p_unsafe_elem;
int[] clonedIntArray = new int[castedParamInt.length];
System.arraycopy(castedParamInt, 0, clonedIntArray, 0, castedParamInt.length);
param_elem = clonedIntArray;
break;
/** Maps */
case Type.STRING_TO_LONG_MAP:
param_elem = (StringLongMap) p_unsafe_elem;
break;
case Type.LONG_TO_LONG_MAP:
param_elem = (LongLongMap) p_unsafe_elem;
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
param_elem = (LongLongArrayMap) p_unsafe_elem;
break;
default:
throw new RuntimeException("Internal Exception, unknown type");
}
} catch (Exception e) {
throw new RuntimeException("mwDB usage error, set method called with type " + Type.typeName(p_type) + " while param object is " + p_unsafe_elem);
}
}
//first value
if (_k == null) {
//we do not allocate for empty element
if (param_elem == null) {
return;
}
_capacity = Constants.MAP_INITIAL_CAPACITY;
_k = new long[_capacity];
_v = new Object[_capacity];
_type = new byte[_capacity];
_k[0] = p_key;
_v[0] = param_elem;
_type[0] = p_type;
_size = 1;
return;
}
int entry = -1;
int p_entry = -1;
int hashIndex = -1;
if (_hash == null) {
for (int i = 0; i < _size; i++) {
if (_k[i] == p_key) {
entry = i;
break;
}
}
} else {
hashIndex = (int) HashHelper.longHash(p_key, _capacity * 2);
int m = _hash[hashIndex];
while (m != -1) {
if (_k[m] == p_key) {
entry = m;
break;
}
p_entry = m;
m = _next[m];
}
}
//case already present
if (entry != -1) {
if (replaceIfPresent || (p_type != _type[entry])) {
if (param_elem == null) {
if (_hash != null) {
//unHash previous
if (p_entry != -1) {
_next[p_entry] = _next[entry];
} else {
_hash[hashIndex] = -1;
}
}
int indexVictim = _size - 1;
//just pop the last value
if (entry == indexVictim) {
_k[entry] = -1;
_v[entry] = null;
_type[entry] = -1;
} else {
//we need to reHash the new last element at our place
_k[entry] = _k[indexVictim];
_v[entry] = _v[indexVictim];
_type[entry] = _type[indexVictim];
if (_hash != null) {
_next[entry] = _next[indexVictim];
int victimHash = (int) HashHelper.longHash(_k[entry], _capacity * 2);
int m = _hash[victimHash];
if (m == indexVictim) {
//the victim was the head of hashing list
_hash[victimHash] = entry;
} else {
//the victim is in the next, rechain it
while (m != -1) {
if (_next[m] == indexVictim) {
_next[m] = entry;
break;
}
m = _next[m];
}
}
}
}
_size
} else {
_v[entry] = param_elem;
if (_type[entry] != p_type) {
//realign
if (unaligned) {
long[] cloned_k = new long[_capacity];
System.arraycopy(_k, 0, cloned_k, 0, _capacity);
_k = cloned_k;
Object[] cloned_v = new Object[_capacity];
System.arraycopy(_v, 0, cloned_v, 0, _capacity);
_v = cloned_v;
byte[] cloned_type = new byte[_capacity];
System.arraycopy(_type, 0, cloned_type, 0, _capacity);
_type = cloned_type;
if(_next != null){
int[] cloned_next = new int[_capacity];
System.arraycopy(_next, 0, cloned_next, 0, _capacity);
_next = cloned_next;
}
if(_hash != null){
int[] cloned_hash = new int[_capacity * 2];
System.arraycopy(_hash, 0, cloned_hash, 0, _capacity * 2);
_hash = cloned_hash;
}
unaligned = false;
}
//TODO deep clone
_type[entry] = p_type;
}
}
}
if (!initial) {
declareDirty();
}
return;
}
if (unaligned) {
if (_k != null) {
long[] cloned_k = new long[_capacity];
System.arraycopy(_k, 0, cloned_k, 0, _capacity);
_k = cloned_k;
}
if (_v != null) {
Object[] cloned_v = new Object[_capacity];
System.arraycopy(_v, 0, cloned_v, 0, _capacity);
_v = cloned_v;
}
if (_type != null) {
byte[] cloned_type = new byte[_capacity];
System.arraycopy(_type, 0, cloned_type, 0, _capacity);
_type = cloned_type;
}
if (_next != null) {
int[] cloned_next = new int[_capacity];
System.arraycopy(_next, 0, cloned_next, 0, _capacity);
_next = cloned_next;
}
if (_hash != null) {
int[] cloned_hash = new int[_capacity * 2];
System.arraycopy(_hash, 0, cloned_hash, 0, _capacity * 2);
_hash = cloned_hash;
}
unaligned = false;
}
if (_size < _capacity) {
_k[_size] = p_key;
_v[_size] = param_elem;
_type[_size] = p_type;
if (_hash != null) {
_next[_size] = _hash[hashIndex];
_hash[hashIndex] = _size;
}
_size++;
declareDirty();
return;
}
//extend capacity
int newCapacity = _capacity * 2;
long[] ex_k = new long[newCapacity];
System.arraycopy(_k, 0, ex_k, 0, _capacity);
_k = ex_k;
Object[] ex_v = new Object[newCapacity];
System.arraycopy(_v, 0, ex_v, 0, _capacity);
_v = ex_v;
byte[] ex_type = new byte[newCapacity];
System.arraycopy(_type, 0, ex_type, 0, _capacity);
_type = ex_type;
_capacity = newCapacity;
//insert the next
_k[_size] = p_key;
_v[_size] = param_elem;
_type[_size] = p_type;
_size++;
//reHash
_hash = new int[_capacity * 2];
Arrays.fill(_hash, 0, _capacity * 2, -1);
_next = new int[_capacity];
Arrays.fill(_next, 0, _capacity, -1);
for (int i = 0; i < _size; i++) {
int keyHash = (int) HashHelper.longHash(_k[i], _capacity * 2);
_next[i] = _hash[keyHash];
_hash[keyHash] = i;
}
if (!initial) {
declareDirty();
}
}
private void allocate(int newCapacity) {
if (newCapacity <= _capacity) {
return;
}
long[] ex_k = new long[newCapacity];
if (_k != null) {
System.arraycopy(_k, 0, ex_k, 0, _capacity);
}
_k = ex_k;
Object[] ex_v = new Object[newCapacity];
if (_v != null) {
System.arraycopy(_v, 0, ex_v, 0, _capacity);
}
_v = ex_v;
byte[] ex_type = new byte[newCapacity];
if (_type != null) {
System.arraycopy(_type, 0, ex_type, 0, _capacity);
}
_type = ex_type;
_capacity = newCapacity;
_hash = new int[_capacity * 2];
Arrays.fill(_hash, 0, _capacity * 2, -1);
_next = new int[_capacity];
Arrays.fill(_next, 0, _capacity, -1);
for (int i = 0; i < _size; i++) {
int keyHash = (int) HashHelper.longHash(_k[i], _capacity * 2);
_next[i] = _hash[keyHash];
_hash[keyHash] = i;
}
}
@Override
public final synchronized void load(final Buffer buffer) {
if (buffer == null || buffer.length() == 0) {
return;
}
final boolean initial = _k == null;
//reset size
int cursor = 0;
long payloadSize = buffer.length();
int previousStart = -1;
long currentChunkElemKey = CoreConstants.NULL_LONG;
byte currentChunkElemType = -1;
//init detections
boolean isFirstElem = true;
//array sub creation variable
double[] currentDoubleArr = null;
long[] currentLongArr = null;
int[] currentIntArr = null;
//map sub creation variables
HeapRelationship currentRelation = null;
StringLongMap currentStringLongMap = null;
LongLongMap currentLongLongMap = null;
LongLongArrayMap currentLongLongArrayMap = null;
//array variables
long currentSubSize = -1;
int currentSubIndex = 0;
//map key variables
long currentMapLongKey = CoreConstants.NULL_LONG;
String currentMapStringKey = null;
while (cursor < payloadSize) {
byte current = buffer.read(cursor);
if (current == CoreConstants.CHUNK_SEP) {
if (isFirstElem) {
//initial the map
isFirstElem = false;
final int stateChunkSize = Base64.decodeToIntWithBounds(buffer, 0, cursor);
final int closePowerOfTwo = (int) Math.pow(2, Math.ceil(Math.log(stateChunkSize) / Math.log(2)));
allocate(closePowerOfTwo);
previousStart = cursor + 1;
} else {
if (currentChunkElemType != -1) {
Object toInsert = null;
switch (currentChunkElemType) {
case Type.BOOL:
if (buffer.read(previousStart) == CoreConstants.BOOL_FALSE) {
toInsert = false;
} else if (buffer.read(previousStart) == CoreConstants.BOOL_TRUE) {
toInsert = true;
}
break;
case Type.STRING:
toInsert = Base64.decodeToStringWithBounds(buffer, previousStart, cursor);
break;
case Type.DOUBLE:
toInsert = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor);
break;
case Type.LONG:
toInsert = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
break;
case Type.INT:
toInsert = Base64.decodeToIntWithBounds(buffer, previousStart, cursor);
break;
case Type.DOUBLE_ARRAY:
if (currentDoubleArr == null) {
currentDoubleArr = new double[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)];
} else {
currentDoubleArr[currentSubIndex] = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor);
}
toInsert = currentDoubleArr;
break;
case Type.LONG_ARRAY:
if (currentLongArr == null) {
currentLongArr = new long[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)];
} else {
currentLongArr[currentSubIndex] = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
}
toInsert = currentLongArr;
break;
case Type.INT_ARRAY:
if (currentIntArr == null) {
currentIntArr = new int[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)];
} else {
currentIntArr[currentSubIndex] = Base64.decodeToIntWithBounds(buffer, previousStart, cursor);
}
toInsert = currentIntArr;
break;
case Type.RELATION:
if (currentRelation == null) {
currentRelation = new HeapRelationship(this, null);
currentRelation.allocate(Base64.decodeToIntWithBounds(buffer, previousStart, cursor));
} else {
currentRelation.add(Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
}
toInsert = currentLongArr;
break;
case Type.STRING_TO_LONG_MAP:
if (currentMapStringKey != null) {
currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
}
toInsert = currentStringLongMap;
break;
case Type.LONG_TO_LONG_MAP:
if (currentMapLongKey != CoreConstants.NULL_LONG) {
currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
}
toInsert = currentLongLongMap;
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
if (currentMapLongKey != CoreConstants.NULL_LONG) {
currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
}
toInsert = currentLongLongArrayMap;
break;
}
if (toInsert != null) {
//insert K/V
internal_set(currentChunkElemKey, currentChunkElemType, toInsert, true, initial); //enhance this with boolean array
}
}
//next round, reset all variables...
previousStart = cursor + 1;
currentChunkElemKey = CoreConstants.NULL_LONG;
currentChunkElemType = -1;
currentSubSize = -1;
currentSubIndex = 0;
currentMapLongKey = CoreConstants.NULL_LONG;
currentMapStringKey = null;
}
} else if (current == CoreConstants.CHUNK_SUB_SEP) { //SEPARATION BETWEEN KEY,TYPE,VALUE
if (currentChunkElemKey == CoreConstants.NULL_LONG) {
currentChunkElemKey = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
previousStart = cursor + 1;
} else if (currentChunkElemType == -1) {
currentChunkElemType = (byte) Base64.decodeToIntWithBounds(buffer, previousStart, cursor);
previousStart = cursor + 1;
}
} else if (current == CoreConstants.CHUNK_SUB_SUB_SEP) { //SEPARATION BETWEEN ARRAY VALUES AND MAP KEY/VALUE TUPLES
if (currentSubSize == -1) {
currentSubSize = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
//init array or maps
switch (currentChunkElemType) {
case Type.DOUBLE_ARRAY:
currentDoubleArr = new double[(int) currentSubSize];
break;
case Type.LONG_ARRAY:
currentLongArr = new long[(int) currentSubSize];
break;
case Type.INT_ARRAY:
currentIntArr = new int[(int) currentSubSize];
break;
case Type.RELATION:
currentRelation = new HeapRelationship(this, null);
currentRelation.allocate((int) currentSubSize);
break;
case Type.STRING_TO_LONG_MAP:
currentStringLongMap = new HeapStringLongMap(this, (int) currentSubSize, null);
break;
case Type.LONG_TO_LONG_MAP:
currentLongLongMap = new HeapLongLongMap(this, (int) currentSubSize, null);
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
currentLongLongArrayMap = new HeapLongLongArrayMap(this, (int) currentSubSize, null);
break;
}
} else {
switch (currentChunkElemType) {
case Type.DOUBLE_ARRAY:
currentDoubleArr[currentSubIndex] = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor);
currentSubIndex++;
break;
case Type.RELATION:
currentRelation.add(Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
break;
case Type.LONG_ARRAY:
currentLongArr[currentSubIndex] = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
currentSubIndex++;
break;
case Type.INT_ARRAY:
currentIntArr[currentSubIndex] = Base64.decodeToIntWithBounds(buffer, previousStart, cursor);
currentSubIndex++;
break;
case Type.STRING_TO_LONG_MAP:
if (currentMapStringKey != null) {
currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
currentMapStringKey = null;
}
break;
case Type.LONG_TO_LONG_MAP:
if (currentMapLongKey != CoreConstants.NULL_LONG) {
currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
currentMapLongKey = CoreConstants.NULL_LONG;
}
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
if (currentMapLongKey != CoreConstants.NULL_LONG) {
currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
currentMapLongKey = CoreConstants.NULL_LONG;
}
break;
}
}
previousStart = cursor + 1;
} else if (current == CoreConstants.CHUNK_SUB_SUB_SUB_SEP) {
switch (currentChunkElemType) {
case Type.STRING_TO_LONG_MAP:
if (currentMapStringKey == null) {
currentMapStringKey = Base64.decodeToStringWithBounds(buffer, previousStart, cursor);
} else {
currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
//reset key for next loop
currentMapStringKey = null;
}
break;
case Type.LONG_TO_LONG_MAP:
if (currentMapLongKey == CoreConstants.NULL_LONG) {
currentMapLongKey = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
} else {
currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
//reset key for next loop
currentMapLongKey = CoreConstants.NULL_LONG;
}
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
if (currentMapLongKey == CoreConstants.NULL_LONG) {
currentMapLongKey = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
} else {
currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
//reset key for next loop
currentMapLongKey = CoreConstants.NULL_LONG;
}
break;
}
previousStart = cursor + 1;
}
cursor++;
}
//take the last element
if (currentChunkElemType != -1) {
Object toInsert = null;
switch (currentChunkElemType) {
/** Primitive Object */
case Type.BOOL:
if (buffer.read(previousStart) == CoreConstants.BOOL_FALSE) {
toInsert = false;
} else if (buffer.read(previousStart) == CoreConstants.BOOL_TRUE) {
toInsert = true;
}
break;
case Type.STRING:
toInsert = Base64.decodeToStringWithBounds(buffer, previousStart, cursor);
break;
case Type.DOUBLE:
toInsert = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor);
break;
case Type.LONG:
toInsert = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
break;
case Type.INT:
toInsert = Base64.decodeToIntWithBounds(buffer, previousStart, cursor);
break;
case Type.DOUBLE_ARRAY:
if (currentDoubleArr == null) {
currentDoubleArr = new double[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)];
} else {
currentDoubleArr[currentSubIndex] = Base64.decodeToDoubleWithBounds(buffer, previousStart, cursor);
}
toInsert = currentDoubleArr;
break;
case Type.LONG_ARRAY:
if (currentLongArr == null) {
currentLongArr = new long[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)];
} else {
currentLongArr[currentSubIndex] = Base64.decodeToLongWithBounds(buffer, previousStart, cursor);
}
toInsert = currentLongArr;
break;
case Type.INT_ARRAY:
if (currentIntArr == null) {
currentIntArr = new int[Base64.decodeToIntWithBounds(buffer, previousStart, cursor)];
} else {
currentIntArr[currentSubIndex] = Base64.decodeToIntWithBounds(buffer, previousStart, cursor);
}
toInsert = currentIntArr;
break;
case Type.RELATION:
if (currentRelation != null) {
currentRelation.add(Base64.decodeToIntWithBounds(buffer, previousStart, cursor));
}
toInsert = currentLongArr;
break;
case Type.STRING_TO_LONG_MAP:
if (currentMapStringKey != null) {
currentStringLongMap.put(currentMapStringKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
}
toInsert = currentStringLongMap;
break;
case Type.LONG_TO_LONG_MAP:
if (currentMapLongKey != CoreConstants.NULL_LONG) {
currentLongLongMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
}
toInsert = currentLongLongMap;
break;
case Type.LONG_TO_LONG_ARRAY_MAP:
if (currentMapLongKey != CoreConstants.NULL_LONG) {
currentLongLongArrayMap.put(currentMapLongKey, Base64.decodeToLongWithBounds(buffer, previousStart, cursor));
}
toInsert = currentLongLongArrayMap;
break;
}
if (toInsert != null) {
internal_set(currentChunkElemKey, currentChunkElemType, toInsert, true, initial); //enhance this with boolean array
}
}
}
} |
package org.ayr.main;
/**
* @author Administrator
*
*/
public class Bootstrap {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Hello Git");
}
} |
/*
* $Id: Poll.java,v 1.79 2003-05-22 01:06:08 claire Exp $
*/
package org.lockss.poller;
import java.io.*;
import java.security.*;
import java.util.*;
import gnu.regexp.*;
import org.mortbay.util.B64Code;
import org.lockss.daemon.*;
import org.lockss.hasher.*;
import org.lockss.plugin.*;
import org.lockss.protocol.*;
import org.lockss.util.*;
import org.lockss.state.PollHistory;
import org.lockss.state.NodeManager;
import org.lockss.daemon.status.*;
/**
* <p>Abstract base class for all poll objects.</p>
* @author Claire Griffin
* @version 1.0
*/
public abstract class Poll implements Serializable {
public static final int NAME_POLL = 0;
public static final int CONTENT_POLL = 1;
public static final int VERIFY_POLL = 2;
public static final String[] PollName = {"Name", "Content", "Verify"};
static final String PARAM_AGREE_VERIFY = Configuration.PREFIX +
"poll.agreeVerify";
static final String PARAM_DISAGREE_VERIFY = Configuration.PREFIX +
"poll.disagreeVerify";
static final String PARAM_VOTE_MARGIN = Configuration.PREFIX +
"poll.voteMargin";
static final String PARAM_TRUSTED_WEIGHT = Configuration.PREFIX +
"poll.trustedWeight";
static final int DEFAULT_VOTE_MARGIN = 75;
static final int DEFAULT_TRUSTED_WEIGHT = 350;
static final int DEFAULT_AGREE_VERIFY = 10;
static final int DEFAULT_DISAGREE_VERIFY = 80;
static final String[] ERROR_STRINGS = {"Poll Complete","Hasher Busy",
"Hashing Error", "IO Error"
};
public static final int ERR_SCHEDULE_HASH = -1;
public static final int ERR_HASHING = -2;
public static final int ERR_IO = -3;
static final int PS_INITING = 0;
static final int PS_WAIT_HASH = 1;
static final int PS_WAIT_VOTE = 2;
static final int PS_WAIT_TALLY = 3;
static final int PS_COMPLETE = 4;
static Logger log=Logger.getLogger("Poll");
LcapMessage m_msg; // The message which triggered the poll
double m_agreeVer = 0; // the max percentage of time we will verify
double m_disagreeVer = 0; // the max percentage of time we will verify
double m_margin = 0; // the margin by which we must win or lose
double m_trustedWeight = 0;// the min ave. weight of the winners, when we lose.
CachedUrlSet m_cus; // the cached url set retrieved from the archival unit
PollSpec m_pollspec;
byte[] m_challenge; // The caller's challenge string
byte[] m_verifier; // Our verifier string - hash of secret
byte[] m_hash; // Our hash of challenge, verifier and content(S)
Deadline m_voteTime; // when to vote
Deadline m_deadline; // when election is over
Deadline m_hashDeadline; // when our hashes must finish by
LcapIdentity m_caller; // who called the poll
int m_replyOpcode = -1; // opcode used to reply to poll
long m_hashTime; // an estimate of the time it will take to hash
long m_createTime; // poll creation time
String m_key; // the string we used to id this poll
int m_pollstate; // one of state constants above
int m_pendingVotes = 0; // the number of votes waiting to be tallied
PollTally m_tally; // the vote tallier
PollManager m_pollmanager; // the pollmanager which should be used by this poll.
IdentityManager idMgr;
/**
* create a new poll from a message
*
* @param msg the <code>Message</code> which contains the information
* @param pollspec the PollSpec on which this poll will operate
* needed to create this poll.
* @param pm the pollmanager
*/
Poll(LcapMessage msg, PollSpec pollspec, PollManager pm) {
m_pollmanager = pm;
idMgr = pm.getIdentityManager();
m_msg = msg;
m_pollspec = pollspec;
m_cus = pollspec.getCachedUrlSet();
// now copy the msg elements we need
m_hashTime = m_cus.estimatedHashDuration();
m_deadline = Deadline.in(msg.getDuration());
if(!msg.isVerifyPoll()) {
m_hashDeadline =
Deadline.at(m_deadline.getExpirationTime() - Constants.MINUTE);
}
m_caller = idMgr.findIdentity(msg.getOriginAddr());
m_challenge = msg.getChallenge();
m_key = msg.getKey();
m_verifier = m_pollmanager.makeVerifier(msg.getDuration());
log.debug("I think poll "+m_challenge
+" will take me this long to hash "+m_hashTime);
m_createTime = TimeBase.nowMs();
// make a new vote tally
m_tally = new PollTally(this, -1, m_createTime, msg.getDuration(),
pm.getQuorum(), msg.getHashAlgorithm());
m_pollstate = PS_INITING;
getConfigValues();
}
/**
* create a human readable string representation of this poll
* @return a String
*/
public String toString() {
StringBuffer sb = new StringBuffer("[Poll: ");
sb.append("url set:");
sb.append(" ");
sb.append(m_cus.toString());
sb.append(" ");
sb.append(m_msg.getOpcodeString());
sb.append(" key:");
sb.append(m_key);
sb.append("]");
return sb.toString();
}
/**
* Returns true if the poll belongs to this Identity
* @return true if we called the poll
*/
public boolean isMyPoll() {
return idMgr.isLocalIdentity(m_caller);
}
void getConfigValues() {
/* initialize with our parameters */
m_agreeVer = ((double)Configuration.getIntParam(PARAM_AGREE_VERIFY,
DEFAULT_AGREE_VERIFY)) / 100;
m_disagreeVer = ((double)Configuration.getIntParam(PARAM_DISAGREE_VERIFY,
DEFAULT_DISAGREE_VERIFY)) / 100;
m_trustedWeight = ((double)Configuration.getIntParam(PARAM_TRUSTED_WEIGHT,
DEFAULT_TRUSTED_WEIGHT));
m_margin = ((double)Configuration.getIntParam(PARAM_VOTE_MARGIN,
DEFAULT_VOTE_MARGIN)) / 100;
}
abstract void receiveMessage(LcapMessage msg);
/**
* schedule the hash for this poll.
* @param hasher the MessageDigest used to hash the content
* @param timer the Deadline by which we must complete
* @param key the Object which will be returned from the hasher. Always the
* message which triggered the hash
* @param callback the hashing callback to use on return
* @return true if hash successfully completed.
*/
abstract boolean scheduleHash(MessageDigest hasher, Deadline timer,
Serializable key,
HashService.Callback callback);
/**
* schedule a vote by a poll. we've already completed the hash so we're
* only interested in how long we have remaining.
*/
void scheduleVote() {
if(m_voteTime.expired()) {
voteInPoll();
}
else {
log.debug("Waiting until " + m_voteTime.toString() + " to vote");
TimerQueue.schedule(m_voteTime, new VoteTimerCallback(), this);
}
}
/**
* check the hash result obtained by the hasher with one stored in the
* originating message.
* @param hashResult byte array containing the result of the hasher
* @param vote the Vote to check.
*/
void checkVote(byte[] hashResult, Vote vote) {
boolean verify = false;
byte[] hashed = vote.getHash();
log.debug3("Checking "+
String.valueOf(B64Code.encode(hashResult))+
" against "+
vote.getHashString());
boolean agree = vote.setAgreeWithHash(hashResult);
LcapIdentity id = idMgr.findIdentity(vote.getIDAddress());
if(!idMgr.isLocalIdentity(vote.getIDAddress())) {
verify = randomVerify(vote, agree);
}
m_tally.addVote(vote, id, idMgr.isLocalIdentity(id));
}
/**
* randomly verify a vote. The random percentage is determined by
* agreement and reputation of the voter.
* @param vote the Vote to check
* @param isAgreeVote true if this vote agreed with ours, false otherwise
* @return true if we called a verify poll, false otherwise.
*/
boolean randomVerify(Vote vote, boolean isAgreeVote) {
LcapIdentity id = idMgr.findIdentity(vote.getIDAddress());
int max = idMgr.getMaxReputaion();
int weight = id.getReputation();
double verify;
boolean callVerifyPoll = false;
if(isAgreeVote) {
verify = ((double)(max - weight)) / max * m_agreeVer;
}
else {
verify = (((double)weight) / (2*max)) * m_disagreeVer;
}
log.debug2("probablitiy of verifying this vote = " + verify);
try {
if(ProbabilisticChoice.choose(verify)) {
long remainingTime = m_deadline.getRemainingTime();
long now = TimeBase.nowMs();
long minTime = now + (remainingTime/2) - (remainingTime/4);
long maxTime = now + (remainingTime/2) + (remainingTime/4);
long duration = Deadline.atRandomRange(minTime, maxTime).getRemainingTime();
m_pollmanager.requestVerifyPoll(m_pollspec, duration, vote);
callVerifyPoll = true;
}
}
catch (IOException ex) {
log.debug("attempt to request verify poll failed ", ex);
}
return callVerifyPoll;
}
/**
* cast our vote for this poll
*/
void castOurVote() {
LcapMessage msg;
LcapIdentity local_id = idMgr.getLocalIdentity();
long remainingTime = m_deadline.getRemainingTime();
try {
msg = LcapMessage.makeReplyMsg(m_msg, m_hash, m_verifier, null,
m_replyOpcode, remainingTime, local_id);
log.debug("vote:" + msg.toString());
m_pollmanager.sendMessage(msg, m_cus.getArchivalUnit());
}
catch(IOException ex) {
log.info("unable to cast our vote.", ex);
}
}
/**
* start the poll.
*/
void startPoll() {
if (m_pollstate != PS_INITING)
return;
log.debug3("scheduling poll to complete by " + m_deadline);
TimerQueue.schedule(m_deadline, new PollTimerCallback(), this);
m_pollstate = PS_WAIT_HASH;
if (!scheduleOurHash()) {
m_pollstate = ERR_SCHEDULE_HASH;
log.debug("couldn't schedule our hash:" + m_voteTime + ", stopping poll.");
stopPoll();
return;
}
}
/**
* attempt to schedule our hash. This will try 3 times to get a deadline
* that will is successfully scheduled
* @return boolean true if we sucessfully schedule hash; false otherwise.
*/
boolean scheduleOurHash() {
MessageDigest hasher = getInitedHasher(m_challenge, m_verifier);
boolean scheduled = false;
long now = TimeBase.nowMs();
long remainingTime = m_deadline.getRemainingTime();
long minTime = now + (remainingTime / 2) - (remainingTime / 4);
long maxTime = now + (remainingTime / 2) + (remainingTime / 4);
long lastHashTime = now + (m_hashTime * (m_tally.quorum + 1));
for (int i = 0; !scheduled && i < 2; i++) {
m_voteTime = Deadline.atRandomRange(minTime, maxTime);
long curTime = m_voteTime.getExpirationTime();
log.debug3("Trying to schedule our hash at " + m_voteTime);
scheduled = scheduleHash(hasher, m_voteTime, m_msg, new PollHashCallback());
if (!scheduled) {
if (curTime < lastHashTime) {
maxTime += curTime - minTime;
minTime = curTime;
}
else {
log.debug("Unable to schedule our hash before " + lastHashTime);
break;
}
}
}
return scheduled;
}
/**
* cast our vote in the current poll
*/
void voteInPoll() {
//we don't vote if we're winning by a landslide
if(!m_tally.isLeadEnough()) {
castOurVote();
}
m_pollstate = PS_WAIT_TALLY;
}
/**
* is our poll currently in an error condition
* @return true if the poll state is an error value
*/
boolean isErrorState() {
return m_pollstate < 0;
}
/**
* finish the poll once the deadline has expired. we update our poll record
* and prevent any more activity in this poll.
*/
void stopPoll() {
if(isErrorState()) {
log.debug("poll stopped with error: " + ERROR_STRINGS[ -m_pollstate]);
}
else {
m_pollstate = Poll.PS_COMPLETE;
}
m_pollmanager.closeThePoll(m_key);
log.debug3("closed the poll:" + m_key);
}
/**
* prepare to check a vote in a poll. This should check any conditions that
* might make running a vote check unneccessary.
* @param msg the message which is triggering the poll
* @return boolean true if the poll should run, false otherwise
*/
boolean shouldCheckVote(LcapMessage msg) {
LcapIdentity voter = idMgr.findIdentity(msg.getOriginAddr());
// make sure we haven't already voted
if(m_tally.hasVoted(voter)) {
log.warning("Ignoring multiple vote from " + voter);
int oldRep = voter.getReputation();
idMgr.changeReputation(voter, IdentityManager.REPLAY_DETECTED);
int newRep = voter.getReputation();
m_tally.adjustReputation(voter,newRep-oldRep);
return false;
}
// make sure our vote will actually matter
if(m_tally.isLeadEnough()) {
log.info(m_key + " lead is enough");
return false;
}
// are we too busy
if(tooManyPending()) {
log.info(m_key + " too busy to count " + m_pendingVotes + " votes");
return false;
}
return true;
}
/**
* start the hash required for a vote cast in this poll
*/
void startVoteCheck() {
m_pendingVotes++;
log.debug3("Number pending votes = " + m_pendingVotes);
}
/**
* stop and record a vote cast in this poll
*/
void stopVoteCheck() {
m_pendingVotes
log.debug3("Number pending votes = " + m_pendingVotes);
}
/**
* are there too many votes waiting to be tallied
* @return true if we have a quorum worth of votes already pending
*/
boolean tooManyPending() {
return m_pendingVotes > m_tally.quorum + 1;
}
Vote copyVote(Vote vote, boolean agree) {
Vote v = new Vote(vote);
v.agree = agree;
return v;
}
/**
* Return the poll spec used by this poll
* @return the PollSpec
*/
public PollSpec getPollSpec() {
return m_pollspec;
}
/**
* get the message used to define this Poll
* @return <code>Message</code>
*/
public LcapMessage getMessage() {
return m_msg;
}
/**
* get the VoteTally for this Poll
* @return VoteTally for this poll
*/
public PollTally getVoteTally() {
return m_tally;
}
public String getKey() {
return m_key;
}
public String getErrorString() {
if(isErrorState()) {
return m_tally.getErrString();
}
return "No Error";
}
double getMargin() {
return m_margin;
}
/**
* Return a hasher preinited with the challenge and verifier
* @param challenge the challenge bytes
* @param verifier the verifier bytes
* @return a MessageDigest
*/
MessageDigest getInitedHasher(byte[] challenge, byte[] verifier) {
MessageDigest hasher = m_pollmanager.getHasher(m_msg);
hasher.update(challenge, 0, challenge.length);
hasher.update(verifier, 0, verifier.length);
log.debug3("hashing: C[" +String.valueOf(B64Code.encode(challenge)) + "] "
+"V[" + String.valueOf(B64Code.encode(verifier)) + "]");
return hasher;
}
class PollHashCallback implements HashService.Callback {
/**
* Called to indicate that hashing the content or names of a
* <code>CachedUrlSet</code> object has succeeded, if <code>e</code>
* is null, or has failed otherwise.
* @param urlset the <code>CachedUrlSet</code> being hashed.
* @param cookie used to disambiguate callbacks.
* @param hasher the <code>MessageDigest</code> object that
* contains the hash.
* @param e the exception that caused the hash to fail.
*/
public void hashingFinished(CachedUrlSet urlset,
Object cookie,
MessageDigest hasher,
Exception e) {
if(m_pollstate != PS_WAIT_HASH) {
log.debug("hasher returned with pollstate: " + m_pollstate);
return;
}
boolean hash_completed = e == null ? true : false;
if(hash_completed) {
m_hash = hasher.digest();
log.debug2("Hash on " + urlset + " complete: "+
String.valueOf(B64Code.encode(m_hash)));
m_pollstate = PS_WAIT_VOTE;
scheduleVote();
}
else {
log.debug("Hash failed : " + e.getMessage());
m_pollstate = ERR_HASHING;
}
}
}
class VoteHashCallback implements HashService.Callback {
/**
* Called to indicate that hashing the content or names of a
* <code>CachedUrlSet</code> object has succeeded, if <code>e</code>
* is null, or has failed otherwise.
* @param urlset the <code>CachedUrlSet</code> being hashed.
* @param cookie used to disambiguate callbacks.
* @param hasher the <code>MessageDigest</code> object that
* contains the hash.
* @param e the exception that caused the hash to fail.
*/
public void hashingFinished(CachedUrlSet urlset,
Object cookie,
MessageDigest hasher,
Exception e) {
boolean hash_completed = e == null ? true : false;
if(hash_completed) {
byte[] out_hash = hasher.digest();
Vote vote = (Vote)cookie;
checkVote(out_hash, vote);
stopVoteCheck();
}
else {
log.info("vote hash failed with exception:" + e.getMessage());
}
}
}
class VoteTimerCallback implements TimerQueue.Callback {
/**
* Called when the timer expires.
* @param cookie data supplied by caller to schedule()
*/
public void timerExpired(Object cookie) {
log.debug3("VoteTimerCallback called, checking if I should vote");
if(m_pollstate == PS_WAIT_VOTE) {
log.debug3("I should vote");
voteInPoll();
log.debug("I just voted");
}
}
}
class PollTimerCallback implements TimerQueue.Callback {
/**
* Called when the timer expires.
* @param cookie data supplied by caller to schedule()
*/
public void timerExpired(Object cookie) {
if(m_pollstate != PS_COMPLETE) {
stopPoll();
}
}
}
} |
package vrampal.connectfour.core.data;
import java.io.Serializable;
import java.util.List;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import vrampal.connectfour.core.Board;
import vrampal.connectfour.core.Game;
import vrampal.connectfour.core.GameStatus;
import vrampal.connectfour.core.Player;
/**
* Pure data class for serialization.
*/
@NoArgsConstructor
@EqualsAndHashCode
@ToString(of = { "id" })
public class GameData implements Serializable {
private static final long serialVersionUID = 2649138486471544477L;
@Getter
@Setter
private String id;
@Getter
@Setter
private int nbPlayers;
@Getter
@Setter
private PlayerData[] players;
@Getter
@Setter
private int width;
@Getter
@Setter
private int height;
@Getter
@Setter
private char[] board;
@Getter
@Setter
private GameStatus status;
@Getter
@Setter
private int turnNumber;
@Getter
@Setter
private String winner;
public GameData(Game in) {
id = in.getId();
List<Player> inPlayers = in.getAllPlayers();
nbPlayers = inPlayers.size();
players = new PlayerData[nbPlayers];
inPlayers.toArray(players);
Board inBoard = in.getBoard();
width = inBoard.getWidth();
height = inBoard.getHeight();
board = new char[width * height];
for (int colIdx = 0; colIdx < width; colIdx++) {
for (int rowIdx = 0; rowIdx < height; rowIdx++) {
Player curCell = inBoard.getCell(colIdx, rowIdx);
board[(colIdx * height) + rowIdx] = curCell.getLetter();
}
}
status = in.getStatus();
turnNumber = in.getTurnNumber();
Player inWinner = in.getWinner();
if (inWinner == null) {
winner = null;
} else {
winner = inWinner.toString();
}
}
} |
package nl.mpi.kinnate.ui;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashSet;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import nl.mpi.arbil.data.ArbilDataNodeLoader;
import nl.mpi.arbil.userstorage.ArbilSessionStorage;
import nl.mpi.arbil.util.XsdChecker;
import nl.mpi.kinnate.entityindexer.EntityCollection;
import nl.mpi.kinnate.gedcomimport.CsvImporter;
import nl.mpi.kinnate.gedcomimport.GedcomImporter;
import nl.mpi.kinnate.gedcomimport.GenericImporter;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
public class GedcomImportPanel extends JPanel {
private EntityCollection entityCollection;
private JTabbedPane jTabbedPane1;
private JTextArea importTextArea;
private JProgressBar progressBar;
private JCheckBox overwriteOnImport;
private JCheckBox validateImportedXml;
private JButton startButton;
private JPanel endPagePanel;
public GedcomImportPanel(JTabbedPane jTabbedPaneLocal) {
jTabbedPane1 = jTabbedPaneLocal;
entityCollection = new EntityCollection();
// private ImdiTree leftTree;
//// private GraphPanel graphPanel;
//// private JungGraph jungGraph;
// private ImdiTable previewTable;
// private ImdiTableModel imdiTableModel;
// private DragTransferHandler dragTransferHandler;
}
protected JPanel getCreatedNodesPane(final GenericImporter gedcomImporter) {
JPanel createdNodesPanel = new JPanel();
createdNodesPanel.setLayout(new BoxLayout(createdNodesPanel, BoxLayout.PAGE_AXIS));
if (gedcomImporter.getCreatedNodeIds().isEmpty()) {
createdNodesPanel.add(new JLabel("No data was imported, nothing to show in the graph."));
} else {
final ArrayList<JCheckBox> checkBoxArray = new ArrayList<JCheckBox>();
for (String typeString : gedcomImporter.getCreatedNodeIds().keySet()) {
JCheckBox currentCheckBox = new JCheckBox(typeString + " ( x " + gedcomImporter.getCreatedNodeIds().get(typeString).size() + ")");
currentCheckBox.setActionCommand(typeString);
checkBoxArray.add(currentCheckBox);
createdNodesPanel.add(currentCheckBox);
}
JButton showButton = new JButton("Show selected types in graph");
showButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final KinDiagramPanel egoSelectionTestPanel = new KinDiagramPanel(null);
// egoSelectionTestPanel.setDisplayNodes("X", selectedIds.toArray(new String[]{}));
jTabbedPane1.add("Imported Entities", egoSelectionTestPanel);
jTabbedPane1.setSelectedComponent(egoSelectionTestPanel);
new Thread() {
@Override
public void run() {
final HashSet<UniqueIdentifier> selectedIds = new HashSet<UniqueIdentifier>();
for (final JCheckBox currentCheckBox : checkBoxArray) {
if (currentCheckBox.isSelected()) {
selectedIds.addAll((gedcomImporter.getCreatedNodeIds().get(currentCheckBox.getActionCommand())));
}
}
egoSelectionTestPanel.addRequiredNodes(selectedIds.toArray(new UniqueIdentifier[]{}));
}
}.start();
}
});
createdNodesPanel.add(showButton);
}
return createdNodesPanel;
}
public void startImport(String importUriString) {
File cachedFile = ArbilSessionStorage.getSingleInstance().updateCache(importUriString, 30);
startImport(cachedFile, null, importUriString);
}
public void startImportJar(String importFileString) {
startImport(null, importFileString, importFileString);
}
private void startImport(final File importFile, final String importFileString, String importLabel) {
if (importFile != null && !importFile.exists()) {
GedcomImportPanel.this.add(new JLabel("File not found"));
} else {
importTextArea = new JTextArea();
JScrollPane importScrollPane = new JScrollPane(importTextArea);
GedcomImportPanel.this.setLayout(new BorderLayout());
GedcomImportPanel.this.add(importScrollPane, BorderLayout.CENTER);
jTabbedPane1.add("Import", GedcomImportPanel.this);
jTabbedPane1.setSelectedComponent(GedcomImportPanel.this);
progressBar = new JProgressBar(0, 100);
endPagePanel = new JPanel(new BorderLayout());
endPagePanel.add(progressBar, BorderLayout.PAGE_START);
GedcomImportPanel.this.add(endPagePanel, BorderLayout.PAGE_END);
progressBar.setVisible(true);
JPanel topPanel = new JPanel();
overwriteOnImport = new JCheckBox("Overwrite Existing");
startButton = new JButton("Start");
topPanel.add(overwriteOnImport);
validateImportedXml = new JCheckBox("Validate Xml");
topPanel.add(validateImportedXml);
topPanel.add(startButton);
JPanel topOuterPanel = new JPanel(new BorderLayout());
topOuterPanel.add(new JLabel(importLabel, JLabel.CENTER), BorderLayout.PAGE_START);
topOuterPanel.add(topPanel, BorderLayout.CENTER);
GedcomImportPanel.this.add(topOuterPanel, BorderLayout.PAGE_START);
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startButton.setEnabled(false);
overwriteOnImport.setEnabled(false);
validateImportedXml.setEnabled(false);
new Thread() {
@Override
public void run() {
boolean overwriteExisting = overwriteOnImport.isSelected();
GenericImporter genericImporter = new GedcomImporter(progressBar, importTextArea, overwriteExisting);
if (importFileString != null) {
if (!genericImporter.canImport(importFileString)) {
genericImporter = new CsvImporter(progressBar, importTextArea, overwriteExisting);
}
} else {
if (!genericImporter.canImport(importFile.toString())) {
genericImporter = new CsvImporter(progressBar, importTextArea, overwriteExisting);
}
}
URI[] treeNodesArray;
importTextArea.append("Importing the kinship data (step 1/4)\n");
if (importFileString != null) {
treeNodesArray = genericImporter.importFile(importFileString);
} else {
treeNodesArray = genericImporter.importFile(importFile);
}
boolean checkFilesAfterImport = validateImportedXml.isSelected();
if (treeNodesArray != null && checkFilesAfterImport) {
// ArrayList<ImdiTreeObject> tempArray = new ArrayList<ImdiTreeObject>();
int maxXsdErrorToShow = 3;
importTextArea.append("Checking XML of imported data (step 3/4)\n");
progressBar.setValue(0);
progressBar.setMaximum(treeNodesArray.length + 1);
for (URI currentNodeUri : treeNodesArray) {
progressBar.setValue(progressBar.getValue() + 1);
if (maxXsdErrorToShow > 0) {
// try {
// ImdiTreeObject currentImdiObject = ImdiLoader.getSingleInstance().getImdiObject(null, new URI(currentNodeString));
// tempArray.add(currentImdiObject);
// JTextPane fileText = new JTextPane();
XsdChecker xsdChecker = new XsdChecker();
if (xsdChecker.simpleCheck(new File(currentNodeUri), currentNodeUri) != null) {
jTabbedPane1.add("XSD Error on Import", xsdChecker);
xsdChecker.checkXML(ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, currentNodeUri));
xsdChecker.setDividerLocation(0.5);
maxXsdErrorToShow
if (maxXsdErrorToShow <= 0) {
importTextArea.append("maximum xsd errors shown, no more files will be tested" + "\n");
}
}
// currentImdiObject.reloadNode();
// try {
// fileText.setPage(currentNodeString);
// } catch (IOException iOException) {
// fileText.setText(iOException.getMessage());
// jTabbedPane1.add("ImportedFile", fileText);
// } catch (URISyntaxException exception) {
// GuiHelper.linorgBugCatcher.logError(exception);
// todo: possibly create a new diagram with a sample of the imported entities for the user
}
}
// leftTree.rootNodeChildren = tempArray.toArray(new ImdiTreeObject[]{});
// imdiTableModel.removeAllImdiRows();
// imdiTableModel.addImdiObjects(leftTree.rootNodeChildren);
} else {
importTextArea.append("Skipping check XML of imported data (step 3/4)\n");
}
progressBar.setIndeterminate(true);
// todo: it might be more efficient to only update the new files
importTextArea.append("Starting update of entity database (step 4/4)\n");
entityCollection.updateDatabase(treeNodesArray, progressBar);
importTextArea.append("Import complete" + "\n");
importTextArea.setCaretPosition(importTextArea.getText().length());
// System.out.println("added the imported files to the database");
progressBar.setIndeterminate(false);
progressBar.setVisible(false);
// leftTree.requestResort();
// GraphData graphData = new GraphData();
// graphData.readData();
// graphPanel.drawNodes(graphData);
GedcomImportPanel.this.endPagePanel.add(GedcomImportPanel.this.getCreatedNodesPane(genericImporter), BorderLayout.CENTER);
GedcomImportPanel.this.revalidate();
}
}.start();
}
});
}
}
} |
package com.rafkind.paintown.animator.events;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import com.rafkind.paintown.animator.Animation;
import com.rafkind.paintown.Token;
import com.rafkind.paintown.animator.events.AnimationEvent;
import org.swixml.SwingEngine;
public class BBoxEvent implements AnimationEvent {
private class Box{
public Box(int x1, int y1, int x2, int y2){
this.x1 = x1;
this.x2 = x2;
this.y1 = y1;
this.y2 = y2;
}
public Box(){
this(0,0,0,0);
}
public int x1;
public int y1;
public int x2;
public int y2;
}
private Box box = new Box();
public void loadToken(Token token){
box.x1 = token.readInt(0);
box.y1 = token.readInt(1);
box.x2 = token.readInt(2);
box.y2 = token.readInt(3);
}
public void interact(Animation animation){
//area.setAttack(new BoundingBox(_x1,_y1,_x2,_y2));
}
public String getName(){
return getToken().toString();
}
public JPanel getEditor( Animation animation ){
SwingEngine engine = new SwingEngine( "animator/eventbbox.xml" );
((JPanel)engine.getRootComponent()).setSize(200,150);
final JSpinner x1spin = (JSpinner) engine.find( "x1" );
x1spin.setValue(new Integer(box.x1));
x1spin.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
box.x1 = ((Integer)x1spin.getValue()).intValue();
}
});
final JSpinner y1spin = (JSpinner) engine.find( "y1" );
y1spin.setValue(new Integer(box.y1));
y1spin.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
box.y1 = ((Integer)y1spin.getValue()).intValue();
}
});
final JSpinner x2spin = (JSpinner) engine.find( "x2" );
x2spin.setValue(new Integer(box.x2));
x2spin.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
box.x2 = ((Integer)x2spin.getValue()).intValue();
}
});
final JSpinner y2spin = (JSpinner) engine.find( "y2" );
y2spin.setValue(new Integer(box.y2));
y2spin.addChangeListener( new ChangeListener()
{
public void stateChanged(ChangeEvent changeEvent)
{
box.y2 = ((Integer)y2spin.getValue()).intValue();
}
});
return (JPanel)engine.getRootComponent();
}
public Token getToken(){
Token temp = new Token("bbox");
temp.addToken(new Token("bbox"));
temp.addToken(new Token(Integer.toString(box.x1)));
temp.addToken(new Token(Integer.toString(box.y1)));
temp.addToken(new Token(Integer.toString(box.x2)));
temp.addToken(new Token(Integer.toString(box.y2)));
return temp;
}
} |
package com.datatorrent.stram.webapp;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import org.apache.hadoop.yarn.util.Times;
import com.datatorrent.stram.StramAppContext;
import com.datatorrent.stram.util.VersionInfo;
/**
*
* Provides application level data like user, appId, elapsed time, etc.<p>
* <br>Current data includes<br>
* <b>Application Id</b><br>
* <b>Application Name</b><br>
* <b>User Name</b><br>
* <b>Start Time</b><br>
* <b>Elapsed Time</b><br>
* <b>Application Path</b><br>
* <br>
*
* @since 0.3.2
*/
@XmlRootElement(name = StramWebServices.PATH_INFO)
@XmlAccessorType(XmlAccessType.FIELD)
public class AppInfo {
protected String appId;
protected String name;
protected String user;
protected long startTime;
protected long elapsedTime;
protected String appPath;
protected String gatewayAddress;
public String appMasterTrackingUrl;
public String version;
public AppStats stats;
/**
* Default constructor for serialization
*/
public AppInfo() {
}
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public static class AppStats {
@javax.xml.bind.annotation.XmlElement
public int getAllocatedContainers() {
return 0;
}
@javax.xml.bind.annotation.XmlElement
public int getPlannedContainers() {
return 0;
}
@javax.xml.bind.annotation.XmlElement
public int getFailedContainers() {
return 0;
}
@javax.xml.bind.annotation.XmlElement
public int getNumOperators() {
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getLatency() {
return 0;
}
@javax.xml.bind.annotation.XmlElement
public List<Integer> getCriticalPath() {
return null;
}
@javax.xml.bind.annotation.XmlElement
public long getCurrentWindowId()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getRecoveryWindowId()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getTuplesProcessedPSMA()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getTotalTuplesProcessed()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getTuplesEmittedPSMA()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getTotalTuplesEmitted()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getTotalMemoryAllocated()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getTotalBufferServerReadBytesPSMA()
{
return 0;
}
@javax.xml.bind.annotation.XmlElement
public long getTotalBufferServerWriteBytesPSMA()
{
return 0;
}
}
/**
*
* @param context
*/
public AppInfo(StramAppContext context) {
this.appId = context.getApplicationID().toString();
this.name = context.getApplicationName();
this.user = context.getUser().toString();
this.startTime = context.getStartTime();
this.elapsedTime = Times.elapsed(this.startTime, 0);
this.appPath = context.getApplicationPath();
this.appMasterTrackingUrl = context.getAppMasterTrackingUrl();
this.stats = context.getStats();
this.gatewayAddress = context.getGatewayAddress();
this.version = VersionInfo.getBuildVersion();
}
/**
*
* @return String
*/
public String getId() {
return this.appId;
}
/**
*
* @return String
*/
public String getName() {
return this.name;
}
/**
*
* @return String
*/
public String getUser() {
return this.user;
}
/**
*
* @return long
*/
public long getStartTime() {
return this.startTime;
}
/**
*
* @return long
*/
public long getElapsedTime() {
return this.elapsedTime;
}
public String getAppPath() {
return this.appPath;
}
public String getGatewayAddress() {
return this.gatewayAddress;
}
} |
package org.mockito;
import org.mockito.stubbing.Answer;
import org.mockito.stubbing.OngoingStubbing;
import org.mockito.stubbing.Stubber;
import org.mockito.verification.VerificationMode;
@SuppressWarnings("unchecked")
public class BDDMockito extends Mockito {
/**
* See original {@link OngoingStubbing}
* @since 1.8.0
*/
public interface BDDMyOngoingStubbing<T> {
/**
* See original {@link OngoingStubbing#thenAnswer(Answer)}
* @since 1.8.0
*/
BDDMyOngoingStubbing<T> willAnswer(Answer<?> answer);
/**
* See original {@link OngoingStubbing#then(Answer)}
* @since 1.9.0
*/
BDDMyOngoingStubbing<T> will(Answer<?> answer);
/**
* See original {@link OngoingStubbing#thenReturn(Object)}
* @since 1.8.0
*/
BDDMyOngoingStubbing<T> willReturn(T value);
/**
* See original {@link OngoingStubbing#thenReturn(Object, Object[])}
* @since 1.8.0
*/
BDDMyOngoingStubbing<T> willReturn(T value, T... values);
/**
* See original {@link OngoingStubbing#thenThrow(Throwable...)}
* @since 1.8.0
*/
BDDMyOngoingStubbing<T> willThrow(Throwable... throwables);
/**
* See original {@link OngoingStubbing#thenThrow(Class[])}
* @since 1.9.0
*/
BDDMyOngoingStubbing<T> willThrow(Class<? extends Throwable>... throwableClasses);
/**
* See original {@link OngoingStubbing#thenCallRealMethod()}
* @since 1.9.0
*/
BDDMyOngoingStubbing<T> willCallRealMethod();
/**
* See original {@link OngoingStubbing#getMock()}
* @since 1.9.0
*/
<M> M getMock();
}
/**
* @deprecated not part of the public API, use {@link BDDMyOngoingStubbing} instead.
*/
@Deprecated
public static class BDDOngoingStubbingImpl<T> implements BDDMyOngoingStubbing<T> {
private final OngoingStubbing<T> mockitoOngoingStubbing;
public BDDOngoingStubbingImpl(OngoingStubbing<T> ongoingStubbing) {
this.mockitoOngoingStubbing = ongoingStubbing;
}
/* (non-Javadoc)
* @see BDDMockito.BDDMyOngoingStubbing#willAnswer(Answer)
*/
public BDDMyOngoingStubbing<T> willAnswer(Answer<?> answer) {
return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenAnswer(answer));
}
/* (non-Javadoc)
* @see BDDMockito.BDDMyOngoingStubbing#will(Answer)
*/
public BDDMyOngoingStubbing<T> will(Answer<?> answer) {
return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.then(answer));
}
/* (non-Javadoc)
* @see BDDMockito.BDDMyOngoingStubbing#willReturn(java.lang.Object)
*/
public BDDMyOngoingStubbing<T> willReturn(T value) {
return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenReturn(value));
}
/* (non-Javadoc)
* @see BDDMockito.BDDMyOngoingStubbing#willReturn(java.lang.Object, T[])
*/
public BDDMyOngoingStubbing<T> willReturn(T value, T... values) {
return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenReturn(value, values));
}
/* (non-Javadoc)
* @see BDDMockito.BDDMyOngoingStubbing#willThrow(java.lang.Throwable[])
*/
public BDDMyOngoingStubbing<T> willThrow(Throwable... throwables) {
return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenThrow(throwables));
}
/* (non-Javadoc)
* @see BDDMockito.BDDMyOngoingStubbing#willThrow(java.lang.Class[])
*/
public BDDMyOngoingStubbing<T> willThrow(Class<? extends Throwable>... throwableClasses) {
return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenThrow(throwableClasses));
}
public BDDMyOngoingStubbing<T> willCallRealMethod() {
return new BDDOngoingStubbingImpl<T>(mockitoOngoingStubbing.thenCallRealMethod());
}
public <M> M getMock() {
return (M) mockitoOngoingStubbing.getMock();
}
}
/**
* see original {@link Mockito#when(Object)}
* @since 1.8.0
*/
public static <T> BDDMyOngoingStubbing<T> given(T methodCall) {
return new BDDOngoingStubbingImpl<T>(Mockito.when(methodCall));
}
/**
* Bdd style verification of mock behavior.
*
* @see #verify(Object)
* @see #verify(Object, VerificationMode)
* @since 1.10.0
*/
public static <T> Then<T> then(T mock) {
return new ThenImpl<T>(mock);
}
/**
* Provides fluent way of mock verification.
*
* @param <T> type of the mock
*
* @since 1.10.5
*/
public static interface Then<T> {
/**
* @see #verify(Object)
* @since 1.10.5
*/
T should();
/**
* @see #verify(Object, VerificationMode)
* @since 1.10.5
*/
T should(VerificationMode mode);
}
static class ThenImpl<T> implements Then<T> {
private final T mock;
ThenImpl(T mock) {
this.mock = mock;
}
/**
* @see #verify(Object)
* @since 1.10.5
*/
public T should() {
return verify(mock);
}
/**
* @see #verify(Object, VerificationMode)
* @since 1.10.5
*/
public T should(VerificationMode mode) {
return verify(mock, mode);
}
}
/**
* See original {@link Stubber}
* @since 1.8.0
*/
public interface BDDStubber {
/**
* See original {@link Stubber#doAnswer(Answer)}
* @since 1.8.0
*/
BDDStubber willAnswer(Answer answer);
/**
* See original {@link Stubber#doNothing()}
* @since 1.8.0
*/
BDDStubber willNothing();
/**
* See original {@link Stubber#doReturn(Object)}
* @since 1.8.0
*/
BDDStubber willReturn(Object toBeReturned);
/**
* See original {@link Stubber#doThrow(Throwable)}
* @since 1.8.0
*/
BDDStubber willThrow(Throwable toBeThrown);
/**
* See original {@link Stubber#doThrow(Class)}
* @since 1.9.0
*/
BDDStubber willThrow(Class<? extends Throwable> toBeThrown);
/**
* See original {@link Stubber#doCallRealMethod()}
* @since 1.9.0
*/
BDDStubber willCallRealMethod();
/**
* See original {@link Stubber#when(Object)}
* @since 1.8.0
*/
<T> T given(T mock);
}
/**
* @deprecated not part of the public API, use {@link BDDStubber} instead.
*/
@Deprecated
public static class BDDStubberImpl implements BDDStubber {
private final Stubber mockitoStubber;
public BDDStubberImpl(Stubber mockitoStubber) {
this.mockitoStubber = mockitoStubber;
}
/* (non-Javadoc)
* @see BDDMockito.BDDStubber#given(java.lang.Object)
*/
public <T> T given(T mock) {
return mockitoStubber.when(mock);
}
/* (non-Javadoc)
* @see BDDMockito.BDDStubber#willAnswer(Answer)
*/
public BDDStubber willAnswer(Answer answer) {
return new BDDStubberImpl(mockitoStubber.doAnswer(answer));
}
/* (non-Javadoc)
* @see BDDMockito.BDDStubber#willNothing()
*/
public BDDStubber willNothing() {
return new BDDStubberImpl(mockitoStubber.doNothing());
}
/* (non-Javadoc)
* @see BDDMockito.BDDStubber#willReturn(java.lang.Object)
*/
public BDDStubber willReturn(Object toBeReturned) {
return new BDDStubberImpl(mockitoStubber.doReturn(toBeReturned));
}
/* (non-Javadoc)
* @see BDDMockito.BDDStubber#willThrow(java.lang.Throwable)
*/
public BDDStubber willThrow(Throwable toBeThrown) {
return new BDDStubberImpl(mockitoStubber.doThrow(toBeThrown));
}
/* (non-Javadoc)
* @see BDDMockito.BDDStubber#willThrow(Class)
*/
public BDDStubber willThrow(Class<? extends Throwable> toBeThrown) {
return new BDDStubberImpl(mockitoStubber.doThrow(toBeThrown));
}
/* (non-Javadoc)
* @see BDDMockito.BDDStubber#willCallRealMethod()
*/
public BDDStubber willCallRealMethod() {
return new BDDStubberImpl(mockitoStubber.doCallRealMethod());
}
}
/**
* see original {@link Mockito#doThrow(Throwable)}
* @since 1.8.0
*/
public static BDDStubber willThrow(Throwable toBeThrown) {
return new BDDStubberImpl(Mockito.doThrow(toBeThrown));
}
/**
* see original {@link Mockito#doThrow(Throwable)}
* @since 1.9.0
*/
public static BDDStubber willThrow(Class<? extends Throwable> toBeThrown) {
return new BDDStubberImpl(Mockito.doThrow(toBeThrown));
}
/**
* see original {@link Mockito#doAnswer(Answer)}
* @since 1.8.0
*/
public static BDDStubber willAnswer(Answer answer) {
return new BDDStubberImpl(Mockito.doAnswer(answer));
}
/**
* see original {@link Mockito#doNothing()}
* @since 1.8.0
*/
public static BDDStubber willDoNothing() {
return new BDDStubberImpl(Mockito.doNothing());
}
/**
* see original {@link Mockito#doReturn(Object)}
* @since 1.8.0
*/
public static BDDStubber willReturn(Object toBeReturned) {
return new BDDStubberImpl(Mockito.doReturn(toBeReturned));
}
/**
* see original {@link Mockito#doCallRealMethod()}
* @since 1.8.0
*/
public static BDDStubber willCallRealMethod() {
return new BDDStubberImpl(Mockito.doCallRealMethod());
}
} |
package org.nutz.dao.util;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.sql.DataSource;
import org.nutz.dao.Chain;
import org.nutz.dao.Condition;
import org.nutz.dao.ConnCallback;
import org.nutz.dao.Dao;
import org.nutz.dao.DaoException;
import org.nutz.dao.FieldFilter;
import org.nutz.dao.FieldMatcher;
import org.nutz.dao.Sqls;
import org.nutz.dao.TableName;
import org.nutz.dao.entity.Entity;
import org.nutz.dao.entity.EntityIndex;
import org.nutz.dao.entity.MappingField;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.impl.NutDao;
import org.nutz.dao.impl.sql.SqlFormat;
import org.nutz.dao.jdbc.JdbcExpert;
import org.nutz.dao.jdbc.Jdbcs;
import org.nutz.dao.jdbc.ValueAdaptor;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.dao.util.tables.TablesFilter;
import org.nutz.lang.Lang;
import org.nutz.lang.Mirror;
import org.nutz.lang.Strings;
import org.nutz.lang.random.R;
import org.nutz.lang.util.Callback2;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.resource.Scans;
import org.nutz.trans.Molecule;
import org.nutz.trans.Trans;
/**
* Dao
*
* @author zozoh(zozohtnt@gmail.com)
* @author wendal(wendal1985@gmail.com)
* @author cqyunqin
* @author rekoe(koukou890@qq.com)
* @author threefish(306955302@qq.com)
*/
public abstract class Daos {
private static final Log log = Logs.get();
/**
* StatementResultSet
*
* @param stat
* Statement,null
* @param rs
* ResultSet,null
*/
public static void safeClose(Statement stat, ResultSet rs) {
safeClose(rs);
safeClose(stat);
}
/**
* Statement
*
* @param stat
* Statement,null
*/
public static void safeClose(Statement stat) {
if (null != stat)
try {
stat.close();
}
catch (Throwable e) {}
}
/**
* =ResultSet
*
* @param rs
* ResultSet,null
*/
public static void safeClose(ResultSet rs) {
if (null != rs)
try {
rs.close();
}
catch (Throwable e) {}
}
/**
* colName
*
* @param meta
* ResultSetMetaData
* @param colName
*
* @return ,
* @throws SQLException
* colName
*/
public static int getColumnIndex(ResultSetMetaData meta, String colName) throws SQLException {
if (meta == null)
return 0;
int columnCount = meta.getColumnCount();
for (int i = 1; i <= columnCount; i++)
if (meta.getColumnName(i).equalsIgnoreCase(colName))
return i;
// TODO meta.getColumnLabel?
log.debugf("Can not find @Column(%s) in table/view (%s)", colName, meta.getTableName(1));
throw Lang.makeThrow(SQLException.class, "Can not find @Column(%s)", colName);
}
/**
*
*
* @param meta
* ResultSetMetaData
* @param index
*
* @return true
* @throws SQLException
*
*/
public static boolean isIntLikeColumn(ResultSetMetaData meta, int index) throws SQLException {
switch (meta.getColumnType(index)) {
case Types.BIGINT:
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
case Types.NUMERIC:
return true;
}
return false;
}
/**
*
*
* @param pager
* ,null
* @param dao
* Dao
* @param entityType
* ,dao.getEntity
* @param cnd
*
* @return Pager
*/
public static Pager updatePagerCount(Pager pager, Dao dao, Class<?> entityType, Condition cnd) {
if (null != pager) {
pager.setRecordCount(dao.count(entityType, cnd));
}
return pager;
}
/**
*
*
* @param pager
* ,null
* @param dao
* Dao
* @param tableName
*
* @param cnd
*
* @return Pager
*/
public static Pager updatePagerCount(Pager pager, Dao dao, String tableName, Condition cnd) {
if (null != pager) {
pager.setRecordCount(dao.count(tableName, cnd));
}
return pager;
}
/**
* sql,
*
* @param dao
* Dao
* @param klass
* Pojo
* @param sql_str
* sql
* @return
*/
public static <T> List<T> queryList(Dao dao, Class<T> klass, String sql_str) {
Sql sql = Sqls.create(sql_str)
.setCallback(Sqls.callback.entities())
.setEntity(dao.getEntity(klass));
dao.execute(sql);
return sql.getList(klass);
}
/**
* sqlcallback
*
* @param dao
* Dao
* @param sql_str
* sql
* @param callback
* sql
* @return
*/
public static Object query(Dao dao, String sql_str, SqlCallback callback) {
Sql sql = Sqls.create(sql_str).setCallback(callback);
dao.execute(sql);
return sql.getResult();
}
/**
*
*
* @param dao
* Dao
* @param classOfT
* Pojo
* @param cnd
*
* @param pager
*
* @param regex
* , dao.fetchLinks
* @return
*/
public static <T> List<T> queryWithLinks(final Dao dao,
final Class<T> classOfT,
final Condition cnd,
final Pager pager,
final String regex) {
Molecule<List<T>> molecule = new Molecule<List<T>>() {
public void run() {
List<T> list = dao.query(classOfT, cnd, pager);
dao.fetchLinks(list, regex);
setObj(list);
}
};
return Trans.exec(molecule);
}
public static StringBuilder dataDict(DataSource ds, String... packages) {
return dataDict(new NutDao(ds), packages);
}
/** Pojo,zdoc */
public static StringBuilder dataDict(Dao dao, String... packages) {
StringBuilder sb = new StringBuilder();
List<Class<?>> ks = new ArrayList<Class<?>>();
for (String packageName : packages) {
ks.addAll(Scans.me().scanPackage(packageName));
}
Iterator<Class<?>> it = ks.iterator();
while (it.hasNext()) {
Class<?> klass = it.next();
if (Mirror.me(klass).getAnnotation(Table.class) == null)
it.remove();
}
// log.infof("Found %d table class", ks.size());
JdbcExpert exp = dao.getJdbcExpert();
Entity<?> entity = null;
String line = "
sb.append("#title:\n");
sb.append("
sb.append("#index:0,1\n").append(line);
for (Class<?> klass : ks) {
sb.append(line);
entity = dao.getEntity(klass);
sb.append(" ").append(entity.getTableName()).append("\n\n");
if (!Strings.isBlank(entity.getTableComment()))
sb.append(": ").append(entity.getTableComment());
sb.append("\t").append("Java ").append(klass.getName()).append("\n\n");
sb.append("\t||||||||||||||java||java||||\n");
int index = 1;
for (MappingField field : entity.getMappingFields()) {
String dataType = exp.evalFieldType(field);
sb.append("\t||")
.append(index++)
.append("||")
.append(field.getColumnName())
.append("||")
.append(dataType)
.append("||")
.append(field.isPk())
.append("||")
.append(field.isNotNull())
.append("||")
.append(field.getDefaultValue(null) == null ? " " : field.getDefaultValue(null))
.append("||")
.append(field.getName())
.append("||")
.append(field.getTypeClass().getName())
.append("||")
.append(field.getColumnComment() == null ? " " : field.getColumnComment())
.append("||\n");
}
}
return sb;
}
/**
* sqlclassList
*/
public static <T> List<T> query(Dao dao,
Class<T> classOfT,
String sql,
Condition cnd,
Pager pager) {
Sql sql2 = Sqls.queryEntity(sql);
sql2.setEntity(dao.getEntity(classOfT));
sql2.setCondition(cnd);
sql2.setPager(pager);
dao.execute(sql2);
return sql2.getList(classOfT);
}
/**
* sql. Sql
*/
@Deprecated
public static long queryCount(Dao dao, String sql) {
String tmpTable = "as _nutz_tmp";
if (dao.meta().isDB2())
tmpTable = "as nutz_tmp_" + R.UU32();
else if (dao.meta().isOracle())
tmpTable = "";
else
tmpTable += "_" + R.UU32();
Sql sql2 = Sqls.fetchLong("select count(1) from (" + sql + ")" + tmpTable);
dao.execute(sql2);
return sql2.getLong();
}
/**
* sql
* @param dao countdao
* @param sql Sql,sql,.
*/
public static long queryCount(Dao dao, Sql sql) {
String tmpTable = "as _nutz_tmp";
if (dao.meta().isDB2())
tmpTable = "as nutz_tmp_" + R.UU32();
else if (dao.meta().isOracle())
tmpTable = "";
else
tmpTable += "_" + R.UU32();
Sql sql2 = Sqls.fetchLong("select count(1) from (" + sql.getSourceSql() + ")" + tmpTable);
sql2.setEntity(sql.getEntity());
for (String key : sql.params().keys()) {
sql2.setParam(key, sql.params().get(key));
}
for (String key : sql.vars().keys()) {
sql2.setVar(key, sql.vars().get(key));
}
return dao.execute(sql2).getLong();
}
/**
* Chain(Chain,)
*
* @see org.nutz.dao.Chain#addSpecial(String, Object)
*/
@SuppressWarnings({"rawtypes"})
public static void insertBySpecialChain(Dao dao, Entity en, String tableName, Chain chain) {
if (en != null)
tableName = en.getTableName();
if (tableName == null)
throw Lang.makeThrow(DaoException.class, "tableName and en is NULL !!");
final StringBuilder sql = new StringBuilder("INSERT INTO ").append(tableName).append(" (");
StringBuilder _value_places = new StringBuilder(" VALUES(");
final List<Object> values = new ArrayList<Object>();
final List<ValueAdaptor> adaptors = new ArrayList<ValueAdaptor>();
Chain head = chain.head();
while (head != null) {
String colName = head.name();
MappingField mf = null;
if (en != null) {
mf = en.getField(colName);
if (mf != null)
colName = mf.getColumnNameInSql();
}
sql.append(colName);
if (head.special()) {
_value_places.append(head.value());
} else {
if (en != null)
mf = en.getField(head.name());
_value_places.append("?");
values.add(head.value());
ValueAdaptor adaptor = head.adaptor();
if (adaptor == null) {
if (mf != null && mf.getAdaptor() != null)
adaptor = mf.getAdaptor();
else
adaptor = Jdbcs.getAdaptorBy(head.value());
}
adaptors.add(adaptor);
}
head = head.next();
if (head != null) {
sql.append(", ");
_value_places.append(", ");
}
}
sql.append(")");
_value_places.append(")");
sql.append(_value_places);
if (log.isDebugEnabled())
log.debug(sql);
dao.run(new ConnCallback() {
public void invoke(Connection conn) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql.toString());
try {
for (int i = 0; i < values.size(); i++)
adaptors.get(i).set(ps, values.get(i), i + 1);
ps.execute();
}
finally {
Daos.safeClose(ps);
}
}
});
}
/**
* package@Tabledao.create(XXX.class, force),
* ,@ManyMany
*
* @param dao
* Dao
* @param packageName
* package,
* @param force
* ,
*/
public static void createTablesInPackage(final Dao dao, String packageName, boolean force) {
List<Class<?>> list = new ArrayList<Class<?>>();
for(Class<?> klass: Scans.me().scanPackage(packageName)) {
if (Mirror.me(klass).getAnnotation(Table.class) != null)
list.add(klass);
};
createTables(dao,list,force);
}
/**
* package@Tabledao.create(XXX.class, force),
*
* @param dao
* Dao
* @param oneClzInPackage
* packageclass, pkgName
* @param force
* ,
*/
public static void createTablesInPackage(Dao dao, Class<?> oneClzInPackage, boolean force) {
createTablesInPackage(dao, oneClzInPackage.getPackage().getName(), force);
}
/**
* package@Tabledao.create(XXX.class, force),
* ,@ManyMany
*
* @param dao
* Dao
* @param oneClzInPackage
* packageclass, pkgName
* @param force
* ,
* @param filter
*
*/
public static void createTablesInPackage(final Dao dao, Class<?> oneClzInPackage, boolean force,TablesFilter filter) {
createTablesInPackage(dao, oneClzInPackage.getPackage().getName(), force,filter);
}
/**
* package@Tabledao.create(XXX.class, force),
* ,@ManyMany
*
* @param dao
* Dao
* @param packageName
* package,
* @param force
* ,
* @param filter
*
*/
public static void createTablesInPackage(final Dao dao, String packageName, boolean force,TablesFilter filter) {
List<Class<?>> list = new ArrayList<Class<?>>();
for(Class<?> klass: Scans.me().scanPackage(packageName)) {
Table table = Mirror.me(klass).getAnnotation(Table.class);
if (table != null && filter.match(klass,table))
list.add(klass);
}
createTables(dao,list,force);
}
/**
*
* ,@ManyMany
*
* @param dao
* Dao
* @param list
*
* @param force
* ,
*/
private static void createTables(final Dao dao, List<Class<?>> list, boolean force){
Collections.sort(list, new Comparator<Class<?>>() {
public int compare(Class<?> prev, Class<?> next) {
int links_prev = dao.getEntity(prev).getLinkFields(null).size();
int links_next = dao.getEntity(next).getLinkFields(null).size();
if (links_prev == links_next)
return 0;
return links_prev > links_next ? 1 : -1;
}
});
ArrayList<Exception> es = new ArrayList<Exception>();
for (Class<?> klass : list)
try {
dao.create(klass, force);
}
catch (Exception e) {
es.add(new RuntimeException("class=" + klass.getName(), e));
}
if (es.size() > 0) {
for (Exception exception : es) {
log.debug(exception.getMessage(), exception);
}
throw (RuntimeException)es.get(0);
}
}
private static Class<?>[] iz = new Class<?>[]{Dao.class};
/**
* FieldFilterDao. ,,Dao.
*
* @param dao
* Dao
* @param filter
*
* @return FieldFilterDao
*/
public static Dao ext(Dao dao, FieldFilter filter) {
return ext(dao, filter, null);
}
/**
* TableNameDao. ,,Dao.
*
* @param dao
* Dao
* @param tableName
*
* @return TableNameDao
*/
public static Dao ext(Dao dao, Object tableName) {
return ext(dao, null, tableName);
}
/**
*
*
* @param dao
* Dao
* @param filter
*
* @param tableName
*
* @return Dao
*/
public static Dao ext(Dao dao, FieldFilter filter, Object tableName) {
if (tableName == null && filter == null)
return dao;
ExtDaoInvocationHandler handler = new ExtDaoInvocationHandler(dao, filter, tableName);
return (Dao) Proxy.newProxyInstance(dao.getClass().getClassLoader(), iz, handler);
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static boolean filterFields(Object obj,
FieldMatcher matcher,
Dao dao,
Callback2<MappingField, Object> callback) {
if (obj == null)
return false;
obj = Lang.first(obj);
if (obj == null) {
return false;
}
if (obj.getClass() == Class.class) {
throw Lang.impossible();
}
if (obj instanceof String || obj instanceof Number || obj instanceof Boolean) {
throw Lang.impossible();
}
Entity en = dao.getEntity(obj.getClass());
if (en == null) {
throw Lang.impossible();
}
List<MappingField> mfs = new ArrayList<MappingField>(en.getMappingFields());
if (matcher != null) {
Iterator<MappingField> it = mfs.iterator();
while (it.hasNext()) {
MappingField mf = it.next();
if (!matcher.match(mf.getName()))
it.remove();
}
}
boolean flag = false;
for (MappingField mf : mfs) {
if (matcher == null) {
Object val = mf.getValue(obj);
callback.invoke(mf, val);
flag = true;
continue;
}
if (!matcher.match(mf, obj))
continue;
callback.invoke(mf, mf.getValue(obj));
flag = true;
}
return flag;
}
/**
*
*
* @param dao
* Dao
* @param klass
* Pojo
* @param add
*
* @param del
*
* @param checkIndex
*
*/
public static void migration(Dao dao,
final Class<?> klass,
final boolean add,
final boolean del,
boolean checkIndex) {
migration(dao, klass, add, del, checkIndex, null);
}
/**
*
*
* @param dao
* Dao
* @param klass
* Pojo
* @param add
*
* @param del
*
*/
public static void migration(Dao dao,
final Class<?> klass,
final boolean add,
final boolean del) {
migration(dao, klass, add, del, false, null);
}
/**
*
*
* @param dao
* Dao
* @param klass
* Pojo
* @param add
*
* @param del
*
* @param tableName
*
*/
public static void migration(Dao dao,
final Class<?> klass,
final boolean add,
final boolean del,
Object tableName) {
migration(dao, klass, add, del, false, tableName);
}
/**
*
*
* @param dao
* Dao
* @param klass
* Pojo
* @param add
*
* @param del
*
* @param checkIndex
*
* @param tableName
*
*/
public static void migration(Dao dao,
final Class<?> klass,
final boolean add,
final boolean del,
final boolean checkIndex,
final Object tableName) {
migration(dao, dao.getEntity(klass), add, del, checkIndex, tableName);
}
public static void migration(Dao dao,
final Entity<?> en,
final boolean add,
final boolean del,
final boolean checkIndex,
final Object tableName) {
final JdbcExpert expert = dao.getJdbcExpert();
if (tableName != null && Strings.isNotBlank(tableName.toString())) {
dao = ext(dao, tableName);
}
final List<Sql> sqls = new ArrayList<Sql>();
final Set<String> _indexs = new HashSet<String>();
dao.run(new ConnCallback() {
public void invoke(Connection conn) throws Exception {
expert.setupEntityField(conn, en);
Statement stat = null;
ResultSet rs = null;
ResultSetMetaData meta = null;
try {
stat = conn.createStatement();
rs = stat.executeQuery("select * from " + en.getTableName() + " where 1 != 1");
meta = rs.getMetaData();
Set<String> columnNames = new HashSet<String>();
int columnCount = meta.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
columnNames.add(meta.getColumnName(i).toLowerCase());
}
for (MappingField mf : en.getMappingFields()) {
if (mf.isReadonly())
continue;
String colName = mf.getColumnName();
if (columnNames.contains(colName.toLowerCase())) {
columnNames.remove(colName.toLowerCase());
continue;
}
if (add) {
log.infof("add column[%s] to table[%s]",
mf.getColumnName(),
en.getTableName());
sqls.add(expert.createAddColumnSql(en, mf));
}
}
if (del) {
for (String colName : columnNames) {
log.infof("del column[%s] from table[%s]", colName, en.getTableName());
Sql sql = Sqls.create("ALTER table $table DROP column $name");
sql.vars().set("table", en.getTableName());
sql.vars().set("name", colName);
sqls.add(sql);
}
}
// show index from mytable;
if (checkIndex)
_indexs.addAll(expert.getIndexNames(en, conn));
}
catch (SQLException e) {
if (log.isDebugEnabled())
log.debugf("migration Table '%s' fail!", en.getTableName(), e);
}
// Close ResultSet and Statement
finally {
Daos.safeClose(stat, rs);
}
}
});
UpdateIndexSql indexSqls = createIndexs(dao, en, _indexs, tableName);
if (checkIndex) {
Sql[] delIndexSqls = indexSqls.getSqlsDel();
if (!Lang.isEmptyArray(delIndexSqls)) {
dao.execute(delIndexSqls);
}
}
for (Sql sql : sqls) {
dao.execute(sql);
}
if (checkIndex) {
Sql[] addIndexSqls = indexSqls.getSqlsAdd();
if (!Lang.isEmptyArray(addIndexSqls)) {
dao.execute(addIndexSqls);
}
}
dao.getJdbcExpert().createRelation(dao, en);
}
static class UpdateIndexSql {
private Sql[] sqlsAdd;
private Sql[] sqlsDel;
public Sql[] getSqlsAdd() {
return sqlsAdd;
}
public void setSqlsAdd(Sql[] sqlsAdd) {
this.sqlsAdd = sqlsAdd;
}
public Sql[] getSqlsDel() {
return sqlsDel;
}
public void setSqlsDel(Sql[] sqlsDel) {
this.sqlsDel = sqlsDel;
}
}
private static UpdateIndexSql createIndexs(Dao dao,
Entity<?> en,
Set<String> indexsHis,
Object t) {
UpdateIndexSql uis = new UpdateIndexSql();
List<Sql> sqls = new ArrayList<Sql>();
List<String> delIndexs = new ArrayList<String>();
List<EntityIndex> indexs = en.getIndexes();
for (EntityIndex index : indexs) {
String indexName = index.getName(en);
if (indexsHis.contains(indexName)) {
indexsHis.remove(indexName);
}
else {
sqls.add(dao.getJdbcExpert().createIndexSql(en, index));
}
}
uis.setSqlsAdd(sqls.toArray(new Sql[sqls.size()]));
Iterator<String> iterator = indexsHis.iterator();
List<Sql> delSqls = new ArrayList<Sql>();
while (iterator.hasNext()) {
String indexName = iterator.next();
if (delIndexs.contains(indexName) || Lang.equals("PRIMARY", indexName)) {
continue;
}
MappingField mf = en.getColumn(indexName);
if (mf != null) {
if (mf.isName())
continue;
}
if (dao.meta().isSqlServer()) {
delSqls.add(Sqls.createf("DROP INDEX %s.%s",
getTableName(dao, en, t),
indexName));
} else {
delSqls.add(Sqls.createf("ALTER TABLE %s DROP INDEX %s",
getTableName(dao, en, t),
indexName));
}
}
uis.setSqlsDel(delSqls.toArray(new Sql[delSqls.size()]));
return uis;
}
/**
* packagepackage@TablePojomigration
*
* @param dao
* Dao
* @param packageName
* package
* @param add
*
* @param del
*
* @param checkIndex
*
* @param nameTable
*
*/
public static void migration(Dao dao,
String packageName,
boolean add,
boolean del,
boolean checkIndex,
Object nameTable) {
for (Class<?> klass : Scans.me().scanPackage(packageName)) {
if (Mirror.me(klass).getAnnotation(Table.class) != null) {
migration(dao, klass, add, del, checkIndex, nameTable);
}
}
}
/**
* packagepackage@TablePojomigration
*
* @param dao
* Dao
* @param packageName
* package
* @param add
*
* @param del
*
* @param nameTable
*
*/
public static void migration(Dao dao,
String packageName,
boolean add,
boolean del,
Object nameTable) {
migration(dao, packageName, add, del, true, nameTable);
}
/**
* packagepackage@TablePojomigration
*
* @param dao
* Dao
* @param packageName
* package
* @param add
*
* @param del
*
* @param checkIndex
*
*/
public static void migration(Dao dao,
String packageName,
boolean add,
boolean del,
boolean checkIndex) {
for (Class<?> klass : Scans.me().scanPackage(packageName)) {
if (Mirror.me(klass).getAnnotation(Table.class) != null) {
migration(dao, klass, add, del, checkIndex, null);
}
}
}
/**
* packagepackage@TablePojomigration
*
* @param dao
* Dao
* @param packageName
* package
* @param add
*
* @param del
*
*/
public static void migration(Dao dao, String packageName, boolean add, boolean del) {
migration(dao, packageName, add, del, true);
}
/**
*
*
* @param dao
* Dao
* @param tableName
*
* @param clsType
* Pojo
*/
public static void checkTableColumn(Dao dao, Object tableName, final Class<?> clsType) {
final NutDao d = (NutDao) dao;
final JdbcExpert expert = d.getJdbcExpert();
ext(d, tableName).run(new ConnCallback() {
public void invoke(Connection conn) throws Exception {
Entity<?> en = d.getEntity(clsType);
expert.setupEntityField(conn, en);
}
});
}
/**
*
*
* @param dao
* Dao
* @param klass
* Pojo
* @param target
*
*/
public static String getTableName(Dao dao, Class<?> klass, Object target) {
return getTableName(dao, dao.getEntity(klass), target);
}
/**
*
*
* @param dao
* Dao
* @param en
* Pojo
* @param target
*
*/
public static String getTableName(Dao dao, final Entity<?> en, Object target) {
if (target == null)
return en.getTableName();
final String[] name = new String[1];
TableName.run(target, new Runnable() {
public void run() {
name[0] = en.getTableName();
}
});
return name[0];
}
private static SqlFormat sqlFormat = SqlFormat.full;
/** SQL */
public static SqlFormat getSqlFormat() {
return sqlFormat;
}
/**
* SQL
*
* @param sqlFormat
* SQL
*/
public static void setSqlFormat(SqlFormat sqlFormat) {
Daos.sqlFormat = sqlFormat;
}
/** SQL2003 */
public static Set<String> sql2003Keywords() {
Set<String> keywords = new HashSet<String>();
String k = "ADD,ALL,ALLOCATE,ALTER,AND,ANY,ARE,ARRAY,AS,ASENSITIVE,ASYMMETRIC,AT,ATOMIC,AUTHORIZATION,BEGIN,BETWEEN,BIGINT,BINARY,BLOB,BOOLEAN,BOTH,BY,CALL,CALLED,CASCADED,CASE,CAST,CHAR,CHARACTER,CHECK,CLOB,CLOSE,COLLATE,COLUMN,COMMIT,CONDITION,CONNECT,CONSTRAINT,CONTINUE,CORRESPONDING,CREATE,CROSS,CUBE,CURRENT,CURRENT_DATE,CURRENT_DEFAULT_TRANSFORM_GROUP,CURRENT_PATH,CURRENT_ROLE,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_TRANSFORM_GROUP_FOR_TYPE,CURRENT_USER,CURSOR,CYCLE,DATE,DAY,DEALLOCATE,DEC,DECIMAL,DECLARE,DEFAULT,DELETE,DEREF,DESCRIBE,DETERMINISTIC,DISCONNECT,DISTINCT,DO,DOUBLE,DROP,DYNAMIC,EACH,ELEMENT,ELSE,ELSEIF,END,ESCAPE,EXCEPT,EXEC,EXECUTE,EXISTS,EXIT,EXTERNAL,FALSE,FETCH,FILTER,FLOAT,FOR,FOREIGN,FREE,FROM,FULL,FUNCTION,GET,GLOBAL,GRANT,GROUP,GROUPING,HANDLER,HAVING,HOLD,HOUR,IDENTITY,IF,IMMEDIATE,IN,INDICATOR,INNER,INOUT,INPUT,INSENSITIVE,INSERT,INT,INTEGER,INTERSECT,INTERVAL,INTO,IS,ITERATE,JOIN,LANGUAGE,LARGE,LATERAL,LEADING,LEAVE,LEFT,LIKE,LOCAL,LOCALTIME,LOCALTIMESTAMP,LOOP,MATCH,MEMBER,MERGE,METHOD,MINUTE,MODIFIES,MODULE,MONTH,MULTISET,NATIONAL,NATURAL,NCHAR,NCLOB,NEW,NO,NONE,NOT,NULL,NUMERIC,OF,OLD,ON,ONLY,OPEN,OR,ORDER,OUT,OUTER,OUTPUT,OVER,OVERLAPS,PARAMETER,PARTITION,PRECISION,PREPARE,PROCEDURE,RANGE,READS,REAL,RECURSIVE,REF,REFERENCES,REFERENCING,RELEASE,REPEAT,RESIGNAL,RESULT,RETURN,RETURNS,REVOKE,RIGHT,ROLLBACK,ROLLUP,ROW,ROWS,SAVEPOINT,SCOPE,SCROLL,SEARCH,SECOND,SELECT,SENSITIVE,SESSION_USER,SET,SIGNAL,SIMILAR,SMALLINT,SOME,SPECIFIC,SPECIFICTYPE,SQL,SQLEXCEPTION,SQLSTATE,SQLWARNING,START,STATIC,SUBMULTISET,SYMMETRIC,SYSTEM,SYSTEM_USER,TABLE,TABLESAMPLE,THEN,TIME,TIMESTAMP,TIMEZONE_HOUR,TIMEZONE_MINUTE,TO,TRAILING,TRANSLATION,TREAT,TRIGGER,TRUE,UNDO,UNION,UNIQUE,UNKNOWN,UNNEST,UNTIL,UPDATE,USER,USING,VALUE,VALUES,VARCHAR,VARYING,WHEN,WHENEVER,WHERE,WHILE,WINDOW,WITH,WITHIN,WITHOUT,YEAR";
for (String keyword : k.split(",")) {
keywords.add(keyword);
}
keywords.remove("VALUE");
keywords.remove("SQL");
keywords.remove("YEAR");
return keywords;
}
public static boolean CHECK_COLUMN_NAME_KEYWORD = false;
public static boolean FORCE_WRAP_COLUMN_NAME = false;
public static boolean FORCE_UPPER_COLUMN_NAME = false;
public static boolean FORCE_HUMP_COLUMN_NAME = false;
/** varchar */
public static int DEFAULT_VARCHAR_WIDTH = 128;
/** Table&View */
public static interface NameMaker {
String make(Class<?> klass);
}
/** Table */
private static NameMaker tableNameMaker = new NameMaker() {
@Override
public String make(Class<?> klass) {
return Strings.lowerWord(klass.getSimpleName(), '_');
}
};
/** View */
private static NameMaker viewNameMaker = new NameMaker() {
@Override
public String make(Class<?> klass) {
return Strings.lowerWord(klass.getSimpleName(), '_');
}
};
public static NameMaker getTableNameMaker() {
return tableNameMaker;
}
public static void setTableNameMaker(NameMaker tableNameMaker) {
Daos.tableNameMaker = tableNameMaker;
}
public static NameMaker getViewNameMaker() {
return viewNameMaker;
}
public static void setViewNameMaker(NameMaker viewNameMaker) {
Daos.viewNameMaker = viewNameMaker;
}
}
class ExtDaoInvocationHandler implements InvocationHandler {
protected ExtDaoInvocationHandler(Dao dao, FieldFilter filter, Object tableName) {
this.dao = dao;
this.filter = filter;
this.tableName = tableName;
}
public Dao dao;
public FieldFilter filter;
public Object tableName;
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
final Molecule<Object> m = new Molecule<Object>() {
public void run() {
try {
setObj(method.invoke(dao, args));
}
catch (Exception e) {
throw Lang.wrapThrow(e);
}
}
};
if (filter != null && tableName != null) {
TableName.run(tableName, new Runnable() {
public void run() {
filter.run(m);
}
});
return m.getObj();
}
if (filter != null)
filter.run(m);
else
TableName.run(tableName, m);
return m.getObj();
}
} |
package org.petschko.lib;
public class Const {
public static final String creator = "Petschko";
public static final String creatorURL = "https://petschko.org/";
// System Constance's
public static final String ds = System.getProperty("file.separator");
public static final String newLine = System.getProperty("line.separator");
/**
* Constructor
*/
private Const() {
// VOID - This is a Static-Class
}
} |
package org.gjt.fredde.silence.format.xm;
/**
* A class that handles a channel
*
* @version $Id: Channel.java,v 1.14 2003/08/23 07:41:19 fredde Exp $
* @author Fredrik Ehnbom
*/
class Channel {
Xm xm;
InstrumentManager im;
EffectManager em;
public Channel(Xm xm) {
this.xm = xm;
im = new InstrumentManager(xm);
em = new EffectManager(this);
}
int currentNote = 0;
int timer = 0;
final int skip(Pattern pattern, int patternpos) {
int check = pattern.data[patternpos++];
if ((check & 0x80) != 0) {
if ((check & 0x1) != 0) patternpos++;
if ((check & 0x2) != 0) patternpos++;
if ((check & 0x4) != 0) patternpos++;
if ((check & 0x8) != 0) patternpos++;
if ((check & 0x10) != 0) patternpos++;
} else {
patternpos += 4;
}
return patternpos;
}
final int update(Pattern pattern, int patternpos) {
int check = pattern.data[patternpos++];
int newNote = -1;
Instrument newInstrument = null;
int newVolume = -1;
int newEffect = -1;
int newEffectParam = -1;
if ((check & 0x80) != 0) {
// note
if ((check & 0x1) != 0) newNote = pattern.data[patternpos++];
// instrument
if ((check & 0x2) != 0) {
int tmp = pattern.data[patternpos++] - 1;
if (tmp < xm.instrument.length)
newInstrument = xm.instrument[tmp];
}
// volume
if ((check & 0x4) != 0) newVolume = pattern.data[patternpos++]&0xff;
// effect
if ((check & 0x8) != 0) newEffect = pattern.data[patternpos++];
// effect param
if ((check & 0x10) != 0) newEffectParam = pattern.data[patternpos++]&0xff;
} else {
newNote = check;
newInstrument = xm.instrument[pattern.data[patternpos++] - 1];
newVolume = pattern.data[patternpos++]&0xff;
newEffect = pattern.data[patternpos++];
newEffectParam = pattern.data[patternpos++]&0xff;
}
if (newInstrument != null) {
im.setInstrument(newInstrument);
}
em.currentEffect = -1;
if (newEffect != -1) {
newNote = em.setEffect(newEffect, newEffectParam, newNote);
}
if (newNote != -1) {
if (newNote == 97) {
im.release();
} else {
currentNote = newNote;
im.playNote(currentNote);
}
}
if (newVolume != -1) {
em.setVolume(newVolume);
}
return patternpos;
}
public final void updateTick() {
em.updateEffects();
im.updateVolumes();
}
final void play(int[] buffer, int off, int len) {
im.play(buffer, off, len);
}
}
/*
* ChangeLog:
* $Log: Channel.java,v $
* Revision 1.14 2003/08/23 07:41:19 fredde
* gets new note from effectmanager
*
* Revision 1.13 2003/08/22 12:36:16 fredde
* moved effects from Channel to EffectManager
*
* Revision 1.12 2003/08/22 06:51:26 fredde
* 0xx,1xx,2xx,rxx implemented. update() from muhmu2-player
*
* Revision 1.11 2003/08/21 09:25:35 fredde
* moved instrument-playing from Channel into InstrumentManager
*
* Revision 1.10 2002/03/20 13:37:25 fredde
* whoa! lots of changes!
* among others:
* * fixed looping (so that some chiptunes does not play false anymore :))
* * pitch, currentPos and some more stuff now uses fixedpoint maths
* * added a volumeScale variable for easier changing of the volumescale
* * a couple of effects that I had implemented in my xm-player for muhmuaudio 0.2
* have been copied and pasted into the file. they are commented out though
*
* Revision 1.9 2001/01/04 18:55:59 fredde
* some smaller changes
*
* Revision 1.8 2000/12/21 17:19:59 fredde
* volumeenvelopes works better, uses precalced k-values,
* pingpong loop fixed
*
* Revision 1.7 2000/10/14 19:09:04 fredde
* changed volume stuff back to 32 since
* sampleData is of type byte[] again
*
* Revision 1.6 2000/10/12 15:04:42 fredde
* fixed volume envelopes after sustain.
* updated volumes to work with (8-bit sample) << 8
*
* Revision 1.5 2000/10/08 18:01:57 fredde
* changes to play the file even better.
*
* Revision 1.4 2000/10/07 13:48:06 fredde
* Lots of fixes to play correct.
* Added volume stuff.
*
* Revision 1.3 2000/10/01 17:06:38 fredde
* basic playing abilities added
*
* Revision 1.2 2000/09/29 19:39:48 fredde
* no need to be public
*
* Revision 1.1.1.1 2000/09/25 16:34:34 fredde
* initial commit
*
*/ |
package org.commcare;
import android.content.Context;
import android.content.Intent;
import android.support.v4.util.Pair;
import android.util.Log;
import org.commcare.android.database.app.models.UserKeyRecord;
import org.commcare.android.mocks.ModernHttpRequesterMock;
import org.commcare.android.util.TestUtils;
import org.commcare.core.encryption.CryptUtil;
import org.commcare.core.network.ModernHttpRequester;
import org.commcare.dalvik.BuildConfig;
import org.commcare.models.AndroidPrototypeFactory;
import org.commcare.models.database.AndroidPrototypeFactorySetup;
import org.commcare.models.database.HybridFileBackedSqlStorage;
import org.commcare.models.database.HybridFileBackedSqlStorageMock;
import org.commcare.models.encryption.ByteEncrypter;
import org.commcare.network.DataPullRequester;
import org.commcare.network.HttpUtils;
import org.commcare.network.LocalDataPullResponseFactory;
import org.commcare.services.CommCareSessionService;
import org.commcare.utils.AndroidCacheDirSetup;
import org.javarosa.core.model.User;
import org.javarosa.core.reference.ReferenceManager;
import org.javarosa.core.reference.ResourceReferenceFactory;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.junit.Assert;
import org.robolectric.Robolectric;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.TestLifecycleApplication;
import org.robolectric.util.ServiceController;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import static junit.framework.Assert.fail;
/**
* @author Phillip Mates (pmates@dimagi.com).
*/
public class CommCareTestApplication extends CommCareApplication implements TestLifecycleApplication {
private static final String TAG = CommCareTestApplication.class.getSimpleName();
private static PrototypeFactory testPrototypeFactory;
private static final ArrayList<String> factoryClassNames = new ArrayList<>();
private String cachedUserPassword;
private final ArrayList<Throwable> asyncExceptions = new ArrayList<>();
@Override
public void onCreate() {
super.onCreate();
// allow "jr://resource" references
ReferenceManager._().addReferenceFactory(new ResourceReferenceFactory());
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
asyncExceptions.add(ex);
Assert.fail(ex.getMessage());
}
});
}
@Override
public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedAppStorage(String name, Class<T> c) {
return getCurrentApp().getFileBackedStorage(name, c);
}
@Override
public <T extends Persistable> HybridFileBackedSqlStorage<T> getFileBackedUserStorage(String storage, Class<T> c) {
return new HybridFileBackedSqlStorageMock<>(storage, c, buildUserDbHandle(), getUserKeyRecordId());
}
@Override
public CommCareApp getCurrentApp() {
CommCareApp superApp = super.getCurrentApp();
if (superApp == null) {
return null;
} else {
return new CommCareTestApp(superApp);
}
}
@Override
public PrototypeFactory getPrototypeFactory(Context c) {
TestUtils.disableSqlOptimizations();
if (testPrototypeFactory != null) {
return testPrototypeFactory;
}
// Sort of hack-y way to get the classfile dirs
initFactoryClassList();
try {
testPrototypeFactory = new AndroidPrototypeFactory(new HashSet<>(factoryClassNames));
} catch (Exception e) {
throw new RuntimeException(e);
}
return testPrototypeFactory;
}
/**
* Get externalizable classes from *.class files in build dirs. Used to
* build PrototypeFactory that mirrors a prod environment
*/
private static void initFactoryClassList() {
if (factoryClassNames.isEmpty()) {
String baseODK = BuildConfig.BUILD_DIR + "/intermediates/classes/commcare/debug/";
String baseCC = BuildConfig.PROJECT_DIR + "/../commcare-core/build/classes/main/";
addExternalizableClassesFromDir(baseODK.replace("/", File.separator), factoryClassNames);
addExternalizableClassesFromDir(baseCC.replace("/", File.separator), factoryClassNames);
}
}
private static void addExternalizableClassesFromDir(String baseClassPath,
List<String> externClasses) {
try {
File f = new File(baseClassPath);
ArrayList<File> files = new ArrayList<>();
getFilesInDir(f, files);
for (File file : files) {
String className = file.getAbsolutePath()
.replace(baseClassPath, "")
.replace(File.separator, ".")
.replace(".class", "")
.replace(".class", "");
AndroidPrototypeFactorySetup.loadClass(className, externClasses);
}
} catch (Exception e) {
Log.w(TAG, e.getMessage());
}
}
/**
* @return Names of externalizable classes loaded from *.class files in the build dir
*/
public static List<String> getTestPrototypeFactoryClasses() {
initFactoryClassList();
return factoryClassNames;
}
private static void getFilesInDir(File currentFile, ArrayList<File> acc) {
for (File f : currentFile.listFiles()) {
if (f.isFile()) {
acc.add(f);
} else {
getFilesInDir(f, acc);
}
}
}
@Override
public void startUserSession(byte[] symetricKey, UserKeyRecord record, boolean restoreSession) {
// manually create/setup session service because robolectric doesn't
// really support services
CommCareSessionService ccService = startRoboCommCareService();
ccService.createCipherPool();
ccService.prepareStorage(symetricKey, record);
User user = getUserFromDb(ccService, record);
if (user == null && cachedUserPassword != null) {
Log.d(TAG, "No user instance found, creating one");
user = new User(record.getUsername(), cachedUserPassword, "some_unique_id");
CommCareApplication._().getRawStorage("USER", User.class, ccService.getUserDbHandle()).write(user);
}
if (user != null) {
user.setCachedPwd(cachedUserPassword);
user.setWrappedKey(ByteEncrypter.wrapByteArrayWithString(CryptUtil.generateSemiRandomKey().getEncoded(), cachedUserPassword));
}
ccService.startSession(user, record);
CommCareApplication._().setTestingService(ccService);
}
private static CommCareSessionService startRoboCommCareService() {
Intent startIntent =
new Intent(RuntimeEnvironment.application, CommCareSessionService.class);
ServiceController<CommCareSessionService> serviceController =
Robolectric.buildService(CommCareSessionService.class, startIntent);
serviceController.attach()
.create()
.startCommand(0, 1);
return serviceController.get();
}
private static User getUserFromDb(CommCareSessionService ccService, UserKeyRecord keyRecord) {
for (User u : CommCareApplication._().getRawStorage("USER", User.class, ccService.getUserDbHandle())) {
if (keyRecord.getUsername().equals(u.getUsername())) {
return u;
}
}
return null;
}
public void setCachedUserPassword(String password) {
cachedUserPassword = password;
}
@Override
public ModernHttpRequester buildModernHttpRequester(Context context, URL url,
HashMap<String, String> params,
boolean isAuthenticatedRequest,
boolean isPostRequest) {
Pair<User, String> userAndDomain = HttpUtils.getUserAndDomain(isAuthenticatedRequest);
return new ModernHttpRequesterMock(new AndroidCacheDirSetup(context),
url, params, userAndDomain.first, userAndDomain.second,
isAuthenticatedRequest, isPostRequest);
}
@Override
public DataPullRequester getDataPullRequester() {
return LocalDataPullResponseFactory.INSTANCE;
}
@Override
public void afterTest(Method method) {
Robolectric.flushBackgroundThreadScheduler();
if (!asyncExceptions.isEmpty()) {
for(Throwable throwable: asyncExceptions) {
throwable.printStackTrace();
fail("Test failed due to " + asyncExceptions.size() +
" threads crashing off the main thread. See error log for more details");
}
}
}
@Override
public void beforeTest(Method method) {
}
@Override
public void prepareTest(Object test) {
}
} |
package fate.webapp.blog.api.open;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.http.client.ClientProtocolException;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import fate.webapp.blog.base.Constants;
import fate.webapp.blog.listener.SiteStatistics;
import fate.webapp.blog.model.Aliyun;
import fate.webapp.blog.model.DuoShuo;
import fate.webapp.blog.model.Forum;
import fate.webapp.blog.model.GlobalSetting;
import fate.webapp.blog.model.Index;
import fate.webapp.blog.model.Navi;
import fate.webapp.blog.model.Param;
import fate.webapp.blog.model.Theme;
import fate.webapp.blog.service.AdvertisementService;
import fate.webapp.blog.service.AnnouncementService;
import fate.webapp.blog.service.DuoShuoService;
import fate.webapp.blog.service.NaviService;
import fate.webapp.blog.service.ParamService;
import fate.webapp.blog.service.ThemeService;
import fate.webapp.blog.service.ThemeTagService;
import fate.webapp.blog.utils.DateUtil;
import fate.webapp.blog.utils.FilterHTMLTag;
import fate.webapp.blog.utils.QRUtil;
@Controller
@RequestMapping("/op")
public class OpenCtl {
private static final Logger LOG = Logger.getLogger(OpenCtl.class);
@Autowired
private ThemeService themeService;
@Autowired
private NaviService naviService;
@Autowired
private ParamService paramService;
@Autowired
private AnnouncementService announcementService;
@Autowired
private AdvertisementService advertisementService;
@Autowired
private DuoShuoService duoShuoService;
@Autowired
private ThemeTagService themeTagService;
@RequestMapping("/footer")
public ModelAndView footer(){
ModelAndView mv = new ModelAndView("base/footer");
Calendar cal = Calendar.getInstance();
mv.addObject("year", cal.get(Calendar.YEAR));
Index index = Index.getInstance();
mv.addObject("adv", index.getAdvBottom());
return mv;
}
@RequestMapping("/head")
public String head(){
return "base/head";
}
@RequestMapping("/header")
public ModelAndView header(HttpServletRequest request){
ModelAndView mv = new ModelAndView("base/header2");
GlobalSetting globalSetting = GlobalSetting.getInstance();
mv.addObject("qq", globalSetting.getQqAccess());
mv.addObject("xinlang", globalSetting.getWeiboAccess());
Index index = Index.getInstance();
if(index.getNavis().isEmpty()){
List<Navi> navis = naviService.searchRoot();
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (Navi n : navis) {
list.add(naviToJson(n));
}
index.setNavis(list);
}
mv.addObject("navis", index.getNavis());
return mv;
}
public Map<String, Object> naviToJson(Navi navi){
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", navi.getId());
map.put("name", navi.getName());
map.put("url", navi.getUrl());
map.put("type", navi.getType());
map.put("order", navi.getOrder());
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
String childUrl = "";
for(Navi n:navi.getChilds()){
list.add(naviToJson(n));
childUrl += n.getUrl()+",";
}
map.put("childUrl", childUrl);
map.put("children", list);
return map;
}
@RequestMapping("/accessDenied")
public ModelAndView accessDenied(String message){
ModelAndView mv = new ModelAndView("login/accessDenied");
mv.addObject("message", message);
return mv;
}
/**
*
* @param fid id
* @return
*/
@RequestMapping("/rightNavi")
public ModelAndView rightNavi(int fid, String url){
ModelAndView mv = new ModelAndView("base/rightNavi");
// Forum forum = forumService.find(fid);
// List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// if(forum!=null){//
// mv.addObject("region", forum.getForumName());
// for (Forum f : forum.getChildForums()) {
// list.add(forumToJson(f));
Index index = Index.getInstance();
mv.addObject("announcements", index.getAnnouncements());
mv.addObject("advertisement", index.getAdvRight());
mv.addObject("online", SiteStatistics.getOnline());
mv.addObject("updateTime", SiteStatistics.getUpdateTime());
mv.addObject("theme", SiteStatistics.getTheme());
mv.addObject("user", SiteStatistics.getUser());
mv.addObject("comment", SiteStatistics.getComment());
mv.addObject("views", SiteStatistics.getViews());
mv.addObject("history_online", SiteStatistics.getHistrry_online());
mv.addObject("search", SiteStatistics.getSearch());
// mv.addObject("forums", list);
mv.addObject("hot", index.getHot());
mv.addObject("searchHot", index.getSearchHot());
mv.addObject("tags", themeTagService.random(30));
return mv;
}
@RequestMapping("/search")
public ModelAndView search(String keyword, @RequestParam(defaultValue = "1")int curPage){
ModelAndView mv = new ModelAndView("search/result");
Param search = paramService.findByKey(Constants.SEARCH_COUNT);
if(search!=null){
search.setIntValue(search.getIntValue()+1);
}else{
search = new Param();
search.setKey(Constants.SEARCH_COUNT);
search.setIntValue(0);
search.setType(Param.TYPE_INT);
}
search = paramService.update(search);
SiteStatistics.setSearch(search.getIntValue());
try {
String res = Aliyun.getInstance().search(keyword, curPage, 10);
JSONObject data = new JSONObject(res);
String status = data.getString("status");
JSONObject result = data.getJSONObject("result");
double searchTime = result.getDouble("searchtime");
long total = result.getLong("total");
long num = result.getLong("num");
long viewTotal = result.getLong("viewtotal");
JSONArray items = result.getJSONArray("items");
List<Theme> themes = new ArrayList<Theme>();
for(int i=0;i<items.length();i++){
Theme theme = new Theme();
JSONObject obj = items.getJSONObject(i);
theme.setGuid(obj.getString("guid"));
theme.setAuthor(obj.getString("author"));
theme.setPublishDate(new Date(obj.getLong("publish_date")));
theme.setPriority(obj.getInt("priority"));
theme.setReplies(obj.getInt("replies"));
theme.setTags(obj.getString("tags"));
theme.setTitle(obj.getString("title"));
theme.setUrl(obj.getString("url"));
theme.setViews(obj.getInt("views"));
theme.setContent(FilterHTMLTag.delHTMLTag(obj.getString("content")));
themes.add(theme);
}
mv.addObject("status", status);
mv.addObject("themes", themes);
mv.addObject("searchTime", searchTime);
mv.addObject("count", total);
mv.addObject("curPage", curPage);
mv.addObject("pageSize", 10);
mv.addObject("keyword", keyword);
} catch (ClientProtocolException e) {
LOG.error("HTTP", e);
} catch (IOException e) {
LOG.error("IO", e);
} catch (JSONException e) {
LOG.error("JSON", e);
}
return mv;
}
@RequestMapping("/getQR")
public void getQR(String url,HttpServletResponse response){
int width = 250;
int height = 250;
String format = "gif";
HashMap<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(url,
BarcodeFormat.QR_CODE, width, height, hints);
URL file = OpenCtl.class.getClassLoader().getResource("log4j.properties");
String path = file.getPath();
path = path.substring(0, path.indexOf("WEB-INF"));
path = path.replaceAll("%20", " ");
path += "images/logo_white.png";
QRUtil.writeToStream(bitMatrix, format, response.getOutputStream(),null);
} catch (WriterException | IOException e) {
LOG.error("", e);
}
}
/**
* Forumjson
* @param forum
* @return
*/
public Map<String, Object> forumToJson(Forum forum) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("forumName", forum.getForumName());
map.put("fid", forum.getFid());
if(forum.getType()!=Forum.TYPE_REGION){
long count = themeService.count(forum.getFid(), false, Theme.STATE_PUBLISH);
map.put("count", count);
}
return map;
}
@RequestMapping("/loading")
public ModelAndView loading(int type){
ModelAndView mv = new ModelAndView("base/loading"+type);
return mv;
}
@RequestMapping("/getSuggest")
@ResponseBody
public Object getSuggest(String query){
return Aliyun.getInstance().suggest(query);
}
@RequestMapping("/duoshuo")
public void duoshuo(String action, String signature){
Index index = Index.getInstance();
if(signature.equals("j6cQY5pEVCVmEnTWW7lywpBtm0I=")){
syncFromDuoShuo(Long.parseLong(index.getLogId().getTextValue()));
}
}
public void syncFromDuoShuo(long sinceId){
HttpClient client = new HttpClient();
Param duoshuoKey = paramService.findByKey(Constants.DUOSHUO_KEY);
Param duoshuoSecret = paramService.findByKey(Constants.DUOSHUO_SECRET);
GetMethod method = new GetMethod("http://api.duoshuo.com/log/list.json?short_name="+duoshuoKey.getTextValue()+"&secret="+duoshuoSecret.getTextValue()+"&since_id="+sinceId);
client.getParams().setContentCharset("UTF-8");
method.setRequestHeader("ContentType", "application/x-www-form-urlencoded;charset=UTF-8");
Index index = Index.getInstance();
try {
client.executeMethod(method);
String submitResult = method.getResponseBodyAsString();
JSONObject dataJson = new JSONObject(submitResult);
if(dataJson.getInt("code")!=0){
LOG.error(dataJson.getString("errorMessage"));
}else{
JSONArray response = dataJson.getJSONArray("response");
for(int i=0;i<response.length();i++){
JSONObject res = response.getJSONObject(i);
long logId = Long.parseLong(res.getString("log_id"));
int userId = res.getInt("user_id");
String action = res.getString("action");
switch (action) {
case "create":
JSONObject meta = res.getJSONObject("meta");
DuoShuo duoShuo = new DuoShuo();
duoShuo.setPostId(Long.parseLong(meta.getString("post_id")));
duoShuo.setThreadId(Long.parseLong(meta.getString("thread_id")));
duoShuo.setTheme(themeService.find(meta.getString("thread_key"), false));
duoShuo.setAuthorId(meta.getInt("author_id"));
duoShuo.setAuthorNmae(meta.getString("author_name"));
duoShuo.setAuthorEmail(meta.getString("author_email"));
duoShuo.setAuthorUrl(meta.getString("author_url"));
duoShuo.setAuthorKey(meta.getString("author_key"));
duoShuo.setIp(meta.getString("ip"));
try {
String date = meta.getString("created_at");
date = date.substring(0,date.lastIndexOf("+")).replace("T", " ");
duoShuo.setCreatedAt(DateUtil.parse(date, "yyyy-MM-dd HH:mm:ss"));
} catch (ParseException e) {
LOG.error("", e);
}
duoShuo.setMessage(meta.getString("message"));
duoShuo.setStatus(meta.getString("status"));
duoShuo.setParentId(Long.parseLong(meta.getString("parent_id")));
duoShuo.setType(meta.getString("type"));
duoShuo.setLastModify(new Date().getTime());
duoShuo.setLogId(logId);
duoShuoService.save(duoShuo);
break;
case "approve":
case "spam":
case "delete":
JSONArray meta2 = res.getJSONArray("meta");
String ids = meta2.toString();
ids = ids.substring(1, ids.length()-1).replace("\"", "");
duoShuoService.update(ids, action, logId);
break;
default:
JSONArray meta3 = res.getJSONArray("meta");
String ids2 = meta3.toString();
ids2 = ids2.substring(1, ids2.length()-1).replace("\"", "");
duoShuoService.delete(ids2);
break;
}
index.getLogId().setTextValue(""+logId);
}
paramService.update(index.getLogId());
Map<Integer,List<Theme>> list = new HashMap<Integer, List<Theme>>();
List<Theme> themes = themeService.pageByFid(0, Constants.INDEX_LIST_LENGTH, 1, false, true, false, Theme.STATE_PUBLISH);
for(Theme theme:themes){
String c = FilterHTMLTag.delHTMLTag(theme.getContent());
theme.setContent((c.length()>200?c.substring(0, 200):c)+"...");
theme.setReplies(theme.getDuoShuos().size());
}
list.put(1, themes);
index.setThemes(list);
}
} catch (IOException e) {
LOG.error(e);
} catch (JSONException e) {
LOG.error(e);
}
}
} |
package com.foc.web.modules.admin;
import java.net.URI;
import java.sql.Date;
import java.util.Collection;
import java.util.Iterator;
import com.fab.codeWriter.CodeWriter;
import com.fab.codeWriter.CodeWriterSet;
import com.fab.model.table.TableDefinition;
import com.foc.ConfigInfo;
import com.foc.Globals;
import com.foc.IFocDescDeclaration;
import com.foc.IFocEnvironment;
import com.foc.OptionDialog;
import com.foc.access.FocLogLineDesc;
import com.foc.access.FocLogger;
import com.foc.admin.ActiveUser;
import com.foc.admin.ActiveUserDesc;
import com.foc.admin.DocRightsGroupDesc;
import com.foc.admin.DocRightsGroupUsersDesc;
import com.foc.admin.FocGroup;
import com.foc.admin.FocGroupDesc;
import com.foc.admin.FocUser;
import com.foc.admin.FocUserDesc;
import com.foc.admin.GroupXMLViewDesc;
import com.foc.admin.MenuRightsDesc;
import com.foc.admin.userModuleAccess.UserModuleList;
import com.foc.business.adrBook.ContactDesc;
import com.foc.business.company.Company;
import com.foc.business.multilanguage.LanguageDesc;
import com.foc.business.workflow.WFSite;
import com.foc.business.workflow.WFTitle;
import com.foc.db.migration.MigFieldMapDesc;
import com.foc.db.migration.MigrationSourceDesc;
import com.foc.desc.AutoPopulatable;
import com.foc.desc.FocDesc;
import com.foc.gui.table.view.ColumnsConfigDesc;
import com.foc.gui.table.view.UserViewDesc;
import com.foc.gui.table.view.ViewConfigDesc;
import com.foc.list.FocLinkSimple;
import com.foc.list.FocList;
import com.foc.menuStructure.FocMenuItem;
import com.foc.menuStructure.FocMenuItemDesc;
import com.foc.menuStructure.IFocMenuItemAction;
import com.foc.saas.manager.SaaSApplicationAdaptor;
import com.foc.saas.manager.SaaSConfig;
import com.foc.saas.manager.SaaSConfigDesc;
import com.foc.shared.xmlView.XMLViewKey;
import com.foc.vaadin.FocWebApplication;
import com.foc.vaadin.FocWebModule;
import com.foc.vaadin.FocWebVaadinWindow;
import com.foc.vaadin.IApplicationConfigurator;
import com.foc.vaadin.ICentralPanel;
import com.foc.vaadin.gui.menuTree.FVMenuTree;
import com.foc.vaadin.gui.windows.optionWindow.IOption;
import com.foc.vaadin.gui.windows.optionWindow.OptionDialogWindow;
import com.foc.vaadin.xmleditor.XMLEditor;
import com.foc.web.gui.INavigationWindow;
import com.foc.web.server.FocWebServer;
import com.foc.web.server.xmlViewDictionary.XMLView;
import com.foc.web.server.xmlViewDictionary.XMLViewDictionary;
import com.foc.web.unitTesting.FocUnitDictionary;
import com.foc.web.unitTesting.FocUnitTestingSuite;
import com.vaadin.server.Page;
public class AdminWebModule extends FocWebModule {
public static final String CTXT_LOGIN = "Login";
public static final String CTXT_LOGIN_AR = "Login-ar";
public static final String CTXT_HISTORY = "History";
public static final String CTXT_GROUP_MENU_RIGHT = "GroupMenuRight";
public static final String CTXT_MIGRATION_SOURCE_SET = "MigrationSourceSet";
public static final String CONTEXT_COMPANY_CONFIGURATION = "ComapnyConfiguration";
public static final String MODULE_NAME = "ADMINISTRATOR";
public static final String CONTEXT_COMPANY_SELECTION = "CompanySelection";
public static final String CONTEXT_COMPANY_SELECTION_AR = "CompanySelectionAr";
public static final String CONTEXT_HOMEPAGE = "HomePage";
public static final String STORAGE_HOMEPAGE = "HOMEPAGE";
public static final String CONTEXT_BEFORE_LOGIN = "BeforeLogin";
public static final String STORAGE_NAME_MANAGE_ACCOUNT = "Manage Account";
public static final String CONTEXT_GROUP_SELECTOR = "Group Selector";
public static final String VIEW_LIMITED = "LIMITED";
public static final String OPTION_WINDOW_STORAGE = "OPTION_WINDOW_STORAGE";
public static final String RIGHT_PANEL_STORAGE = "RIGHT_PANEL_STORAGE";
public static final String CONTEXT_CONTACT ="ContactUser";
public static final String MNU_CODE_UNIT_TEST_LOG = "UNIT_TEST_LOG";
public AdminWebModule(){
super(MODULE_NAME, "Administrator");
setAdminConsole(true);
}
public static void adapt_BarmajaUser(){
}
public void declareXMLViewsInDictionary() {
XMLViewDictionary.getInstance().put(
DocRightsGroupDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/DocRightsGroup_Table.xml", 0, DocRightsGroup_Table.class.getName());
XMLViewDictionary.getInstance().put(
DocRightsGroupDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/DocRightsGroup_Form.xml", 0, DocRightsGroup_Form.class.getName());
XMLViewDictionary.getInstance().put(
DocRightsGroupUsersDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/DocRightsGroupUsers_Table.xml", 0, DocRightsGroupUsers_Table.class.getName());
XMLViewDictionary.getInstance().put(
MigrationSourceDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/MigrationSource_Table.xml", 0, MigrationSource_Table.class.getName());
XMLViewDictionary.getInstance().put(
ActiveUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/ActiveUser_Table.xml", 0, ActiveUser_Table.class.getName());
XMLViewDictionary.getInstance().put(
SaaSConfigDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/SaaSConfig_Form.xml", 0, SaaSConfig_Form.class.getName());
XMLViewDictionary.getInstance().put(
MigrationSourceDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
true,
"/xml/com/foc/admin/MigrationSource_Form.xml", 0, null);
XMLViewDictionary.getInstance().put(
MigrationSourceDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
false,
"/xml/com/foc/admin/MigrationSource_Set_Form.xml", 0, MigrationSource_Set_Form.class.getName());
XMLViewDictionary.getInstance().put(
MigFieldMapDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/MigFieldMap_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
"FVERSION",
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/Fversion_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
"FVERSION",
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/Fversion_Form.xml", 0, null);
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocUser_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocUser_Form.xml", 0, FocUser_Form.class.getName());
XMLViewDictionary.getInstance().put(
STORAGE_NAME_MANAGE_ACCOUNT,
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/ManageAccount_Form.xml", 0, ManageAccount_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CONTEXT_CONTACT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocUser_Contact_Form.xml", 0, FocUser_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CONTEXT_COMPANY_SELECTION,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocUser_CompanySelection_Form.xml", 0, FocUser_CompanySelection_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CONTEXT_COMPANY_SELECTION_AR,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocUser_CompanySelection_Form-ar.xml", 0, FocUser_CompanySelection_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CONTEXT_COMPANY_SELECTION,
VIEW_LIMITED,
"/xml/com/foc/admin/FocUser_CompanySelection_Limited_Form.xml", 0, FocUser_CompanySelection_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocGroupDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CONTEXT_COMPANY_CONFIGURATION,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocGroup_CompanyConfiguration_Form.xml", 0, FocGroup_CompanyConfiguration_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocGroupDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CONTEXT_GROUP_SELECTOR,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocGroup_Selector_Form.xml", 0, FocGroup_Selector_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CONTEXT_HOMEPAGE,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocUser_HomePage_Form.xml", 0, FocUser_HomePage_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocGroupDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocGroup_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
FocGroupDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocGroup_Form.xml", 0, FocGroup_Form.class.getName());
XMLViewDictionary.getInstance().put(
UserViewDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/UserView_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
UserViewDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/UserView_Form.xml", 0, null);
XMLViewDictionary.getInstance().put(
ViewConfigDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/ViewConfig_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
ViewConfigDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/ViewConfig_Form.xml", 0, null);
XMLViewDictionary.getInstance().put(
ColumnsConfigDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/ColumnsConfig_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
ColumnsConfigDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/ColumnsConfig_Form.xml", 0, null);
XMLViewDictionary.getInstance().put(
MenuRightsDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/MenuRights_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
MenuRightsDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/MenuRights_Form.xml", 0, null);
XMLViewDictionary.getInstance().put(
LanguageDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/Language_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
LanguageDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/Language_Form.xml", 0, null);
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CTXT_LOGIN,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/login.xml", 0, FocUser_Login_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CTXT_LOGIN_AR,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/login-ar.xml", 0, FocUser_Login_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocUserDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
CTXT_LOGIN,
"No Buttons",
"/xml/com/foc/admin/login_nobuttons.xml", 0, FocUser_Login_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocMenuItemDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TREE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocMenuItem_Tree.xml", 0, FVMenuTree.class.getName());
XMLViewDictionary.getInstance().put(
FocMenuItemDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TREE,
CTXT_HISTORY,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocMenuItem_History_Tree.xml", 0, FVMenuTree.class.getName());
XMLViewDictionary.getInstance().put(
FocMenuItemDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TREE,
CTXT_GROUP_MENU_RIGHT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocMenuItem_GroupMenuRight_Tree.xml", 0, FocMenuItem_GroupMenuRight_Tree.class.getName());
XMLViewDictionary.getInstance().put(
STORAGE_HOMEPAGE,
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/HomePage_AfterLogin_Form.xml", 0, HomePage_AfterLogin_Form.class.getName());
XMLViewKey key = new XMLViewKey(STORAGE_HOMEPAGE, XMLViewKey.TYPE_FORM, XMLViewKey.CONTEXT_DEFAULT, XMLViewKey.VIEW_DEFAULT);
key.setMobileFriendly(true);
XMLView view = new XMLView(key, "/xml/com/foc/admin/HomePage_AfterLogin_Mobile_Form.xml", HomePage_AfterLogin_Mobile_Form.class.getName());
XMLViewDictionary.getInstance().put(view);
// XMLViewDictionary.getInstance().put(
// STORAGE_HOMEPAGE,
// XMLViewKey.TYPE_FORM,
// XMLViewKey.CONTEXT_DEFAULT,
// XMLViewKey.VIEW_MOBILE,
// "/xml/com/foc/admin/HomePage_AfterLogin_Mobile_Form.xml", 0, HomePage_AfterLogin_Mobile_Form.class.getName());
// XMLViewDictionary.getInstance().put(
// STORAGE_HOMEPAGE,
// XMLViewKey.TYPE_FORM,
// XMLViewKey.CONTEXT_DEFAULT,
// XMLViewKey.VIEW_MOBILE,
// "/xml/com/foc/admin/HomePage_AfterLogin_Mobile_Form.xml", 0, HomePage_AfterLogin_Mobile_Form.class.getName());
XMLViewDictionary.getInstance().put(
STORAGE_HOMEPAGE,
XMLViewKey.TYPE_FORM,
CONTEXT_BEFORE_LOGIN,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/HomePage_BeforeLogin_Form.xml", 0, HomePage_BeforeLogin_Form.class.getName());
XMLViewDictionary.getInstance().put(
STORAGE_HOMEPAGE,
XMLViewKey.TYPE_FORM,
CONTEXT_BEFORE_LOGIN,
XMLViewKey.VIEW_MOBILE,
"/xml/com/foc/admin/HomePage_BeforeLogin_Mobile_Form.xml", 0, HomePage_BeforeLogin_Form.class.getName());
XMLViewDictionary.getInstance().put(
FocLogLineDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TREE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/Log_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
FocLogLineDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/Log_Table.xml", 0, null);
XMLViewDictionary.getInstance().put(
GroupXMLViewDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TABLE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/GroupXMLView_Table.xml", 0, GroupXMLView_Table.class.getName());
XMLViewDictionary.getInstance().put(
GroupXMLViewDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/GroupXMLView_Form.xml", 0, GroupXMLView_Form.class.getName());
XMLViewDictionary.getInstance().put(
MenuRightsDesc.getInstance().getStorageName(),
XMLViewKey.TYPE_TREE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/MenuRights_Tree.xml", 0, null);
XMLViewDictionary.getInstance().put(
OPTION_WINDOW_STORAGE,
XMLViewKey.TYPE_FORM,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/OptionDialog_Form.xml", 0, OptionDialog_Form.class.getName());
XMLViewDictionary.getInstance().put(
RIGHT_PANEL_STORAGE,
XMLViewKey.TYPE_TREE,
XMLViewKey.CONTEXT_DEFAULT,
XMLViewKey.VIEW_DEFAULT,
"/xml/com/foc/admin/FocRightPanel_Tree.xml", 0, FocRightPanel_Tree.class.getName());
}
public void menu_FillMenuTree(FVMenuTree menuTree, FocMenuItem fatherMenuItem) {
FocMenuItem systemMenu = menuTree.pushRootMenu("System", "System");
FocMenuItem menuItem = systemMenu.pushMenu("ADAPT_DATA_MODEL", "Adapt Data Model");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
OptionDialog dialog = new OptionDialog("Adapt data to model","This may take a few minutes to adapt the database tables and fields according to the executable's version.") {
@Override
public boolean executeOption(String optionName) {
if(optionName != null && optionName.equals("ADAPT")){
Globals.getApp().adaptDataModel(false, false);
}
return false;
}
};
dialog.addOption("ADAPT", "Yes Adapt");
dialog.addOption("CANCEL", "No Cancel Adapt");
dialog.setWidth("500px");
dialog.setHeight("200px");
Globals.popupDialog(dialog);
}
});
menuItem = systemMenu.pushMenu("ADAPT_DATA_MODEL_FORCED", "Adapt Data Model - Forced");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
OptionDialog dialog = new OptionDialog("Adapt data to model","This may take a few minutes to adapt the database tables and fields according to the executable's version.") {
@Override
public boolean executeOption(String optionName) {
if(optionName != null && optionName.equals("ADAPT")){
Globals.getApp().adaptDataModel(true, false);
}
return false;
}
};
dialog.addOption("ADAPT", "Yes Adapt");
dialog.addOption("CANCEL", "No Cancel Adapt");
dialog.setWidth("500px");
dialog.setHeight("200px");
Globals.popupDialog(dialog);
}
});
menuItem = systemMenu.pushMenu("ACTIVE_USERS", "Active Users");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
if(FocWebServer.getInstance() != null) {
FocWebServer.getInstance().removeApplicationsNotRunning();
}
FocList list = new FocList(new FocLinkSimple(ActiveUserDesc.getInstance()));
for(int i=0; i<FocWebServer.getInstance().getApplicationCount(); i++){
FocWebApplication app = FocWebServer.getInstance().getApplicationAt(i);
if(app != null && app.getFocWebSession() != null && app.getFocWebSession().getFocUser() != null && !app.isClosing()){
FocUser user = app.getFocWebSession().getFocUser();
if(user != null){
Company company = user.getCurrentCompany();
WFSite site = user.getCurrentSite();
WFTitle title = user.getCurrentTitle();
ActiveUser activeUser = (ActiveUser) list.newEmptyItem();
activeUser.setUserCompany(company);
activeUser.setUser(user);
activeUser.setUserSite(site);
activeUser.setUserTitle(title);
long lastHeartBeat = app.getLastHeartbeatTimestamp();
Date lastHeartBeatDate = new Date(lastHeartBeat);
activeUser.setLastHeartBeat(lastHeartBeatDate);
list.add(activeUser);
}
}
}
XMLViewKey xmlViewKey = new XMLViewKey(ActiveUserDesc.getInstance().getStorageName(), XMLViewKey.TYPE_TABLE);
ICentralPanel centralPanel = XMLViewDictionary.getInstance().newCentralPanel((FocWebVaadinWindow) mainWindow, xmlViewKey, list);
centralPanel.setFocDataOwner(true);
mainWindow.changeCentralPanelContent(centralPanel, true);
}
});
menuItem = systemMenu.pushMenu("ADMIN_CLEAR_LOGGER", "Clear Logger Tree");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
FocLogger.getInstance().dispose();
}
});
menuItem = systemMenu.pushMenu("FREE_UNUSED_MEMORY", "Free unused memory");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
// INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
String beforeMessage = Globals.logMemory("Before freeing ");
System.gc();
Globals.logMemory("");
System.gc();
Globals.logMemory("");
System.gc();
String afterMessage = Globals.logMemory("After freeing ");
Globals.showNotification(beforeMessage, afterMessage, IFocEnvironment.TYPE_HUMANIZED_MESSAGE);
}
});
menuItem = systemMenu.pushMenu("MEMORY", "Memory");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
String message = Globals.logMemory("");
Globals.showNotification("", message, IFocEnvironment.TYPE_HUMANIZED_MESSAGE);
}
});
FocMenuItem mainMenu = menuTree.pushRootMenu("Admin", "Admin");
menuItem = mainMenu.pushMenu("FOC_USER", "Users");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
FocList focList = FocUserDesc.getList();
mainWindow.changeCentralPanelContent_ToTableForFocList(focList);
}
});
menuItem = mainMenu.pushMenu("DOC_RIGHTS_GROUPS", "Doc Rights Group");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
FocList focList = DocRightsGroupDesc.getInstance().getFocList();
mainWindow.changeCentralPanelContent_ToTableForFocList(focList);
}
});
menuItem = mainMenu.pushMenu("FOC_GROUP", "Groups");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
FocList focList = FocGroup.getList(FocList.LOAD_IF_NEEDED);
mainWindow.changeCentralPanelContent_ToTableForFocList(focList);
}
});
menuItem = mainMenu.pushMenu("APP_CONFIG", "App Configuration");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
SaaSConfig appConfiguration = SaaSConfig.getInstance();
XMLViewKey xmlViewKey = new XMLViewKey(SaaSConfigDesc.getInstance().getStorageName(), XMLViewKey.TYPE_FORM);
ICentralPanel centralPanel = XMLViewDictionary.getInstance().newCentralPanel(mainWindow, xmlViewKey, appConfiguration);
mainWindow.changeCentralPanelContent(centralPanel, true);
}
});
menuItem = mainMenu.pushMenu("APP_CONFIGURATOR", "Adapt User Rights");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
SaaSApplicationAdaptor adapter = SaaSConfig.getInstance().getSaasApplicationAdaptor();
adapter.adaptApplication(true);
adapter.adaptUserRights();
}
});
menuItem = mainMenu.pushMenu("ADMIN_DOWNLOAD_USER_ACCESS", "Download user access to modules");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
UserModuleList list = new UserModuleList();
list.fill();
UserModuleAccess_ExcelExport userExport = new UserModuleAccess_ExcelExport(list);
userExport.init();
userExport.dispose();
list.dispose();
}
});
menuItem = mainMenu.pushMenu("FOC_MIGRATION_SOURCE", "Migration Source");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
FocList focList = MigrationSourceDesc.getInstance().getFocList();
mainWindow.changeCentralPanelContent_ToTableForFocList(focList);
}
});
menuItem = mainMenu.pushMenu("DOCUMENT_HEADER_EDIT", "Document header format");
menuItem.setExtraAction0("Reset");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
if(extraActionIndex == 0){
XMLViewKey key = XMLViewDictionary.getInstance().newXMLViewKey_ForDocumentHeader(XMLViewKey.VIEW_DEFAULT);
XMLView view = XMLViewDictionary.getInstance().get(key);
FocWebApplication.getInstanceForThread().addWindow(new XMLEditor(view, "Document header", view.getXmlviewDefinition().getXML()));
}else if(extraActionIndex == 1){
OptionDialog dialog = new OptionDialog("Confirmation", "Are you sure you want to reset the transaction header layout?"){
public boolean executeOption(String optionName){
if(optionName.equals("YES")){
XMLViewKey key = XMLViewDictionary.getInstance().newXMLViewKey_ForDocumentHeader(XMLViewKey.VIEW_DEFAULT);
XMLView view = XMLViewDictionary.getInstance().get(key);
if(view != null){
XMLViewDictionary.getInstance().updateDocumentHearerView(view.getXmlviewDefinition());
}
}
return false;
}
};
dialog.addOption("YES", "Yes reset");
dialog.addOption("CANCEL", "No cancel");
dialog.setWidth("500px");
dialog.setHeight("200px");
Globals.popupDialog(dialog);
}
}
});
menuItem = mainMenu.pushMenu("DOCUMENT_HEADER_PRINT_EDIT", "Document header printing format");
menuItem.setExtraAction0("Reset");
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
if(extraActionIndex == 0){
XMLViewKey key = XMLViewDictionary.getInstance().newXMLViewKey_ForDocumentHeader(XMLViewKey.VIEW_PRINTING);
XMLView view = XMLViewDictionary.getInstance().get_WithoutAdjustToLastSelection(key);
FocWebApplication.getInstanceForThread().addWindow(new XMLEditor(view, "Document header", view.getXmlviewDefinition().getXML()));
}else if(extraActionIndex == 1){
OptionDialog dialog = new OptionDialog("Confirmation", "Are you sure you want to reset the transaction header printing layout?"){
public boolean executeOption(String optionName){
if(optionName.equals("YES")){
XMLViewKey key = XMLViewDictionary.getInstance().newXMLViewKey_ForDocumentHeader(XMLViewKey.VIEW_PRINTING);
XMLView view = XMLViewDictionary.getInstance().get(key);
if(view != null){
XMLViewDictionary.getInstance().updateDocumentHearerView_Printing(view.getXmlviewDefinition());
} }
return false;
}
};
dialog.addOption("YES", "Yes reset");
dialog.addOption("CANCEL", "No cancel");
Globals.popupDialog(dialog);
}
}
});
FocMenuItem countryPresetingsMenu = null;
if(FocWebServer.getInstance() != null && FocWebServer.getInstance().applicationConfigurators_Size() > 0){
for(int i=0; i<FocWebServer.getInstance().applicationConfigurators_Size(); i++){
IApplicationConfigurator config = FocWebServer.getInstance().applicationConfigurators_Get(i);
if(countryPresetingsMenu == null){
countryPresetingsMenu = mainMenu.pushMenu("Country Presettings", "Country presettings");
}
FocMenuItem countryMenuItem = countryPresetingsMenu.pushMenu(config.getCode(), config.getTitle());
countryMenuItem.setMenuAction(config);
}
}
URI uri = Page.getCurrent().getLocation();
if(Globals.getApp().isUnitTest()){
menuItem = mainMenu.pushMenu(MNU_CODE_UNIT_TEST_LOG, "Unit Test Logs");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
FocUnitDictionary.getInstance().popupLogger(mainWindow);
}
});
}
if(ConfigInfo.isUnitAllowed() && uri.getHost().equals("localhost")){
menuItem = mainMenu.pushMenu("UNIT_TEST_LOG", "Unit Test Logs");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
FocUnitDictionary.getInstance().popupLogger(mainWindow);
}
});
FocMenuItem unitTestingMenuList = mainMenu.pushMenu("UNIT_TEST", "Unit Tests");
FocUnitDictionary dictionary = FocUnitDictionary.getInstance();
Collection<FocUnitTestingSuite> collection = dictionary != null ? dictionary.getTestingSuiteMapValues() : null;
if(collection != null){
Iterator<FocUnitTestingSuite> itr = collection.iterator();
while(itr != null && itr.hasNext()) {
final FocUnitTestingSuite suite = (FocUnitTestingSuite)itr.next();
if(suite.isShowInMenu()){
menuItem = unitTestingMenuList.pushMenu(suite.getName(), suite.getName());
menuItem.setMenuAction(new IFocMenuItemAction() {
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
INavigationWindow mainWindow = (INavigationWindow) navigationWindow;
FocUnitDictionary dictionary = FocUnitDictionary.getInstance();
try{
dictionary.runUnitTest(suite.getName());
}catch (Exception e){
Globals.logException(e);
}
dictionary.popupLogger(mainWindow);
}
});
}
}
}
}
menuItem = mainMenu.pushMenu("MAKE_DATA_ANONIMOUS", "_Make Data Anonimous");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
OptionDialogWindow optionWindow = new OptionDialogWindow("ARE YOU SURE YOU WANT TO LOOSE DATA NAMES!!!!! (NOT RECOMMENDED) SHOULD NEVER BE USED FOR PRODUCTION REAL DATA !!!!!!!!!!! !!!!!!!!!!!! !!!!!!!!!!!!! !!!!!!!!!!!11", null);
optionWindow.setWidth("500px");
optionWindow.setHeight("200px");
optionWindow.addOption("Yes, Loose Data", new IOption() {
@Override
public void optionSelected(Object contextObject) {
FocWebServer.getInstance().makeDataAnonymous();
}
});
optionWindow.addOption("Cancel", new IOption() {
@Override
public void optionSelected(Object contextObject) {
}
});
FocWebApplication.getInstanceForThread().addWindow(optionWindow);
}
});
FocMenuItem autoPopulateMenu = null;
Iterator<IFocDescDeclaration> focDescDeclarationIterator = Globals.getApp().getFocDescDeclarationIterator();
while(focDescDeclarationIterator != null && focDescDeclarationIterator.hasNext()){
IFocDescDeclaration focDescDeclaration = focDescDeclarationIterator.next();
if(focDescDeclaration != null){
FocDesc focDesc = focDescDeclaration.getFocDescription();
if(focDesc instanceof AutoPopulatable){
final AutoPopulatable autoPopulatable = (AutoPopulatable) focDesc;
if(autoPopulateMenu == null){
autoPopulateMenu = mainMenu.pushMenu("AUTO_POPULATE", "Auto Populate");
FocMenuItem allautoPopulateMenu = autoPopulateMenu.pushMenu("ALL_AUTO_POPULATE", "All Auto Populate");
if(allautoPopulateMenu != null){
allautoPopulateMenu.setMenuAction(new AllAutoPopulateListener());
}
}
final String autoPopulatableTitle = autoPopulatable.getAutoPopulatableTitle();
FocMenuItem autoPopulatableMenuItem = autoPopulateMenu.pushMenu(autoPopulatableTitle.toUpperCase(), autoPopulatableTitle);
autoPopulatableMenuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
OptionDialog optionDialog = new OptionDialog("Confirm Auto Populate", "This may take a few minutes to populate " + autoPopulatableTitle){
@Override
public boolean executeOption(String optionName) {
if(optionName.equals("OK_BUTTON")){
autoPopulatable.populate();
}
return false;
}
};
optionDialog.addOption("OK_BUTTON", "Auto Populate");
optionDialog.addOption("CANCEL", "Cancel");
optionDialog.setWidth("500px");
optionDialog.setHeight("200px");
Globals.popupDialog(optionDialog);
}
});
}
}
}
menuItem = mainMenu.pushMenu("GENERATE_MOBILE_APP_SOURCE", "_Generate Source Code For Mobile Apps");
menuItem.setMenuAction(new IFocMenuItemAction() {
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
String rootDir = "C:/eclipseworkspace_everpro/xeverpro/src/com/barmaja/everpro/mobileApp/modules";
String rootPackkage = "com.barmaja.everpro.mobileApp.modules";
TableDefinition tableDef = TableDefinition.getTableDefinitionForFocDesc(ContactDesc.getInstance());
CodeWriterSet cws = new CodeWriterSet(tableDef);
CodeWriter codeWriter = null;
codeWriter = cws.getCodeWriter_Proxy();
codeWriter.generateCode();
codeWriter = null;
}
});
}
public class AllAutoPopulateListener implements IFocMenuItemAction{
@Override
public void actionPerformed(Object navigationWindow, FocMenuItem menuItem, int extraActionIndex) {
OptionDialog optionDialog = new OptionDialog("Auto populate", "This may take a few minutes to auto populate all modules.") {
@Override
public boolean executeOption(String option) {
if(option.equals("YES")){
Iterator<IFocDescDeclaration> focDescDeclarationIterator = Globals.getApp().getFocDescDeclarationIterator();
while(focDescDeclarationIterator != null && focDescDeclarationIterator.hasNext()){
IFocDescDeclaration focDescDeclaration = focDescDeclarationIterator.next();
if(focDescDeclaration != null){
FocDesc focDesc = focDescDeclaration.getFocDescription();
if(focDesc instanceof AutoPopulatable){
AutoPopulatable autoPopulatable = (AutoPopulatable) focDesc;
if(autoPopulatable != null){
autoPopulatable.populate();
}
}
}
}
}
return false;
}
};
optionDialog.addOption("YES", "Yes");
optionDialog.addOption("CANCEL", "Cancel");
optionDialog.setWidth("600px");
optionDialog.setHeight("170px");
Globals.popupDialog(optionDialog);
}
}
} |
package pattypan;
import java.io.File;
import java.util.Map;
public class UploadElement {
private Map<String, String> data;
private String wikicode;
public UploadElement() {
}
public UploadElement(Map<String, String> data, String wikicode) {
this.data = data;
this.wikicode = wikicode;
}
public Map<String, String> getData() {
return data;
}
public File getFile() {
return new File(getData("path"));
}
public String getData(String key) {
return data.get(key);
}
public String getWikicode() {
return wikicode + "\n[[Category:Uploaded with pattypan]]";
}
public UploadElement setData(Map<String, String> data) {
this.data = data;
return this;
}
public UploadElement setWikicode(String wikicode) {
this.wikicode = wikicode;
return this;
}
} |
package org.peerbox;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertyHandler {
PropertyHandler propHandler = new PropertyHandler();
static Properties prop = new Properties();
//check if property file is already existing in project folder
public static void checkFileExists(){
File f = new File("config.properties");
if(f.exists() && !f.isDirectory()) {
//read in property file
loadPropertyFile();
System.out.println("Existing property file found.");
} else {
//create new property file if no existing is found
createPropertyFile();
}
}
//load existing property file
public static void loadPropertyFile(){
InputStream input = null;
try {
input = new FileInputStream("config.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// load a properties file
try {
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
//if no property file is found, a new one will be written to the project folder
public static void createPropertyFile(){
try {
//Dummy test set
prop.setProperty("peerAddress", "localhost");
prop.setProperty("username", "myuser");
prop.setProperty("password", "mypwd");
prop.setProperty("pin", "1234");
//save properties to project root folder
prop.store(new FileOutputStream("config.properties"), null);
System.out.println("New property file created.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
//write root path from SelectRootPathController to property file
public static void setRootPath(String path){
try {
prop.setProperty("rootpath",path);
//save properties to project root folder
prop.store(new FileOutputStream("config.properties"),null);
System.out.println("Root path stored in property file.");
} catch (IOException ex) {
ex.printStackTrace();
}
}
//check whether the property file already holds a rootpath property
public static boolean rootPathExists(){
boolean exists = false;
if(prop.getProperty("rootpath") != null){
exists = true;
System.out.println("using rootpath from property file.");
}
return exists;
}
//returns rootpath value from property file
public static String getRootPath(){
String path = prop.getProperty("rootpath");
return path;
}
} |
package com.psddev.dari.db;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.psddev.dari.util.DebugFilter;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PaginatedResult;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.UuidUtils;
@DebugFilter.Path("query")
@SuppressWarnings("serial")
public class QueryDebugServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
@SuppressWarnings("all")
Page page = new Page(getServletContext(), request, response);
page.render();
}
private static class Page extends DebugFilter.PageWriter {
private final Pattern ID_PATTERN = Pattern.compile("([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})");
private final Pattern DATE_FIELD_PATTERN = Pattern.compile("(?m)^(\\s*\".*\" : (\\d{11,}),)$");
public static final double INITIAL_VISIBILITY_HUE = Math.random();
private enum SortOrder {
ASCENDING("Ascending"),
DESCENDING("Descending");
public final String displayName;
private SortOrder(String displayName) {
this.displayName = displayName;
}
}
private enum SubAction {
RAW("Raw"),
EDIT_RAW("Edit Raw"),
EDIT_FIELDED("Edit Fielded");
public final String displayName;
private SubAction(String displayName) {
this.displayName = displayName;
}
}
private final String databaseName;
private Database database;
private final ObjectType type;
private final String where;
private final String sortField;
private final SortOrder sortOrder;
private final String additionalFieldsString;
private final String ignoreReadConnectionString;
private final boolean ignoreReadConnection;
private final long offset;
private final int limit;
private final String filter;
private final boolean showVisible;
private final Map<String, List<String>> visibilityFilters;
private final Map<String, Double> visibilityColors;
private final Query<Object> query;
public Page(ServletContext context, HttpServletRequest request, HttpServletResponse response) throws IOException {
super(context, request, response);
databaseName = page.param(String.class, "db");
database = Database.Static.getInstance(databaseName);
type = database.getEnvironment().getTypeById(page.param(UUID.class, "from"));
where = page.paramOrDefault(String.class, "where", "").trim();
sortField = page.param(String.class, "sortField");
sortOrder = page.paramOrDefault(SortOrder.class, "sortOrder", SortOrder.ASCENDING);
additionalFieldsString = page.param(String.class, "additionalFields");
ignoreReadConnectionString = page.param(String.class, "ignoreReadConnection");
ignoreReadConnection = ignoreReadConnectionString == null ? true : Boolean.parseBoolean(ignoreReadConnectionString);
visibilityFilters = new HashMap<String, List<String>>();
boolean showVisible = false;
for (String visibilityFilterString : page.params(String.class, "visibilityFilters")) {
if ("VISIBLE".equals(visibilityFilterString)) {
showVisible = true;
continue;
}
String[] parts = visibilityFilterString.split("\\x7c");
if (parts.length == 2) {
String uniqueIndexName = parts[0];
String indexValue = parts[1];
List<String> indexValues = visibilityFilters.get(uniqueIndexName);
if (indexValues == null) {
indexValues = new ArrayList<String>();
visibilityFilters.put(uniqueIndexName, indexValues);
}
indexValues.add(indexValue);
}
}
if (visibilityFilters.isEmpty()) {
showVisible = true;
}
this.showVisible = showVisible;
visibilityColors = new HashMap<String, Double>();
if (!visibilityFilters.isEmpty()) {
}
offset = page.param(long.class, "offset");
limit = page.paramOrDefault(int.class, "limit", 50);
filter = "Filter".equals(page.param(String.class, "action")) ? page.param(String.class, "filter") : null;
UUID idFromWhere = ObjectUtils.to(UUID.class, where);
if (idFromWhere != null) {
query = Query.from(Object.class).where("_id = ?", idFromWhere);
} else {
if (visibilityFilters.isEmpty()) {
query = Query.fromType(type);
} else {
query = Query.from(Object.class);
}
Double timeout = page.param(Double.class, "timeout");
if (timeout != null) {
query.setTimeout(timeout);
}
if (!visibilityFilters.isEmpty()) {
query.where(getVisibilitiesPredicate());
}
if (!ObjectUtils.isBlank(where)) {
if (visibilityFilters.isEmpty()) {
query.where(where);
} else {
query.where(getFullyQualifiedPredicateForType(type, PredicateParser.Static.parse(where)));
}
}
if (!ObjectUtils.isBlank(sortField)) {
if (SortOrder.DESCENDING.equals(sortOrder)) {
query.sortDescending(sortField);
} else {
query.sortAscending(sortField);
}
}
}
if (ObjectUtils.isBlank(additionalFieldsString) &&
ObjectUtils.isBlank(filter)) {
query.resolveToReferenceOnly();
}
if (ObjectUtils.isBlank(databaseName)) {
query.setDatabase(null);
database = query.getDatabase();
}
CachingDatabase caching = new CachingDatabase();
caching.setDelegate(database);
query.using(caching);
}
public void render() throws IOException {
try {
Database.Static.setIgnoreReadConnection(ignoreReadConnection);
String action = page.param(String.class, "action");
if ("count".equals(action)) {
renderCount();
} else if ("form".equals(action)) {
renderForm();
} else if ("select".equals(action)) {
renderSelect();
} else if ("visibilityFilters".equals(action)) {
renderVisibilityFilters();
} else {
renderDefault();
}
} catch (Exception ex) {
writeObject(ex);
} finally {
Database.Static.setIgnoreReadConnection(false);
}
}
private Predicate getFullyQualifiedPredicateForType(ObjectType type, Predicate predicate) {
if (type == null) {
return predicate;
}
if (predicate instanceof ComparisonPredicate) {
ComparisonPredicate comparison = (ComparisonPredicate) predicate;
String operator = comparison.getOperator();
boolean isIgnoreCase = comparison.isIgnoreCase();
List<Object> values = comparison.getValues();
// try to get the full qualified version of the key based on the type
String key = comparison.getKey();
int slashAt = key.indexOf('/');
if (slashAt >= 0) {
String firstPart = key.substring(0, slashAt);
if (ObjectUtils.getClassByName(firstPart) == null) {
String lastPart = key.substring(slashAt);
ObjectIndex index = type.getIndex(firstPart);
if (index != null) {
key = index.getUniqueName() + lastPart;
}
}
} else {
ObjectIndex index = type.getIndex(key);
if (index != null) {
key = index.getUniqueName();
}
}
return new ComparisonPredicate(operator, isIgnoreCase, key, values);
} else if (predicate instanceof CompoundPredicate) {
CompoundPredicate compound = (CompoundPredicate) predicate;
List<Predicate> children = null;
if (compound.getChildren() != null) {
children = new ArrayList<Predicate>();
for (Predicate child : compound.getChildren()) {
children.add(getFullyQualifiedPredicateForType(type, child));
}
}
return new CompoundPredicate(compound.getOperator(), children);
} else {
return predicate;
}
}
private Predicate getVisibilitiesPredicate() {
if (!visibilityFilters.isEmpty()) {
Predicate visibilityIndexPredicate = null;
for (Map.Entry<String, List<String>> entry : visibilityFilters.entrySet()) {
String indexUniqueName = entry.getKey();
List<String> indexValues = entry.getValue();
Iterator<String> indexValuesIterator = indexValues.iterator();
if (showVisible) {
Predicate predicate = PredicateParser.Static.parse(indexUniqueName + " is missing");
if (visibilityIndexPredicate == null) {
visibilityIndexPredicate = predicate;
} else {
visibilityIndexPredicate = CompoundPredicate.combine(
PredicateParser.OR_OPERATOR,
visibilityIndexPredicate,
predicate);
}
}
while (indexValuesIterator.hasNext()) {
Predicate predicate = PredicateParser.Static.parse(indexUniqueName + " = ?", indexValuesIterator.next());
if (visibilityIndexPredicate == null) {
visibilityIndexPredicate = predicate;
} else {
visibilityIndexPredicate = CompoundPredicate.combine(
PredicateParser.OR_OPERATOR,
visibilityIndexPredicate,
predicate);
}
}
}
Predicate typePredicate = null;
if (type != null) {
Set<UUID> typeIds = new HashSet<UUID>();
if (showVisible) {
for (ObjectType concreteType : type.findConcreteTypes()) {
typeIds.add(concreteType.getId());
}
}
for (Map.Entry<String, List<String>> entry : visibilityFilters.entrySet()) {
String indexUniqueName = entry.getKey();
List<String> indexValues = entry.getValue();
String indexName;
int slashAt = indexUniqueName.indexOf('/');
if (slashAt >= 0) {
indexName = indexUniqueName.substring(slashAt+1);
} else {
indexName = indexUniqueName;
}
typeIds.addAll(getVisbilityTypeIdsForValuesAndTypes(indexName, new HashSet<String>(indexValues), type.findConcreteTypes()));
}
typePredicate = PredicateParser.Static.parse("_type = ?", typeIds);
}
if (typePredicate == null) {
return visibilityIndexPredicate;
} else {
return CompoundPredicate.combine(PredicateParser.AND_OPERATOR, typePredicate, visibilityIndexPredicate);
}
} else {
return PredicateParser.Static.parse("true");
}
}
private Set<UUID> getVisbilityTypeIdsForValuesAndTypes(String indexName, Set<String> indexValues, Set<ObjectType> types) {
Set<UUID> visibilityTypeIds = new HashSet<UUID>();
for (String indexValue : indexValues) {
for (ObjectType type : types) {
byte[] md5 = StringUtils.md5(indexName + "/" + indexValue);
byte[] typeId = UuidUtils.toBytes(type.getId());
for (int i = 0, length = typeId.length; i < length; ++ i) {
typeId[i] ^= md5[i];
}
visibilityTypeIds.add(UuidUtils.fromBytes(typeId));
}
}
return visibilityTypeIds;
}
private ObjectField getVisibilityAwareField(State state) {
@SuppressWarnings("unchecked")
List<String> visibilities = (List<String>) state.get("dari.visibilities");
if (visibilities != null && !visibilities.isEmpty()) {
String fieldName = visibilities.get(visibilities.size() - 1);
ObjectField field = state.getField(fieldName);
return field;
}
return null;
}
private void renderVisibilityFilters() throws IOException {
if (page.param(boolean.class, "showVisibilityFiltersLink")) {
writeStart("a",
"target", "visibilityFilters",
"href", page.url("", "action", "visibilityFilters", "showVisibilityFiltersLink", null));
writeHtml("Show Visibility Filters");
writeEnd();
return;
}
Map<ObjectIndex, List<Object>> visibilityIndexValues = new HashMap<ObjectIndex, List<Object>>();
boolean hasVisibilityValues = false;
for (ObjectIndex index : database.getEnvironment().getIndexes()) {
// ignore inRowIndexes
if (index.isVisibility() && !index.isShortConstant()) {
visibilityIndexValues.put(index, new ArrayList<Object>());
}
}
if (type != null) {
for (ObjectIndex index : type.getIndexes()) {
// ignore inRowIndexes
if (index.isVisibility() && !index.isShortConstant()) {
visibilityIndexValues.put(index, new ArrayList<Object>());
}
}
}
for (Map.Entry<ObjectIndex, List<Object>> entry : visibilityIndexValues.entrySet()) {
ObjectIndex index = entry.getKey();
String uniqueName = index.getUniqueName();
for (Grouping<Object> grouping : Query.from(Object.class).where(uniqueName + " != missing").groupBy(uniqueName)) {
Object key0 = grouping.getKeys().get(0);
if (key0 instanceof byte[]) {
key0 = new String((byte[]) key0);
}
entry.getValue().add(key0);
hasVisibilityValues = true;
}
}
if (!hasVisibilityValues) {
return;
}
writeStart("div", "class", "visibilityFilters");
writeStart("ul", "class", "unstyled");
writeStart("li");
writeTag("input",
"class", "visibility-input",
"type", "checkbox",
"name", "visibilityFilters",
"value", "VISIBLE",
"checked", showVisible ? "checked" : null);
writeStart("span",
"class", "label visibility-label" + (showVisible ? "" : " disabled"),
"title", "Show visible objects",
"style", "background-color: #000;");
writeObject("VISIBLE");
writeEnd();
writeEnd();
double goldenRatio = 0.618033988749895;
double hue = INITIAL_VISIBILITY_HUE;
for (Map.Entry<ObjectIndex, List<Object>> entry : visibilityIndexValues.entrySet()) {
ObjectIndex index = entry.getKey();
List<Object> visibilityValues = entry.getValue();
ObjectField field = null;
ObjectType declaringType = null;
Class<?> declaringClass = ObjectUtils.getClassByName(index.getJavaDeclaringClassName());
if (declaringClass != null) {
declaringType = ObjectType.getInstance(declaringClass);
if (declaringType != null) {
field = declaringType.getField(index.getName());
}
}
for (Object visibilityValue : visibilityValues) {
hue += goldenRatio;
hue %= 1.0;
visibilityColors.put(index.getUniqueName() + "/" + visibilityValue, hue);
boolean visibilityValueChecked = false;
if (visibilityFilters != null) {
List<String> selectedVisibilityValues = visibilityFilters.get(index.getUniqueName());
if (selectedVisibilityValues != null) {
visibilityValueChecked = selectedVisibilityValues.contains(visibilityValue);
}
}
String visibilityLabel = visibilityValue.toString();
try {
if (field != null) {
State state = new State();
state.put(index.getName(), visibilityValue);
Object declaringObject = state.as(declaringClass);
if (declaringObject instanceof VisibilityLabel) {
visibilityLabel = ((VisibilityLabel) declaringObject).createVisibilityLabel(field);
}
}
} catch (Exception e) {
}
writeStart("li");
writeTag("input",
"class", "visibility-input",
"type", "checkbox",
"name", "visibilityFilters",
"value", index.getUniqueName() + "|" + visibilityValue,
"checked", visibilityValueChecked ? "checked" : null);
writeStart("span",
"class", "label visibility-label" + (visibilityValueChecked ? "" : " disabled"),
"title", index.getUniqueName(),
"style", "background: hsl(" + (hue * 360) + ",50%,50%);");
writeObject(visibilityLabel);
writeEnd();
writeEnd();
}
}
writeEnd();
writeEnd();
}
private void renderCount() throws IOException {
try {
if (query.getTimeout() == null) {
query.setTimeout(1.0);
}
writeObject(query.count());
} catch (Exception ex) {
writeHtml("Many (");
writeStart("a", "href", page.url("", "timeout", 0));
writeHtml("Force Count");
writeEnd();
writeHtml(")");
}
}
@SuppressWarnings("unchecked")
private void renderForm() throws IOException {
State state = State.getInstance(Query.from(Object.class).where("_id = ?", page.param(UUID.class, "id")).using(database).first());
if (state == null) {
writeStart("p", "class", "alert").writeHtml("No object!").writeEnd();
} else {
ObjectType type = state.getType();
writeStart("div", "class", "edit", "style", "padding: 10px;");
writeStart("h2");
writeHtml(type != null ? type.getLabel() : "Unknown Type");
writeHtml(": ");
writeHtml(state.getLabel());
writeEnd();
SubAction subAction = page.paramOrDefault(SubAction.class, "subAction", SubAction.RAW);
writeStart("ul", "class", "nav nav-tabs");
for (SubAction a : SubAction.values()) {
writeStart("li", "class", a.equals(subAction) ? "active" : null);
writeStart("a", "href", page.url("", "subAction", a));
writeHtml(a.displayName);
writeEnd();
writeEnd();
}
writeEnd();
if (SubAction.EDIT_RAW.equals(subAction)) {
if (page.isFormPost()) {
try {
state.setValues((Map<String, Object>) ObjectUtils.fromJson(page.param(String.class, "data")));
state.save();
writeStart("p", "class", "alert alert-success").writeHtml("Saved successfully at " + new Date() + "!").writeEnd();
} catch (Exception error) {
writeStart("div", "class", "alert alert-error").writeObject(error).writeEnd();
}
}
writeStart("form", "method", "post", "action", page.url(""));
writeStart("div", "class", "json");
writeStart("textarea", "name", "data", "style", "box-sizing: border-box; height: 40em; width: 100%;");
writeHtml(ObjectUtils.toJson(state.getSimpleValues(), true));
writeEnd();
writeEnd();
writeStart("div", "class", "form-actions");
writeTag("input", "class", "btn btn-success", "type", "submit", "value", "Save");
writeEnd();
writeEnd();
} else if (SubAction.EDIT_FIELDED.equals(subAction)) {
@SuppressWarnings("all")
FormWriter form = new FormWriter(this);
form.putAllStandardInputProcessors();
if (page.isFormPost()) {
try {
form.updateAll(state, page.getRequest());
state.save();
writeStart("p", "class", "alert alert-success").writeHtml("Saved successfully at " + new Date() + "!").writeEnd();
} catch (Exception error) {
writeStart("div", "class", "alert alert-error").writeObject(error).writeEnd();
}
}
writeStart("form", "method", "post", "action", page.url(""));
form.allInputs(state);
writeStart("div", "class", "form-actions");
writeTag("input", "class", "btn btn-success", "type", "submit", "value", "Save");
writeEnd();
writeEnd();
} else {
writeStart("pre");
String json = ObjectUtils.toJson(state.getSimpleValues(), true);
Matcher dateFieldMatcher = DATE_FIELD_PATTERN.matcher(json);
StringBuilder newJson = new StringBuilder();
int end = 0;
for (; dateFieldMatcher.find(); end = dateFieldMatcher.end()) {
String dateString = dateFieldMatcher.group(2);
newJson.append(json.substring(end, dateFieldMatcher.start()));
newJson.append(dateFieldMatcher.group(1));
newJson.append(" /* ");
newJson.append(ObjectUtils.to(Date.class, dateString));
newJson.append(" */");
}
newJson.append(json.substring(end));
Matcher idMatcher = ID_PATTERN.matcher(page.h(newJson.toString()));
write(idMatcher.replaceAll("<a href=\"/_debug/query?where=id+%3D+$1\" target=\"_blank\">$1</a>"));
writeEnd();
writeEnd();
}
}
}
private void renderSelect() throws IOException {
writeStart("div", "style", "padding: 10px;");
writeStart("form", "action", page.url(null), "class", "form-inline", "method", "get");
writeStart("h2").writeHtml("Query").writeEnd();
writeStart("div", "class", "row");
writeStart("div", "class", "span6");
writeStart("select", "class", "span6", "name", "from");
writeStart("option", "value", "").writeHtml("ALL TYPES").writeEnd();
List<ObjectType> types = new ArrayList<ObjectType>(database.getEnvironment().getTypes());
Collections.sort(types, new ObjectFieldComparator("name", false));
for (ObjectType t : types) {
if (!t.isEmbedded()) {
writeStart("option",
"selected", t.equals(type) ? "selected" : null,
"value", t.getId());
writeHtml(t.getLabel());
writeHtml(" (");
writeHtml(t.getInternalName());
writeHtml(")");
writeEnd();
}
}
writeEnd();
includeStylesheet("/_resource/chosen/chosen.css");
includeScript("/_resource/chosen/chosen.jquery.min.js");
writeStart("script", "type", "text/javascript");
write("(function() {");
write("$('select[name=from]').chosen({ 'search_contains': true });");
write("})();");
writeEnd();
writeStart("textarea",
"class", "span6",
"name", "where",
"placeholder", "ID or Predicate (Leave Blank to Return All)",
"rows", 4,
"style", "margin-bottom: 4px; margin-top: 4px;");
writeHtml(where);
writeEnd();
writeTag("input", "class", "btn btn-primary", "type", "submit", "name", "action", "value", "Run");
writeEnd();
writeStart("div", "class", "span6");
writeStart("select", "name", "db", "style", "margin-bottom: 4px;");
writeStart("option",
"value", "",
"selected", ObjectUtils.isBlank(databaseName) ? "selected" : null);
writeHtml("Default");
writeEnd();
for (Database db : Database.Static.getAll()) {
String dbName = db.getName();
writeStart("option",
"value", dbName,
"selected", dbName.equals(databaseName) ? "selected" : null);
writeHtml(dbName);
writeEnd();
}
writeEnd();
writeTag("br");
writeTag("input",
"class", "input-small",
"name", "sortField",
"type", "text",
"placeholder", "Sort",
"value", sortField);
writeHtml(' ');
writeStart("select", "class", "input-small", "name", "sortOrder");
for (SortOrder so : SortOrder.values()) {
writeStart("option",
"selected", so.equals(sortOrder) ? "selected" : null,
"value", so.name());
writeHtml(so.displayName);
writeEnd();
}
writeEnd();
writeHtml(' ');
writeTag("input",
"class", "input-small",
"name", "limit",
"type", "text",
"placeholder", "Limit",
"value", limit);
writeTag("br");
writeTag("input",
"class", "span6",
"name", "additionalFields",
"type", "text",
"placeholder", "Additional Fields (Comma Separated)",
"style", "margin-top: 4px;",
"value", additionalFieldsString);
writeEnd();
writeEnd();
writeEnd();
try {
PaginatedResult<Object> result = query.select(offset, limit);
List<Object> items = result.getItems();
if (offset == 0 && items.isEmpty()) {
writeStart("p", "class", "alert").writeHtml("No matches!").writeEnd();
} else {
writeStart("h2");
writeHtml("Result ");
writeObject(result.getFirstItemIndex());
writeHtml(" to ");
writeObject(result.getLastItemIndex());
writeHtml(" of ");
writeStart("span", "class", "frame");
writeStart("a", "href", page.url("", "action", "count")).writeHtml("?").writeEnd();
writeEnd();
writeEnd();
writeStart("div", "class", "btn-group");
writeStart("a",
"class", "btn" + (offset > 0 ? "" : " disabled"),
"href", page.url("", "offset", 0));
writeStart("i", "class", "icon-fast-backward").writeEnd();
writeHtml(" First");
writeEnd();
writeStart("a",
"class", "btn" + (result.hasPrevious() ? "" : " disabled"),
"href", page.url("", "offset", result.getPreviousOffset()));
writeStart("i", "class", "icon-step-backward").writeEnd();
writeHtml(" Previous");
writeEnd();
writeStart("a",
"class", "btn" + (result.hasNext() ? "" : " disabled"),
"href", page.url("", "offset", result.getNextOffset()));
writeHtml("Next ");
writeStart("i", "class", "icon-step-forward").writeEnd();
writeEnd();
writeEnd();
String[] additionalFields;
if (ObjectUtils.isBlank(additionalFieldsString)) {
additionalFields = new String[0];
} else {
additionalFields = additionalFieldsString.trim().split("\\s*,\\s*");
}
writeStart("table", "class", "table table-condensed");
writeStart("thead");
writeStart("tr");
writeStart("th").writeHtml("#").writeEnd();
writeStart("th").writeHtml("ID").writeEnd();
writeStart("th").writeHtml("Type").writeEnd();
writeStart("th").writeHtml("Label").writeEnd();
for (String additionalField : additionalFields) {
writeStart("th").writeHtml(additionalField).writeEnd();
}
writeEnd();
writeEnd();
writeStart("tbody");
long offsetCopy = offset;
for (Object item : items) {
State itemState = State.getInstance(item);
ObjectType itemType = itemState.getType();
writeStart("tr");
writeStart("td").writeHtml(++ offsetCopy).writeEnd();
writeStart("td");
writeStart("span",
"class", "link",
"onclick",
"var $input = $(this).popup('source').prev();" +
"$input.val('" + itemState.getId() + "');" +
"$input.prev().text('" + StringUtils.escapeJavaScript(itemState.getLabel()) + "');" +
"$(this).popup('close');" +
"return false;");
writeHtml(itemState.getId());
writeEnd();
writeEnd();
writeStart("td").writeHtml(itemType != null ? itemType.getLabel() : null).writeEnd();
writeStart("td").writeHtml(itemState.getLabel()).writeEnd();
for (String additionalField : additionalFields) {
writeStart("td").writeHtml(itemState.getByPath(additionalField)).writeEnd();
}
writeEnd();
}
writeEnd();
writeEnd();
}
} catch (Exception ex) {
writeStart("div", "class", "alert alert-error");
writeObject(ex);
writeEnd();
}
writeEnd();
}
private void renderDefault() throws IOException {
startPage("Database", "Query");
writeStart("style", "type", "text/css");
write(".edit input[type=text], .edit textarea { width: 90%; }");
write(".edit textarea { min-height: 6em; }");
// for visibility filters
write(".visibilityFilters li { display: inline-block; }");
write(".visibilityFilters input::-moz-focus-inner { border: 0; padding: 0; outline: 0; }");
write(".visibilityFilters .visibility-input { margin-right: 4px; }");
write(".visibilityFilters .visibility-label { margin-right: 12px; cursor: pointer }");
write(".visibilityFilters .visibility-label { -moz-user-select: none; -ms-user-select: none; -o-user-select: none; -webkit-user-select: none; user-select: none; }");
write(".visibilityFilters .visibility-label.disabled { background: #999 !important; }");
writeEnd();
includeStylesheet("/_resource/jquery/jquery.objectId.css");
includeStylesheet("/_resource/jquery/jquery.repeatable.css");
includeScript("/_resource/jquery/jquery.objectId.js");
includeScript("/_resource/jquery/jquery.repeatable.js");
writeStart("script", "type", "text/javascript");
write("(function() {");
write("$('.repeatable').repeatable();");
write("$('.objectId').objectId();");
// for visibility filters
write("$(document).on('change', '.visibility-input', function(evt) {");
write("var $input = $(evt.target);");
write("$input.next('.visibility-label').toggleClass('disabled', !$input.prop('checked'));");
write("});");
write("$(document).on('click', '.visibility-label', function(evt) {");
write("var $label = $(evt.target);");
write("$label.prev('.visibility-input').trigger('click');");
write("});");
write("$(document).on('change', 'select[name=from]', function(evt) {");
write("console.log('changed!', $(evt.target).val());");
write("$('.typeChangeForm').find('input[name=from]').val($(evt.target).val()).end().submit();");
write("});");
write("})();");
writeEnd();
writeStart("form", "action", page.url(null), "class", "form-inline", "method", "get");
writeStart("h2").writeHtml("Query").writeEnd();
writeStart("div", "class", "row");
writeStart("div", "class", "span6");
writeStart("select", "class", "span6", "name", "from");
writeStart("option", "value", "").writeHtml("ALL TYPES").writeEnd();
List<ObjectType> types = new ArrayList<ObjectType>(database.getEnvironment().getTypes());
Collections.sort(types, new ObjectFieldComparator("name", false));
for (ObjectType t : types) {
if (!t.isEmbedded()) {
writeStart("option",
"selected", t.equals(type) ? "selected" : null,
"value", t.getId());
writeHtml(t.getLabel());
writeHtml(" (");
writeHtml(t.getInternalName());
writeHtml(")");
writeEnd();
}
}
writeEnd();
includeStylesheet("/_resource/chosen/chosen.css");
includeScript("/_resource/chosen/chosen.jquery.min.js");
writeStart("script", "type", "text/javascript");
write("(function() {");
write("$('select[name=from]').chosen({ 'search_contains': true });");
write("})();");
writeEnd();
writeStart("textarea",
"class", "span6",
"name", "where",
"placeholder", "ID or Predicate (Leave Blank to Return All)",
"rows", 4,
"style", "margin-bottom: 4px; margin-top: 4px;");
writeHtml(where);
writeEnd();
writeTag("input", "class", "btn btn-primary", "type", "submit", "name", "action", "value", "Run");
writeEnd();
writeStart("div", "class", "span6");
writeStart("select", "name", "db", "style", "margin-bottom: 4px;");
writeStart("option",
"value", "",
"selected", ObjectUtils.isBlank(databaseName) ? "selected" : null);
writeHtml("Default");
writeEnd();
for (Database db : Database.Static.getAll()) {
String dbName = db.getName();
writeStart("option",
"value", dbName,
"selected", dbName.equals(databaseName) ? "selected" : null);
writeHtml(dbName);
writeEnd();
}
writeEnd();
writeTag("br");
writeTag("input",
"class", "input-small",
"name", "sortField",
"type", "text",
"placeholder", "Sort",
"value", sortField);
writeHtml(' ');
writeStart("select", "class", "input-small", "name", "sortOrder");
for (SortOrder so : SortOrder.values()) {
writeStart("option",
"selected", so.equals(sortOrder) ? "selected" : null,
"value", so.name());
writeHtml(so.displayName);
writeEnd();
}
writeEnd();
writeHtml(' ');
writeTag("input",
"class", "input-small",
"name", "limit",
"type", "text",
"placeholder", "Limit",
"value", limit);
writeTag("br");
writeTag("input",
"class", "span6",
"name", "additionalFields",
"type", "text",
"placeholder", "Additional Fields (Comma Separated)",
"style", "margin-top: 4px;",
"value", additionalFieldsString);
writeTag("br");
writeStart("label", "class", "checkbox");
writeTag("input",
"name", "ignoreReadConnection",
"type", "checkbox",
"style", "margin-top: 4px;",
"value", "true",
"checked", ignoreReadConnection ? "checked" : null);
writeHtml(" Ignore read-specific connection settings");
writeEnd();
writeTag("br");
writeStart("div", "class", "frame", "name", "visibilityFilters");
if (visibilityFilters.isEmpty()) {
writeStart("a",
"target", "visibilityFilters",
"href", page.url("", "action", "visibilityFilters"));
writeHtml("Show Visibility Filters");
writeEnd();
} else {
renderVisibilityFilters();
}
writeEnd();
writeEnd();
writeEnd();
writeStart("h2", "style", "margin-top: 18px;").writeHtml("Filter").writeEnd();
writeStart("div", "class", "row");
writeStart("div", "class", "span12");
writeStart("textarea",
"class", "span12",
"name", "filter",
"placeholder", "Predicate (Leave Blank to Return All)",
"rows", 2,
"style", "margin-bottom: 4px;");
writeHtml(filter);
writeEnd();
writeTag("input", "class", "btn btn-primary", "type", "submit", "name", "action", "value", "Filter");
writeEnd();
writeEnd();
writeEnd();
writeStart("form",
"target", "visibilityFilters",
"action", page.url("", "action", "visibilityFilters", "from", null),
"class", "form-inline typeChangeForm",
"method", "get");
writeTag("input",
"type", "hidden",
"name", "from",
"value", type != null ? type.getId() : null);
writeTag("input",
"type", "hidden",
"name", "showVisibilityFiltersLink",
"value", "true");
writeEnd();
try {
if (ObjectUtils.isBlank(filter)) {
PaginatedResult<Object> result = query.select(offset, limit);
List<Object> items = result.getItems();
if (offset == 0 && items.isEmpty()) {
writeStart("p", "class", "alert").writeHtml("No matches!").writeEnd();
} else {
writeStart("h2");
writeHtml("Result ");
writeObject(result.getFirstItemIndex());
writeHtml(" to ");
writeObject(result.getLastItemIndex());
writeHtml(" of ");
writeStart("span", "class", "frame");
writeStart("a", "href", page.url("", "action", "count")).writeHtml("?").writeEnd();
writeEnd();
writeEnd();
writeStart("div", "class", "btn-group");
writeStart(offset > 0 ? "a" : "span",
"class", "btn" + (offset > 0 ? "" : " disabled"),
"href", offset > 0 ? page.url("", "offset", 0) : null);
writeStart("i", "class", "icon-fast-backward").writeEnd();
writeHtml(" First");
writeEnd();
writeStart(result.hasPrevious() ? "a" : "span",
"class", "btn" + (result.hasPrevious() ? "" : " disabled"),
"href", result.hasPrevious() ? page.url("", "offset", result.getPreviousOffset()) : null);
writeStart("i", "class", "icon-step-backward").writeEnd();
writeHtml(" Previous");
writeEnd();
writeStart(result.hasNext() ? "a" : "span",
"class", "btn" + (result.hasNext() ? "" : " disabled"),
"href", result.hasNext() ? page.url("", "offset", result.getNextOffset()) : null);
writeHtml("Next ");
writeStart("i", "class", "icon-step-forward").writeEnd();
writeEnd();
writeEnd();
String[] additionalFields;
if (ObjectUtils.isBlank(additionalFieldsString)) {
additionalFields = new String[0];
} else {
additionalFields = additionalFieldsString.trim().split("\\s*,\\s*");
}
writeStart("table", "class", "table table-condensed");
writeStart("thead");
writeStart("tr");
writeStart("th").writeHtml("#").writeEnd();
writeStart("th").writeHtml("ID").writeEnd();
writeStart("th").writeHtml("Type").writeEnd();
if (!visibilityFilters.isEmpty()) {
writeStart("th").writeHtml("Visibility").writeEnd();
}
writeStart("th").writeHtml("Label").writeEnd();
for (String additionalField : additionalFields) {
writeStart("th").writeHtml(additionalField).writeEnd();
}
writeEnd();
writeEnd();
writeStart("tbody");
long offsetCopy = offset;
for (Object item : items) {
State itemState = State.getInstance(item);
ObjectType itemType = itemState.getType();
writeStart("tr");
writeStart("td").writeHtml(++ offsetCopy).writeEnd();
writeStart("td").writeHtml(itemState.getId()).writeEnd();
writeStart("td").writeHtml(itemType != null ? itemType.getLabel() : null).writeEnd();
if (!visibilityFilters.isEmpty()) {
writeStart("td");
String visibilityLabel = itemState.getVisibilityLabel();
if (!StringUtils.isBlank(visibilityLabel)) {
Double hue = null;
ObjectField visibilityField = getVisibilityAwareField(itemState);
if (visibilityField != null) {
Object visibilityValue = itemState.get(visibilityField.getInternalName());
if (visibilityValue != null) {
hue = visibilityColors.get(visibilityField.getUniqueName() + "/" + String.valueOf(visibilityValue).toLowerCase().trim());
}
}
writeStart("span",
"class", "label",
"style", (hue != null ? "background: hsl(" + (hue * 360) + ",50%,50%);" : null));
writeHtmlOrDefault(itemState.getVisibilityLabel(), "?");
writeEnd();
}
writeEnd();
}
writeStart("td");
writeStart("a",
"target", "show",
"href", page.url("",
"action", "form",
"id", itemState.getId()));
writeHtml(itemState.getLabel());
writeEnd();
writeEnd();
for (String additionalField : additionalFields) {
writeStart("td").writeHtml(itemState.getByPath(additionalField)).writeEnd();
}
writeEnd();
}
writeEnd();
writeEnd();
}
} else {
Predicate filterPredicate = PredicateParser.Static.parse(filter);
List<Object> items = new ArrayList<Object>();
writeStart("h2");
writeHtml("Filtered Result");
writeEnd();
String[] additionalFields;
if (ObjectUtils.isBlank(additionalFieldsString)) {
additionalFields = new String[0];
} else {
additionalFields = additionalFieldsString.trim().split("\\s*,\\s*");
}
writeStart("table", "class", "table table-condensed");
writeStart("thead");
writeStart("tr");
writeStart("th").writeHtml("#").writeEnd();
writeStart("th").writeHtml("ID").writeEnd();
writeStart("th").writeHtml("Type").writeEnd();
if (!visibilityFilters.isEmpty()) {
writeStart("th").writeHtml("Visibility").writeEnd();
}
writeStart("th").writeHtml("Label").writeEnd();
for (String additionalField : additionalFields) {
writeStart("th").writeHtml(additionalField).writeEnd();
}
writeEnd();
writeEnd();
writeStart("tbody");
long total = 0;
long matched = 0;
for (Object item : query.iterable(0)) {
++ total;
if (total % 1000 == 0) {
writeStart("tr");
writeStart("td", "colspan", additionalFields.length + 4);
writeHtml("Read ").writeObject(total).writeHtml(" items");
writeEnd();
writeEnd();
flush();
}
if (!PredicateParser.Static.evaluate(item, filterPredicate)) {
continue;
}
++ matched;
items.add(item);
State itemState = State.getInstance(item);
ObjectType itemType = itemState.getType();
writeStart("tr");
writeStart("td").writeHtml(matched).writeEnd();
writeStart("td").writeHtml(itemState.getId()).writeEnd();
writeStart("td").writeHtml(itemType != null ? itemType.getLabel() : null).writeEnd();
if (!visibilityFilters.isEmpty()) {
writeStart("td");
String visibilityLabel = itemState.getVisibilityLabel();
if (!StringUtils.isBlank(visibilityLabel)) {
Double hue = null;
ObjectField visibilityField = getVisibilityAwareField(itemState);
if (visibilityField != null) {
Object visibilityValue = itemState.get(visibilityField.getInternalName());
if (visibilityValue != null) {
hue = visibilityColors.get(visibilityField.getUniqueName() + "/" + String.valueOf(visibilityValue).toLowerCase().trim());
}
}
writeStart("span",
"class", "label",
"style", (hue != null ? "background: hsl(" + (hue * 360) + ",50%,50%);" : null));
writeHtmlOrDefault(itemState.getVisibilityLabel(), "?");
writeEnd();
}
writeEnd();
}
writeStart("td");
writeStart("a", "href", "?where=id+%3D+" + itemState.getId(), "target", "_blank");
writeHtml(itemState.getLabel());
writeEnd();
writeEnd();
for (String additionalField : additionalFields) {
writeStart("td").writeHtml(itemState.getByPath(additionalField)).writeEnd();
}
writeEnd();
if (matched >= limit) {
break;
}
}
writeEnd();
writeEnd();
}
} catch (Exception ex) {
writeStart("div", "class", "alert alert-error");
writeObject(ex);
writeEnd();
}
endPage();
}
}
} |
package org.pwsafe.lib;
import org.apache.commons.logging.LogFactory;
//import org.apache.log4j.Logger;
//import org.apache.log4j.xml.DOMConfigurator;
/**
* This class provides logging facilities using log4j.
*
* @author Kevin Preece
*/
public class Log
{
private int DebugLevel;
private org.apache.commons.logging.Log TheLogger;
static
{
//DOMConfigurator.configure( "log-config.xml" );
}
private Log( String name )
{
//TheLogger = Logger.getLogger( name );
TheLogger = LogFactory.getLog(name);
setDebugLevel( 3 );
}
/**
* Returns an instance of <code>Log</code> for the Log4j logger named <code>name</code>.
*
* @param name the Log4j logger name.
*
* @return An <code>Log</code> instance.
*/
public static Log getInstance( String name )
{
return new Log( name );
}
/**
* Writes a message at debug level 1
*
* @param msg the message to issue.
*/
public void debug1( String msg )
{
if ( isDebug1Enabled() )
{
TheLogger.debug( msg );
}
}
/**
* Writes a message at debug level 2
*
* @param msg the message to issue.
*/
public void debug2( String msg )
{
if ( isDebug2Enabled() )
{
TheLogger.debug( msg );
}
}
/**
* Writes a message at debug level 3
*
* @param msg the message to issue.
*/
public void debug3( String msg )
{
if ( isDebug3Enabled() )
{
TheLogger.debug( msg );
}
}
/**
* Writes a message at debug level 4
*
* @param msg the message to issue.
*/
public void debug4( String msg )
{
if ( isDebug4Enabled() )
{
TheLogger.debug( msg );
}
}
/**
* Writes a message at debug level 5
*
* @param msg the message to issue.
*/
public void debug5( String msg )
{
if ( isDebug5Enabled() )
{
TheLogger.debug( msg );
}
}
/**
* Logs entry to a method.
*
* @param method the method name.
*/
public void enterMethod( String method )
{
if ( TheLogger.isDebugEnabled() )
{
if ( !method.endsWith( ")" ) )
{
method = method + "()";
}
TheLogger.debug( "Entering method " + method );
}
}
/**
* Writes a message at error level
*
* @param msg the message to issue.
*/
public void error( String msg )
{
TheLogger.error( msg );
}
/**
* Writes a message at error level along with details of the exception
*
* @param msg the message to issue.
* @param except the exeption to be logged.
*/
public void error( String msg, Throwable except )
{
TheLogger.error( msg, except );
}
/**
* Logs the exception at a level of error.
*
* @param except the <code>Exception</code> to log.
*/
public void error( Throwable except )
{
TheLogger.error( "An Exception has occurred", except );
}
/**
* Returns the current debug level.
*
* @return Returns the debugLevel.
*/
public int getDebugLevel()
{
return DebugLevel;
}
/**
* Writes a message at info level
*
* @param msg the message to issue.
*/
public void info( String msg )
{
TheLogger.info( msg );
}
/**
* Returns <code>true</code> if debuuging at level 1 is enabled, <code>false</code> if it isn't.
*
* @return <code>true</code> if debuuging at level 1 is enabled, <code>false</code> if it isn't.
*/
public boolean isDebug1Enabled()
{
return TheLogger.isDebugEnabled();
}
/**
* Returns <code>true</code> if debuuging at level 2 is enabled, <code>false</code> if it isn't.
*
* @return <code>true</code> if debuuging at level 2 is enabled, <code>false</code> if it isn't.
*/
public boolean isDebug2Enabled()
{
return TheLogger.isDebugEnabled() && (DebugLevel >= 2);
}
/**
* Returns <code>true</code> if debuuging at level 3 is enabled, <code>false</code> if it isn't.
*
* @return <code>true</code> if debuuging at level 3 is enabled, <code>false</code> if it isn't.
*/
public boolean isDebug3Enabled()
{
return TheLogger.isDebugEnabled() && (DebugLevel >= 3);
}
/**
* Returns <code>true</code> if debuuging at level 4 is enabled, <code>false</code> if it isn't.
*
* @return <code>true</code> if debuuging at level 4 is enabled, <code>false</code> if it isn't.
*/
public boolean isDebug4Enabled()
{
return TheLogger.isDebugEnabled() && (DebugLevel >= 4);
}
/**
* Returns <code>true</code> if debuuging at level 5 is enabled, <code>false</code> if it isn't.
*
* @return <code>true</code> if debuuging at level 5 is enabled, <code>false</code> if it isn't.
*/
public boolean isDebug5Enabled()
{
return TheLogger.isDebugEnabled() && (DebugLevel >= 5);
}
/**
* Logs exit from a method.
*
* @param method the method name.
*/
public void leaveMethod( String method )
{
if ( TheLogger.isDebugEnabled() )
{
if ( !method.endsWith( ")" ) )
{
method = method + "()";
}
TheLogger.debug( "Leaving method " + method );
}
}
/**
* Sets the debug level.
*
* @param debugLevel The debugLevel to set.
*/
public void setDebugLevel( int debugLevel )
{
if ( debugLevel < 1 )
{
debugLevel = 1;
}
else if ( debugLevel > 5 )
{
debugLevel = 5;
}
DebugLevel = debugLevel;
}
/**
* Logs a message at the warning level.
*
* @param msg the message to issue.
*/
public void warn( String msg )
{
TheLogger.warn( msg );
}
} |
package VASSAL.tools;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.zip.ZipFile;
import VASSAL.Info;
import VASSAL.build.GameModule;
import VASSAL.configure.DirectoryConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.preferences.Prefs;
import VASSAL.tools.filechooser.FileChooser;
import VASSAL.tools.image.svg.SVGImageUtils;
import VASSAL.tools.imageop.Op;
import VASSAL.tools.io.FileArchive;
import VASSAL.tools.io.ZipArchive;
import org.apache.commons.lang3.StringUtils;
import javax.swing.JOptionPane;
/**
* An ArchiveWriter is a writeable DataArchive. New files may be added
* with the {@link #addFile} and {@link #addImage} methods. {@link #save()} and {@link #saveAs()} will
* cause the archive to be written out, with FileChooser invoked if appropriate.
*/
public class ArchiveWriter extends DataArchive {
private String archiveName;
private String defaultExtension;
private boolean isTempArchive = false;
/**
* Create a new writeable archive.
*
* @param zipName the name of the archive. If null, the user will be
* prompted for a filename when saving. If not null, new entries will
* be added to the named archive. If the file exists and is not a zip
* archive, it will be overwritten.
* @param defaultExtension the default file extension for the archive.
* If non-null, and the user needs to be prompted for a filename, this will
* be the default file extension added automatically.
*/
public ArchiveWriter(String zipName, String defaultExtension) {
archiveName = zipName;
this.defaultExtension = defaultExtension;
if (archiveName == null) {
isTempArchive = true;
if (this.defaultExtension == null) {
this.defaultExtension = ".zip"; //NON-NLS
}
try {
archiveName = Files.createTempFile(Info.getTempDir().toPath(), "tmp_", this.defaultExtension).toAbsolutePath().toString(); //NON-NLS
}
catch (IOException e) {
WriteErrorDialog.error(e, archiveName);
}
}
final File f = new File(archiveName);
try {
if (f.exists()) {
try {
archive = new ZipArchive(archiveName);
}
catch (IOException e1) {
// the file is not a valid ZIP archive, truncate it
archive = new ZipArchive(archiveName, true);
}
}
else {
archive = new ZipArchive(archiveName);
}
}
catch (IOException e) {
archive = null;
WriteErrorDialog.error(e, archiveName);
}
}
public ArchiveWriter(FileArchive archive, String defaultExtension) {
archiveName = archive.getName();
this.defaultExtension = defaultExtension;
this.archive = archive;
}
/**
* Create a new writeable archive.
*
* @param zipName the name of the archive. If null, the user will be
* prompted for a filename when saving. If not null, new entries will
* be added to the named archive. If the file exists and is not a zip
* archive, it will be overwritten.
*/
public ArchiveWriter(String zipName) {
this(zipName, null);
}
public ArchiveWriter(FileArchive archive) {
this(archive, null);
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public ArchiveWriter(ZipFile archive) {
ProblemDialog.showDeprecated("2020-08-06");
archiveName = archive.getName();
try {
this.archive = new ZipArchive(archiveName);
}
catch (IOException e) {
archive = null;
WriteErrorDialog.error(e, archiveName);
}
}
/**
* Add an image file to the archive. The file will be copied into an
* "images" directory in the archive. Storing another image with the
* same name will overwrite the previous image.
*
* @param path the full path of the image file on the user's filesystem
* @param name the name under which to store the image in the archive
*/
public void addImage(String path, String name) {
// check SVG for external references and pull them in
if (name.toLowerCase().endsWith(".svg")) { //$NON-NLS-1$//
final List<String> exrefs;
try {
exrefs = SVGImageUtils.getExternalReferences(path);
}
catch (IOException e) {
ReadErrorDialog.error(e, name);
return;
}
for (final String s : exrefs) {
final File f = new File(s);
final byte[] buf;
try {
buf = SVGImageUtils.relativizeExternalReferences(s);
}
catch (IOException e) {
ReadErrorDialog.error(e, f);
continue;
}
addFile(imageDir + f.getName(), buf);
}
}
// otherwise just add what we were given
else {
addFile(path, imageDir + name);
}
Op.load(name).update();
localImages = null;
}
public void addImage(String name, byte[] contents) {
addFile(imageDir + name, contents);
localImages = null;
}
public void addSound(String path, String fileName) {
addFile(path, soundDir + fileName);
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public boolean isImageAdded(String name) {
ProblemDialog.showDeprecated("2020-08-06");
try {
return archive.contains(imageDir + name);
}
catch (IOException e) {
return false;
}
}
public void removeImage(String name) {
removeFile(imageDir + name);
localImages = null;
}
/**
* Removes a file in the archive
* @param name file in the archive to be removed
*/
public void removeFile(String name) {
try {
archive.remove(name);
}
catch (IOException e) {
WriteErrorDialog.error(e, archive.getName());
}
}
/**
* Copy a file from the user's filesystem to the archive.
*
* @param path the full path of the file on the user's filesystem
* @param fileName the name under which to store the file in the archive
*/
public void addFile(String path, String fileName) {
try {
archive.add(fileName, path);
}
catch (IOException e) {
WriteErrorDialog.error(e, archive.getName());
}
}
/**
* Copy an <code>InputStream</code> into the archive
*
* @param fileName the name under which to store the contents of the stream
* @param in the stream to copy
*/
public void addFile(String fileName, InputStream in) {
try (OutputStream out = archive.getOutputStream(fileName)) {
in.transferTo(out);
}
catch (IOException e) {
WriteErrorDialog.error(e, archive.getName());
}
}
/**
* Copy am array of <code>bytes</code> into the archive
*
* @param fileName the name under which to store the contents of the stream
* @param content array of bytes to copy
*/
public void addFile(String fileName, byte[] content) {
try {
archive.add(fileName, content);
}
catch (IOException e) {
WriteErrorDialog.error(e, archive.getName());
}
}
/**
* Saves the archive, prompting for a name only if none has ever been provided.
* @throws IOException IOException
*/
public boolean save() throws IOException {
return save(false);
}
/**
* Saves the archive, prompting for a name only if none has ever been provided.
* @param notifyModuleManager If true, notifies Module Manager that the save has occurred
* @throws IOException IOException
*/
public boolean save(boolean notifyModuleManager) throws IOException {
if (isTempArchive) {
return saveAs(notifyModuleManager);
}
else {
write(archive, notifyModuleManager);
}
return true;
}
/**
* Saves the archive, always prompting for a new filename.
* @throws IOException IOException
*/
public boolean saveAs() throws IOException {
return saveAs(false);
}
/**
* Writes the file archive.
* @param fa File archive
* @param notifyModuleManager if true, notifies the module manager that a file has been saved.
* @throws IOException IOException
*/
protected void write(FileArchive fa, boolean notifyModuleManager)
throws IOException {
fa.flush();
}
/**
* Saves the archive, always prompting for a new filename. If a defaultExtension has been
* provided, it will be added to the filename unless the user specifies a different one explicitly.
* @param notifyModuleManager If true, notifies Module Manager that the save has occurred
* @return true if operation proceeded, false if it was cancelled by user at file chooser or confirmation dialog
* @throws IOException IOException
*/
public boolean saveAs(boolean notifyModuleManager) throws IOException {
final FileChooser fc = FileChooser.createFileChooser(
GameModule.getGameModule().getPlayerWindow(),
(DirectoryConfigurer) Prefs.getGlobalPrefs()
.getOption(Prefs.MODULES_DIR_KEY));
if (fc.showSaveDialog() != FileChooser.APPROVE_OPTION) return false;
String filename = fc.getSelectedFile().getPath();
if (!StringUtils.isEmpty(defaultExtension) && (filename.lastIndexOf('.') < 0)) {
filename = filename + defaultExtension;
if (new File(filename).exists() && JOptionPane.NO_OPTION == JOptionPane.showConfirmDialog(GameModule.getGameModule().getPlayerWindow(), Resources.getString("Editor.ArchiveWriter.overwrite", filename), Resources.getString("Editor.ArchiveWriter.file_exists"), JOptionPane.YES_NO_OPTION)) {
return false;
}
}
if (!filename.equals(archive.getName())) {
// Copy the current state to the new archive.
final FileArchive tmp = archive;
archiveName = filename; // Set archive name before we open the new one, so if we get an exception we can complain using specified new filename
archive = new ZipArchive(tmp, filename);
archive.flush();
tmp.revert();
tmp.close();
write(archive, notifyModuleManager);
if (isTempArchive) {
tmp.getFile().delete();
isTempArchive = false;
}
}
else {
write(archive, notifyModuleManager);
}
return true;
}
/**
* If the ArchiveWriter was initialized with non-null file name, then
* write the contents of the archive to the named archive. If it was
* initialized with a null name, prompt the user to select a new file
* into which to write archive.
*/
@Deprecated(since = "2020-08-06", forRemoval = true)
public void write() throws IOException {
ProblemDialog.showDeprecated("2020-08-06");
write(false);
}
@Deprecated(since = "2020-08-06", forRemoval = true)
public void write(boolean notifyModuleManager) throws IOException {
ProblemDialog.showDeprecated("2020-08-06");
save(notifyModuleManager);
}
} |
package com.psddev.dari.db;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.RepeatingTask;
import com.psddev.dari.util.Stats;
import com.psddev.dari.util.StringUtils;
/**
* Periodically updates indexes annotated with {@code \@Recalculate}.
*/
public class RecalculationTask extends RepeatingTask {
private static final int UPDATE_LATEST_EVERY_SECONDS = 60;
private static final int QUERY_ITERABLE_SIZE = 200;
private static final Logger LOGGER = LoggerFactory.getLogger(RecalculationTask.class);
private static final Stats STATS = new Stats("Recalculation Task");
private int progressIndex = 0;
private int progressTotal = 0;
@Override
protected DateTime calculateRunTime(DateTime currentTime) {
return everyMinute(currentTime);
}
@Override
protected void doRepeatingTask(DateTime runTime) throws Exception {
progressIndex = 0;
progressTotal = 0;
for (RecalculationContext context : getIndexableMethods()) {
Stats.Timer timer = STATS.startTimer();
long recalculated = recalculateIfNecessary(context);
if (recalculated > 0L) {
timer.stop("Recalculate " + context.getKey(), recalculated);
}
}
}
/**
* Checks the LastRecalculation and DistributedLock and executes recalculate if it should.
*/
private long recalculateIfNecessary(RecalculationContext context) {
String updateKey = context.getKey();
long recalculated = 0;
LastRecalculation last = Query.from(LastRecalculation.class).master().noCache().where("key = ?", updateKey).first();
boolean shouldExecute = false;
boolean canExecute = false;
if (last == null) {
last = new LastRecalculation();
last.setKey(updateKey);
shouldExecute = true;
context.setReindexAll(true);
} else {
if (last.getLastExecutedDate() == null && last.getCurrentRunningDate() == null) {
// this has never been executed, and it's not currently executing.
shouldExecute = true;
context.setReindexAll(true);
} else if (last.getLastExecutedDate() != null && context.delay.isUpdateDue(new DateTime(), last.getLastExecutedDate())) {
// this has been executed before and an update is due.
shouldExecute = true;
}
if (last.getCurrentRunningDate() != null) {
// this is currently executing
shouldExecute = false;
if (context.delay.isUpdateDue(new DateTime(), last.getCurrentRunningDate())) {
// the task is running, but another update is already due.
// It probably died. Clear it out and pick it up next
// time if it hasn't updated, but don't run this time.
last.setCurrentRunningDate(null);
last.saveImmediately();
}
}
}
if (shouldExecute) {
// Check to see if any other processes are currently running on other hosts.
if (Query.from(LastRecalculation.class).where("currentRunningDate > ?", new DateTime().minusSeconds(UPDATE_LATEST_EVERY_SECONDS * 5)).hasMoreThan(0)) {
shouldExecute = false;
}
}
if (shouldExecute) {
boolean locked = false;
DistributedLock lock = new DistributedLock(Database.Static.getDefault(), updateKey);
try {
if (lock.tryLock()) {
locked = true;
last.setCurrentRunningDate(new DateTime());
last.saveImmediately();
canExecute = true;
}
} finally {
if (locked) {
lock.unlock();
}
}
if (canExecute) {
try {
recalculated = recalculate(context, last);
} finally {
last.setLastExecutedDate(new DateTime());
last.setCurrentRunningDate(null);
last.saveImmediately();
}
}
}
return recalculated;
}
/**
* Actually does the work of iterating through the records and updating indexes.
*/
private long recalculate(RecalculationContext context, LastRecalculation last) {
long recalculated = 0L;
// Still testing this out.
boolean useMetricQuery = false;
try {
Query<?> query = Query.fromAll().noCache().resolveToReferenceOnly();
query.getOptions().put(SqlDatabase.USE_JDBC_FETCH_SIZE_QUERY_OPTION, false);
if (!context.isReindexAll()) {
for (ObjectMethod method : context.methods) {
query.or(method.getUniqueName() + " != missing");
}
}
ObjectField metricField = context.getMetric();
DateTime processedLastRunDate = last.getLastExecutedDate();
if (metricField != null) {
if (last.getLastExecutedDate() != null) {
MetricInterval interval = metricField.as(MetricAccess.FieldData.class).getEventDateProcessor();
if (interval != null) {
processedLastRunDate = new DateTime(interval.process(processedLastRunDate));
if (useMetricQuery) {
query.and(metricField.getUniqueName() + "#date >= ?", processedLastRunDate);
query.and(metricField.getUniqueName() + " != 0");
}
}
}
}
for (Object obj : query.iterable(QUERY_ITERABLE_SIZE)) {
try {
if (!shouldContinue()) {
break;
}
setProgressTotal(++progressTotal);
State objState = State.getInstance(obj);
if (objState == null) {
continue;
}
if (!useMetricQuery) {
if (last.getLastExecutedDate() != null) {
if (metricField != null) {
Metric metric = new Metric(objState, metricField);
DateTime lastMetricUpdate = metric.getLastUpdate();
if (lastMetricUpdate == null) {
// there's no metric data, so just pass.
continue;
}
if (!context.isReindexAll() && lastMetricUpdate.isBefore(processedLastRunDate.minusSeconds(1))) {
// metric data is older than the last run date, so skip it.
continue;
}
}
}
}
setProgressIndex(++progressIndex);
objState.setResolveToReferenceOnly(false);
for (ObjectMethod method : context.methods) {
LOGGER.debug("Updating Index: " + method.getInternalName() + " for " + objState.getId());
method.recalculate(objState);
recalculated++;
}
} finally {
if (last.getCurrentRunningDate().plusSeconds(UPDATE_LATEST_EVERY_SECONDS).isBeforeNow()) {
last.setCurrentRunningDate(new DateTime());
last.saveImmediately();
}
}
}
} finally {
last.setCurrentRunningDate(new DateTime());
last.saveImmediately();
}
return recalculated;
}
/**
* Saves the last time the index update was executed for each context.
*/
public static class LastRecalculation extends Record {
// null if it's not running
@Indexed
private Long currentRunningDate;
private Long lastExecutedDate;
@Indexed(unique = true)
private String key;
public DateTime getCurrentRunningDate() {
return (currentRunningDate == null ? null : new DateTime(currentRunningDate));
}
public void setCurrentRunningDate(DateTime currentRunningDate) {
this.currentRunningDate = (currentRunningDate == null ? null : currentRunningDate.getMillis());
}
public DateTime getLastExecutedDate() {
return (lastExecutedDate == null ? null : new DateTime(lastExecutedDate));
}
public void setLastExecutedDate(DateTime lastExecutedDate) {
this.lastExecutedDate = (lastExecutedDate == null ? null : lastExecutedDate.getMillis());
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
private static Collection<RecalculationContext> getIndexableMethods() {
Map<String, RecalculationContext> contextsByGroupsAndDelayAndMetric = new HashMap<String, RecalculationContext>();
for (ObjectType type : Database.Static.getDefault().getEnvironment().getTypes()) {
for (ObjectMethod method : type.getMethods()) {
if (method.getJavaDeclaringClassName().equals(type.getObjectClassName()) &&
!method.as(RecalculationFieldData.class).isImmediate() &&
method.as(RecalculationFieldData.class).getRecalculationDelay() != null) {
TreeSet<String> groups = new TreeSet<String>();
if (Modification.class.isAssignableFrom(type.getObjectClass())) {
@SuppressWarnings("unchecked")
Class<? extends Modification<?>> modClass = ((Class<? extends Modification<?>>) type.getObjectClass());
for (Class<?> modifiedClass : Modification.Static.getModifiedClasses(modClass)) {
ObjectType modifiedType = ObjectType.getInstance(modifiedClass);
if (modifiedType != null) {
groups.add(modifiedType.getInternalName());
} else {
groups.add(modifiedClass.getName());
}
}
} else {
groups.add(type.getInternalName());
}
RecalculationContext context = new RecalculationContext(type, groups, method.as(RecalculationFieldData.class).getRecalculationDelay());
context.methods.add(method);
String key = context.getKey();
if (!contextsByGroupsAndDelayAndMetric.containsKey(key)) {
contextsByGroupsAndDelayAndMetric.put(key, context);
}
contextsByGroupsAndDelayAndMetric.get(key).methods.add(method);
}
}
}
return contextsByGroupsAndDelayAndMetric.values();
}
private static final class RecalculationContext {
public final ObjectType type;
public final RecalculationDelay delay;
public final TreeSet<String> groups;
public final Set<ObjectMethod> methods = new HashSet<ObjectMethod>();
public boolean reindexAll = false;
public RecalculationContext(ObjectType type, TreeSet<String> groups, RecalculationDelay delay) {
this.type = type;
this.groups = groups;
this.delay = delay;
}
public ObjectField getMetric() {
boolean first = true;
ObjectField metricField = null;
ObjectField useMetricField = null;
for (ObjectMethod method : methods) {
String methodMetricFieldName = method.as(MetricAccess.FieldData.class).getRecalculableFieldName();
ObjectField methodMetricField = null;
if (methodMetricFieldName != null) {
methodMetricField = type.getState().getDatabase().getEnvironment().getField(methodMetricFieldName);
if (methodMetricField == null) {
methodMetricField = type.getField(methodMetricFieldName);
}
if (methodMetricField == null) {
LOGGER.warn("Invalid metric field: " + methodMetricFieldName);
}
}
if (first) {
metricField = methodMetricField;
useMetricField = metricField;
} else {
if (!ObjectUtils.equals(metricField, methodMetricField)) {
useMetricField = null;
}
}
first = false;
}
return useMetricField;
}
public String getKey() {
if (methods.isEmpty()) {
throw new IllegalStateException("Add a method before you get the key!");
}
ObjectField metricField = getMetric();
return type.getInternalName() + " " +
StringUtils.join(groups.toArray(new String[0]), ",") + " " +
delay.getClass().getName() +
(metricField != null ? " " + metricField.getUniqueName() : "");
}
public boolean isReindexAll() {
return reindexAll;
}
public void setReindexAll(boolean reindexAll) {
this.reindexAll = reindexAll;
}
}
} |
package at.sw2017.q_up;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeoutException;
public class PlaceDetails extends Activity implements OnClickListener {
static String id, title;
static String user_id;
static String place_id;
private DatabaseHandler db_handle;
private String outplace;
private boolean decision ;
private Button ButtonLike;
private Button ButtonDislike;
TextView peopleInQueue;
boolean QdUP;
Calendar cal;
int start;
int end;
int time;
TextView time_1;
ToggleButton ButtonQ;
public void LikeDislike()
{
ButtonLike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db_handle.votePlacePositive(id);
ButtonLike.setEnabled(false);
ButtonDislike.setEnabled(false);
//ButtonLike.setVisibility(View.INVISIBLE);
}
});
ButtonDislike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
db_handle.votePlaceNegative(id);
ButtonLike.setEnabled(false);
ButtonDislike.setEnabled(false);
}
});
}
public void InfoButton()
{
Button ButtonInfo = (Button) findViewById(R.id.buttoninfo);
ButtonInfo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(PlaceDetails.this, InfoActivity.class);
intent.putExtra("title", title);
intent.putExtra("id", id);
startActivity(intent);
}
});
}
public void EvaluationOnTime()
{
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(10);
runOnUiThread(new Runnable() {
@Override
public void run() {
Bundle bundle = getIntent().getExtras();
id = bundle.getString("id");
db_handle = QUpApp.getInstance().getDBHandler();
Place place = new Place();
db_handle.placesLock();
for (Place p : db_handle.getPlacesList()) {
if (p.placeId.equals(id)) {
place = p;
break;
}
}
db_handle.placesUnlock();
TextView txtViewtitle = (TextView) findViewById(R.id.txtview_title);
TextView txtViewlike = (TextView) findViewById(R.id.txt_like);
TextView txtViewdislike = (TextView) findViewById(R.id.txt_dislike);
txtViewtitle.setText(place.placeName);
txtViewlike.setText(place.ratingPos);
txtViewdislike.setText(place.ratingNeg);
LikeDislike();
getNumberOfUsers();
if(QdUP == true) {
TextView txtViewNumberQUP = (TextView) findViewById(R.id.txtView_numberqup);
txtViewNumberQUP.setText("You are queued up");
}
else
NumberQUP(db_handle.getQueuedUserCountFromPlace(place.placeId));
title = place.placeName;
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
t.start();
}
public void NumberQUP(int number)
{
String text;
switch (number)
{
case 0:
text= "Be the first in the Q!";
break;
case 1:
text = "Be the second in the Q!";
break;
case 2:
text = "Be the third in the Q!";
break;
default:
text = "Be the " + Integer.toString(number+1) + "th in the Q!";
break;
}
TextView txtViewNumberQUP = (TextView) findViewById(R.id.txtView_numberqup);
txtViewNumberQUP.setText(text);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_details);
QUpApp.getInstance().setCurrentActivity(this);
ButtonQ = (ToggleButton) findViewById(R.id.btn_qup);
peopleInQueue = (TextView)findViewById(R.id.UserNr);
time_1 = (TextView) findViewById(R.id.time8);
ButtonQ.setOnClickListener(this);
time_1.setText("");
decision = false;
// ButtonQ.setChecked(getDefaults("togglekey",this));
//setDefaults("togglekey",ButtonQ.isChecked(),this);
ButtonLike = (Button) findViewById(R.id.buttonlike);
ButtonDislike = (Button) findViewById(R.id.buttondislike);
ButtonLike.setEnabled(false);
ButtonDislike.setEnabled(false);
start = 0;
end = 0;
time = 0;
EvaluationOnTime();
InfoButton();
getNumberOfUsers();
}
public void getNumberOfUsers()
{
Bundle bundle = getIntent().getExtras();
place_id = bundle.getString("id");
DatabaseHandler db_handle = QUpApp.getInstance().getDBHandler();
peopleInQueue.setText(Integer.toString(db_handle.getQueuedUserCountFromPlace(place_id)));
}
@Override
protected void onResume() {
super.onResume();
}
/*
public static void setDefaults(String key,Boolean value,Context context)
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key,value);
editor.apply();
}
public static Boolean getDefaults(String key,Context context)
{
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key,true);
}
@Override
public void onStart(){
super.onStart();
ButtonQ.setChecked(getDefaults("togglekey",this));
DatabaseHandler db_handle = QUpApp.getInstance().getDBHandler();
String Username = (MainActivity.currentUser.userName);
db_handle.usersLock();
for (Place p : db_handle.getPlacesList()) {
p.placeId
Toast.makeText(getApplicationContext(),
p.idCheckInPlace, Toast.LENGTH_SHORT).show();
}
db_handle.usersUnlock();
}
@Override
public void onStop(){
super.onStop();
setDefaults("togglekey",ButtonQ.isChecked(),this);
}
*/
@Override
public void onClick(View v) {
final String CHECKED_IN_MSG = "User checked in..";
final String CHECKED_OUT_MSG = "User checked out..";
ToggleButton clicked = (ToggleButton)v;
DatabaseHandler db_handle = QUpApp.getInstance().getDBHandler();
String Username = (MainActivity.currentUser.userName);
Bundle bundle = getIntent().getExtras();
place_id = bundle.getString("id");
//String text = (String) clicked.getText();
if(clicked.isChecked()) {
db_handle.usersLock();
for (User u : db_handle.getUsersList()) {
if (u.userName.equals(Username)) {
user_id = u.userId;
}
}
db_handle.usersUnlock();
db_handle.checkUserIntoPlace(user_id, place_id);
QdUP = true;
decision = true;
cal = Calendar.getInstance();
start = cal.get(Calendar.SECOND);
time_1.setText("");
}
else {
db_handle.checkOutOfPlace(user_id);
QdUP = false;
decision = false;
ButtonLike.setEnabled(true);
ButtonDislike.setEnabled(true);
cal = Calendar.getInstance();
end = cal.get(Calendar.SECOND);
if(end < start)
{
end += 60;
time = end - start;
if(time < 0)
time = time * (-1);
time_1.setText(Integer.toString(time));
}
else
{
time = start - end;
if(time < 0)
time = time * (-1);
time_1.setText(Integer.toString(time));
}
}
}
@Override
public void onBackPressed() {
if (decision) {
Toast.makeText(getApplicationContext(),
"You have to exit the queue first !", Toast.LENGTH_SHORT).show();
} else {
super.onBackPressed(); // Process Back key default behavior.
}
}
} |
package ifc.view;
import com.sun.star.beans.PropertyValue;
import com.sun.star.uno.UnoRuntime;
import com.sun.star.view.PrintJobEvent;
import com.sun.star.view.XPrintJobBroadcaster;
import com.sun.star.view.XPrintJobListener;
import com.sun.star.view.XPrintable;
import java.io.File;
import lib.MultiMethodTest;
import lib.Status;
import lib.StatusException;
import util.utils;
/**
* Test the XPrintJobBroadcaster interface
*/
public class _XPrintJobBroadcaster extends MultiMethodTest {
public XPrintJobBroadcaster oObj = null;
MyPrintJobListener listenerImpl = null;
/**
* Get an object implementation of the _XPrintJobListener interface from the
* test environment.
*/
public void before() {
listenerImpl = (MyPrintJobListener)tEnv.getObjRelation("XPrintJobBroadcaster.XPrintJobListener");
if (listenerImpl == null) {
throw new StatusException(Status.failed(" No test possible. The XPrintJobListener interface has to be implemented."));
}
}
/**
* add the listener, see if it's called.
*/
public void _addPrintJobListener() {
oObj.addPrintJobListener(listenerImpl);
listenerImpl.fireEvent();
util.utils.shortWait(1000);
tRes.tested("addPrintJobListener()", listenerImpl.actionTriggered());
}
/**
* remove the listener, see if it's still caleed.
*/
public void _removePrintJobListener() {
requiredMethod("addPrintJobListener");
oObj.removePrintJobListener(listenerImpl);
util.utils.shortWait(5000);
listenerImpl.reset();
listenerImpl.fireEvent();
tRes.tested("removePrintJobListener()", !listenerImpl.actionTriggered());
}
/**
* Implementation for testing the XPrintJobBroadcaster interface:
* a listener to add.
*/
public static class MyPrintJobListener implements XPrintJobListener {
boolean eventCalled = false;
// object to trigger the event
XPrintable xPrintable = null;
PropertyValue[]printProps = null;
String printFileName = null;
/**
* Constructor
* @param An object that can be cast to an XPrintable.
*/
public MyPrintJobListener(Object printable, String printFileName) {
this.printFileName = printFileName;
xPrintable = (XPrintable)UnoRuntime.queryInterface(XPrintable.class, printable);
printProps = new PropertyValue[2];
printProps[0] = new PropertyValue();
printProps[0].Name = "FileName";
printProps[0].Value = printFileName;
printProps[0].State = com.sun.star.beans.PropertyState.DEFAULT_VALUE;
printProps[1] = new PropertyValue();
printProps[1].Name = "Wait";
printProps[1].Value = new Boolean(true);
}
/**
* Has the action been triggered?
* @return True if "printJobEvent" has been called.
*/
public boolean actionTriggered() {
return eventCalled;
}
/**
* Fire the event that calls the printJobEvent
*/
public void fireEvent() {
try {
xPrintable.print(printProps);
}
catch(com.sun.star.lang.IllegalArgumentException e) {
}
}
public void reset() {
File f = new File(printFileName);
if (f.exists())
f.delete();
eventCalled = false;
}
/**
* The print job event: has to be called when the action is triggered.
*/
public void printJobEvent(PrintJobEvent printJobEvent) {
eventCalled = true;
}
/**
* Disposing event: ignore.
*/
public void disposing(com.sun.star.lang.EventObject eventObject) {
}
}
} |
package incident;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import javafx.application.Platform;
/**
*
* @author Eric
*/
public class IncidentContainer extends Observable {
private List<Incident> incidents;
private List<Incident> approved;
private static IncidentContainer instance = null;
protected IncidentContainer() {
// Exists only to defeat instantiation.
incidents = new ArrayList<>();
approved = new ArrayList<>();
}
public static IncidentContainer getInstance() {
if (instance == null) {
instance = new IncidentContainer();
}
return instance;
}
public Incident getIncidentByName(String name) {
for (Incident incident : incidents) {
if (incident.toString().equals(name)) {
return incident;
}
}
return null;
}
public List<Incident> getIncidents() {
return this.incidents;
}
public List<Incident> getApprovedIncidents() {
return approved;
}
public void addIncident(String location, String submitter, String typeOfIncident, String situationDescription, String date) {
Incident incident = new Incident(location, submitter, typeOfIncident, situationDescription, date);
this.incidents.add(incident);
Platform.runLater(new Runnable() {
@Override
public void run() {
setChanged();
notifyObservers(getIncidents());
}
});
}
public void deleteIncident(Incident incident) {
this.incidents.remove(incident);
setChanged();
notifyObservers(this.incidents);
}
public void approveIncident(Incident incident) {
incident.approve();
approved.add(incident);
deleteIncident(incident);
}
} |
package com.exedio.cope;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Savepoint;
import java.sql.Statement;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.exedio.cope.junit.CopeAssert;
public class ConnectionPoolTest extends CopeAssert
{
public void testCp() throws SQLException
{
final Conn c1 = new Conn();
final Factory f = new Factory(listg(c1));
f.assertV(0);
final ConnectionPool cp = new ConnectionPool(f, 1, 1, 0);
c1.assertV(false, 0, 0, 0);
f.assertV(0);
// get and create
assertSame(c1, cp.getConnection(true));
c1.assertV(true, 1, 0, 0);
f.assertV(1);
// put into idle
cp.putConnection(c1);
c1.assertV(true, 1, 1, 0);
f.assertV(1);
// get from idle
assertSame(c1, cp.getConnection(true));
c1.assertV(true, 2, 1, 0);
f.assertV(1);
// put into idle
cp.putConnection(c1);
c1.assertV(true, 2, 2, 0);
f.assertV(1);
// get from idle with other autoCommit
assertSame(c1, cp.getConnection(false));
c1.assertV(false, 3, 2, 0);
f.assertV(1);
}
public void testOverflow() throws SQLException
{
final Conn c1 = new Conn();
final Conn c2 = new Conn();
final Factory f = new Factory(listg(c1, c2));
f.assertV(0);
final ConnectionPool cp = new ConnectionPool(f, 2, 1, 0);
c1.assertV(false, 0, 0, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(0);
// get and create
assertSame(c1, cp.getConnection(true));
c1.assertV(true, 1, 0, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(1);
// get and create (2)
assertSame(c2, cp.getConnection(true));
c1.assertV(true, 1, 0, 0);
c2.assertV(true, 1, 0, 0);
f.assertV(2);
// put into idle
cp.putConnection(c1);
c1.assertV(true, 1, 1, 0);
c2.assertV(true, 1, 0, 0);
f.assertV(2);
// put and close
cp.putConnection(c2);
c1.assertV(true, 1, 1, 0);
c2.assertV(true, 1, 1, 1);
f.assertV(2);
}
public void testIdleInitial() throws SQLException
{
final Conn c1 = new Conn();
final Factory f = new Factory(listg(c1));
f.assertV(0);
final ConnectionPool cp = new ConnectionPool(f, 1, 1, 1);
c1.assertV(false, 0, 0, 0);
f.assertV(1); // already created
// get and create
assertSame(c1, cp.getConnection(true));
c1.assertV(true, 1, 0, 0);
f.assertV(1);
}
public void testActiveLimit() throws SQLException
{
final Conn c1 = new Conn();
final Factory f = new Factory(listg(c1));
f.assertV(0);
final ConnectionPool cp = new ConnectionPool(f, 1, 1, 0);
c1.assertV(false, 0, 0, 0);
f.assertV(0);
// get and create
assertSame(c1, cp.getConnection(true));
c1.assertV(true, 1, 0, 0);
f.assertV(1);
// get and run into limit
try
{
cp.getConnection(true);
fail();
}
catch(IllegalStateException e)
{
assertEquals("connectionPool.activeLimit reached: 1", e.getMessage());
}
}
public void testIsClosed() throws SQLException
{
final Conn c1 = new Conn();
final Conn c2 = new Conn();
final Factory f = new Factory(listg(c1, c2));
f.assertV(0);
final ConnectionPool cp = new ConnectionPool(f, 1/*important to test, that a closed connection decrements activeCount*/, 1, 0);
c1.assertV(false, 0, 0, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(0);
// get and create
assertSame(c1, cp.getConnection(true));
c1.assertV(true, 1, 0, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(1);
// dont put into idle, because its closed
c1.isClosed = true;
try
{
cp.putConnection(c1);
fail();
}
catch(IllegalArgumentException e)
{
assertEquals("unexpected closed connection", e.getMessage());
}
c1.assertV(true, 1, 1, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(1);
// create new because no idle available
assertSame(c2, cp.getConnection(true));
c1.assertV(true, 1, 1, 0);
c2.assertV(true, 1, 0, 0);
f.assertV(2);
}
public void testFlush() throws SQLException
{
final Conn c1 = new Conn();
final Conn c2 = new Conn();
final Factory f = new Factory(listg(c1, c2));
f.assertV(0);
final ConnectionPool cp = new ConnectionPool(f, 1/*important to test, that flush decrements activeCount*/, 1, 0);
c1.assertV(false, 0, 0, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(0);
// get and create
assertSame(c1, cp.getConnection(true));
c1.assertV(true, 1, 0, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(1);
// put into idle
cp.putConnection(c1);
c1.assertV(true, 1, 1, 0);
c2.assertV(false, 0, 0, 0);
f.assertV(1);
// flush closes c1
cp.flush();
c1.assertV(true, 1, 1, 1);
c2.assertV(false, 0, 0, 0);
f.assertV(1);
// create new because flushed
assertSame(c2, cp.getConnection(true));
c1.assertV(true, 1, 1, 1);
c2.assertV(true, 1, 0, 0);
f.assertV(2);
}
static class Factory implements ConnectionPool.Factory
{
final Iterator<Conn> connections;
int createCount = 0;
Factory(final List<Conn> connections)
{
this.connections = connections.iterator();
}
void assertV(final int createCount)
{
assertEquals(createCount, this.createCount);
}
public java.sql.Connection createConnection() throws SQLException
{
createCount++;
return connections.next();
}
}
static class Conn implements Connection
{
boolean autoCommit = false;
int autoCommitCount = 0;
boolean isClosed = false;
int isClosedCount = 0;
int closedCount = 0;
void assertV(final boolean autoCommit, final int autoCommitCount, final int isClosedCount, final int closedCount)
{
assertEquals(autoCommit, this.autoCommit);
assertEquals(autoCommitCount, this.autoCommitCount);
assertEquals(isClosedCount, this.isClosedCount);
assertEquals(closedCount, this.closedCount);
}
public void setAutoCommit(final boolean autoCommit) throws SQLException
{
this.autoCommit = autoCommit;
this.autoCommitCount++;
}
public boolean isClosed() throws SQLException
{
isClosedCount++;
return isClosed;
}
public void close() throws SQLException
{
closedCount++;
}
public Statement createStatement() throws SQLException
{
throw new RuntimeException();
}
public PreparedStatement prepareStatement(String sql) throws SQLException
{
throw new RuntimeException();
}
public CallableStatement prepareCall(String sql) throws SQLException
{
throw new RuntimeException();
}
public String nativeSQL(String sql) throws SQLException
{
throw new RuntimeException();
}
public boolean getAutoCommit() throws SQLException
{
throw new RuntimeException();
}
public void commit() throws SQLException
{
throw new RuntimeException();
}
public void rollback() throws SQLException
{
throw new RuntimeException();
}
public DatabaseMetaData getMetaData() throws SQLException
{
throw new RuntimeException();
}
public void setReadOnly(boolean readOnly) throws SQLException
{
throw new RuntimeException();
}
public boolean isReadOnly() throws SQLException
{
throw new RuntimeException();
}
public void setCatalog(String catalog) throws SQLException
{
throw new RuntimeException();
}
public String getCatalog() throws SQLException
{
throw new RuntimeException();
}
public void setTransactionIsolation(int level) throws SQLException
{
throw new RuntimeException();
}
public int getTransactionIsolation() throws SQLException
{
throw new RuntimeException();
}
public SQLWarning getWarnings() throws SQLException
{
throw new RuntimeException();
}
public void clearWarnings() throws SQLException
{
throw new RuntimeException();
}
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
throw new RuntimeException();
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
throw new RuntimeException();
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
throw new RuntimeException();
}
public Map<String, Class<?>> getTypeMap() throws SQLException
{
throw new RuntimeException();
}
public void setTypeMap(Map<String, Class<?>> arg0) throws SQLException
{
throw new RuntimeException();
}
public void setHoldability(int holdability) throws SQLException
{
throw new RuntimeException();
}
public int getHoldability() throws SQLException
{
throw new RuntimeException();
}
public Savepoint setSavepoint() throws SQLException
{
throw new RuntimeException();
}
public Savepoint setSavepoint(String name) throws SQLException
{
throw new RuntimeException();
}
public void rollback(Savepoint savepoint) throws SQLException
{
throw new RuntimeException();
}
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
throw new RuntimeException();
}
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
throw new RuntimeException();
}
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
throw new RuntimeException();
}
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
{
throw new RuntimeException();
}
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException
{
throw new RuntimeException();
}
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException
{
throw new RuntimeException();
}
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException
{
throw new RuntimeException();
}
}
} |
package io.spacedog.utils;
import com.google.common.io.Resources;
public class ClassResources {
public static String loadToString(Object context, String resourceName) {
try {
Class<?> contextClass = context instanceof Class<?>
? (Class<?>) context
: context.getClass();
return Resources.toString(
Resources.getResource(contextClass, resourceName),
Utils.UTF8);
} catch (Exception e) {
throw Exceptions.runtime(e, "error loading resource [%s]", resourceName);
}
}
} |
package com.sababado.circularview;
import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
/**
* TODO: document your custom view class.
*/
public class CircularView extends View {
private static final String TAG = CircularView.class.getSimpleName();
private String mText; //TODO add customization for the text (style, color, etc)
private TextPaint mTextPaint;
private float mTextWidth;
private float mTextHeight;
private Paint mCirclePaint;
private static final float CIRCLE_WEIGHT_LONG_ORIENTATION = 0.8f;
private static final float CIRCLE_TO_MARKER_PADDING = 20f;
private final float DEFAULT_MARKER_RADIUS = 40;
private float mMarkerStartingPoint;
private BaseCircularViewAdapter mAdapter;
private final AdapterDataSetObserver mAdapterDataSetObserver = new AdapterDataSetObserver();
private OnClickListener mOnCircularViewObjectClickListener;
private OnHighlightAnimationEndListener mOnHighlightAnimationEndListener;
private ArrayList<Marker> mMarkerList;
private CircularViewObject mCircle;
private float mHighlightedDegree;
private Marker mHighlightedMarker;
private int mHighlightedMarkerPosition;
private boolean mDrawHighlightedMarkerOnTop;
/**
* Use this to specify that no degree should be highlighted.
*/
public static final float HIGHLIGHT_NONE = Float.MIN_VALUE;
private boolean mAnimateMarkersOnStillHighlight;
private boolean mAnimateMarkersOnHighlightAnimation;
private boolean mIsAnimating;
private ObjectAnimator mHighlightedDegreeObjectAnimator;
private int paddingLeft;
private int paddingTop;
private int paddingRight;
private int paddingBottom;
private int mWidth;
private int mHeight;
public static final int TOP = 270;
public static final int BOTTOM = 90;
public static final int LEFT = 180;
public static final int RIGHT = 0;
public CircularView(Context context) {
super(context);
init(null, 0);
}
public CircularView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public CircularView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.CircularView, defStyle, 0);
final int centerBackgroundColor = a.getColor(
R.styleable.CircularView_centerBackgroundColor,
CircularViewObject.NO_COLOR);
// Set up a default TextPaint object
mTextPaint = new TextPaint();
mTextPaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setTextAlign(Paint.Align.LEFT);
mText = a.getString(R.styleable.CircularView_text);
mTextPaint.setTextSize(a.getDimension(
R.styleable.CircularView_textSize,
24f));
mTextPaint.setColor(a.getColor(
R.styleable.CircularView_textColor,
mTextPaint.getColor()));
Drawable circleDrawable = null;
if (a.hasValue(R.styleable.CircularView_centerDrawable)) {
circleDrawable = a.getDrawable(
R.styleable.CircularView_centerDrawable);
circleDrawable.setCallback(this);
}
mHighlightedDegreeObjectAnimator = new ObjectAnimator();
mHighlightedDegreeObjectAnimator.setTarget(CircularView.this);
mHighlightedDegreeObjectAnimator.setPropertyName("highlightedDegree");
mHighlightedDegreeObjectAnimator.addListener(mAnimatorListener);
// Update TextPaint and text measurements from attributes
invalidateTextPaintAndMeasurements();
mCirclePaint = new Paint();
mCirclePaint.setFlags(Paint.ANTI_ALIAS_FLAG);
mCirclePaint.setStyle(Paint.Style.FILL);
mCirclePaint.setColor(Color.RED);
mDrawHighlightedMarkerOnTop = a.getBoolean(R.styleable.CircularView_drawHighlightedMarkerOnTop, false);
mHighlightedMarker = null;
mHighlightedMarkerPosition = -1;
mHighlightedDegree = a.getFloat(R.styleable.CircularView_highlightedDegree, HIGHLIGHT_NONE);
mMarkerStartingPoint = a.getFloat(R.styleable.CircularView_markerStartingPoint, 0f);
mAnimateMarkersOnStillHighlight = a.getBoolean(R.styleable.CircularView_animateMarkersOnStillHighlight, false);
mAnimateMarkersOnHighlightAnimation = false;
mIsAnimating = false;
mCircle = new CircularViewObject(getContext(), CIRCLE_TO_MARKER_PADDING, centerBackgroundColor);
mCircle.setSrc(circleDrawable);
a.recycle();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// init circle dimens
final int shortDimension = Math.min(
mHeight = getMeasuredHeight(),
mWidth = getMeasuredWidth());
final float circleRadius = (shortDimension * CIRCLE_WEIGHT_LONG_ORIENTATION - DEFAULT_MARKER_RADIUS * 4f - CIRCLE_TO_MARKER_PADDING * 2f) / 2f;
final float circleCenter = shortDimension / 2f;
mCircle.init(circleCenter, circleCenter, circleRadius, mAdapterDataSetObserver);
}
/**
* Make sure a degree value is less than or equal to 360 and greater than or equal to 0.
*
* @param degree Degree to normalize
* @return Return a positive degree value
*/
private float normalizeDegree(float degree) {
if (degree < 0f) {
degree = 360f + degree;
}
return degree % 360f;
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
paddingLeft = getPaddingLeft();
paddingTop = getPaddingTop();
paddingRight = getPaddingRight();
paddingBottom = getPaddingBottom();
setupMarkerList();
}
private void setupMarkerList() {
if (mAdapter != null) {
// init marker dimens
final int markerCount = mAdapter.getCount();
assert (markerCount >= 0);
if (mMarkerList == null) {
mMarkerList = new ArrayList<>(markerCount);
}
int markerViewListSize = mMarkerList.size();
final float degreeInterval = 360.0f / markerCount;
final float radiusFromCenter = mCircle.getRadius() + CIRCLE_TO_MARKER_PADDING + DEFAULT_MARKER_RADIUS;
int position = 0;
float degree = mMarkerStartingPoint;
// loop clockwise
for (; position < markerCount; position++) {
final boolean positionHasExistingMarkerInList = position < markerViewListSize;
final float actualDegree = normalizeDegree(degree);
final double rad = Math.toRadians(actualDegree);
final float sectionMin = actualDegree - degreeInterval / 2f;
// get the old marker view if it exists.
final Marker newMarker;
if (positionHasExistingMarkerInList) {
newMarker = mMarkerList.get(position);
} else {
newMarker = new Marker(getContext());
mMarkerList.add(newMarker);
}
// Initialize all other necessary values
newMarker.init(
(float) (radiusFromCenter * Math.cos(rad)) + mCircle.getX(),
(float) (radiusFromCenter * Math.sin(rad)) + mCircle.getY(),
DEFAULT_MARKER_RADIUS,
normalizeDegree(sectionMin),
normalizeDegree(sectionMin + degreeInterval) - 0.001f,
mAdapterDataSetObserver);
newMarker.setShouldAnimateWhenHighlighted(mAnimateMarkersOnStillHighlight);
// get the new marker view.
mAdapter.setupMarker(position, newMarker);
// Make sure it's drawable has the callback set
newMarker.setCallback(this);
degree += degreeInterval;
}
// Remove extra markers that aren't used in this list anymore.
markerViewListSize = mMarkerList.size();
for (; position < markerViewListSize; position++) {
mMarkerList.remove(position
markerViewListSize
}
mMarkerList.trimToSize();
// Force any effect of highlighting.
}
// Workaround. Setting the state of a drawable immediately doesn't seem to update correctly.
// Delaying the action works.
postDelayed(setCurrentHighlightedDegree, 5);
}
private final Runnable setCurrentHighlightedDegree = new Runnable() {
@Override
public void run() {
setHighlightedDegree(mHighlightedDegree);
}
};
private void invalidateTextPaintAndMeasurements() {
mTextWidth = mText == null ? 0 : mTextPaint.measureText(mText);
Paint.FontMetrics fontMetrics = mTextPaint.getFontMetrics();
mTextHeight = fontMetrics.bottom;
}
//TODO always draw the animating markers on top.
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int contentWidth = mWidth - paddingLeft - paddingRight;
int contentHeight = mHeight - paddingTop - paddingBottom;
mCirclePaint.setStyle(Paint.Style.FILL);
mCirclePaint.setColor(Color.RED);
// Draw CircularViewObject
mCircle.draw(canvas);
// Draw non-highlighted Markers
if (mMarkerList != null && !mMarkerList.isEmpty()) {
for (final Marker marker : mMarkerList) {
if (!mDrawHighlightedMarkerOnTop || !marker.equals(mHighlightedMarker)) {
marker.draw(canvas);
}
}
}
// Draw highlighted marker
if (mDrawHighlightedMarkerOnTop && mHighlightedMarker != null) {
mHighlightedMarker.draw(canvas);
}
// Draw line
if (mIsAnimating) {
final float radiusFromCenter = mCircle.getRadius() + CIRCLE_TO_MARKER_PADDING + DEFAULT_MARKER_RADIUS;
final float x = (float) Math.cos(Math.toRadians(mHighlightedDegree)) * radiusFromCenter + mCircle.getX();
final float y = (float) Math.sin(Math.toRadians(mHighlightedDegree)) * radiusFromCenter + mCircle.getY();
canvas.drawLine(mCircle.getX(), mCircle.getY(), x, y, mCirclePaint);
}
// Draw the text.
if (!TextUtils.isEmpty(mText)) {
canvas.drawText(mText,
mCircle.getX() - mTextWidth / 2f,
mCircle.getY() - mTextHeight / 2f,
// paddingLeft + (contentWidth - mTextWidth) / 2,
// paddingTop + (contentHeight + mTextHeight) / 2,
mTextPaint);
}
}
/**
* Set the adapter to use on this view.
*
* @param adapter Adapter to set.
*/
public void setAdapter(final BaseCircularViewAdapter adapter) {
mAdapter = adapter;
if (mAdapter != null) {
mAdapter.registerDataSetObserver(mAdapterDataSetObserver);
}
postInvalidate();
}
/**
* Get the adapter that has been set on this view.
*
* @return The adapter that has been set on this view.
* @see #setAdapter(BaseCircularViewAdapter)
*/
public BaseCircularViewAdapter getAdapter() {
return mAdapter;
}
/**
* Gets the text for this view.
*
* @return The text for this view.
* @attr ref R.styleable#CircularView_text
*/
public String getText() {
return mText;
}
/**
* Sets the view's text.
*
* @param text The view's text.
* @attr ref R.styleable#CircularView_text
*/
public void setText(String text) {
mText = text;
invalidateTextPaintAndMeasurements();
}
/**
* Gets the example dimension attribute value.
*
* @return The example dimension attribute value.
* @attr ref R.styleable#CircularView_textSize
*/
public float getTextSize() {
return mTextPaint.getTextSize();
}
/**
* Set the default text size to the given value, interpreted as "scaled
* pixel" units. This size is adjusted based on the current density and
* user font size preference.
*
* @param size The scaled pixel size.
* @attr ref R.styleable#CircularView_textSize
*/
public void setTextSize(float size) {
setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}
/**
* Set the default text size to a given unit and value. See {@link
* TypedValue} for the possible dimension units.
*
* @param unit The desired dimension unit.
* @param size The desired size in the given units.
* @attr ref R.styleable#CircularView_textSize
*/
public void setTextSize(int unit, float size) {
Context c = getContext();
Resources r;
if (c == null)
r = Resources.getSystem();
else
r = c.getResources();
setRawTextSize(TypedValue.applyDimension(
unit, size, r.getDisplayMetrics()));
}
private void setRawTextSize(float size) {
if (size != mTextPaint.getTextSize()) {
mTextPaint.setTextSize(size);
invalidateTextPaintAndMeasurements();
postInvalidate();
}
}
/**
* Set the paint's color. Note that the color is an int containing alpha
* as well as r,g,b. This 32bit value is not premultiplied, meaning that
* its alpha can be any value, regardless of the values of r,g,b.
* See the Color class for more details.
*
* @param color The new color (including alpha) to set for the text.
* @attr ref R.styleable#CircularView_textColor
*/
public void setTextColor(int color) {
if (mTextPaint.getColor() != color) {
mTextPaint.setColor(color);
postInvalidate();
}
}
* /**
* Return the paint's color. Note that the color is a 32bit value
* containing alpha as well as r,g,b. This 32bit value is not premultiplied,
* meaning that its alpha can be any value, regardless of the values of
* r,g,b. See the Color class for more details.
*
* @return the text's color (and alpha).
* @attr ref R.styleable#CircularView_textColor
*/
public int getTextColor() {
return mTextPaint.getColor();
}
/**
* Get the degree that is currently highlighted.
*
* @return The highlighted degree
* @attr ref R.styleable#CircularView_highlightedDegree
*/
public float getHighlightedDegree() {
return mHighlightedDegree;
}
/**
* Set the degree that will trigger highlighting a marker. You can also set {@link #HIGHLIGHT_NONE} to not highlight any degree.
*
* @param highlightedDegree Value in degrees.
* @attr ref R.styleable#CircularView_highlightedDegree
*/
public void setHighlightedDegree(final float highlightedDegree) {
this.mHighlightedDegree = highlightedDegree;
mHighlightedMarker = null;
mHighlightedMarkerPosition = -1;
// Loop through all markers to see if any of them are highlighted.
if (mMarkerList != null) {
final int size = mMarkerList.size();
for (int i = 0; i < size; i++) {
final Marker marker = mMarkerList.get(i);
// Only check the marker if the visibility is not "gone"
if (marker.getVisibility() != View.GONE) {
final boolean markerIsHighlighted = mHighlightedDegree != HIGHLIGHT_NONE && marker.hasInSection(mHighlightedDegree % 360);
marker.setHighlighted(markerIsHighlighted);
if (markerIsHighlighted) {
// Marker is highlighted!
mHighlightedMarker = marker;
mHighlightedMarkerPosition = i;
final boolean highlightAnimationAndAnimateMarker = mIsAnimating && mAnimateMarkersOnHighlightAnimation;
final boolean stillAndAnimateMarker = !mIsAnimating && mAnimateMarkersOnStillHighlight;
final boolean wantsToAnimateMarker = highlightAnimationAndAnimateMarker || stillAndAnimateMarker;
// Animate only if necessary
if (wantsToAnimateMarker && !marker.isAnimating()) {
marker.animateBounce();
}
}
}
// Continue looping through the rest to reset other markers.
}
}
postInvalidate();
}
/**
* Check if a marker should animate when it is highlighted. By default this is false and when it is
* set to true the marker will constantly be animating.
*
* @return True if a marker should animate when it is highlighted, false if not.
* @see #setHighlightedDegree(float)
* @attr ref R.styleable#CircularView_animateMarkersOnStillHighlight
*/
public boolean isAnimateMarkerOnStillHighlight() {
return mAnimateMarkersOnStillHighlight;
}
/**
* If set to true the marker that is highlighted with {@link #setHighlightedDegree(float)} will
* animate continuously when the highlight degree is not animating. This is set to false by default.
*
* @param animateMarkerOnHighlight True to continuously animate, false to turn it off.
* @attr ref R.styleable#CircularView_animateMarkersOnStillHighlight
*/
public void setAnimateMarkerOnStillHighlight(boolean animateMarkerOnHighlight) {
this.mAnimateMarkersOnStillHighlight = animateMarkerOnHighlight;
if (mMarkerList != null) {
for (final Marker marker : mMarkerList) {
marker.setShouldAnimateWhenHighlighted(animateMarkerOnHighlight);
}
}
postInvalidate();
}
/**
* Get the center circle object.
*
* @return The center circle object.
*/
public CircularViewObject getCenterCircle() {
return mCircle;
}
/**
* Get the marker that is currently highlighted. Null is returned if no marker is highlighted.
*
* @return The marker that is currently highlighted.
*/
public Marker getHighlightedMarker() {
return mHighlightedMarker;
}
/**
* Returns the flag the determines if the highlighted marker will draw on top of other markers.
*
* @return True if the highlighted marker will draw on top of other markers, false if they're all drawn in order.
* @attr ref R.styleable#CircularView_drawHighlightedMarkerOnTop
*/
public boolean isDrawHighlightedMarkerOnTop() {
return mDrawHighlightedMarkerOnTop;
}
/**
* Set the flag that determines if the highlighted marker will draw on top of other markers.
* This is false by default.
*
* @param drawHighlightedMarkerOnTop the flag that determines if the highlighted marker will draw on top of other markers.
* @attr ref R.styleable#CircularView_drawHighlightedMarkerOnTop
*/
public void setDrawHighlightedMarkerOnTop(boolean drawHighlightedMarkerOnTop) {
this.mDrawHighlightedMarkerOnTop = drawHighlightedMarkerOnTop;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean handled = false;
// check all markers
if (mMarkerList != null) {
int position = 0;
for (final Marker marker : mMarkerList) {
final int status = marker.onTouchEvent(event);
if (status >= 0) {
handled = status != MotionEvent.ACTION_MOVE;
if (status == MotionEvent.ACTION_UP && mOnCircularViewObjectClickListener != null) {
mOnCircularViewObjectClickListener.onMarkerClick(this, marker, position);
}
break;
}
position++;
}
}
// check center circle
if (!handled && mCircle != null) {
final int status = mCircle.onTouchEvent(event);
if (status >= 0) {
handled = true;
if (status == MotionEvent.ACTION_UP && mOnCircularViewObjectClickListener != null) {
mOnCircularViewObjectClickListener.onClick(this);
}
}
}
return handled || super.onTouchEvent(event);
}
/**
* Set the click listener that will receive a callback when the center circle is clicked.
*
* @param l Listener to receive a callback.
*/
public void setOnCircularViewObjectClickListener(final OnClickListener l) {
mOnCircularViewObjectClickListener = l;
}
/**
* Set the listener that will receive callbacks when a highlight animation has ended.
*
* @param l Listener to receive callbacks.
* @see #animateHighlightedDegree(float, float, long)
*/
public void setOnHighlightAnimationEndListener(final OnHighlightAnimationEndListener l) {
mOnHighlightAnimationEndListener = l;
}
/**
* Start animating the highlighted degree. This will cancel any current animations of this type.
* Pass <code>true</code> to {@link #setAnimateMarkerOnStillHighlight(boolean)} in order to see individual
* marker animations when the highlighted degree reaches each marker.
*
* @param startDegree Degree to start the animation at.
* @param endDegree Degree to end the animation at.
* @param duration Duration the animation should be.
*/
public void animateHighlightedDegree(final float startDegree, final float endDegree, final long duration) {
animateHighlightedDegree(startDegree, endDegree, duration, true);
}
/**
* Start animating the highlighted degree. This will cancel any current animations of this type.
* Pass <code>true</code> to {@link #setAnimateMarkerOnStillHighlight(boolean)} in order to see individual
* marker animations when the highlighted degree reaches each marker.
*
* @param startDegree Degree to start the animation at.
* @param endDegree Degree to end the animation at.
* @param duration Duration the animation should be.
* @param animateMarkers True to animate markers during the animation. False to not animate the markers.
*/
public void animateHighlightedDegree(final float startDegree, final float endDegree, final long duration, final boolean animateMarkers) {
mHighlightedDegreeObjectAnimator.cancel();
mHighlightedDegreeObjectAnimator.setFloatValues(startDegree, endDegree);
mHighlightedDegreeObjectAnimator.setDuration(duration);
mAnimateMarkersOnHighlightAnimation = animateMarkers;
mIsAnimating = true;
mHighlightedDegreeObjectAnimator.start();
}
private boolean mAnimationWasCanceled = false;
private final Animator.AnimatorListener mAnimatorListener = new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
mAnimateMarkersOnHighlightAnimation = mIsAnimating = false;
if (!mAnimationWasCanceled) {
setHighlightedDegree(getHighlightedDegree());
if (mOnHighlightAnimationEndListener != null && mHighlightedMarker != null) {
// Highlighted marker will be set by setHighlightedDegree
mOnHighlightAnimationEndListener.onHighlightAnimationEnd(CircularView.this, mHighlightedMarker, mHighlightedMarkerPosition);
}
} else {
mAnimationWasCanceled = false;
}
}
@Override
public void onAnimationCancel(Animator animation) {
mAnimationWasCanceled = true;
}
@Override
public void onAnimationRepeat(Animator animation) {
}
};
/**
* Get the starting point for the markers.
*
* @return The starting point for the markers.
* @attr ref R.styleable#CircularView_markerStartingPoint
*/
public float getMarkerStartingPoint() {
return mMarkerStartingPoint;
}
/**
* Set the starting point for the markers
*
* @param startingPoint Starting point for the markers
* @attr ref R.styleable#CircularView_markerStartingPoint
*/
public void setMarkerStartingPoint(final float startingPoint) {
mMarkerStartingPoint = startingPoint;
requestLayout();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
// Remove all callback references from the center circle
mCircle.setCallback(null);
// Remove all callback references from the markers
if (mMarkerList != null) {
for (final Marker marker : mMarkerList) {
marker.cancelAnimation();
marker.setCallback(null);
}
}
// Unregister adapter observer
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mAdapterDataSetObserver);
}
}
class AdapterDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
requestLayout();
}
/**
* Does the same thing as {@link #onChanged()}.
*/
@Override
public void onInvalidated() {
postInvalidate();
}
}
/**
* Use this to register for click event callbacks from CircularEventObjects
*/
public interface OnClickListener {
/**
* Called when the center view object has been clicked.
*
* @param view The circular view that was clicked.
*/
public void onClick(CircularView view);
/**
* Called when a marker is clicked.
*
* @param view The circular view that the marker belongs to
* @param marker The marker that was clicked.
* @param position The position of the marker in the adapter
*/
public void onMarkerClick(CircularView view, Marker marker, int position);
}
/**
* Use this to register for callback events when the highlight animation finishes executing.
*/
public interface OnHighlightAnimationEndListener {
/**
* Called when the highlight animation ends. This is <b>not</b> called when the animation is canceled.
*
* @param view The circular view that the marker belongs to.
* @param marker The circular view object that the animation ended on.
* @param position The position of the marker in the adapter.
*/
public void onHighlightAnimationEnd(CircularView view, Marker marker, int position);
}
} |
package io.vertx.ext.web;
import io.vertx.core.Handler;
import io.vertx.core.MultiMap;
import io.vertx.core.http.HttpMethod;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
public class RouterTest extends WebTestBase {
@Test
public void testSimpleRoute() throws Exception {
router.route().handler(rc -> rc.response().end());
testRequest(HttpMethod.GET, "/", 200, "OK");
}
@Test
public void testInvalidPath() throws Exception {
try {
router.route("blah");
fail();
} catch (IllegalArgumentException e) {
}
try {
router.route().path("blah");
fail();
} catch (IllegalArgumentException e) {
}
}
@Test
public void testRouteGetPath() throws Exception {
assertEquals("/foo", router.route("/foo").getPath());
assertEquals("/foo/:id", router.route("/foo/:id").getPath());
}
@Test
public void testRouteGetPathWithParamsInHandler() throws Exception {
router.route("/foo/:id").handler(rc -> {
assertEquals("/foo/123", rc.normalisedPath());
rc.response().end();
});
testRequest(HttpMethod.GET, "/foo/123", 200, "OK");
}
@Test
public void testRoutePathAndMethod() throws Exception {
for (HttpMethod meth: METHODS) {
testRoutePathAndMethod(meth, true);
}
}
@Test
public void testRoutePathAndMethodBegin() throws Exception {
for (HttpMethod meth: METHODS) {
testRoutePathAndMethod(meth, false);
}
}
private void testRoutePathAndMethod(HttpMethod method, boolean exact) throws Exception {
String path = "/blah";
router.clear();
router.route(method, exact ? path : path + "*").handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
if (exact) {
testPathExact(method, path);
} else {
testPathBegin(method, path);
}
for (HttpMethod meth: METHODS) {
if (meth != method) {
testRequest(meth, path, 404, "Not Found");
}
}
}
@Test
public void testRoutePathOnly() throws Exception {
String path1 = "/blah";
router.route(path1).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
String path2 = "/quux";
router.route(path2).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathExact(path1);
testPathExact(path2);
}
@Test
public void testRoutePathOnlyBegin() throws Exception {
String path1 = "/blah";
router.route(path1 + "*").handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
String path2 = "/quux";
router.route(path2 + "*").handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathBegin(path1);
testPathBegin(path2);
}
@Test
public void testRoutePathWithTrailingSlashOnlyBegin() throws Exception {
String path = "/some/path/";
router.route(path + "*").handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathBegin(path);
}
@Test
public void testRoutePathBuilder() throws Exception {
String path = "/blah";
router.route().path(path).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathExact(path);
}
@Test
public void testRoutePathBuilderBegin() throws Exception {
String path = "/blah";
router.route().path(path + "*").handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathBegin(path);
}
@Test
public void testRoutePathAndMethodBuilder() throws Exception {
String path = "/blah";
router.route().path(path).method(HttpMethod.GET).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathExact(HttpMethod.GET, path);
testRequest(HttpMethod.POST, path, 404, "Not Found");
}
@Test
public void testRoutePathAndMethodBuilderBegin() throws Exception {
String path = "/blah";
router.route().path(path + "*").method(HttpMethod.GET).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathBegin(HttpMethod.GET, path);
testRequest(HttpMethod.POST, path, 404, "Not Found");
}
@Test
public void testRoutePathAndMultipleMethodBuilder() throws Exception {
String path = "/blah";
router.route().path(path).method(HttpMethod.GET).method(HttpMethod.POST).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathExact(HttpMethod.GET, path);
testPathExact(HttpMethod.POST, path);
testRequest(HttpMethod.PUT, path, 404, "Not Found");
}
@Test
public void testRoutePathAndMultipleMethodBuilderBegin() throws Exception {
String path = "/blah";
router.route().path(path + "*").method(HttpMethod.GET).method(HttpMethod.POST).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testPathBegin(HttpMethod.GET, path);
testPathBegin(HttpMethod.POST, path);
testRequest(HttpMethod.PUT, path, 404, "Not Found");
}
private void testPathBegin(String path) throws Exception {
for (HttpMethod meth: METHODS) {
testPathBegin(meth, path);
}
}
private void testPathExact(String path) throws Exception {
for (HttpMethod meth: METHODS) {
testPathExact(meth, path);
}
}
private void testPathBegin(HttpMethod method, String path) throws Exception {
testRequest(method, path, 200, path);
testRequest(method, path + "wibble", 200, path + "wibble");
if (path.endsWith("/")) {
testRequest(method, path.substring(0, path.length() - 1) + "wibble", 404, "Not Found");
testRequest(method, path.substring(0, path.length() - 1) + "/wibble", 200, path.substring(0, path.length() - 1) + "/wibble");
} else {
testRequest(method, path + "/wibble", 200, path + "/wibble");
testRequest(method, path + "/wibble/floob", 200, path + "/wibble/floob");
testRequest(method, path.substring(0, path.length() - 1), 404, "Not Found");
}
testRequest(method, "/", 404, "Not Found");
testRequest(method, "/" + UUID.randomUUID().toString(), 404, "Not Found");
}
private void testPathExact(HttpMethod method, String path) throws Exception {
testRequest(method, path, 200, path);
testRequest(method, path + "wibble", 404, "Not Found");
testRequest(method, path + "/wibble", 404, "Not Found");
testRequest(method, path + "/wibble/floob", 404, "Not Found");
testRequest(method, path.substring(0, path.length() - 1), 404, "Not Found");
testRequest(method, "/", 404, "Not Found");
testRequest(method, "/" + UUID.randomUUID().toString(), 404, "Not Found");
}
@Test
public void testRouteNoPath() throws Exception {
router.route().handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
for (HttpMethod meth: METHODS) {
testNoPath(meth);
}
}
@Test
public void testRouteNoPath2() throws Exception {
router.route().handler(rc -> {
rc.response().setStatusMessage(rc.request().path());
rc.next();
});
router.route().handler(rc -> {
rc.response().setStatusCode(200).end();
});
for (HttpMethod meth: METHODS) {
testNoPath(meth);
}
}
@Test
public void testRouteNoPathWithMethod() throws Exception {
for (HttpMethod meth: METHODS) {
testRouteNoPathWithMethod(meth);
}
}
private void testRouteNoPathWithMethod(HttpMethod meth) throws Exception {
router.clear();
router.route().method(meth).handler(rc -> {
rc.response().setStatusCode(200).setStatusMessage(rc.request().path()).end();
});
testNoPath(meth);
for (HttpMethod m: METHODS) {
if (m != meth) {
testRequest(m, "/whatever", 404, "Not Found");
}
}
}
private void testNoPath(HttpMethod method) throws Exception {
testRequest(method, "/", 200, "/");
testRequest(method, "/wibble", 200, "/wibble");
String rand = "/" + UUID.randomUUID().toString();
testRequest(method, rand, 200, rand);
}
@Test
public void testChaining() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.response().setChunked(true);
rc.response().write("apples");
rc.next();
});
router.route(path).handler(rc -> {
rc.response().write("oranges");
rc.next();
});
router.route(path).handler(rc -> {
rc.response().write("bananas");
rc.response().end();
});
testRequest(HttpMethod.GET, path, 200, "OK", "applesorangesbananas");
}
@Test
public void testAsyncChaining() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.response().setChunked(true);
rc.response().write("apples");
vertx.runOnContext(v -> rc.next());
});
router.route(path).handler(rc -> {
rc.response().write("oranges");
vertx.runOnContext(v -> rc.next());
});
router.route(path).handler(rc -> {
rc.response().write("bananas");
rc.response().end();
});
testRequest(HttpMethod.GET, path, 200, "OK", "applesorangesbananas");
}
@Test
public void testChainingWithTimers() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.response().setChunked(true);
rc.response().write("apples");
vertx.setTimer(1, v -> rc.next());
});
router.route(path).handler(rc -> {
rc.response().write("oranges");
vertx.setTimer(1, v -> rc.next());
});
router.route(path).handler(rc -> {
rc.response().write("bananas");
rc.response().end();
});
testRequest(HttpMethod.GET, path, 200, "OK", "applesorangesbananas");
}
@Test
public void testOrdering() throws Exception {
String path = "/blah";
router.route(path).order(1).handler(rc -> {
rc.response().write("apples");
rc.next();
});
router.route(path).order(2).handler(rc -> {
rc.response().write("oranges");
rc.response().end();
});
router.route(path).order(0).handler(rc -> {
rc.response().setChunked(true);
rc.response().write("bananas");
rc.next();
});
testRequest(HttpMethod.GET, path, 200, "OK", "bananasapplesoranges");
}
@Test
public void testLast() throws Exception {
String path = "/blah";
Route route = router.route(path);
router.route(path).handler(rc -> {
rc.response().setChunked(true);
rc.response().write("oranges");
rc.next();
});
router.route(path).handler(rc -> {
rc.response().write("bananas");
rc.next();
});
route.last();
route.handler(rc -> {
rc.response().write("apples");
rc.response().end();
});
testRequest(HttpMethod.GET, path, 200, "OK", "orangesbananasapples");
}
@Test
public void testDisableEnable() throws Exception {
String path = "/blah";
Route route1 = router.route(path).handler(rc -> {
rc.response().setChunked(true);
rc.response().write("apples");
rc.next();
});;
Route route2 = router.route(path).handler(rc -> {
rc.response().write("oranges");
rc.next();
});
Route route3 = router.route(path).handler(rc -> {
rc.response().write("bananas");
rc.response().end();
});
testRequest(HttpMethod.GET, path, 200, "OK", "applesorangesbananas");
route2.disable();
testRequest(HttpMethod.GET, path, 200, "OK", "applesbananas");
route1.disable();
route3.disable();
testRequest(HttpMethod.GET, path, 404, "Not Found");
route3.enable();
route1.enable();
testRequest(HttpMethod.GET, path, 200, "OK", "applesbananas");
route2.enable();
testRequest(HttpMethod.GET, path, 200, "OK", "applesorangesbananas");
}
@Test
public void testRemove() throws Exception {
String path = "/blah";
Route route1 = router.route(path).handler(rc -> {
rc.response().setChunked(true);
rc.response().write("apples");
rc.next();
});;
Route route2 = router.route(path).handler(rc -> {
rc.response().write("oranges");
rc.next();
});
Route route3 = router.route(path).handler(rc -> {
rc.response().write("bananas");
rc.response().end();
});
testRequest(HttpMethod.GET, path, 200, "OK", "applesorangesbananas");
route2.remove();
testRequest(HttpMethod.GET, path, 200, "OK", "applesbananas");
route1.remove();
route3.remove();
testRequest(HttpMethod.GET, path, 404, "Not Found");
}
@Test
public void testClear() throws Exception {
router.route().handler(rc -> {
rc.response().setChunked(true);
rc.response().write("apples");
rc.next();
});
router.route().handler(rc -> {
rc.response().write("bananas");
rc.response().end();
});
testRequest(HttpMethod.GET, "/whatever", 200, "OK", "applesbananas");
router.clear();
router.route().handler(rc -> {
rc.response().setChunked(true);
rc.response().write("grapes");
rc.response().end();
});
testRequest(HttpMethod.GET, "/whatever", 200, "OK", "grapes");
}
@Test
public void testChangeOrderAfterActive1() throws Exception {
String path = "/blah";
Route route = router.route(path).handler(rc -> {
rc.response().write("apples");
rc.next();
});
try {
route.order(23);
fail();
} catch (IllegalStateException e) {
}
}
@Test
public void testChangeOrderAfterActive2() throws Exception {
String path = "/blah";
Route route = router.route(path).failureHandler(rc -> {
rc.response().write("apples");
rc.next();
});
try {
route.order(23);
fail();
} catch (IllegalStateException e) {
}
}
@Test
public void testNextAfterResponseEnded() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.response().end();
rc.next(); // Call next
});
router.route(path).handler(rc -> {
assertTrue(rc.response().ended());
});
testRequest(HttpMethod.GET, path, 200, "OK");
}
@Test
public void testFailureHandler1() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
throw new RuntimeException("ouch!");
}).failureHandler(frc -> {
frc.response().setStatusCode(555).setStatusMessage("oh dear").end();
});
testRequest(HttpMethod.GET, path, 555, "oh dear");
}
@Test
public void testFailureinHandlingFailure() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
throw new RuntimeException("ouch!");
}).failureHandler(frc -> {
throw new RuntimeException("super ouch!");
});
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
}
@Test
public void testFailureUsingInvalidCharsInStatus() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.response().setStatusMessage("Hello\nWorld!").end();
});
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
}
@Test
public void testFailureinHandlingFailureWithInvalidStatusMessage() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
throw new RuntimeException("ouch!");
}).failureHandler(frc -> {
frc.response().setStatusMessage("Hello\nWorld").end();
});
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
}
@Test
public void testSetExceptionHandler() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
throw new RuntimeException("ouch!");
});
CountDownLatch latch = new CountDownLatch(1);
router.exceptionHandler(t -> {
assertEquals("ouch!", t.getMessage());
latch.countDown();
});
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
awaitLatch(latch);
}
@Test
public void testFailureHandler1CallFail() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.fail(400);
}).failureHandler(frc -> {
assertEquals(400, frc.statusCode());
frc.response().setStatusCode(400).setStatusMessage("oh dear").end();
});
testRequest(HttpMethod.GET, path, 400, "oh dear");
}
@Test
public void testFailureHandler2() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
throw new RuntimeException("ouch!");
});
router.route("/bl*").failureHandler(frc -> {
frc.response().setStatusCode(555).setStatusMessage("oh dear").end();
});
testRequest(HttpMethod.GET, path, 555, "oh dear");
}
@Test
public void testFailureHandler2CallFail() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.fail(400);
});
router.route("/bl*").failureHandler(frc -> {
assertEquals(400, frc.statusCode());
frc.response().setStatusCode(400).setStatusMessage("oh dear").end();
});
testRequest(HttpMethod.GET, path, 400, "oh dear");
}
@Test
public void testDefaultFailureHandler() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
throw new RuntimeException("ouch!");
});
// Default failure response
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
}
@Test
public void testDefaultFailureHandlerCallFail() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.fail(400);
});
// Default failure response
testRequest(HttpMethod.GET, path, 400, "Bad Request");
}
@Test
public void testFailureHandlerNoMatch() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
throw new RuntimeException("ouch!");
});
router.route("/other").failureHandler(frc -> {
frc.response().setStatusCode(555).setStatusMessage("oh dear").end();
});
// Default failure response
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
}
@Test
public void testFailureWithThrowable() throws Exception {
String path = "/blah";
Throwable failure = new Throwable();
router.route(path).handler(rc -> {
rc.fail(failure);
}).failureHandler(frc -> {
assertEquals(-1, frc.statusCode());
assertSame(failure, frc.failure());
frc.response().setStatusCode(500).setStatusMessage("Internal Server Error").end();
});
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
}
@Test
public void testFailureWithNullThrowable() throws Exception {
String path = "/blah";
router.route(path).handler(rc -> {
rc.fail(null);
}).failureHandler(frc -> {
assertEquals(-1, frc.statusCode());
assertTrue(frc.failure() instanceof NullPointerException);
frc.response().setStatusCode(500).setStatusMessage("Internal Server Error").end();
});
testRequest(HttpMethod.GET, path, 500, "Internal Server Error");
}
@Test
public void testPattern1() throws Exception {
router.route("/:abc").handler(rc -> {
rc.response().setStatusMessage(rc.request().params().get("abc")).end();
});
testPattern("/tim", "tim");
}
@Test
public void testParamEscape() throws Exception {
router.route("/demo/:abc").handler(rc -> {
assertEquals("Hello World!", rc.request().params().get("abc"));
rc.response().end(rc.request().params().get("abc"));
});
testRequest(HttpMethod.GET, "/demo/Hello%20World!", 200, "OK", "Hello World!");
}
@Test
public void testParamEscape2() throws Exception {
router.route("/demo/:abc").handler(rc -> {
assertEquals("Hello/World!", rc.request().params().get("abc"));
rc.response().end(rc.request().params().get("abc"));
});
testRequest(HttpMethod.GET, "/demo/Hello%2FWorld!", 200, "OK", "Hello/World!");
}
@Test
public void testParamEscape3() throws Exception {
router.route("/demo/:abc").handler(rc -> {
assertEquals("http:
rc.response().end(rc.request().params().get("abc"));
});
testRequest(HttpMethod.GET, "/demo/http%3A%2F%2Fwww.google.com", 200, "OK", "http:
}
@Test
public void testParamEscape4() throws Exception {
router.route("/:var").handler(rc -> {
assertEquals("/ping", rc.request().params().get("var"));
rc.response().end(rc.request().params().get("var"));
});
testRequest(HttpMethod.GET, "/%2Fping", 200, "OK", "/ping");
}
@Test
public void testPattern1WithMethod() throws Exception {
router.route(HttpMethod.GET, "/:abc").handler(rc -> {
rc.response().setStatusMessage(rc.request().params().get("abc")).end();
});
testPattern("/tim", "tim");
testRequest(HttpMethod.POST, "/tim", 404, "Not Found");
}
@Test
public void testPattern1WithBuilder() throws Exception {
router.route().path("/:abc").handler(rc -> {
rc.response().setStatusMessage(rc.request().params().get("abc")).end();
});
testPattern("/tim", "tim");
}
@Test
public void testPattern2() throws Exception {
router.route("/blah/:abc").handler(rc -> {
rc.response().setStatusMessage(rc.request().params().get("abc")).end();
});
testPattern("/blah/tim", "tim");
}
@Test
public void testPattern3() throws Exception {
router.route("/blah/:abc/blah").handler(rc -> {
rc.response().setStatusMessage(rc.request().params().get("abc")).end();
});
testPattern("/blah/tim/blah", "tim");
}
@Test
public void testPattern4() throws Exception {
router.route("/blah/:abc/foo").handler(rc -> {
rc.response().setStatusMessage(rc.request().params().get("abc")).end();
});
testPattern("/blah/tim/foo", "tim");
}
@Test
public void testPattern5() throws Exception {
router.route("/blah/:abc/:def/:ghi").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("abc") + params.get("def") + params.get("ghi")).end();
});
testPattern("/blah/tim/julien/nick", "timjuliennick");
}
@Test
public void testPattern6() throws Exception {
router.route("/blah/:abc/:def/:ghi/blah").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("abc") + params.get("def") + params.get("ghi")).end();
});
testPattern("/blah/tim/julien/nick/blah", "timjuliennick");
}
@Test
public void testPattern7() throws Exception {
router.route("/blah/:abc/quux/:def/eep/:ghi").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("abc") + params.get("def") + params.get("ghi")).end();
});
testPattern("/blah/tim/quux/julien/eep/nick", "timjuliennick");
}
@Test
public void testPathParamsAreFulfilled() throws Exception {
router.route("/blah/:abc/quux/:def/eep/:ghi").handler(rc -> {
Map<String, String> params = rc.pathParams();
rc.response().setStatusMessage(params.get("abc") + params.get("def") + params.get("ghi")).end();
});
testPattern("/blah/tim/quux/julien/eep/nick", "timjuliennick");
}
@Test
public void testPathParamsDoesNotOverrideQueryParam() throws Exception {
final String paramName = "param";
final String pathParamValue = "pathParamValue";
final String queryParamValue1 = "queryParamValue1";
final String queryParamValue2 = "queryParamValue2";
final String sep = ",";
router.route("/blah/:" + paramName + "/test").handler(rc -> {
Map<String, String> params = rc.pathParams();
MultiMap queryParams = rc.request().params();
List<String> values = queryParams.getAll(paramName);
String qValue = values.stream().collect(Collectors.joining(sep));
rc.response().setStatusMessage(params.get(paramName) + "|" + qValue).end();
});
testRequest(HttpMethod.GET,
"/blah/" + pathParamValue + "/test?" + paramName + "=" + queryParamValue1 + "&" + paramName + "=" + queryParamValue2,
200,
pathParamValue + "|" + queryParamValue1 + sep + queryParamValue2);
}
@Test
public void testPathParamsWithReroute() throws Exception {
String paramName = "param";
String firstParamValue = "fpv";
String secondParamValue = "secondParamValue";
router.route("/first/:" + paramName + "/route").handler(rc -> {
assertEquals(firstParamValue, rc.pathParam(paramName));
rc.reroute(HttpMethod.GET, "/second/" + secondParamValue + "/route");
});
router.route("/second/:" + paramName + "/route").handler(rc -> {
rc.response().setStatusMessage(rc.pathParam(paramName)).end();
});
testRequest(HttpMethod.GET, "/first/" + firstParamValue + "/route", 200, secondParamValue);
}
private void testPattern(String pathRoot, String expected) throws Exception {
testRequest(HttpMethod.GET, pathRoot, 200, expected);
testRequest(HttpMethod.GET, pathRoot + "/", 404, "Not Found");
testRequest(HttpMethod.GET, pathRoot + "/wibble", 404, "Not Found");
testRequest(HttpMethod.GET, pathRoot + "/wibble/blibble", 404, "Not Found");
}
@Test
public void testInvalidPattern() throws Exception {
router.route("/blah/:!!!/").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("!!!")).end();
});
testRequest(HttpMethod.GET, "/blah/tim", 404, "Not Found"); // Because it won't match
}
@Test
public void testInvalidPatternWithBuilder() throws Exception {
router.route().path("/blah/:!!!/").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("!!!")).end();
});
testRequest(HttpMethod.GET, "/blah/tim", 404, "Not Found"); // Because it won't match
}
@Test
public void testGroupMoreThanOne() throws Exception {
try {
router.route("/blah/:abc/:abc");
fail();
} catch (IllegalArgumentException e) {
}
}
@Test
public void testRegex1() throws Exception {
router.routeWithRegex("\\/([^\\/]+)\\/([^\\/]+)").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("param0") + params.get("param1")).end();
});
testPattern("/dog/cat", "dogcat");
}
@Test
public void testRegex1WithBuilder() throws Exception {
router.route().pathRegex("\\/([^\\/]+)\\/([^\\/]+)").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("param0") + params.get("param1")).end();
});
testPattern("/dog/cat", "dogcat");
}
@Test
public void testRegex1WithMethod() throws Exception {
router.routeWithRegex(HttpMethod.GET, "\\/([^\\/]+)\\/([^\\/]+)").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("param0") + params.get("param1")).end();
});
testPattern("/dog/cat", "dogcat");
testRequest(HttpMethod.POST, "/dog/cat", 404, "Not Found");
}
@Test
public void testRegex2() throws Exception {
router.routeWithRegex("\\/([^\\/]+)\\/([^\\/]+)/blah").handler(rc -> {
MultiMap params = rc.request().params();
rc.response().setStatusMessage(params.get("param0") + params.get("param1")).end();
});
testPattern("/dog/cat/blah", "dogcat");
}
@Test
public void testRegex3() throws Exception {
router.routeWithRegex(".*foo.txt").handler(rc -> {
rc.response().setStatusMessage("ok").end();
});
testPattern("/dog/cat/foo.txt", "ok");
testRequest(HttpMethod.POST, "/dog/cat/foo.bar", 404, "Not Found");
}
@Test
public void testConsumes() throws Exception {
router.route().consumes("text/html").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 404, "Not Found");
testRequestWithContentType(HttpMethod.GET, "/foo", "something/html", 404, "Not Found");
}
@Test
public void testConsumesMultiple() throws Exception {
router.route().consumes("text/html").consumes("application/json").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 404, "Not Found");
testRequestWithContentType(HttpMethod.GET, "/foo", "something/html", 404, "Not Found");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 404, "Not Found");
testRequestWithContentType(HttpMethod.GET, "/foo", "application/blah", 404, "Not Found");
}
@Test
public void testConsumesMissingSlash() throws Exception {
// will assume "*/json"
router.route().consumes("json").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 404, "Not Found");
}
@Test
public void testConsumesSubtypeWildcard() throws Exception {
router.route().consumes("text/*").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 404, "Not Found");
}
@Test
public void testConsumesTopLevelTypeWildcard() throws Exception {
router.route().consumes("*/json").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "text/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "application/html", 404, "Not Found");
}
@Test
public void testConsumesAll1() throws Exception {
router.route().consumes("*/*").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html; someparam=12", 200, "OK");
testRequest(HttpMethod.GET, "/foo", 200, "OK");
}
@Test
public void testConsumesAll2() throws Exception {
router.route().consumes("*").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "application/json", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html", 200, "OK");
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html; someparam=12", 200, "OK");
testRequest(HttpMethod.GET, "/foo", 200, "OK");
}
@Test
public void testConsumesCTParamsIgnored() throws Exception {
router.route().consumes("text/html").handler(rc -> rc.response().end());
testRequestWithContentType(HttpMethod.GET, "/foo", "text/html; someparam=12", 200, "OK");
}
@Test
public void testConsumesNoContentType() throws Exception {
router.route().consumes("text/html").handler(rc -> rc.response().end());
testRequest(HttpMethod.GET, "/foo", 404, "Not Found");
}
@Test
public void testProduces() throws Exception {
router.route().produces("text/html").handler(rc -> rc.response().end());
testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 200, "OK");
testRequestWithAccepts(HttpMethod.GET, "/foo", "text/json", 404, "Not Found");
testRequestWithAccepts(HttpMethod.GET, "/foo", "something/html", 404, "Not Found");
testRequest(HttpMethod.GET, "/foo", 200, "OK");
}
@Test
public void testProducesMultiple() throws Exception {
router.route().produces("text/html").produces("application/json").handler(rc -> rc.response().end());
testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html", 200, "OK");
testRequestWithAccepts(HttpMethod.GET, "/foo", "application/json", 200, "OK");
testRequestWithAccepts(HttpMethod.GET, "/foo", "text/json", 404, "Not Found");
testRequestWithAccepts(HttpMethod.GET, "/foo", "something/html", 404, "Not Found");
testRequestWithAccepts(HttpMethod.GET, "/foo", "text/json", 404, "Not Found");
testRequestWithAccepts(HttpMethod.GET, "/foo", "application/blah", 404, "Not Found");
}
@Test
public void testProducesMissingSlash() throws Exception {
// will assume "*/json"
router.route().produces("application/json").handler(rc -> {
rc.response().setStatusMessage(rc.getAcceptableContentType());
rc.response().end();
});
testRequestWithAccepts(HttpMethod.GET, "/foo", "json", 200, "application/json");
testRequestWithAccepts(HttpMethod.GET, "/foo", "text", 404, "Not Found");
}
@Test
public void testProducesSubtypeWildcard() throws Exception {
router.route().produces("text/html").handler(rc -> {
rc.response().setStatusMessage(rc.getAcceptableContentType());
rc.response().end();
});
testRequestWithAccepts(HttpMethod.GET, "/foo", "application/*", 404, "Not Found");
}
@Test
public void testProducesTopLevelTypeWildcard() throws Exception {
router.route().produces("application/json").handler(rc -> {
rc.response().setStatusMessage(rc.getAcceptableContentType());
rc.response().end();
});
testRequestWithAccepts(HttpMethod.GET, "/foo", "*/json", 200, "application/json");
testRequestWithAccepts(HttpMethod.GET, "/foo", "*/html", 404, "Not Found");
}
@Test
public void testProducesAll1() throws Exception {
router.route().produces("application/json").handler(rc -> {
rc.response().setStatusMessage(rc.getAcceptableContentType());
rc.response().end();
});
testRequestWithAccepts(HttpMethod.GET, "/foo", "*/*", 200, "application/json");
}
@Test
public void testProducesAll2() throws Exception {
router.route().produces("application/json").handler(rc -> {
rc.response().setStatusMessage(rc.getAcceptableContentType());
rc.response().end();
});
testRequestWithAccepts(HttpMethod.GET, "/foo", "*", 200, "application/json");
}
@Test
public void testAcceptsMultiple1() throws Exception {
router.route().produces("application/json").handler(rc -> {
rc.response().setStatusMessage(rc.getAcceptableContentType());
rc.response().end();
});
testRequestWithAccepts(HttpMethod.GET, "/foo", "text/html,application/json,text/plain", 200, "application/json");
}
@Test
public void testAcceptsMultiple2() throws Exception {
router.route().produces("application/json").handler(rc -> {
rc.response().setStatusMessage(rc.getAcceptableContentType());
rc.response().end();
}); |
package aQute.bnd.build;
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.*;
import aQute.bnd.differ.*;
import aQute.bnd.differ.Baseline.Info;
import aQute.bnd.header.*;
import aQute.bnd.osgi.*;
import aQute.bnd.service.*;
import aQute.bnd.service.repository.*;
import aQute.bnd.service.repository.SearchableRepository.ResourceDescriptor;
import aQute.bnd.version.*;
import aQute.lib.collections.*;
import aQute.lib.io.*;
public class ProjectBuilder extends Builder {
private final DiffPluginImpl differ = new DiffPluginImpl();
Project project;
boolean initialized;
public ProjectBuilder(Project project) {
super(project);
this.project = project;
String diffignore = project.getProperty(Constants.DIFFIGNORE);
if (diffignore != null)
differ.setIgnore(diffignore);
}
public ProjectBuilder(ProjectBuilder builder) {
super(builder);
this.project = builder.project;
}
@Override
public long lastModified() {
return Math.max(project.lastModified(), super.lastModified());
}
/**
* We put our project and our workspace on the macro path.
*/
@Override
protected Object[] getMacroDomains() {
return new Object[] {
project, project.getWorkspace()
};
}
@Override
public Builder getSubBuilder() throws Exception {
return project.getBuilder(this);
}
public Project getProject() {
return project;
}
@Override
public void init() {
try {
if (!initialized) {
initialized = true;
for (Container file : project.getClasspath()) {
addClasspath(file.getFile());
}
for (Container file : project.getBuildpath()) {
addClasspath(file.getFile());
}
for (Container file : project.getBootclasspath()) {
addClasspath(file.getFile());
}
for (File file : project.getAllsourcepath()) {
addSourcepath(file);
}
}
}
catch (Exception e) {
msgs.Unexpected_Error_("ProjectBuilder init", e);
}
}
@Override
public List<Jar> getClasspath() {
init();
return super.getClasspath();
}
@Override
protected void changedFile(File f) {
project.getWorkspace().changedFile(f);
}
/**
* Compare this builder's JAR with a baseline
*
* @throws Exception
*/
@Override
public void doBaseline(Jar dot) throws Exception {
Jar fromRepo = getBaselineJar();
if (fromRepo == null) {
trace("No baseline jar %s", getProperty(Constants.BASELINE));
return;
}
Version newer = new Version(getVersion());
Version older = new Version(fromRepo.getVersion());
if (!getBsn().equals(fromRepo.getBsn())) {
error("The symbolic name of this project (%s) is not the same as the baseline: %s", getBsn(),
fromRepo.getBsn());
return;
}
// Check if we want to overwrite an equal version that is not staging
if (newer.getWithoutQualifier().equals(older.getWithoutQualifier())) {
RepositoryPlugin rr = getReleaseRepo();
if (rr instanceof InfoRepository) {
ResourceDescriptor descriptor = ((InfoRepository) rr).getDescriptor(getBsn(), older);
if (descriptor != null && descriptor.phase != Phase.STAGING) {
error("Baselining %s against same version %s but the repository says the older repository version is not the required %s but is instead %s",
getBsn(), getVersion(), Phase.STAGING, descriptor.phase);
return;
}
}
}
trace("baseline %s-%s against: %s", getBsn(), getVersion(), fromRepo.getName());
try {
Baseline baseliner = new Baseline(this, differ);
Set<Info> infos = baseliner.baseline(dot, fromRepo, null);
if (infos.isEmpty())
trace("no deltas");
for (Info info : infos) {
if (info.mismatch) {
SetLocation l = error(
"Baseline mismatch for package %s, %s change. Current is %s, repo is %s, suggest %s or %s\n",
info.packageName, info.packageDiff.getDelta(), info.newerVersion, info.olderVersion,
info.suggestedVersion, info.suggestedIfProviders == null ? "-" : info.suggestedIfProviders);
l.header(Constants.BASELINE);
fillInLocationForPackageInfo(l.location(), info.packageName);
if (getPropertiesFile() != null)
l.file(getPropertiesFile().getAbsolutePath());
l.details(info);
}
}
aQute.bnd.differ.Baseline.BundleInfo binfo = baseliner.getBundleInfo();
if (binfo.mismatch) {
SetLocation error = error("The bundle version %s is too low, must be at least %s", binfo.version,
binfo.suggestedVersion);
error.context("Baselining");
error.header(Constants.BUNDLE_VERSION);
error.details(binfo);
FileLine fl = getHeader(Pattern.compile("^" + Constants.BUNDLE_VERSION, Pattern.MULTILINE));
if (fl != null) {
error.file(fl.file.getAbsolutePath());
error.line(fl.line);
error.length(fl.length);
}
}
}
finally {
fromRepo.close();
}
}
public void fillInLocationForPackageInfo(Location location, String packageName) throws Exception {
Parameters eps = getExportPackage();
Attrs attrs = eps.get(packageName);
FileLine fl;
if (attrs != null && attrs.containsKey(Constants.VERSION_ATTRIBUTE)) {
fl = getHeader(Pattern.compile(Constants.EXPORT_PACKAGE, Pattern.CASE_INSENSITIVE));
if (fl != null) {
location.file = fl.file.getAbsolutePath();
location.line = fl.line;
location.length = fl.length;
return;
}
}
Parameters ecs = getExportContents();
attrs = ecs.get(packageName);
if (attrs != null && attrs.containsKey(Constants.VERSION_ATTRIBUTE)) {
fl = getHeader(Pattern.compile(Constants.EXPORT_CONTENTS, Pattern.CASE_INSENSITIVE));
if (fl != null) {
location.file = fl.file.getAbsolutePath();
location.line = fl.line;
location.length = fl.length;
return;
}
}
for (File src : project.getSourcePath()) {
String path = packageName.replace('.', '/');
File packageDir = IO.getFile(src, path);
File pi = IO.getFile(packageDir, "package-info.java");
if (pi.isFile()) {
fl = findHeader(pi, Pattern.compile("@Version\\s*([^)]+)"));
if (fl != null) {
location.file = fl.file.getAbsolutePath();
location.line = fl.line;
location.length = fl.length;
return;
}
}
pi = IO.getFile(packageDir, "packageinfo");
if (pi.isFile()) {
fl = findHeader(pi, Pattern.compile("^\\s*version.*$"));
if (fl != null) {
location.file = fl.file.getAbsolutePath();
location.line = fl.line;
location.length = fl.length;
return;
}
}
}
}
public Jar getLastRevision() throws Exception {
RepositoryPlugin releaseRepo = getReleaseRepo();
SortedSet<Version> versions = releaseRepo.versions(getBsn());
if (versions.isEmpty())
return null;
Jar jar = new Jar(releaseRepo.get(getBsn(), versions.last(), null));
addClose(jar);
return jar;
}
/**
* This method attempts to find the baseline jar for the current project. It
* reads the -baseline property and treats it as instructions. These
* instructions are matched against the bsns of the jars (think sub
* builders!). If they match, the sub builder is selected.
* <p>
* The instruction can then specify the following options:
*
* <pre>
* version : baseline version from repository
* file : a file path
* </pre>
*
* If neither is specified, the current version is used to find the highest
* version (without qualifier) that is below the current version. If a
* version is specified, we take the highest version with the same base
* version.
* <p>
* Since baselining is expensive and easily generates errors you must enable
* it. The easiest solution is to {@code -baseline: *}. This will match all
* sub builders and will calculate the version.
*
* @return a Jar or null
*/
public Jar getBaselineJar() throws Exception {
String bl = getProperty(Constants.BASELINE);
if (bl == null || Constants.NONE.equals(bl))
return null;
Instructions baselines = new Instructions(getProperty(Constants.BASELINE));
if (baselines.isEmpty())
return null; // no baselining
RepositoryPlugin repo = getReleaseRepo();
if (repo == null)
return null; // errors reported already
String bsn = getBsn();
Version version = new Version(getVersion());
SortedSet<Version> versions = removeStagedAndFilter(repo.versions(bsn));
if (versions.isEmpty()) {
// We have a repo
Version v = new Version(getVersion());
if (v.getWithoutQualifier().compareTo(Version.ONE) > 0) {
warning("There is no baseline for %s in the baseline repo %s. The build is for version %s, which is <= 1.0.0 which suggests that there should be a prior version.",
getBsn(), repo, v);
}
return null;
}
// Loop over the instructions, first match commits.
for (Entry<Instruction,Attrs> e : baselines.entrySet()) {
if (e.getKey().matches(bsn)) {
Attrs attrs = e.getValue();
Version target;
if (attrs.containsKey("version")) {
// Specified version!
String v = attrs.get("version");
if (!Verifier.isVersion(v)) {
error("Not a valid version in %s %s", Constants.BASELINE, v);
return null;
}
Version base = new Version(v);
SortedSet<Version> later = versions.tailSet(base);
if (later.isEmpty()) {
error("For baselineing %s-%s, specified version %s not found", bsn, version, base);
return null;
}
// First element is equal or next to the base we desire
target = later.first();
// Now, we could end up with a higher version than our
// current
// project
} else if (attrs.containsKey("file")) {
// Can be useful to specify a file
// for example when copying a bundle with a public api
File f = getProject().getFile(attrs.get("file"));
if (f != null && f.isFile()) {
Jar jar = new Jar(f);
addClose(jar);
return jar;
}
error("Specified file for baseline but could not find it %s", f);
return null;
} else {
target = versions.last();
}
// Fetch the revision
if (target.getWithoutQualifier().compareTo(version.getWithoutQualifier()) > 0) {
error("The baseline version %s is higher than the current version %s for %s in %s", target,
version, bsn, repo);
return null;
}
if (target.getWithoutQualifier().compareTo(version.getWithoutQualifier()) == 0) {
if (isPedantic()) {
warning("Baselining against jar");
}
}
File file = repo.get(bsn, target, attrs);
if (file == null || !file.isFile()) {
error("Decided on version %s-%s but cannot get file from repo %s", bsn, version, repo);
return null;
}
Jar jar = new Jar(file);
addClose(jar);
return jar;
}
}
// Ignore, nothing matched
return null;
}
/**
* Remove any staging versions that have a variant with a higher qualifier.
*
* @param versions
* @return
*/
private SortedSet<Version> removeStagedAndFilter(SortedSet<Version> versions) {
List<Version> filtered = new ArrayList<Version>(versions);
Collections.reverse(filtered);
Version last = null;
for (Iterator<Version> i = filtered.iterator(); i.hasNext();) {
Version current = i.next().getWithoutQualifier();
if (last != null && current.equals(last))
i.remove();
else
last = current;
}
SortedList<Version> set = new SortedList<Version>(filtered);
trace("filtered for only latest staged: %s from %s in range ", set, versions);
return set;
}
private RepositoryPlugin getReleaseRepo() {
RepositoryPlugin repo = null;
String repoName = getReleaseRepoName();
List<RepositoryPlugin> repos = getPlugins(RepositoryPlugin.class);
for (RepositoryPlugin r : repos) {
if (r.canWrite()) {
if (repoName == null || r.getName().equals(repoName)) {
repo = r;
break;
}
}
}
if (repo == null) {
if (repoName != null)
error("No writeable repo with name %s found", repoName);
else
error("No writeable repo found");
}
return repo;
}
private String getReleaseRepoName() {
String repoName = getProperty(Constants.BASELINEREPO);
if (repoName == null)
repoName = getProperty(Constants.RELEASEREPO);
if (repoName != null && Constants.NONE.equals(repoName))
return null;
return repoName;
}
} |
package es.boart.model;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
@Entity
public class Publication {
private final int DEFAULT_VISITS = 0;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@ManyToOne
private User user;
private String title;
private String description;
private String media;
private int media_type;
private Timestamp date;
private int num_visits;
private int numberOfLikes;
@OneToMany(cascade=CascadeType.ALL)
private List<Comment> comments = new ArrayList<>();
@OneToMany(mappedBy="publication")
private List<Like> likes;
@ManyToMany(mappedBy="publications")
private Set<Tag> tags;
public Publication(){}
/**
* @param user
* @param title
* @param description
* @param media
* @param media_type
* @param date
* @param num_visits
* @param likes
*/
public Publication(User author, String title, String description, String media, int media_type) {
this.user = author;
this.title = title;
this.description = description;
this.media = media;
this.media_type = media_type;
this.date = new Timestamp(new Date().getTime());
this.num_visits = DEFAULT_VISITS;
this.tags = new HashSet<>();
this.numberOfLikes = 0;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @return the user
*/
public User getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUsername(User autor) {
this.user = autor;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String titulo) {
this.title = titulo;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String descripcion) {
this.description = descripcion;
}
/**
* @return the media
*/
public String getMedia() {
return media;
}
/**
* @param media the media to set
*/
public void setMedia(String media) {
this.media = media;
}
/**
* @return the media_type
*/
public int getMedia_type() {
return media_type;
}
/**
* @param media_type the media_type to set
*/
public void setMedia_type(int tipo_media) {
this.media_type = tipo_media;
}
/**
* @return the date
*/
public Timestamp getDate() {
return date;
}
/**
* @param date the date to set
*/
public void setDate(Timestamp fecha) {
this.date = fecha;
}
/**
* @return the num_visits
*/
public int getNum_visits() {
return num_visits;
}
/**
* @param num_visits the num_visits to set
*/
public void setNum_visits(int num_visitas) {
this.num_visits = num_visitas;
}
/**
* @return the likes
*/
public List<Like> getLikes() {
return likes;
}
/**
* @param likes the likes to set
*/
public void setLikes(List<Like> likes) {
this.likes = likes;
}
public void addLike(Like like) {
this.likes.add(like);
this.setNumberOfLikes(this.getNumberOfLikes() + 1);
}
public void removeLike(Like like) {
this.likes.remove(like);
this.setNumberOfLikes(this.getNumberOfLikes() - 1);
}
/**
* @return the comentariosPublicacion
*/
public List<Comment> getComments() {
return comments;
}
/**
* @param comentariosPublicacion the comentariosPublicacion to set
*/
public void setComments(List<Comment> comentariosPublicacion) {
this.comments = comentariosPublicacion;
}
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
/**
* @return the numberOfLikes
*/
public int getNumberOfLikes() {
return numberOfLikes;
}
/**
* @param numberOfLikes the numberOfLikes to set
*/
public void setNumberOfLikes(int numberOfLikes) {
this.numberOfLikes = numberOfLikes;
}
} |
package com.intellij.icons;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
/**
* NOTE THIS FILE IS AUTO-GENERATED
* DO NOT EDIT IT BY HAND, run "Generate icon classes" configuration instead
*/
public class AllIcons {
public static class Actions {
public static final Icon AddFacesSupport = IconLoader.getIcon("/actions/addFacesSupport.png"); // 16x16
public static final Icon AddMulticaret = IconLoader.getIcon("/actions/AddMulticaret.png"); // 16x16
public static final Icon AllLeft = IconLoader.getIcon("/actions/allLeft.png"); // 16x16
public static final Icon AllRight = IconLoader.getIcon("/actions/allRight.png"); // 16x16
public static final Icon Annotate = IconLoader.getIcon("/actions/annotate.png"); // 16x16
public static final Icon Back = IconLoader.getIcon("/actions/back.png"); // 16x16
public static final Icon Browser_externalJavaDoc = IconLoader.getIcon("/actions/browser-externalJavaDoc.png"); // 16x16
public static final Icon Cancel = IconLoader.getIcon("/actions/cancel.png"); // 16x16
public static final Icon ChangeView = IconLoader.getIcon("/actions/changeView.png"); // 16x16
public static final Icon Checked = IconLoader.getIcon("/actions/checked.png"); // 12x12
public static final Icon Checked_selected = IconLoader.getIcon("/actions/checked_selected.png"); // 12x12
public static final Icon Checked_small = IconLoader.getIcon("/actions/checked_small.png"); // 11x11
public static final Icon Checked_small_selected = IconLoader.getIcon("/actions/checked_small_selected.png"); // 11x11
public static final Icon CheckedBlack = IconLoader.getIcon("/actions/checkedBlack.png"); // 12x12
public static final Icon CheckedGrey = IconLoader.getIcon("/actions/checkedGrey.png"); // 12x12
public static final Icon CheckMulticaret = IconLoader.getIcon("/actions/CheckMulticaret.png"); // 16x16
public static final Icon CheckOut = IconLoader.getIcon("/actions/checkOut.png"); // 16x16
public static final Icon Clean = IconLoader.getIcon("/actions/clean.png"); // 16x16
public static final Icon CleanLight = IconLoader.getIcon("/actions/cleanLight.png"); // 16x16
public static final Icon Clear = IconLoader.getIcon("/actions/clear.png"); // 16x16
public static final Icon Close = IconLoader.getIcon("/actions/close.png"); // 16x16
public static final Icon CloseHovered = IconLoader.getIcon("/actions/closeHovered.png"); // 16x16
public static final Icon CloseNew = IconLoader.getIcon("/actions/closeNew.png"); // 16x16
public static final Icon CloseNewHovered = IconLoader.getIcon("/actions/closeNewHovered.png"); // 16x16
public static final Icon Collapseall = IconLoader.getIcon("/actions/collapseall.png"); // 16x16
public static final Icon Commit = IconLoader.getIcon("/actions/commit.png"); // 16x16
public static final Icon Compile = IconLoader.getIcon("/actions/compile.png"); // 16x16
public static final Icon Copy = IconLoader.getIcon("/actions/copy.png"); // 16x16
public static final Icon CreateFromUsage = IconLoader.getIcon("/actions/createFromUsage.png"); // 16x16
public static final Icon CreatePatch = IconLoader.getIcon("/actions/createPatch.png"); // 16x16
public static final Icon Cross = IconLoader.getIcon("/actions/cross.png"); // 12x12
public static final Icon Delete = IconLoader.getIcon("/actions/delete.png"); // 16x16
public static final Icon DiagramDiff = IconLoader.getIcon("/actions/diagramDiff.png"); // 16x16
public static final Icon Diff = IconLoader.getIcon("/actions/diff.png"); // 16x16
public static final Icon DiffPreview = IconLoader.getIcon("/actions/diffPreview.png"); // 16x16
public static final Icon DiffWithClipboard = IconLoader.getIcon("/actions/diffWithClipboard.png"); // 16x16
public static final Icon DiffWithCurrent = IconLoader.getIcon("/actions/diffWithCurrent.png"); // 16x16
public static final Icon Down = IconLoader.getIcon("/actions/down.png"); // 16x16
public static final Icon Download = IconLoader.getIcon("/actions/download.png"); // 16x16
public static final Icon Dump = IconLoader.getIcon("/actions/dump.png"); // 16x16
public static final Icon Edit = IconLoader.getIcon("/actions/edit.png"); // 14x14
public static final Icon EditSource = IconLoader.getIcon("/actions/editSource.png"); // 16x16
public static final Icon ErDiagram = IconLoader.getIcon("/actions/erDiagram.png"); // 16x16
public static final Icon Exclude = IconLoader.getIcon("/actions/exclude.png"); // 14x14
public static final Icon Execute = IconLoader.getIcon("/actions/execute.png"); // 16x16
public static final Icon Exit = IconLoader.getIcon("/actions/exit.png"); // 16x16
public static final Icon Expandall = IconLoader.getIcon("/actions/expandall.png"); // 16x16
public static final Icon Export = IconLoader.getIcon("/actions/export.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon FileStatus = IconLoader.getIcon("/actions/fileStatus.png"); // 16x16
public static final Icon Filter_small = IconLoader.getIcon("/actions/filter_small.png"); // 16x16
public static final Icon Find = IconLoader.getIcon("/actions/find.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon FindPlain = IconLoader.getIcon("/actions/findPlain.png"); // 16x16
public static final Icon FindWhite = IconLoader.getIcon("/actions/findWhite.png"); // 16x16
public static final Icon ForceRefresh = IconLoader.getIcon("/actions/forceRefresh.png"); // 16x16
public static final Icon Forward = IconLoader.getIcon("/actions/forward.png"); // 16x16
public static final Icon GC = IconLoader.getIcon("/actions/gc.png"); // 16x16
public static final Icon Get = IconLoader.getIcon("/actions/get.png"); // 16x16
public static final Icon GroupBy = IconLoader.getIcon("/actions/groupBy.png"); // 16x16
public static final Icon GroupByClass = IconLoader.getIcon("/actions/GroupByClass.png"); // 16x16
public static final Icon GroupByFile = IconLoader.getIcon("/actions/GroupByFile.png"); // 16x16
public static final Icon GroupByMethod = IconLoader.getIcon("/actions/groupByMethod.png"); // 16x16
public static final Icon GroupByModule = IconLoader.getIcon("/actions/GroupByModule.png"); // 16x16
public static final Icon GroupByModuleGroup = IconLoader.getIcon("/actions/GroupByModuleGroup.png"); // 16x16
public static final Icon GroupByPackage = IconLoader.getIcon("/actions/GroupByPackage.png"); // 16x16
public static final Icon GroupByPrefix = IconLoader.getIcon("/actions/GroupByPrefix.png"); // 16x16
public static final Icon GroupByTestProduction = IconLoader.getIcon("/actions/groupByTestProduction.png"); // 16x16
public static final Icon Help = IconLoader.getIcon("/actions/help.png"); // 16x16
public static final Icon Install = IconLoader.getIcon("/actions/install.png"); // 16x16
public static final Icon IntentionBulb = IconLoader.getIcon("/actions/intentionBulb.png"); // 16x16
public static final Icon Left = IconLoader.getIcon("/actions/left.png"); // 16x16
public static final Icon Lightning = IconLoader.getIcon("/actions/lightning.png"); // 16x16
public static final Icon ListChanges = IconLoader.getIcon("/actions/listChanges.png"); // 16x16
public static final Icon Menu_cut = IconLoader.getIcon("/actions/menu-cut.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon Menu_find = IconLoader.getIcon("/actions/menu-find.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon Menu_help = IconLoader.getIcon("/actions/menu-help.png"); // 16x16
public static final Icon Menu_open = IconLoader.getIcon("/actions/menu-open.png"); // 16x16
public static final Icon Menu_paste = IconLoader.getIcon("/actions/menu-paste.png"); // 16x16
public static final Icon Menu_replace = IconLoader.getIcon("/actions/menu-replace.png"); // 16x16
public static final Icon Menu_saveall = IconLoader.getIcon("/actions/menu-saveall.png"); // 16x16
public static final Icon Minimize = IconLoader.getIcon("/actions/minimize.png"); // 16x16
public static final Icon Module = IconLoader.getIcon("/actions/module.png"); // 16x16
public static final Icon Move_to_button_top = IconLoader.getIcon("/actions/move-to-button-top.png"); // 11x12
public static final Icon Move_to_button = IconLoader.getIcon("/actions/move-to-button.png"); // 11x10
public static final Icon MoveDown = IconLoader.getIcon("/actions/moveDown.png"); // 14x14
public static final Icon MoveTo2 = IconLoader.getIcon("/actions/MoveTo2.png"); // 16x16
public static final Icon MoveToAnotherChangelist = IconLoader.getIcon("/actions/moveToAnotherChangelist.png"); // 16x16
public static final Icon MoveToStandardPlace = IconLoader.getIcon("/actions/moveToStandardPlace.png"); // 16x16
public static final Icon MoveUp = IconLoader.getIcon("/actions/moveUp.png"); // 14x14
public static final Icon Multicaret = IconLoader.getIcon("/actions/multicaret.png"); // 16x16
public static final Icon New = IconLoader.getIcon("/actions/new.png"); // 16x16
public static final Icon NewFolder = IconLoader.getIcon("/actions/newFolder.png"); // 16x16
public static final Icon Nextfile = IconLoader.getIcon("/actions/nextfile.png"); // 16x16
public static final Icon NextOccurence = IconLoader.getIcon("/actions/nextOccurence.png"); // 16x16
public static final Icon Pause = IconLoader.getIcon("/actions/pause.png"); // 16x16
public static final Icon PopFrame = IconLoader.getIcon("/actions/popFrame.png"); // 16x16
public static final Icon Prevfile = IconLoader.getIcon("/actions/prevfile.png"); // 16x16
public static final Icon Preview = IconLoader.getIcon("/actions/preview.png"); // 16x16
public static final Icon PreviewDetails = IconLoader.getIcon("/actions/previewDetails.png"); // 16x16
public static final Icon PreviousOccurence = IconLoader.getIcon("/actions/previousOccurence.png"); // 16x16
public static final Icon Profile = IconLoader.getIcon("/actions/profile.png"); // 16x16
public static final Icon ProfileCPU = IconLoader.getIcon("/actions/profileCPU.png"); // 16x16
public static final Icon ProfileMemory = IconLoader.getIcon("/actions/profileMemory.png"); // 16x16
public static final Icon Properties = IconLoader.getIcon("/actions/properties.png"); // 16x16
public static final Icon QuickfixBulb = IconLoader.getIcon("/actions/quickfixBulb.png"); // 16x16
public static final Icon QuickfixOffBulb = IconLoader.getIcon("/actions/quickfixOffBulb.png"); // 16x16
public static final Icon QuickList = IconLoader.getIcon("/actions/quickList.png"); // 16x16
public static final Icon RealIntentionBulb = IconLoader.getIcon("/actions/realIntentionBulb.png"); // 16x16
public static final Icon RealIntentionOffBulb = IconLoader.getIcon("/actions/realIntentionOffBulb.png"); // 16x16
public static final Icon Redo = IconLoader.getIcon("/actions/redo.png"); // 16x16
public static final Icon RefactoringBulb = IconLoader.getIcon("/actions/refactoringBulb.png"); // 16x16
public static final Icon Refresh = IconLoader.getIcon("/actions/refresh.png"); // 16x16
public static final Icon RemoveMulticaret = IconLoader.getIcon("/actions/RemoveMulticaret.png"); // 16x16
public static final Icon Replace = IconLoader.getIcon("/actions/replace.png"); // 16x16
public static final Icon Rerun = IconLoader.getIcon("/actions/rerun.png"); // 16x16
public static final Icon Reset_to_default = IconLoader.getIcon("/actions/reset-to-default.png"); // 16x16
public static final Icon Reset = IconLoader.getIcon("/actions/reset.png"); // 16x16
public static final Icon Reset_to_empty = IconLoader.getIcon("/actions/Reset_to_empty.png"); // 16x16
public static final Icon Restart = IconLoader.getIcon("/actions/restart.png"); // 16x16
public static final Icon RestartDebugger = IconLoader.getIcon("/actions/restartDebugger.png"); // 16x16
public static final Icon Resume = IconLoader.getIcon("/actions/resume.png"); // 16x16
public static final Icon Right = IconLoader.getIcon("/actions/right.png"); // 16x16
public static final Icon Rollback = IconLoader.getIcon("/actions/rollback.png"); // 16x16
public static final Icon RunToCursor = IconLoader.getIcon("/actions/runToCursor.png"); // 16x16
public static final Icon Scratch = IconLoader.getIcon("/actions/scratch.png"); // 16x16
public static final Icon Search = IconLoader.getIcon("/actions/search.png"); // 16x16
public static final Icon SearchNewLine = IconLoader.getIcon("/actions/searchNewLine.png"); // 16x16
public static final Icon SearchNewLineHover = IconLoader.getIcon("/actions/searchNewLineHover.png"); // 16x16
public static final Icon Selectall = IconLoader.getIcon("/actions/selectall.png"); // 16x16
public static final Icon Share = IconLoader.getIcon("/actions/share.png"); // 14x14
public static final Icon ShortcutFilter = IconLoader.getIcon("/actions/shortcutFilter.png"); // 16x16
public static final Icon ShowAsTree = IconLoader.getIcon("/actions/showAsTree.png"); // 16x16
public static final Icon ShowChangesOnly = IconLoader.getIcon("/actions/showChangesOnly.png"); // 16x16
public static final Icon ShowHiddens = IconLoader.getIcon("/actions/showHiddens.png"); // 16x16
public static final Icon ShowImportStatements = IconLoader.getIcon("/actions/showImportStatements.png"); // 16x16
public static final Icon ShowReadAccess = IconLoader.getIcon("/actions/showReadAccess.png"); // 16x16
public static final Icon ShowViewer = IconLoader.getIcon("/actions/showViewer.png"); // 16x16
public static final Icon ShowWriteAccess = IconLoader.getIcon("/actions/showWriteAccess.png"); // 16x16
public static final Icon SortAsc = IconLoader.getIcon("/actions/sortAsc.png"); // 9x8
public static final Icon SortDesc = IconLoader.getIcon("/actions/sortDesc.png"); // 9x8
public static final Icon SplitHorizontally = IconLoader.getIcon("/actions/splitHorizontally.png"); // 16x16
public static final Icon SplitVertically = IconLoader.getIcon("/actions/splitVertically.png"); // 16x16
public static final Icon StartDebugger = IconLoader.getIcon("/actions/startDebugger.png"); // 16x16
public static final Icon StartMemoryProfile = IconLoader.getIcon("/actions/startMemoryProfile.png"); // 16x16
public static final Icon StepOut = IconLoader.getIcon("/actions/stepOut.png"); // 16x16
public static final Icon Stub = IconLoader.getIcon("/actions/stub.png"); // 16x16
public static final Icon Submit1 = IconLoader.getIcon("/actions/submit1.png"); // 11x11
public static final Icon Suspend = IconLoader.getIcon("/actions/suspend.png"); // 16x16
public static final Icon SwapPanels = IconLoader.getIcon("/actions/swapPanels.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon SynchronizeFS = IconLoader.getIcon("/actions/synchronizeFS.png"); // 16x16
public static final Icon SynchronizeScrolling = IconLoader.getIcon("/actions/synchronizeScrolling.png"); // 16x16
public static final Icon SyncPanels = IconLoader.getIcon("/actions/syncPanels.png"); // 16x16
public static final Icon ToggleSoftWrap = IconLoader.getIcon("/actions/toggleSoftWrap.png"); // 16x16
public static final Icon TraceInto = IconLoader.getIcon("/actions/traceInto.png"); // 16x16
public static final Icon TraceOver = IconLoader.getIcon("/actions/traceOver.png"); // 16x16
public static final Icon Undo = IconLoader.getIcon("/actions/undo.png"); // 16x16
public static final Icon Uninstall = IconLoader.getIcon("/actions/uninstall.png"); // 16x16
public static final Icon Unselectall = IconLoader.getIcon("/actions/unselectall.png"); // 16x16
public static final Icon Unshare = IconLoader.getIcon("/actions/unshare.png"); // 14x14
public static final Icon UP = IconLoader.getIcon("/actions/up.png"); // 16x16
public static final Icon Upload = IconLoader.getIcon("/actions/upload.png"); // 16x16
}
public static class CodeStyle {
public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/AddNewSectionRule.png"); // 16x16
public static final Icon Gear = IconLoader.getIcon("/codeStyle/Gear.png"); // 16x16
public static class Mac {
public static final Icon AddNewSectionRule = IconLoader.getIcon("/codeStyle/mac/AddNewSectionRule.png"); // 16x16
}
}
public static class Css {
/** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */
@SuppressWarnings("unused")
@Deprecated
public static final Icon Atrule = IconLoader.getIcon("/css/atrule.png"); // 16x16
/** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */
@SuppressWarnings("unused")
@Deprecated
public static final Icon Import = IconLoader.getIcon("/css/import.png"); // 16x16
/** @deprecated use 'icons.CssIcons' from 'intellij.css' module instead */
@SuppressWarnings("unused")
@Deprecated
public static final Icon Property = IconLoader.getIcon("/css/property.png"); // 16x16
}
public static class Darcula {
public static final Icon DoubleComboArrow = IconLoader.getIcon("/darcula/doubleComboArrow.png"); // 7x11
public static final Icon TreeNodeCollapsed = IconLoader.getIcon("/darcula/treeNodeCollapsed.png"); // 9x9
public static final Icon TreeNodeExpanded = IconLoader.getIcon("/darcula/treeNodeExpanded.png"); // 9x9
}
public static class Debugger {
public static class Actions {
public static final Icon Force_run_to_cursor = IconLoader.getIcon("/debugger/actions/force_run_to_cursor.png"); // 16x16
public static final Icon Force_step_into = IconLoader.getIcon("/debugger/actions/force_step_into.png"); // 16x16
public static final Icon Force_step_over = IconLoader.getIcon("/debugger/actions/force_step_over.png"); // 16x16
}
public static final Icon AddToWatch = IconLoader.getIcon("/debugger/addToWatch.png"); // 16x16
public static final Icon AttachToProcess = IconLoader.getIcon("/debugger/attachToProcess.png"); // 16x16
public static final Icon AutoVariablesMode = IconLoader.getIcon("/debugger/autoVariablesMode.png"); // 16x16
public static final Icon BreakpointAlert = IconLoader.getIcon("/debugger/breakpointAlert.png"); // 16x16
public static final Icon Class_filter = IconLoader.getIcon("/debugger/class_filter.png"); // 16x16
public static final Icon CommandLine = IconLoader.getIcon("/debugger/commandLine.png"); // 16x16
public static final Icon Console = IconLoader.getIcon("/debugger/console.png"); // 16x16
public static final Icon Console_log = IconLoader.getIcon("/debugger/console_log.png"); // 16x16
public static final Icon Db_array = IconLoader.getIcon("/debugger/db_array.png"); // 16x16
public static final Icon Db_db_object = IconLoader.getIcon("/debugger/db_db_object.png"); // 16x16
public static final Icon Db_dep_exception_breakpoint = IconLoader.getIcon("/debugger/db_dep_exception_breakpoint.png"); // 12x12
public static final Icon Db_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_dep_field_breakpoint.png"); // 12x12
public static final Icon Db_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_dep_line_breakpoint.png"); // 12x12
public static final Icon Db_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_dep_method_breakpoint.png"); // 12x12
public static final Icon Db_disabled_breakpoint = IconLoader.getIcon("/debugger/db_disabled_breakpoint.png"); // 12x12
public static final Icon Db_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_disabled_breakpoint_process.png"); // 16x16
public static final Icon Db_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_disabled_exception_breakpoint.png"); // 12x12
public static final Icon Db_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_disabled_field_breakpoint.png"); // 12x12
public static final Icon Db_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_disabled_method_breakpoint.png"); // 12x12
public static final Icon Db_exception_breakpoint = IconLoader.getIcon("/debugger/db_exception_breakpoint.png"); // 12x12
public static final Icon Db_field_breakpoint = IconLoader.getIcon("/debugger/db_field_breakpoint.png"); // 12x12
public static final Icon Db_field_warning_breakpoint = IconLoader.getIcon("/debugger/db_field_warning_breakpoint.png"); // 16x16
public static final Icon Db_invalid_breakpoint = IconLoader.getIcon("/debugger/db_invalid_breakpoint.png"); // 12x12
public static final Icon Db_invalid_field_breakpoint = IconLoader.getIcon("/debugger/db_invalid_field_breakpoint.png"); // 12x12
public static final Icon Db_invalid_method_breakpoint = IconLoader.getIcon("/debugger/db_invalid_method_breakpoint.png"); // 12x12
public static final Icon Db_method_breakpoint = IconLoader.getIcon("/debugger/db_method_breakpoint.png"); // 12x12
public static final Icon Db_method_warning_breakpoint = IconLoader.getIcon("/debugger/db_method_warning_breakpoint.png"); // 16x16
public static final Icon Db_muted_breakpoint = IconLoader.getIcon("/debugger/db_muted_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_exception_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_line_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_line_breakpoint.png"); // 12x12
public static final Icon Db_muted_dep_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_dep_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_breakpoint_process = IconLoader.getIcon("/debugger/db_muted_disabled_breakpoint_process.png"); // 16x16
public static final Icon Db_muted_disabled_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_exception_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_disabled_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_disabled_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_exception_breakpoint = IconLoader.getIcon("/debugger/db_muted_exception_breakpoint.png"); // 12x12
public static final Icon Db_muted_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_field_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_field_warning_breakpoint.png"); // 16x16
public static final Icon Db_muted_invalid_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_breakpoint.png"); // 12x12
public static final Icon Db_muted_invalid_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_invalid_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_invalid_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_method_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_method_warning_breakpoint.png"); // 16x16
public static final Icon Db_muted_temporary_breakpoint = IconLoader.getIcon("/debugger/db_muted_temporary_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_field_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_method_breakpoint.png"); // 12x12
public static final Icon Db_muted_verified_warning_breakpoint = IconLoader.getIcon("/debugger/db_muted_verified_warning_breakpoint.png"); // 16x16
public static final Icon Db_obsolete = IconLoader.getIcon("/debugger/db_obsolete.png"); // 12x12
public static final Icon Db_primitive = IconLoader.getIcon("/debugger/db_primitive.png"); // 16x16
public static final Icon Db_set_breakpoint = IconLoader.getIcon("/debugger/db_set_breakpoint.png"); // 12x12
public static final Icon Db_temporary_breakpoint = IconLoader.getIcon("/debugger/db_temporary_breakpoint.png"); // 12x12
public static final Icon Db_verified_breakpoint = IconLoader.getIcon("/debugger/db_verified_breakpoint.png"); // 12x12
public static final Icon Db_verified_field_breakpoint = IconLoader.getIcon("/debugger/db_verified_field_breakpoint.png"); // 12x12
public static final Icon Db_verified_method_breakpoint = IconLoader.getIcon("/debugger/db_verified_method_breakpoint.png"); // 12x12
public static final Icon Db_verified_warning_breakpoint = IconLoader.getIcon("/debugger/db_verified_warning_breakpoint.png"); // 16x16
public static final Icon Disable_value_calculation = IconLoader.getIcon("/debugger/disable_value_calculation.png"); // 16x16
public static final Icon EvaluateExpression = IconLoader.getIcon("/debugger/evaluateExpression.png"); // 16x16
public static final Icon Explosion = IconLoader.getIcon("/debugger/explosion.png"); // 256x256
public static final Icon Frame = IconLoader.getIcon("/debugger/frame.png"); // 16x16
public static final Icon KillProcess = IconLoader.getIcon("/debugger/killProcess.png"); // 16x16
public static final Icon LambdaBreakpoint = IconLoader.getIcon("/debugger/LambdaBreakpoint.png"); // 12x12
public static class MemoryView {
public static final Icon Active = IconLoader.getIcon("/debugger/memoryView/active.png"); // 13x13
public static final Icon ClassTracked = IconLoader.getIcon("/debugger/memoryView/classTracked.png"); // 16x16
public static final Icon ToolWindowDisabled = IconLoader.getIcon("/debugger/memoryView/toolWindowDisabled.png"); // 13x13
public static final Icon ToolWindowEnabled = IconLoader.getIcon("/debugger/memoryView/toolWindowEnabled.png"); // 13x13
}
public static final Icon MultipleBreakpoints = IconLoader.getIcon("/debugger/MultipleBreakpoints.png"); // 12x12
public static final Icon MuteBreakpoints = IconLoader.getIcon("/debugger/muteBreakpoints.png"); // 16x16
public static final Icon NewWatch = IconLoader.getIcon("/debugger/newWatch.png"); // 16x16
public static final Icon Overhead = IconLoader.getIcon("/debugger/overhead.png"); // 16x16
public static final Icon Question_badge = IconLoader.getIcon("/debugger/question_badge.png"); // 6x9
public static final Icon RestoreLayout = IconLoader.getIcon("/debugger/restoreLayout.png"); // 16x16
public static final Icon Selfreference = IconLoader.getIcon("/debugger/selfreference.png"); // 16x16
public static final Icon ShowCurrentFrame = IconLoader.getIcon("/debugger/showCurrentFrame.png"); // 16x16
public static final Icon SmartStepInto = IconLoader.getIcon("/debugger/smartStepInto.png"); // 16x16
public static final Icon StackFrame = IconLoader.getIcon("/debugger/stackFrame.png"); // 16x16
public static final Icon ThreadAtBreakpoint = IconLoader.getIcon("/debugger/threadAtBreakpoint.png"); // 16x16
public static final Icon ThreadCurrent = IconLoader.getIcon("/debugger/threadCurrent.png"); // 16x16
public static final Icon ThreadFrozen = IconLoader.getIcon("/debugger/threadFrozen.png"); // 16x16
public static final Icon ThreadGroup = IconLoader.getIcon("/debugger/threadGroup.png"); // 16x16
public static final Icon ThreadGroupCurrent = IconLoader.getIcon("/debugger/threadGroupCurrent.png"); // 16x16
public static final Icon ThreadRunning = IconLoader.getIcon("/debugger/threadRunning.png"); // 16x16
public static final Icon Threads = IconLoader.getIcon("/debugger/threads.png"); // 16x16
public static class ThreadStates {
public static final Icon Daemon_sign = IconLoader.getIcon("/debugger/threadStates/daemon_sign.png"); // 16x16
public static final Icon EdtBusy = IconLoader.getIcon("/debugger/threadStates/edtBusy.png"); // 16x16
public static final Icon Exception = IconLoader.getIcon("/debugger/threadStates/exception.png"); // 16x16
public static final Icon Idle = IconLoader.getIcon("/debugger/threadStates/idle.png"); // 16x16
public static final Icon IO = IconLoader.getIcon("/debugger/threadStates/io.png"); // 16x16
public static final Icon Locked = IconLoader.getIcon("/debugger/threadStates/locked.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon Paused = IconLoader.getIcon("/debugger/threadStates/paused.png"); // 16x16
public static final Icon Running = IconLoader.getIcon("/debugger/threadStates/running.png"); // 16x16
public static final Icon Socket = IconLoader.getIcon("/debugger/threadStates/socket.png"); // 16x16
public static final Icon Threaddump = IconLoader.getIcon("/debugger/threadStates/threaddump.png"); // 16x16
}
public static final Icon ThreadSuspended = IconLoader.getIcon("/debugger/threadSuspended.png"); // 16x16
public static final Icon ToolConsole = IconLoader.getIcon("/debugger/toolConsole.png"); // 16x16
public static final Icon Value = IconLoader.getIcon("/debugger/value.png"); // 16x16
public static final Icon ViewBreakpoints = IconLoader.getIcon("/debugger/viewBreakpoints.png"); // 16x16
public static final Icon Watch = IconLoader.getIcon("/debugger/watch.png"); // 16x16
public static final Icon Watches = IconLoader.getIcon("/debugger/watches.png"); // 16x16
public static final Icon WatchLastReturnValue = IconLoader.getIcon("/debugger/watchLastReturnValue.png"); // 16x16
}
public static class Diff {
public static final Icon ApplyNotConflicts = IconLoader.getIcon("/diff/applyNotConflicts.png"); // 16x16
public static final Icon ApplyNotConflictsLeft = IconLoader.getIcon("/diff/applyNotConflictsLeft.png"); // 16x16
public static final Icon ApplyNotConflictsRight = IconLoader.getIcon("/diff/applyNotConflictsRight.png"); // 16x16
public static final Icon Arrow = IconLoader.getIcon("/diff/arrow.png"); // 11x11
public static final Icon ArrowLeftDown = IconLoader.getIcon("/diff/arrowLeftDown.png"); // 11x11
public static final Icon ArrowRight = IconLoader.getIcon("/diff/arrowRight.png"); // 11x11
public static final Icon ArrowRightDown = IconLoader.getIcon("/diff/arrowRightDown.png"); // 11x11
public static final Icon Compare3LeftMiddle = IconLoader.getIcon("/diff/compare3LeftMiddle.png"); // 16x16
public static final Icon Compare3LeftRight = IconLoader.getIcon("/diff/compare3LeftRight.png"); // 16x16
public static final Icon Compare3MiddleRight = IconLoader.getIcon("/diff/compare3MiddleRight.png"); // 16x16
public static final Icon Compare4LeftBottom = IconLoader.getIcon("/diff/compare4LeftBottom.png"); // 16x16
public static final Icon Compare4LeftMiddle = IconLoader.getIcon("/diff/compare4LeftMiddle.png"); // 16x16
public static final Icon Compare4LeftRight = IconLoader.getIcon("/diff/compare4LeftRight.png"); // 16x16
public static final Icon Compare4MiddleBottom = IconLoader.getIcon("/diff/compare4MiddleBottom.png"); // 16x16
public static final Icon Compare4MiddleRight = IconLoader.getIcon("/diff/compare4MiddleRight.png"); // 16x16
public static final Icon Compare4RightBottom = IconLoader.getIcon("/diff/compare4RightBottom.png"); // 16x16
public static final Icon CurrentLine = IconLoader.getIcon("/diff/currentLine.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon Diff = IconLoader.getIcon("/diff/Diff.png"); // 16x16
public static final Icon GutterCheckBox = IconLoader.getIcon("/diff/gutterCheckBox.png"); // 11x11
public static final Icon GutterCheckBoxSelected = IconLoader.getIcon("/diff/gutterCheckBoxSelected.png"); // 11x11
public static final Icon MagicResolve = IconLoader.getIcon("/diff/magicResolve.png"); // 12x12
public static final Icon MagicResolveToolbar = IconLoader.getIcon("/diff/magicResolveToolbar.png"); // 16x16
public static final Icon Remove = IconLoader.getIcon("/diff/remove.png"); // 11x11
}
public static class Duplicates {
public static final Icon SendToTheLeft = IconLoader.getIcon("/duplicates/sendToTheLeft.png"); // 16x16
public static final Icon SendToTheLeftGrayed = IconLoader.getIcon("/duplicates/sendToTheLeftGrayed.png"); // 16x16
public static final Icon SendToTheRight = IconLoader.getIcon("/duplicates/sendToTheRight.png"); // 16x16
public static final Icon SendToTheRightGrayed = IconLoader.getIcon("/duplicates/sendToTheRightGrayed.png"); // 16x16
}
public static class FileTypes {
public static final Icon Any_type = IconLoader.getIcon("/fileTypes/any_type.png"); // 16x16
public static final Icon Archive = IconLoader.getIcon("/fileTypes/archive.png"); // 16x16
public static final Icon AS = IconLoader.getIcon("/fileTypes/as.png"); // 16x16
public static final Icon Aspectj = IconLoader.getIcon("/fileTypes/aspectj.png"); // 16x16
public static final Icon Config = IconLoader.getIcon("/fileTypes/config.png"); // 16x16
public static final Icon Css = IconLoader.getIcon("/fileTypes/css.png"); // 16x16
public static final Icon Custom = IconLoader.getIcon("/fileTypes/custom.png"); // 16x16
public static final Icon Diagram = IconLoader.getIcon("/fileTypes/diagram.png"); // 16x16
public static final Icon Dtd = IconLoader.getIcon("/fileTypes/dtd.png"); // 16x16
public static final Icon Facelets = IconLoader.getIcon("/fileTypes/facelets.png"); // 16x16
public static final Icon FacesConfig = IconLoader.getIcon("/fileTypes/facesConfig.png"); // 16x16
public static final Icon Htaccess = IconLoader.getIcon("/fileTypes/htaccess.png"); // 16x16
public static final Icon Html = IconLoader.getIcon("/fileTypes/html.png"); // 16x16
public static final Icon Idl = IconLoader.getIcon("/fileTypes/idl.png"); // 16x16
public static final Icon Java = IconLoader.getIcon("/fileTypes/java.png"); // 16x16
public static final Icon JavaClass = IconLoader.getIcon("/fileTypes/javaClass.png"); // 16x16
public static final Icon JavaOutsideSource = IconLoader.getIcon("/fileTypes/javaOutsideSource.png"); // 16x16
public static final Icon JavaScript = IconLoader.getIcon("/fileTypes/javaScript.png"); // 16x16
public static final Icon Json = IconLoader.getIcon("/fileTypes/json.png"); // 16x16
public static final Icon JsonSchema = IconLoader.getIcon("/fileTypes/jsonSchema.png"); // 16x16
public static final Icon Jsp = IconLoader.getIcon("/fileTypes/jsp.png"); // 16x16
public static final Icon Jspx = IconLoader.getIcon("/fileTypes/jspx.png"); // 16x16
public static final Icon Manifest = IconLoader.getIcon("/fileTypes/manifest.png"); // 16x16
public static final Icon Properties = IconLoader.getIcon("/fileTypes/properties.png"); // 16x16
public static final Icon Text = IconLoader.getIcon("/fileTypes/text.png"); // 16x16
public static final Icon TypeScript = IconLoader.getIcon("/fileTypes/typeScript.png"); // 16x16
public static final Icon UiForm = IconLoader.getIcon("/fileTypes/uiForm.png"); // 16x16
public static final Icon Unknown = IconLoader.getIcon("/fileTypes/unknown.png"); // 16x16
public static final Icon WsdlFile = IconLoader.getIcon("/fileTypes/wsdlFile.png"); // 16x16
public static final Icon Xhtml = IconLoader.getIcon("/fileTypes/xhtml.png"); // 16x16
public static final Icon Xml = IconLoader.getIcon("/fileTypes/xml.png"); // 16x16
public static final Icon XsdFile = IconLoader.getIcon("/fileTypes/xsdFile.png"); // 16x16
}
public static class General {
public static final Icon Add = IconLoader.getIcon("/general/add.png"); // 16x16
public static final Icon AddFavoritesList = IconLoader.getIcon("/general/addFavoritesList.png"); // 16x16
public static final Icon AddJdk = IconLoader.getIcon("/general/addJdk.png"); // 16x16
public static final Icon ArrowDown = IconLoader.getIcon("/general/arrowDown.png"); // 7x6
public static final Icon ArrowDown_white = IconLoader.getIcon("/general/arrowDown_white.png"); // 7x6
public static final Icon AutohideOff = IconLoader.getIcon("/general/autohideOff.png"); // 14x14
public static final Icon AutohideOffInactive = IconLoader.getIcon("/general/autohideOffInactive.png"); // 14x14
public static final Icon AutohideOffPressed = IconLoader.getIcon("/general/autohideOffPressed.png"); // 22x20
public static final Icon AutoscrollFromSource = IconLoader.getIcon("/general/autoscrollFromSource.png"); // 16x16
public static final Icon AutoscrollToSource = IconLoader.getIcon("/general/autoscrollToSource.png"); // 16x16
public static final Icon Balloon = IconLoader.getIcon("/general/balloon.png"); // 16x16
public static final Icon BalloonClose = IconLoader.getIcon("/general/balloonClose.png"); // 32x32
public static final Icon BalloonError = IconLoader.getIcon("/general/balloonError.png"); // 16x16
public static final Icon BalloonInformation = IconLoader.getIcon("/general/balloonInformation.png"); // 16x16
public static final Icon BalloonWarning = IconLoader.getIcon("/general/balloonWarning.png"); // 16x16
public static final Icon BalloonWarning12 = IconLoader.getIcon("/general/balloonWarning12.png"); // 12x12
public static final Icon Bullet = IconLoader.getIcon("/general/bullet.png"); // 16x16
public static final Icon CollapseAll = IconLoader.getIcon("/general/collapseAll.png"); // 11x16
public static final Icon CollapseAllHover = IconLoader.getIcon("/general/collapseAllHover.png"); // 11x16
public static final Icon CollapseComponent = IconLoader.getIcon("/general/collapseComponent.png"); // 12x12
public static final Icon CollapseComponentHover = IconLoader.getIcon("/general/collapseComponentHover.png"); // 12x12
public static final Icon Combo = IconLoader.getIcon("/general/combo.png"); // 16x16
public static final Icon Combo2 = IconLoader.getIcon("/general/combo2.png"); // 16x16
public static final Icon Combo3 = IconLoader.getIcon("/general/combo3.png"); // 16x16
public static final Icon ComboArrow = IconLoader.getIcon("/general/comboArrow.png"); // 16x16
public static final Icon ComboArrowDown = IconLoader.getIcon("/general/comboArrowDown.png"); // 9x5
public static final Icon ComboArrowLeft = IconLoader.getIcon("/general/comboArrowLeft.png"); // 5x9
public static final Icon ComboArrowLeftPassive = IconLoader.getIcon("/general/comboArrowLeftPassive.png"); // 5x9
public static final Icon ComboArrowRight = IconLoader.getIcon("/general/comboArrowRight.png"); // 5x9
public static final Icon ComboArrowRightPassive = IconLoader.getIcon("/general/comboArrowRightPassive.png"); // 5x9
public static final Icon ComboBoxButtonArrow = IconLoader.getIcon("/general/comboBoxButtonArrow.png"); // 16x16
public static final Icon ComboUpPassive = IconLoader.getIcon("/general/comboUpPassive.png"); // 16x16
public static final Icon ConfigurableDefault = IconLoader.getIcon("/general/configurableDefault.png"); // 32x32
public static final Icon Configure = IconLoader.getIcon("/general/Configure.png"); // 32x32
public static final Icon ContextHelp = IconLoader.getIcon("/general/contextHelp.png"); // 16x16
public static final Icon CopyHovered = IconLoader.getIcon("/general/copyHovered.png"); // 16x16
public static final Icon CreateNewProject = IconLoader.getIcon("/general/createNewProject.png"); // 32x32
public static final Icon CreateNewProjectfromExistingFiles = IconLoader.getIcon("/general/CreateNewProjectfromExistingFiles.png"); // 32x32
@SuppressWarnings("unused")
@Deprecated
public static final Icon Debug = IconLoader.getIcon("/general/debug.png"); // 16x16
public static final Icon DefaultKeymap = IconLoader.getIcon("/general/defaultKeymap.png"); // 32x32
public static final Icon Divider = IconLoader.getIcon("/general/divider.png"); // 2x19
public static final Icon DownloadPlugin = IconLoader.getIcon("/general/downloadPlugin.png"); // 16x16
public static final Icon Dropdown = IconLoader.getIcon("/general/dropdown.png"); // 16x16
public static final Icon EditColors = IconLoader.getIcon("/general/editColors.png"); // 16x16
public static final Icon EditItemInSection = IconLoader.getIcon("/general/editItemInSection.png"); // 16x16
public static final Icon Ellipsis = IconLoader.getIcon("/general/ellipsis.png"); // 9x9
public static final Icon Error = IconLoader.getIcon("/general/error.png"); // 16x16
public static final Icon ErrorDialog = IconLoader.getIcon("/general/errorDialog.png"); // 32x32
public static final Icon ErrorsInProgress = IconLoader.getIcon("/general/errorsInProgress.png"); // 12x12
public static final Icon ExclMark = IconLoader.getIcon("/general/exclMark.png"); // 16x16
public static final Icon ExpandAll = IconLoader.getIcon("/general/expandAll.png"); // 11x16
public static final Icon ExpandAllHover = IconLoader.getIcon("/general/expandAllHover.png"); // 11x16
public static final Icon ExpandComponent = IconLoader.getIcon("/general/expandComponent.png"); // 12x12
public static final Icon ExpandComponentHover = IconLoader.getIcon("/general/expandComponentHover.png"); // 12x12
public static final Icon ExportSettings = IconLoader.getIcon("/general/ExportSettings.png"); // 32x32
public static final Icon ExternalTools = IconLoader.getIcon("/general/externalTools.png"); // 32x32
public static final Icon ExternalToolsSmall = IconLoader.getIcon("/general/externalToolsSmall.png"); // 16x16
public static final Icon Filter = IconLoader.getIcon("/general/filter.png"); // 16x16
public static final Icon Floating = IconLoader.getIcon("/general/floating.png"); // 14x14
public static final Icon Gear = IconLoader.getIcon("/general/gear.png"); // 21x16
public static final Icon GearHover = IconLoader.getIcon("/general/gearHover.png"); // 21x16
public static final Icon GearPlain = IconLoader.getIcon("/general/gearPlain.png"); // 16x16
public static final Icon GetProjectfromVCS = IconLoader.getIcon("/general/getProjectfromVCS.png"); // 32x32
public static final Icon Help = IconLoader.getIcon("/general/help.png"); // 10x10
public static final Icon Help_small = IconLoader.getIcon("/general/help_small.png"); // 16x16
public static final Icon HideDown = IconLoader.getIcon("/general/hideDown.png"); // 16x16
public static final Icon HideDownHover = IconLoader.getIcon("/general/hideDownHover.png"); // 16x16
public static final Icon HideDownPart = IconLoader.getIcon("/general/hideDownPart.png"); // 16x16
public static final Icon HideDownPartHover = IconLoader.getIcon("/general/hideDownPartHover.png"); // 16x16
public static final Icon HideLeft = IconLoader.getIcon("/general/hideLeft.png"); // 16x16
public static final Icon HideLeftHover = IconLoader.getIcon("/general/hideLeftHover.png"); // 16x16
public static final Icon HideLeftPart = IconLoader.getIcon("/general/hideLeftPart.png"); // 16x16
public static final Icon HideLeftPartHover = IconLoader.getIcon("/general/hideLeftPartHover.png"); // 16x16
public static final Icon HideRight = IconLoader.getIcon("/general/hideRight.png"); // 16x16
public static final Icon HideRightHover = IconLoader.getIcon("/general/hideRightHover.png"); // 16x16
public static final Icon HideRightPart = IconLoader.getIcon("/general/hideRightPart.png"); // 16x16
public static final Icon HideRightPartHover = IconLoader.getIcon("/general/hideRightPartHover.png"); // 16x16
public static final Icon HideToolWindow = IconLoader.getIcon("/general/hideToolWindow.png"); // 14x14
public static final Icon HideToolWindowInactive = IconLoader.getIcon("/general/hideToolWindowInactive.png"); // 14x14
public static final Icon HideWarnings = IconLoader.getIcon("/general/hideWarnings.png"); // 16x16
public static final Icon IjLogo = IconLoader.getIcon("/general/ijLogo.png"); // 16x16
public static final Icon ImplementingMethod = IconLoader.getIcon("/general/implementingMethod.png"); // 10x14
public static final Icon ImportProject = IconLoader.getIcon("/general/importProject.png"); // 32x32
public static final Icon ImportSettings = IconLoader.getIcon("/general/ImportSettings.png"); // 32x32
public static final Icon Information = IconLoader.getIcon("/general/information.png"); // 16x16
public static final Icon InformationDialog = IconLoader.getIcon("/general/informationDialog.png"); // 32x32
public static final Icon InheritedMethod = IconLoader.getIcon("/general/inheritedMethod.png"); // 11x14
public static final Icon Inline_edit = IconLoader.getIcon("/general/inline_edit.png"); // 16x16
public static final Icon Inline_edit_hovered = IconLoader.getIcon("/general/inline_edit_hovered.png"); // 16x16
public static final Icon InspectionsError = IconLoader.getIcon("/general/inspectionsError.png"); // 14x14
public static final Icon InspectionsEye = IconLoader.getIcon("/general/inspectionsEye.png"); // 14x14
public static final Icon InspectionsOff = IconLoader.getIcon("/general/inspectionsOff.png"); // 16x16
public static final Icon InspectionsOK = IconLoader.getIcon("/general/inspectionsOK.png"); // 14x14
public static final Icon InspectionsPause = IconLoader.getIcon("/general/inspectionsPause.png"); // 14x14
public static final Icon InspectionsTrafficOff = IconLoader.getIcon("/general/inspectionsTrafficOff.png"); // 14x14
public static final Icon InspectionsTypos = IconLoader.getIcon("/general/inspectionsTypos.png"); // 14x14
public static final Icon Jdk = IconLoader.getIcon("/general/jdk.png"); // 16x16
public static final Icon KeyboardShortcut = IconLoader.getIcon("/general/keyboardShortcut.png"); // 13x13
public static final Icon Keymap = IconLoader.getIcon("/general/keymap.png"); // 32x32
public static final Icon LayoutEditorOnly = IconLoader.getIcon("/general/layoutEditorOnly.png"); // 16x16
public static final Icon LayoutEditorPreview = IconLoader.getIcon("/general/layoutEditorPreview.png"); // 16x16
public static final Icon LayoutPreviewOnly = IconLoader.getIcon("/general/layoutPreviewOnly.png"); // 16x16
public static final Icon LinkDropTriangle = IconLoader.getIcon("/general/linkDropTriangle.png"); // 14x14
public static final Icon Locate = IconLoader.getIcon("/general/locate.png"); // 14x16
public static final Icon LocateHover = IconLoader.getIcon("/general/locateHover.png"); // 14x16
public static final Icon MacCorner = IconLoader.getIcon("/general/macCorner.png"); // 16x16
public static final Icon Mdot_empty = IconLoader.getIcon("/general/mdot-empty.png"); // 8x8
public static final Icon Mdot_white = IconLoader.getIcon("/general/mdot-white.png"); // 8x8
public static final Icon Mdot = IconLoader.getIcon("/general/mdot.png"); // 8x8
public static final Icon MessageHistory = IconLoader.getIcon("/general/messageHistory.png"); // 16x16
public static final Icon Modified = IconLoader.getIcon("/general/modified.png"); // 24x16
public static final Icon MoreTabs = IconLoader.getIcon("/general/moreTabs.png"); // 16x16
public static final Icon Mouse = IconLoader.getIcon("/general/mouse.png"); // 32x32
public static final Icon MouseShortcut = IconLoader.getIcon("/general/mouseShortcut.png"); // 13x13
public static final Icon NotificationError = IconLoader.getIcon("/general/notificationError.png"); // 24x24
public static final Icon NotificationInfo = IconLoader.getIcon("/general/notificationInfo.png"); // 24x24
public static final Icon NotificationWarning = IconLoader.getIcon("/general/notificationWarning.png"); // 24x24
public static final Icon OpenDisk = IconLoader.getIcon("/general/openDisk.png"); // 16x16
public static final Icon OpenDiskHover = IconLoader.getIcon("/general/openDiskHover.png"); // 16x16
public static final Icon OpenProject = IconLoader.getIcon("/general/openProject.png"); // 32x32
public static final Icon OverridenMethod = IconLoader.getIcon("/general/overridenMethod.png"); // 10x14
public static final Icon OverridingMethod = IconLoader.getIcon("/general/overridingMethod.png"); // 10x14
public static final Icon PackagesTab = IconLoader.getIcon("/general/packagesTab.png"); // 16x16
public static final Icon PasswordLock = IconLoader.getIcon("/general/passwordLock.png"); // 64x64
public static final Icon PathVariables = IconLoader.getIcon("/general/pathVariables.png"); // 32x32
public static final Icon Pin_tab = IconLoader.getIcon("/general/pin_tab.png"); // 16x16
public static final Icon PluginManager = IconLoader.getIcon("/general/pluginManager.png"); // 32x32
public static final Icon Progress = IconLoader.getIcon("/general/progress.png"); // 8x10
public static final Icon ProjectConfigurable = IconLoader.getIcon("/general/projectConfigurable.png"); // 9x9
public static final Icon ProjectConfigurableBanner = IconLoader.getIcon("/general/projectConfigurableBanner.png"); // 9x9
public static final Icon ProjectConfigurableSelected = IconLoader.getIcon("/general/projectConfigurableSelected.png"); // 9x9
public static final Icon ProjectSettings = IconLoader.getIcon("/general/projectSettings.png"); // 16x16
public static final Icon ProjectStructure = IconLoader.getIcon("/general/projectStructure.png"); // 16x16
public static final Icon ProjectTab = IconLoader.getIcon("/general/projectTab.png"); // 16x16
public static final Icon QuestionDialog = IconLoader.getIcon("/general/questionDialog.png"); // 32x32
public static final Icon ReadHelp = IconLoader.getIcon("/general/readHelp.png"); // 32x32
public static final Icon Recursive = IconLoader.getIcon("/general/recursive.png"); // 16x16
public static final Icon Remove = IconLoader.getIcon("/general/remove.png"); // 16x16
public static final Icon Reset = IconLoader.getIcon("/general/reset.png"); // 16x16
public static final Icon Run = IconLoader.getIcon("/general/run.png"); // 7x10
public static final Icon RunWithCoverage = IconLoader.getIcon("/general/runWithCoverage.png"); // 16x16
public static final Icon SafeMode = IconLoader.getIcon("/general/safeMode.png"); // 13x13
public static final Icon SearchEverywhereGear = IconLoader.getIcon("/general/searchEverywhereGear.png"); // 16x16
public static final Icon SecondaryGroup = IconLoader.getIcon("/general/secondaryGroup.png"); // 16x16
public static final Icon SeparatorH = IconLoader.getIcon("/general/separatorH.png"); // 17x11
public static final Icon Settings = IconLoader.getIcon("/general/settings.png"); // 16x16
public static final Icon Show_to_implement = IconLoader.getIcon("/general/show_to_implement.png"); // 16x16
public static final Icon Show_to_override = IconLoader.getIcon("/general/show_to_override.png"); // 16x16
public static final Icon SmallConfigurableVcs = IconLoader.getIcon("/general/smallConfigurableVcs.png"); // 16x16
public static final Icon SplitCenterH = IconLoader.getIcon("/general/splitCenterH.png"); // 7x7
public static final Icon SplitCenterV = IconLoader.getIcon("/general/splitCenterV.png"); // 6x7
public static final Icon SplitDown = IconLoader.getIcon("/general/splitDown.png"); // 7x7
public static final Icon SplitGlueH = IconLoader.getIcon("/general/splitGlueH.png"); // 6x17
public static final Icon SplitGlueV = IconLoader.getIcon("/general/splitGlueV.png"); // 17x6
public static final Icon SplitLeft = IconLoader.getIcon("/general/splitLeft.png"); // 7x7
public static final Icon SplitRight = IconLoader.getIcon("/general/splitRight.png"); // 7x7
public static final Icon SplitUp = IconLoader.getIcon("/general/splitUp.png"); // 7x7
public static final Icon Tab_white_center = IconLoader.getIcon("/general/tab-white-center.png"); // 1x17
public static final Icon Tab_white_left = IconLoader.getIcon("/general/tab-white-left.png"); // 4x17
public static final Icon Tab_white_right = IconLoader.getIcon("/general/tab-white-right.png"); // 4x17
public static final Icon Tab_grey_bckgrnd = IconLoader.getIcon("/general/tab_grey_bckgrnd.png"); // 1x17
public static final Icon Tab_grey_left = IconLoader.getIcon("/general/tab_grey_left.png"); // 4x17
public static final Icon Tab_grey_left_inner = IconLoader.getIcon("/general/tab_grey_left_inner.png"); // 4x17
public static final Icon Tab_grey_right = IconLoader.getIcon("/general/tab_grey_right.png"); // 4x17
public static final Icon Tab_grey_right_inner = IconLoader.getIcon("/general/tab_grey_right_inner.png"); // 4x17
public static final Icon TbHidden = IconLoader.getIcon("/general/tbHidden.png"); // 16x16
public static final Icon TbShown = IconLoader.getIcon("/general/tbShown.png"); // 16x16
public static final Icon TemplateProjectSettings = IconLoader.getIcon("/general/TemplateProjectSettings.png"); // 32x32
public static final Icon TemplateProjectStructure = IconLoader.getIcon("/general/TemplateProjectStructure.png"); // 32x32
public static final Icon Tip = IconLoader.getIcon("/general/tip.png"); // 32x32
public static final Icon TodoDefault = IconLoader.getIcon("/general/todoDefault.png"); // 12x12
public static final Icon TodoImportant = IconLoader.getIcon("/general/todoImportant.png"); // 12x12
public static final Icon TodoQuestion = IconLoader.getIcon("/general/todoQuestion.png"); // 12x12
public static final Icon UninstallPlugin = IconLoader.getIcon("/general/uninstallPlugin.png"); // 16x16
public static final Icon Warning = IconLoader.getIcon("/general/warning.png"); // 16x16
public static final Icon WarningDecorator = IconLoader.getIcon("/general/warningDecorator.png"); // 16x16
public static final Icon WarningDialog = IconLoader.getIcon("/general/warningDialog.png"); // 32x32
public static final Icon Web = IconLoader.getIcon("/general/web.png"); // 13x13
public static final Icon WebSettings = IconLoader.getIcon("/general/webSettings.png"); // 16x16
}
public static class Graph {
public static final Icon ActualZoom = IconLoader.getIcon("/graph/actualZoom.png"); // 16x16
public static final Icon Export = IconLoader.getIcon("/graph/export.png"); // 16x16
public static final Icon FitContent = IconLoader.getIcon("/graph/fitContent.png"); // 16x16
public static final Icon Grid = IconLoader.getIcon("/graph/grid.png"); // 16x16
public static final Icon Layout = IconLoader.getIcon("/graph/layout.png"); // 16x16
public static final Icon NodeSelectionMode = IconLoader.getIcon("/graph/nodeSelectionMode.png"); // 16x16
public static final Icon Print = IconLoader.getIcon("/graph/print.png"); // 16x16
public static final Icon PrintPreview = IconLoader.getIcon("/graph/printPreview.png"); // 16x16
public static final Icon SnapToGrid = IconLoader.getIcon("/graph/snapToGrid.png"); // 16x16
public static final Icon ZoomIn = IconLoader.getIcon("/graph/zoomIn.png"); // 16x16
public static final Icon ZoomOut = IconLoader.getIcon("/graph/zoomOut.png"); // 16x16
}
public static class Gutter {
public static final Icon Colors = IconLoader.getIcon("/gutter/colors.png"); // 12x12
public static final Icon ExtAnnotation = IconLoader.getIcon("/gutter/extAnnotation.png"); // 12x12
public static final Icon ImplementedMethod = IconLoader.getIcon("/gutter/implementedMethod.png"); // 12x12
public static final Icon ImplementingFunctionalInterface = IconLoader.getIcon("/gutter/implementingFunctionalInterface.png"); // 12x12
public static final Icon ImplementingMethod = IconLoader.getIcon("/gutter/implementingMethod.png"); // 12x12
public static final Icon Java9Service = IconLoader.getIcon("/gutter/java9Service.png"); // 12x12
public static final Icon OverridenMethod = IconLoader.getIcon("/gutter/overridenMethod.png"); // 12x12
public static final Icon OverridingMethod = IconLoader.getIcon("/gutter/overridingMethod.png"); // 12x12
public static final Icon RecursiveMethod = IconLoader.getIcon("/gutter/recursiveMethod.png"); // 12x12
public static final Icon SiblingInheritedMethod = IconLoader.getIcon("/gutter/siblingInheritedMethod.png"); // 12x12
public static final Icon Unique = IconLoader.getIcon("/gutter/unique.png"); // 8x8
}
public static class Hierarchy {
public static final Icon Base = IconLoader.getIcon("/hierarchy/base.png"); // 16x16
public static final Icon Callee = IconLoader.getIcon("/hierarchy/callee.png"); // 16x16
public static final Icon Caller = IconLoader.getIcon("/hierarchy/caller.png"); // 16x16
public static final Icon Class = IconLoader.getIcon("/hierarchy/class.png"); // 16x16
public static final Icon MethodDefined = IconLoader.getIcon("/hierarchy/methodDefined.png"); // 9x9
public static final Icon MethodNotDefined = IconLoader.getIcon("/hierarchy/methodNotDefined.png"); // 8x8
public static final Icon ShouldDefineMethod = IconLoader.getIcon("/hierarchy/shouldDefineMethod.png"); // 9x9
public static final Icon Subtypes = IconLoader.getIcon("/hierarchy/subtypes.png"); // 16x16
public static final Icon Supertypes = IconLoader.getIcon("/hierarchy/supertypes.png"); // 16x16
}
public static final Icon Icon = IconLoader.getIcon("/icon.png"); // 32x32
public static final Icon Icon_128 = IconLoader.getIcon("/icon_128.png"); // 128x128
public static final Icon Icon_CE = IconLoader.getIcon("/icon_CE.png"); // 32x32
public static final Icon Icon_CE_128 = IconLoader.getIcon("/icon_CE_128.png"); // 128x128
public static final Icon Icon_CE_256 = IconLoader.getIcon("/icon_CE_256.png"); // 256x256
public static final Icon Icon_CE_512 = IconLoader.getIcon("/icon_CE_512.png"); // 512x512
public static final Icon Icon_CE_64 = IconLoader.getIcon("/icon_CE_64.png"); // 64x64
public static final Icon Icon_CEsmall = IconLoader.getIcon("/icon_CEsmall.png"); // 16x16
public static final Icon Icon_small = IconLoader.getIcon("/icon_small.png"); // 16x16
public static class Icons {
public static class Ide {
public static final Icon NextStep = IconLoader.getIcon("/icons/ide/nextStep.png"); // 12x12
public static final Icon NextStepGrayed = IconLoader.getIcon("/icons/ide/nextStepGrayed.png"); // 12x12
public static final Icon NextStepInverted = IconLoader.getIcon("/icons/ide/nextStepInverted.png"); // 12x12
public static final Icon SpeedSearchPrompt = IconLoader.getIcon("/icons/ide/speedSearchPrompt.png"); // 16x16
}
}
public static class Ide {
public static class Dnd {
public static final Icon Bottom = IconLoader.getIcon("/ide/dnd/bottom.png"); // 16x16
public static final Icon Left = IconLoader.getIcon("/ide/dnd/left.png"); // 16x16
public static final Icon Right = IconLoader.getIcon("/ide/dnd/right.png"); // 16x16
public static final Icon Top = IconLoader.getIcon("/ide/dnd/top.png"); // 16x16
}
public static final Icon EmptyFatalError = IconLoader.getIcon("/ide/emptyFatalError.png"); // 16x16
public static final Icon Error = IconLoader.getIcon("/ide/error.png"); // 16x16
public static final Icon Error_notifications = IconLoader.getIcon("/ide/error_notifications.png"); // 16x16
public static final Icon ErrorPoint = IconLoader.getIcon("/ide/errorPoint.png"); // 6x6
public static final Icon External_link_arrow = IconLoader.getIcon("/ide/external_link_arrow.png"); // 14x14
public static final Icon FatalError_read = IconLoader.getIcon("/ide/fatalError-read.png"); // 16x16
public static final Icon FatalError = IconLoader.getIcon("/ide/fatalError.png"); // 16x16
public static final Icon HectorNo = IconLoader.getIcon("/ide/hectorNo.png"); // 16x16
public static final Icon HectorOff = IconLoader.getIcon("/ide/hectorOff.png"); // 16x16
public static final Icon HectorOn = IconLoader.getIcon("/ide/hectorOn.png"); // 16x16
public static final Icon HectorSyntax = IconLoader.getIcon("/ide/hectorSyntax.png"); // 16x16
public static final Icon IncomingChangesOff = IconLoader.getIcon("/ide/incomingChangesOff.png"); // 16x16
public static final Icon IncomingChangesOn = IconLoader.getIcon("/ide/incomingChangesOn.png"); // 16x16
public static final Icon Info_notifications = IconLoader.getIcon("/ide/info_notifications.png"); // 16x16
public static final Icon Link = IconLoader.getIcon("/ide/link.png"); // 12x12
public static final Icon LocalScope = IconLoader.getIcon("/ide/localScope.png"); // 16x16
public static final Icon LookupAlphanumeric = IconLoader.getIcon("/ide/lookupAlphanumeric.png"); // 12x12
public static final Icon LookupRelevance = IconLoader.getIcon("/ide/lookupRelevance.png"); // 12x12
public static class Macro {
public static final Icon Recording_1 = IconLoader.getIcon("/ide/macro/recording_1.png"); // 16x16
public static final Icon Recording_2 = IconLoader.getIcon("/ide/macro/recording_2.png"); // 16x16
public static final Icon Recording_3 = IconLoader.getIcon("/ide/macro/recording_3.png"); // 16x16
public static final Icon Recording_4 = IconLoader.getIcon("/ide/macro/recording_4.png"); // 16x16
public static final Icon Recording_stop = IconLoader.getIcon("/ide/macro/recording_stop.png"); // 16x16
}
public static final Icon NoNotifications13 = IconLoader.getIcon("/ide/noNotifications13.png"); // 13x13
public static class Notification {
public static final Icon Close = IconLoader.getIcon("/ide/notification/close.png"); // 16x16
public static final Icon CloseHover = IconLoader.getIcon("/ide/notification/closeHover.png"); // 16x16
public static final Icon Collapse = IconLoader.getIcon("/ide/notification/collapse.png"); // 16x16
public static final Icon CollapseHover = IconLoader.getIcon("/ide/notification/collapseHover.png"); // 16x16
public static final Icon DropTriangle = IconLoader.getIcon("/ide/notification/dropTriangle.png"); // 11x8
public static final Icon ErrorEvents = IconLoader.getIcon("/ide/notification/errorEvents.png"); // 13x13
public static final Icon Expand = IconLoader.getIcon("/ide/notification/expand.png"); // 16x16
public static final Icon ExpandHover = IconLoader.getIcon("/ide/notification/expandHover.png"); // 16x16
public static final Icon Gear = IconLoader.getIcon("/ide/notification/gear.png"); // 16x16
public static final Icon GearHover = IconLoader.getIcon("/ide/notification/gearHover.png"); // 16x16
public static final Icon InfoEvents = IconLoader.getIcon("/ide/notification/infoEvents.png"); // 13x13
public static final Icon NoEvents = IconLoader.getIcon("/ide/notification/noEvents.png"); // 13x13
public static class Shadow {
public static final Icon Bottom_left = IconLoader.getIcon("/ide/notification/shadow/bottom-left.png"); // 14x16
public static final Icon Bottom_right = IconLoader.getIcon("/ide/notification/shadow/bottom-right.png"); // 14x16
public static final Icon Bottom = IconLoader.getIcon("/ide/notification/shadow/bottom.png"); // 4x8
public static final Icon Left = IconLoader.getIcon("/ide/notification/shadow/left.png"); // 6x4
public static final Icon Right = IconLoader.getIcon("/ide/notification/shadow/right.png"); // 6x4
public static final Icon Top_left = IconLoader.getIcon("/ide/notification/shadow/top-left.png"); // 14x12
public static final Icon Top_right = IconLoader.getIcon("/ide/notification/shadow/top-right.png"); // 14x12
public static final Icon Top = IconLoader.getIcon("/ide/notification/shadow/top.png"); // 4x4
}
public static final Icon WarningEvents = IconLoader.getIcon("/ide/notification/warningEvents.png"); // 13x13
}
public static final Icon Notifications = IconLoader.getIcon("/ide/notifications.png"); // 16x16
public static final Icon OutgoingChangesOn = IconLoader.getIcon("/ide/outgoingChangesOn.png"); // 16x16
public static final Icon Pipette = IconLoader.getIcon("/ide/pipette.png"); // 16x16
public static final Icon Pipette_rollover = IconLoader.getIcon("/ide/pipette_rollover.png"); // 16x16
public static final Icon Rating = IconLoader.getIcon("/ide/rating.png"); // 11x11
public static final Icon Rating1 = IconLoader.getIcon("/ide/rating1.png"); // 11x11
public static final Icon Rating2 = IconLoader.getIcon("/ide/rating2.png"); // 11x11
public static final Icon Rating3 = IconLoader.getIcon("/ide/rating3.png"); // 11x11
public static final Icon Rating4 = IconLoader.getIcon("/ide/rating4.png"); // 11x11
public static final Icon Readonly = IconLoader.getIcon("/ide/readonly.png"); // 16x16
public static final Icon Readwrite = IconLoader.getIcon("/ide/readwrite.png"); // 16x16
public static class Shadow {
public static final Icon Bottom_left = IconLoader.getIcon("/ide/shadow/bottom-left.png"); // 70x70
public static final Icon Bottom_right = IconLoader.getIcon("/ide/shadow/bottom-right.png"); // 70x70
public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/bottom.png"); // 1x49
public static final Icon Left = IconLoader.getIcon("/ide/shadow/left.png"); // 35x1
public static class Popup {
public static final Icon Bottom_left = IconLoader.getIcon("/ide/shadow/popup/bottom-left.png"); // 20x20
public static final Icon Bottom_right = IconLoader.getIcon("/ide/shadow/popup/bottom-right.png"); // 20x20
public static final Icon Bottom = IconLoader.getIcon("/ide/shadow/popup/bottom.png"); // 1x10
public static final Icon Left = IconLoader.getIcon("/ide/shadow/popup/left.png"); // 7x1
public static final Icon Right = IconLoader.getIcon("/ide/shadow/popup/right.png"); // 7x1
public static final Icon Top_left = IconLoader.getIcon("/ide/shadow/popup/top-left.png"); // 14x14
public static final Icon Top_right = IconLoader.getIcon("/ide/shadow/popup/top-right.png"); // 14x14
public static final Icon Top = IconLoader.getIcon("/ide/shadow/popup/top.png"); // 1x4
}
public static final Icon Right = IconLoader.getIcon("/ide/shadow/right.png"); // 35x1
public static final Icon Top_left = IconLoader.getIcon("/ide/shadow/top-left.png"); // 70x70
public static final Icon Top_right = IconLoader.getIcon("/ide/shadow/top-right.png"); // 70x70
public static final Icon Top = IconLoader.getIcon("/ide/shadow/top.png"); // 1x20
}
public static final Icon Statusbar_arrows = IconLoader.getIcon("/ide/statusbar_arrows.png"); // 7x10
public static final Icon UpDown = IconLoader.getIcon("/ide/upDown.png"); // 16x16
public static final Icon Warning_notifications = IconLoader.getIcon("/ide/warning_notifications.png"); // 16x16
}
public static final Icon Idea_logo_background = IconLoader.getIcon("/idea_logo_background.png"); // 500x500
public static final Icon Idea_logo_welcome = IconLoader.getIcon("/idea_logo_welcome.png"); // 100x100
public static class Javaee {
public static final Icon Application_xml = IconLoader.getIcon("/javaee/application_xml.png"); // 16x16
public static final Icon BuildOnFrameDeactivation = IconLoader.getIcon("/javaee/buildOnFrameDeactivation.png"); // 16x16
public static final Icon DataSourceImport = IconLoader.getIcon("/javaee/dataSourceImport.png"); // 16x16
public static final Icon DbSchemaImportBig = IconLoader.getIcon("/javaee/dbSchemaImportBig.png"); // 32x32
public static final Icon Ejb_jar_xml = IconLoader.getIcon("/javaee/ejb-jar_xml.png"); // 16x16
public static final Icon EjbClass = IconLoader.getIcon("/javaee/ejbClass.png"); // 16x16
public static final Icon EjbModule = IconLoader.getIcon("/javaee/ejbModule.png"); // 16x16
public static final Icon EmbeddedAttributeOverlay = IconLoader.getIcon("/javaee/embeddedAttributeOverlay.png"); // 16x16
public static final Icon EntityBean = IconLoader.getIcon("/javaee/entityBean.png"); // 16x16
public static final Icon EntityBeanBig = IconLoader.getIcon("/javaee/entityBeanBig.png"); // 24x24
public static final Icon Home = IconLoader.getIcon("/javaee/home.png"); // 16x16
public static final Icon InheritedAttributeOverlay = IconLoader.getIcon("/javaee/inheritedAttributeOverlay.png"); // 16x16
public static final Icon InterceptorClass = IconLoader.getIcon("/javaee/interceptorClass.png"); // 16x16
public static final Icon InterceptorMethod = IconLoader.getIcon("/javaee/interceptorMethod.png"); // 16x16
public static final Icon JavaeeAppModule = IconLoader.getIcon("/javaee/JavaeeAppModule.png"); // 16x16
public static final Icon JpaFacet = IconLoader.getIcon("/javaee/jpaFacet.png"); // 16x16
public static final Icon Local = IconLoader.getIcon("/javaee/local.png"); // 16x16
public static final Icon LocalHome = IconLoader.getIcon("/javaee/localHome.png"); // 16x16
public static final Icon MessageBean = IconLoader.getIcon("/javaee/messageBean.png"); // 16x16
public static final Icon PersistenceAttribute = IconLoader.getIcon("/javaee/persistenceAttribute.png"); // 16x16
public static final Icon PersistenceEmbeddable = IconLoader.getIcon("/javaee/persistenceEmbeddable.png"); // 16x16
public static final Icon PersistenceEntity = IconLoader.getIcon("/javaee/persistenceEntity.png"); // 16x16
public static final Icon PersistenceEntityListener = IconLoader.getIcon("/javaee/persistenceEntityListener.png"); // 16x16
public static final Icon PersistenceId = IconLoader.getIcon("/javaee/persistenceId.png"); // 16x16
public static final Icon PersistenceIdRelationship = IconLoader.getIcon("/javaee/persistenceIdRelationship.png"); // 16x16
public static final Icon PersistenceMappedSuperclass = IconLoader.getIcon("/javaee/persistenceMappedSuperclass.png"); // 16x16
public static final Icon PersistenceRelationship = IconLoader.getIcon("/javaee/persistenceRelationship.png"); // 16x16
public static final Icon PersistenceUnit = IconLoader.getIcon("/javaee/persistenceUnit.png"); // 16x16
public static final Icon Remote = IconLoader.getIcon("/javaee/remote.png"); // 16x16
public static final Icon SessionBean = IconLoader.getIcon("/javaee/sessionBean.png"); // 16x16
public static final Icon UpdateRunningApplication = IconLoader.getIcon("/javaee/updateRunningApplication.png"); // 16x16
public static final Icon Web_xml = IconLoader.getIcon("/javaee/web_xml.png"); // 16x16
public static final Icon WebModule = IconLoader.getIcon("/javaee/webModule.png"); // 16x16
public static final Icon WebModuleGroup = IconLoader.getIcon("/javaee/webModuleGroup.png"); // 16x16
public static final Icon WebService = IconLoader.getIcon("/javaee/WebService.png"); // 16x16
public static final Icon WebService2 = IconLoader.getIcon("/javaee/WebService2.png"); // 16x16
public static final Icon WebServiceClient = IconLoader.getIcon("/javaee/WebServiceClient.png"); // 16x16
public static final Icon WebServiceClient2 = IconLoader.getIcon("/javaee/WebServiceClient2.png"); // 16x16
}
public static class Json {
public static final Icon Array = IconLoader.getIcon("/json/array.png"); // 16x16
public static final Icon Object = IconLoader.getIcon("/json/object.png"); // 16x16
public static final Icon Property_braces = IconLoader.getIcon("/json/property_braces.png"); // 16x16
public static final Icon Property_brackets = IconLoader.getIcon("/json/property_brackets.png"); // 16x16
}
public static final Icon Logo_welcomeScreen = IconLoader.getIcon("/Logo_welcomeScreen.png"); // 80x80
public static class Mac {
public static final Icon AppIconOk512 = IconLoader.getIcon("/mac/appIconOk512.png"); // 55x55
public static final Icon Text = IconLoader.getIcon("/mac/text.png"); // 32x32
public static final Icon Tree_black_right_arrow = IconLoader.getIcon("/mac/tree_black_right_arrow.png"); // 11x11
public static final Icon Tree_white_down_arrow = IconLoader.getIcon("/mac/tree_white_down_arrow.png"); // 11x11
public static final Icon Tree_white_right_arrow = IconLoader.getIcon("/mac/tree_white_right_arrow.png"); // 11x11
public static final Icon YosemiteOptionButtonSelector = IconLoader.getIcon("/mac/yosemiteOptionButtonSelector.png"); // 8x12
}
public static class Modules {
public static final Icon AddContentEntry = IconLoader.getIcon("/modules/addContentEntry.png"); // 16x16
public static final Icon AddExcludedRoot = IconLoader.getIcon("/modules/addExcludedRoot.png"); // 16x16
public static final Icon Annotation = IconLoader.getIcon("/modules/annotation.png"); // 16x16
public static final Icon DeleteContentFolder = IconLoader.getIcon("/modules/deleteContentFolder.png"); // 9x9
public static final Icon DeleteContentFolderRollover = IconLoader.getIcon("/modules/deleteContentFolderRollover.png"); // 9x9
public static final Icon DeleteContentRoot = IconLoader.getIcon("/modules/deleteContentRoot.png"); // 9x9
public static final Icon DeleteContentRootRollover = IconLoader.getIcon("/modules/deleteContentRootRollover.png"); // 9x9
public static final Icon Edit = IconLoader.getIcon("/modules/edit.png"); // 16x16
public static final Icon EditFolder = IconLoader.getIcon("/modules/editFolder.png"); // 16x16
public static final Icon ExcludedGeneratedRoot = IconLoader.getIcon("/modules/excludedGeneratedRoot.png"); // 16x16
public static final Icon ExcludeRoot = IconLoader.getIcon("/modules/excludeRoot.png"); // 16x16
public static final Icon GeneratedFolder = IconLoader.getIcon("/modules/generatedFolder.png"); // 16x16
public static final Icon GeneratedSourceRoot = IconLoader.getIcon("/modules/generatedSourceRoot.png"); // 16x16
public static final Icon GeneratedTestRoot = IconLoader.getIcon("/modules/generatedTestRoot.png"); // 16x16
public static final Icon Library = IconLoader.getIcon("/modules/library.png"); // 16x16
public static final Icon Merge = IconLoader.getIcon("/modules/merge.png"); // 16x16
public static final Icon ModulesNode = IconLoader.getIcon("/modules/modulesNode.png"); // 16x16
public static final Icon Output = IconLoader.getIcon("/modules/output.png"); // 16x16
public static final Icon ResourcesRoot = IconLoader.getIcon("/modules/resourcesRoot.png"); // 16x16
public static final Icon SetPackagePrefix = IconLoader.getIcon("/modules/setPackagePrefix.png"); // 9x9
public static final Icon SetPackagePrefixRollover = IconLoader.getIcon("/modules/setPackagePrefixRollover.png"); // 9x9
public static final Icon SourceFolder = IconLoader.getIcon("/modules/sourceFolder.png"); // 16x16
public static final Icon SourceRoot = IconLoader.getIcon("/modules/sourceRoot.png"); // 16x16
public static final Icon SourceRootFileLayer = IconLoader.getIcon("/modules/sourceRootFileLayer.png"); // 16x16
public static final Icon Sources = IconLoader.getIcon("/modules/sources.png"); // 16x16
public static final Icon Split = IconLoader.getIcon("/modules/split.png"); // 16x16
public static final Icon TestResourcesRoot = IconLoader.getIcon("/modules/testResourcesRoot.png"); // 16x16
public static final Icon TestRoot = IconLoader.getIcon("/modules/testRoot.png"); // 16x16
public static final Icon TestSourceFolder = IconLoader.getIcon("/modules/testSourceFolder.png"); // 16x16
public static class Types {
public static final Icon UserDefined = IconLoader.getIcon("/modules/types/userDefined.png"); // 16x16
}
public static final Icon UnloadedModule = IconLoader.getIcon("/modules/unloadedModule.png"); // 16x16
public static final Icon UnmarkWebroot = IconLoader.getIcon("/modules/unmarkWebroot.png"); // 16x16
public static final Icon WebRoot = IconLoader.getIcon("/modules/webRoot.png"); // 16x16
}
public static class Nodes {
public static final Icon AbstractClass = IconLoader.getIcon("/nodes/abstractClass.png"); // 16x16
public static final Icon AbstractException = IconLoader.getIcon("/nodes/abstractException.png"); // 16x16
public static final Icon AbstractMethod = IconLoader.getIcon("/nodes/abstractMethod.png"); // 16x16
public static final Icon Advice = IconLoader.getIcon("/nodes/advice.png"); // 16x16
public static final Icon Annotationtype = IconLoader.getIcon("/nodes/annotationtype.png"); // 16x16
public static final Icon AnonymousClass = IconLoader.getIcon("/nodes/anonymousClass.png"); // 16x16
public static final Icon Artifact = IconLoader.getIcon("/nodes/artifact.png"); // 16x16
public static final Icon Aspect = IconLoader.getIcon("/nodes/aspect.png"); // 16x16
public static final Icon C_plocal = IconLoader.getIcon("/nodes/c_plocal.png"); // 16x16
public static final Icon C_private = IconLoader.getIcon("/nodes/c_private.png"); // 16x16
public static final Icon C_protected = IconLoader.getIcon("/nodes/c_protected.png"); // 16x16
public static final Icon C_public = IconLoader.getIcon("/nodes/c_public.png"); // 16x16
public static final Icon Class = IconLoader.getIcon("/nodes/class.png"); // 16x16
public static final Icon ClassInitializer = IconLoader.getIcon("/nodes/classInitializer.png"); // 16x16
public static final Icon CollapseNode = IconLoader.getIcon("/nodes/collapseNode.png"); // 9x9
public static final Icon CompiledClassesFolder = IconLoader.getIcon("/nodes/compiledClassesFolder.png"); // 16x16
public static final Icon CopyOfFolder = IconLoader.getIcon("/nodes/copyOfFolder.png"); // 16x16
public static final Icon CustomRegion = IconLoader.getIcon("/nodes/customRegion.png"); // 16x16
public static final Icon Cvs_global = IconLoader.getIcon("/nodes/cvs_global.png"); // 16x16
public static final Icon Cvs_roots = IconLoader.getIcon("/nodes/cvs_roots.png"); // 16x16
public static final Icon DataColumn = IconLoader.getIcon("/nodes/dataColumn.png"); // 16x16
public static final Icon DataSchema = IconLoader.getIcon("/nodes/dataSchema.png"); // 16x16
public static final Icon DataSource = IconLoader.getIcon("/nodes/DataSource.png"); // 16x16
public static final Icon DataTables = IconLoader.getIcon("/nodes/DataTables.png"); // 16x16
public static final Icon DataView = IconLoader.getIcon("/nodes/dataView.png"); // 16x16
public static final Icon Deploy = IconLoader.getIcon("/nodes/deploy.png"); // 16x16
public static final Icon Desktop = IconLoader.getIcon("/nodes/desktop.png"); // 16x16
public static final Icon DisabledPointcut = IconLoader.getIcon("/nodes/disabledPointcut.png"); // 16x16
public static final Icon Ejb = IconLoader.getIcon("/nodes/ejb.png"); // 16x16
public static final Icon EjbBusinessMethod = IconLoader.getIcon("/nodes/ejbBusinessMethod.png"); // 16x16
public static final Icon EjbCmpField = IconLoader.getIcon("/nodes/ejbCmpField.png"); // 16x16
public static final Icon EjbCmrField = IconLoader.getIcon("/nodes/ejbCmrField.png"); // 16x16
public static final Icon EjbCreateMethod = IconLoader.getIcon("/nodes/ejbCreateMethod.png"); // 16x16
public static final Icon EjbFinderMethod = IconLoader.getIcon("/nodes/ejbFinderMethod.png"); // 16x16
public static final Icon EjbPrimaryKeyClass = IconLoader.getIcon("/nodes/ejbPrimaryKeyClass.png"); // 16x16
public static final Icon EjbReference = IconLoader.getIcon("/nodes/ejbReference.png"); // 16x16
public static final Icon EmptyNode = IconLoader.getIcon("/nodes/emptyNode.png"); // 18x18
public static final Icon EnterpriseProject = IconLoader.getIcon("/nodes/enterpriseProject.png"); // 16x16
public static final Icon EntryPoints = IconLoader.getIcon("/nodes/entryPoints.png"); // 16x16
public static final Icon Enum = IconLoader.getIcon("/nodes/enum.png"); // 16x16
public static final Icon ErrorIntroduction = IconLoader.getIcon("/nodes/errorIntroduction.png"); // 16x16
public static final Icon ErrorMark = IconLoader.getIcon("/nodes/errorMark.png"); // 16x16
public static final Icon ExceptionClass = IconLoader.getIcon("/nodes/exceptionClass.png"); // 16x16
public static final Icon ExcludedFromCompile = IconLoader.getIcon("/nodes/excludedFromCompile.png"); // 16x16
public static final Icon ExpandNode = IconLoader.getIcon("/nodes/expandNode.png"); // 9x9
public static final Icon ExtractedFolder = IconLoader.getIcon("/nodes/extractedFolder.png"); // 16x16
public static final Icon Field = IconLoader.getIcon("/nodes/field.png"); // 16x16
public static final Icon FieldPK = IconLoader.getIcon("/nodes/fieldPK.png"); // 16x16
public static final Icon FinalMark = IconLoader.getIcon("/nodes/finalMark.png"); // 16x16
public static final Icon Folder = IconLoader.getIcon("/nodes/folder.png"); // 16x16
public static final Icon Function = IconLoader.getIcon("/nodes/function.png"); // 16x16
public static final Icon HomeFolder = IconLoader.getIcon("/nodes/homeFolder.png"); // 16x16
public static final Icon IdeaModule = IconLoader.getIcon("/nodes/ideaModule.png"); // 16x16
public static final Icon IdeaProject = IconLoader.getIcon("/nodes/ideaProject.png"); // 16x16
public static final Icon InspectionResults = IconLoader.getIcon("/nodes/inspectionResults.png"); // 16x16
public static final Icon Interface = IconLoader.getIcon("/nodes/interface.png"); // 16x16
public static final Icon J2eeParameter = IconLoader.getIcon("/nodes/j2eeParameter.png"); // 16x16
public static final Icon JarDirectory = IconLoader.getIcon("/nodes/jarDirectory.png"); // 16x16
public static final Icon JavaDocFolder = IconLoader.getIcon("/nodes/javaDocFolder.png"); // 16x16
public static final Icon JavaModule = IconLoader.getIcon("/nodes/javaModule.png"); // 16x16
public static final Icon JavaModuleRoot = IconLoader.getIcon("/nodes/javaModuleRoot.png"); // 16x16
public static class Jsf {
public static final Icon Component = IconLoader.getIcon("/nodes/jsf/component.png"); // 16x16
public static final Icon Converter = IconLoader.getIcon("/nodes/jsf/converter.png"); // 16x16
public static final Icon General = IconLoader.getIcon("/nodes/jsf/general.png"); // 16x16
public static final Icon GenericValue = IconLoader.getIcon("/nodes/jsf/genericValue.png"); // 16x16
public static final Icon ManagedBean = IconLoader.getIcon("/nodes/jsf/managedBean.png"); // 16x16
public static final Icon NavigationCase = IconLoader.getIcon("/nodes/jsf/navigationCase.png"); // 16x16
public static final Icon NavigationRule = IconLoader.getIcon("/nodes/jsf/navigationRule.png"); // 16x16
public static final Icon Renderer = IconLoader.getIcon("/nodes/jsf/renderer.png"); // 16x16
public static final Icon RenderKit = IconLoader.getIcon("/nodes/jsf/renderKit.png"); // 16x16
public static final Icon Validator = IconLoader.getIcon("/nodes/jsf/validator.png"); // 16x16
}
public static final Icon Jsr45 = IconLoader.getIcon("/nodes/jsr45.png"); // 16x16
public static final Icon JunitTestMark = IconLoader.getIcon("/nodes/junitTestMark.png"); // 16x16
public static final Icon KeymapAnt = IconLoader.getIcon("/nodes/keymapAnt.png"); // 16x16
public static final Icon KeymapEditor = IconLoader.getIcon("/nodes/keymapEditor.png"); // 16x16
public static final Icon KeymapMainMenu = IconLoader.getIcon("/nodes/keymapMainMenu.png"); // 16x16
public static final Icon KeymapOther = IconLoader.getIcon("/nodes/keymapOther.png"); // 16x16
public static final Icon KeymapTools = IconLoader.getIcon("/nodes/keymapTools.png"); // 16x16
public static final Icon Locked = IconLoader.getIcon("/nodes/locked.png"); // 16x16
public static final Icon Method = IconLoader.getIcon("/nodes/method.png"); // 16x16
public static final Icon MethodReference = IconLoader.getIcon("/nodes/methodReference.png"); // 16x16
public static final Icon Module = IconLoader.getIcon("/nodes/Module.png"); // 16x16
public static final Icon ModuleGroup = IconLoader.getIcon("/nodes/moduleGroup.png"); // 16x16
public static final Icon NativeLibrariesFolder = IconLoader.getIcon("/nodes/nativeLibrariesFolder.png"); // 16x16
public static final Icon NewException = IconLoader.getIcon("/nodes/newException.png"); // 16x16
public static final Icon NewFolder = IconLoader.getIcon("/nodes/newFolder.png"); // 16x16
public static final Icon NewParameter = IconLoader.getIcon("/nodes/newParameter.png"); // 16x16
public static final Icon NodePlaceholder = IconLoader.getIcon("/nodes/nodePlaceholder.png"); // 16x16
public static final Icon Package = IconLoader.getIcon("/nodes/package.png"); // 16x16
public static final Icon Padlock = IconLoader.getIcon("/nodes/padlock.png"); // 16x16
public static final Icon Parameter = IconLoader.getIcon("/nodes/parameter.png"); // 16x16
public static final Icon PinToolWindow = IconLoader.getIcon("/nodes/pinToolWindow.png"); // 13x13
public static final Icon Plugin = IconLoader.getIcon("/nodes/plugin.png"); // 16x16
public static final Icon PluginJB = IconLoader.getIcon("/nodes/pluginJB.png"); // 16x16
public static final Icon PluginLogo = IconLoader.getIcon("/nodes/pluginLogo.png"); // 32x32
public static final Icon Pluginnotinstalled = IconLoader.getIcon("/nodes/pluginnotinstalled.png"); // 16x16
public static final Icon Pluginobsolete = IconLoader.getIcon("/nodes/pluginobsolete.png"); // 16x16
public static final Icon PluginRestart = IconLoader.getIcon("/nodes/pluginRestart.png"); // 16x16
public static final Icon PluginUpdate = IconLoader.getIcon("/nodes/pluginUpdate.png"); // 16x16
public static final Icon Pointcut = IconLoader.getIcon("/nodes/pointcut.png"); // 16x16
public static final Icon PpFile = IconLoader.getIcon("/nodes/ppFile.png"); // 16x16
public static final Icon PpInvalid = IconLoader.getIcon("/nodes/ppInvalid.png"); // 16x16
public static final Icon PpJar = IconLoader.getIcon("/nodes/ppJar.png"); // 16x16
public static final Icon PpJdk = IconLoader.getIcon("/nodes/ppJdk.png"); // 16x16
public static final Icon PpLib = IconLoader.getIcon("/nodes/ppLib.png"); // 16x16
public static final Icon PpLibFolder = IconLoader.getIcon("/nodes/ppLibFolder.png"); // 16x16
public static final Icon PpWeb = IconLoader.getIcon("/nodes/ppWeb.png"); // 16x16
public static final Icon PpWebLogo = IconLoader.getIcon("/nodes/ppWebLogo.png"); // 32x32
public static final Icon Project = IconLoader.getIcon("/nodes/project.png"); // 16x16
public static final Icon Property = IconLoader.getIcon("/nodes/property.png"); // 16x16
public static final Icon PropertyRead = IconLoader.getIcon("/nodes/propertyRead.png"); // 16x16
public static final Icon PropertyReadStatic = IconLoader.getIcon("/nodes/propertyReadStatic.png"); // 16x16
public static final Icon PropertyReadWrite = IconLoader.getIcon("/nodes/propertyReadWrite.png"); // 16x16
public static final Icon PropertyReadWriteStatic = IconLoader.getIcon("/nodes/propertyReadWriteStatic.png"); // 16x16
public static final Icon PropertyWrite = IconLoader.getIcon("/nodes/propertyWrite.png"); // 16x16
public static final Icon PropertyWriteStatic = IconLoader.getIcon("/nodes/propertyWriteStatic.png"); // 16x16
public static final Icon Read_access = IconLoader.getIcon("/nodes/read-access.png"); // 13x9
public static final Icon ResourceBundle = IconLoader.getIcon("/nodes/resourceBundle.png"); // 16x16
public static final Icon RunnableMark = IconLoader.getIcon("/nodes/runnableMark.png"); // 16x16
public static final Icon Rw_access = IconLoader.getIcon("/nodes/rw-access.png"); // 13x9
public static final Icon SecurityRole = IconLoader.getIcon("/nodes/SecurityRole.png"); // 16x16
public static final Icon Servlet = IconLoader.getIcon("/nodes/servlet.png"); // 16x16
public static final Icon Shared = IconLoader.getIcon("/nodes/shared.png"); // 16x16
public static final Icon SortBySeverity = IconLoader.getIcon("/nodes/sortBySeverity.png"); // 16x16
public static final Icon SourceFolder = IconLoader.getIcon("/nodes/sourceFolder.png"); // 16x16
public static final Icon Static = IconLoader.getIcon("/nodes/static.png"); // 16x16
public static final Icon StaticMark = IconLoader.getIcon("/nodes/staticMark.png"); // 16x16
public static final Icon Symlink = IconLoader.getIcon("/nodes/symlink.png"); // 16x16
public static final Icon TabAlert = IconLoader.getIcon("/nodes/tabAlert.png"); // 16x16
public static final Icon TabPin = IconLoader.getIcon("/nodes/tabPin.png"); // 16x16
public static final Icon Tag = IconLoader.getIcon("/nodes/tag.png"); // 16x16
public static final Icon TestSourceFolder = IconLoader.getIcon("/nodes/testSourceFolder.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon TreeClosed = IconLoader.getIcon("/nodes/TreeClosed.png"); // 16x16
public static final Icon TreeCollapseNode = IconLoader.getIcon("/nodes/treeCollapseNode.png"); // 16x16
public static final Icon TreeDownArrow = IconLoader.getIcon("/nodes/treeDownArrow.png"); // 11x11
public static final Icon TreeExpandNode = IconLoader.getIcon("/nodes/treeExpandNode.png"); // 16x16
@SuppressWarnings("unused")
@Deprecated
public static final Icon TreeOpen = IconLoader.getIcon("/nodes/TreeOpen.png"); // 16x16
public static final Icon TreeRightArrow = IconLoader.getIcon("/nodes/treeRightArrow.png"); // 11x11
public static final Icon Undeploy = IconLoader.getIcon("/nodes/undeploy.png"); // 16x16
public static final Icon UnknownJdk = IconLoader.getIcon("/nodes/unknownJdk.png"); // 16x16
public static final Icon UpFolder = IconLoader.getIcon("/nodes/upFolder.png"); // 16x16
public static final Icon UpLevel = IconLoader.getIcon("/nodes/upLevel.png"); // 16x16
public static final Icon Variable = IconLoader.getIcon("/nodes/variable.png"); // 16x16
public static final Icon WarningIntroduction = IconLoader.getIcon("/nodes/warningIntroduction.png"); // 16x16
public static final Icon WebFolder = IconLoader.getIcon("/nodes/webFolder.png"); // 16x16
public static final Icon Weblistener = IconLoader.getIcon("/nodes/weblistener.png"); // 16x16
public static final Icon Write_access = IconLoader.getIcon("/nodes/write-access.png"); // 13x9
}
public static class ObjectBrowser {
public static final Icon AbbreviatePackageNames = IconLoader.getIcon("/objectBrowser/abbreviatePackageNames.png"); // 16x16
public static final Icon CompactEmptyPackages = IconLoader.getIcon("/objectBrowser/compactEmptyPackages.png"); // 16x16
public static final Icon FlattenModules = IconLoader.getIcon("/objectBrowser/flattenModules.png"); // 16x16
public static final Icon FlattenPackages = IconLoader.getIcon("/objectBrowser/flattenPackages.png"); // 16x16
public static final Icon ShowEditorHighlighting = IconLoader.getIcon("/objectBrowser/showEditorHighlighting.png"); // 16x16
public static final Icon ShowLibraryContents = IconLoader.getIcon("/objectBrowser/showLibraryContents.png"); // 16x16
public static final Icon ShowMembers = IconLoader.getIcon("/objectBrowser/showMembers.png"); // 16x16
public static final Icon ShowModules = IconLoader.getIcon("/objectBrowser/showModules.png"); // 16x16
public static final Icon SortByType = IconLoader.getIcon("/objectBrowser/sortByType.png"); // 16x16
public static final Icon Sorted = IconLoader.getIcon("/objectBrowser/sorted.png"); // 16x16
public static final Icon SortedByUsage = IconLoader.getIcon("/objectBrowser/sortedByUsage.png"); // 16x16
public static final Icon VisibilitySort = IconLoader.getIcon("/objectBrowser/visibilitySort.png"); // 16x16
}
public static class Plugins {
public static final Icon Downloads = IconLoader.getIcon("/plugins/downloads.png"); // 12x12
public static final Icon PluginLogo_40 = IconLoader.getIcon("/plugins/pluginLogo_40.png"); // 40x40
public static final Icon PluginLogo_80 = IconLoader.getIcon("/plugins/pluginLogo_80.png"); // 80x80
public static final Icon PluginLogoDisabled_40 = IconLoader.getIcon("/plugins/pluginLogoDisabled_40.png"); // 40x40
public static final Icon PluginLogoDisabled_80 = IconLoader.getIcon("/plugins/pluginLogoDisabled_80.png"); // 80x80
public static final Icon Rating = IconLoader.getIcon("/plugins/rating.png"); // 12x12
public static final Icon Updated = IconLoader.getIcon("/plugins/updated.png"); // 12x12
}
public static class Preferences {
public static final Icon Appearance = IconLoader.getIcon("/preferences/Appearance.png"); // 32x32
public static final Icon CodeStyle = IconLoader.getIcon("/preferences/CodeStyle.png"); // 32x32
public static final Icon Compiler = IconLoader.getIcon("/preferences/Compiler.png"); // 32x32
public static final Icon Editor = IconLoader.getIcon("/preferences/Editor.png"); // 32x32
public static final Icon FileColors = IconLoader.getIcon("/preferences/FileColors.png"); // 32x32
public static final Icon FileTypes = IconLoader.getIcon("/preferences/FileTypes.png"); // 32x32
public static final Icon General = IconLoader.getIcon("/preferences/General.png"); // 32x32
public static final Icon Keymap = IconLoader.getIcon("/preferences/Keymap.png"); // 32x32
public static final Icon Plugins = IconLoader.getIcon("/preferences/Plugins.png"); // 32x32
public static final Icon Updates = IconLoader.getIcon("/preferences/Updates.png"); // 32x32
public static final Icon VersionControl = IconLoader.getIcon("/preferences/VersionControl.png"); // 32x32
}
public static class Process {
public static class Big {
public static final Icon Step_1 = IconLoader.getIcon("/process/big/step_1.png"); // 32x32
public static final Icon Step_10 = IconLoader.getIcon("/process/big/step_10.png"); // 32x32
public static final Icon Step_11 = IconLoader.getIcon("/process/big/step_11.png"); // 32x32
public static final Icon Step_12 = IconLoader.getIcon("/process/big/step_12.png"); // 32x32
public static final Icon Step_2 = IconLoader.getIcon("/process/big/step_2.png"); // 32x32
public static final Icon Step_3 = IconLoader.getIcon("/process/big/step_3.png"); // 32x32
public static final Icon Step_4 = IconLoader.getIcon("/process/big/step_4.png"); // 32x32
public static final Icon Step_5 = IconLoader.getIcon("/process/big/step_5.png"); // 32x32
public static final Icon Step_6 = IconLoader.getIcon("/process/big/step_6.png"); // 32x32
public static final Icon Step_7 = IconLoader.getIcon("/process/big/step_7.png"); // 32x32
public static final Icon Step_8 = IconLoader.getIcon("/process/big/step_8.png"); // 32x32
public static final Icon Step_9 = IconLoader.getIcon("/process/big/step_9.png"); // 32x32
public static final Icon Step_passive = IconLoader.getIcon("/process/big/step_passive.png"); // 32x32
}
public static final Icon DisabledDebug = IconLoader.getIcon("/process/disabledDebug.png"); // 13x13
public static final Icon DisabledRun = IconLoader.getIcon("/process/disabledRun.png"); // 13x13
public static class FS {
public static final Icon Step_1 = IconLoader.getIcon("/process/fs/step_1.png"); // 16x16
public static final Icon Step_10 = IconLoader.getIcon("/process/fs/step_10.png"); // 16x16
public static final Icon Step_11 = IconLoader.getIcon("/process/fs/step_11.png"); // 16x16
public static final Icon Step_12 = IconLoader.getIcon("/process/fs/step_12.png"); // 16x16
public static final Icon Step_13 = IconLoader.getIcon("/process/fs/step_13.png"); // 16x16
public static final Icon Step_14 = IconLoader.getIcon("/process/fs/step_14.png"); // 16x16
public static final Icon Step_15 = IconLoader.getIcon("/process/fs/step_15.png"); // 16x16
public static final Icon Step_16 = IconLoader.getIcon("/process/fs/step_16.png"); // 16x16
public static final Icon Step_17 = IconLoader.getIcon("/process/fs/step_17.png"); // 16x16
public static final Icon Step_18 = IconLoader.getIcon("/process/fs/step_18.png"); // 16x16
public static final Icon Step_2 = IconLoader.getIcon("/process/fs/step_2.png"); // 16x16
public static final Icon Step_3 = IconLoader.getIcon("/process/fs/step_3.png"); // 16x16
public static final Icon Step_4 = IconLoader.getIcon("/process/fs/step_4.png"); // 16x16
public static final Icon Step_5 = IconLoader.getIcon("/process/fs/step_5.png"); // 16x16
public static final Icon Step_6 = IconLoader.getIcon("/process/fs/step_6.png"); // 16x16
public static final Icon Step_7 = IconLoader.getIcon("/process/fs/step_7.png"); // 16x16
public static final Icon Step_8 = IconLoader.getIcon("/process/fs/step_8.png"); // 16x16
public static final Icon Step_9 = IconLoader.getIcon("/process/fs/step_9.png"); // 16x16
public static final Icon Step_mask = IconLoader.getIcon("/process/fs/step_mask.png"); // 16x16
public static final Icon Step_passive = IconLoader.getIcon("/process/fs/step_passive.png"); // 16x16
}
public static final Icon ProgressPause = IconLoader.getIcon("/process/progressPause.png"); // 14x14
public static final Icon ProgressPauseHover = IconLoader.getIcon("/process/progressPauseHover.png"); // 14x14
public static final Icon ProgressPauseSmall = IconLoader.getIcon("/process/progressPauseSmall.png"); // 12x12
public static final Icon ProgressPauseSmallHover = IconLoader.getIcon("/process/progressPauseSmallHover.png"); // 12x12
public static final Icon ProgressResume = IconLoader.getIcon("/process/progressResume.png"); // 14x14
public static final Icon ProgressResumeHover = IconLoader.getIcon("/process/progressResumeHover.png"); // 14x14
public static final Icon ProgressResumeSmall = IconLoader.getIcon("/process/progressResumeSmall.png"); // 12x12
public static final Icon ProgressResumeSmallHover = IconLoader.getIcon("/process/progressResumeSmallHover.png"); // 12x12
public static class State {
public static final Icon GreenOK = IconLoader.getIcon("/process/state/GreenOK.png"); // 16x16
public static final Icon GreyProgr = IconLoader.getIcon("/process/state/GreyProgr.png"); // 16x16
public static final Icon GreyProgr_1 = IconLoader.getIcon("/process/state/GreyProgr_1.png"); // 16x16
public static final Icon GreyProgr_2 = IconLoader.getIcon("/process/state/GreyProgr_2.png"); // 16x16
public static final Icon GreyProgr_3 = IconLoader.getIcon("/process/state/GreyProgr_3.png"); // 16x16
public static final Icon GreyProgr_4 = IconLoader.getIcon("/process/state/GreyProgr_4.png"); // 16x16
public static final Icon GreyProgr_5 = IconLoader.getIcon("/process/state/GreyProgr_5.png"); // 16x16
public static final Icon GreyProgr_6 = IconLoader.getIcon("/process/state/GreyProgr_6.png"); // 16x16
public static final Icon GreyProgr_7 = IconLoader.getIcon("/process/state/GreyProgr_7.png"); // 16x16
public static final Icon GreyProgr_8 = IconLoader.getIcon("/process/state/GreyProgr_8.png"); // 16x16
public static final Icon RedExcl = IconLoader.getIcon("/process/state/RedExcl.png"); // 16x16
public static final Icon YellowStr = IconLoader.getIcon("/process/state/YellowStr.png"); // 16x16
}
public static final Icon Step_1 = IconLoader.getIcon("/process/step_1.png"); // 16x16
public static final Icon Step_10 = IconLoader.getIcon("/process/step_10.png"); // 16x16
public static final Icon Step_11 = IconLoader.getIcon("/process/step_11.png"); // 16x16
public static final Icon Step_12 = IconLoader.getIcon("/process/step_12.png"); // 16x16
public static final Icon Step_2 = IconLoader.getIcon("/process/step_2.png"); // 16x16
public static final Icon Step_3 = IconLoader.getIcon("/process/step_3.png"); // 16x16
public static final Icon Step_4 = IconLoader.getIcon("/process/step_4.png"); // 16x16
public static final Icon Step_5 = IconLoader.getIcon("/process/step_5.png"); // 16x16
public static final Icon Step_6 = IconLoader.getIcon("/process/step_6.png"); // 16x16
public static final Icon Step_7 = IconLoader.getIcon("/process/step_7.png"); // 16x16
public static final Icon Step_8 = IconLoader.getIcon("/process/step_8.png"); // 16x16
public static final Icon Step_9 = IconLoader.getIcon("/process/step_9.png"); // 16x16
public static final Icon Step_mask = IconLoader.getIcon("/process/step_mask.png"); // 16x16
public static final Icon Step_passive = IconLoader.getIcon("/process/step_passive.png"); // 16x16
public static final Icon Stop = IconLoader.getIcon("/process/stop.png"); // 14x14
public static final Icon StopHovered = IconLoader.getIcon("/process/stopHovered.png"); // 14x14
public static final Icon StopSmall = IconLoader.getIcon("/process/stopSmall.png"); // 12x12
public static final Icon StopSmallHovered = IconLoader.getIcon("/process/stopSmallHovered.png"); // 12x12
}
public static class Providers {
public static final Icon Apache = IconLoader.getIcon("/providers/apache.png"); // 16x16
public static final Icon ApacheDerby = IconLoader.getIcon("/providers/apacheDerby.png"); // 16x16
public static final Icon Azure = IconLoader.getIcon("/providers/azure.png"); // 16x16
public static final Icon Bea = IconLoader.getIcon("/providers/bea.png"); // 16x16
public static final Icon Cvs = IconLoader.getIcon("/providers/cvs.png"); // 16x16
public static final Icon DB2 = IconLoader.getIcon("/providers/DB2.png"); // 16x16
public static final Icon Eclipse = IconLoader.getIcon("/providers/eclipse.png"); // 16x16
public static final Icon Exasol = IconLoader.getIcon("/providers/exasol.png"); // 16x16
public static final Icon H2 = IconLoader.getIcon("/providers/h2.png"); // 16x16
public static final Icon Hibernate = IconLoader.getIcon("/providers/hibernate.png"); // 16x16
public static final Icon Hsqldb = IconLoader.getIcon("/providers/hsqldb.png"); // 16x16
public static final Icon Ibm = IconLoader.getIcon("/providers/ibm.png"); // 16x16
public static final Icon Mariadb = IconLoader.getIcon("/providers/mariadb.png"); // 16x16
public static final Icon Microsoft = IconLoader.getIcon("/providers/microsoft.png"); // 16x16
public static final Icon Mysql = IconLoader.getIcon("/providers/mysql.png"); // 16x16
public static final Icon Oracle = IconLoader.getIcon("/providers/oracle.png"); // 16x16
public static final Icon Postgresql = IconLoader.getIcon("/providers/postgresql.png"); // 16x16
public static final Icon Redshift = IconLoader.getIcon("/providers/redshift.png"); // 16x16
public static final Icon Sqlite = IconLoader.getIcon("/providers/sqlite.png"); // 16x16
public static final Icon SqlServer = IconLoader.getIcon("/providers/sqlServer.png"); // 16x16
public static final Icon Sun = IconLoader.getIcon("/providers/sun.png"); // 16x16
public static final Icon Sybase = IconLoader.getIcon("/providers/sybase.png"); // 16x16
}
public static class RunConfigurations {
public static final Icon Applet = IconLoader.getIcon("/runConfigurations/applet.png"); // 16x16
public static final Icon Application = IconLoader.getIcon("/runConfigurations/application.png"); // 16x16
public static final Icon ConfigurationWarning = IconLoader.getIcon("/runConfigurations/configurationWarning.png"); // 16x16
public static final Icon HideIgnored = IconLoader.getIcon("/runConfigurations/hideIgnored.png"); // 16x16
public static final Icon HidePassed = IconLoader.getIcon("/runConfigurations/hidePassed.png"); // 16x16
public static final Icon IgnoredTest = IconLoader.getIcon("/runConfigurations/ignoredTest.png"); // 16x16
public static final Icon IncludeNonStartedTests_Rerun = IconLoader.getIcon("/runConfigurations/includeNonStartedTests_Rerun.png"); // 16x16
public static final Icon InvalidConfigurationLayer = IconLoader.getIcon("/runConfigurations/invalidConfigurationLayer.png"); // 16x16
public static final Icon Junit = IconLoader.getIcon("/runConfigurations/junit.png"); // 16x16
public static final Icon LoadingTree = IconLoader.getIcon("/runConfigurations/loadingTree.png"); // 16x16
public static final Icon Ql_console = IconLoader.getIcon("/runConfigurations/ql_console.png"); // 16x16
public static final Icon Remote = IconLoader.getIcon("/runConfigurations/remote.png"); // 16x16
public static final Icon RerunFailedTests = IconLoader.getIcon("/runConfigurations/rerunFailedTests.png"); // 16x16
public static final Icon SaveTempConfig = IconLoader.getIcon("/runConfigurations/saveTempConfig.png"); // 16x16
public static final Icon Scroll_down = IconLoader.getIcon("/runConfigurations/scroll_down.png"); // 16x16
public static final Icon ScrollToStackTrace = IconLoader.getIcon("/runConfigurations/scrollToStackTrace.png"); // 16x16
public static final Icon SelectFirstDefect = IconLoader.getIcon("/runConfigurations/selectFirstDefect.png"); // 16x16
public static final Icon SortbyDuration = IconLoader.getIcon("/runConfigurations/sortbyDuration.png"); // 16x16
public static final Icon SourceAtException = IconLoader.getIcon("/runConfigurations/sourceAtException.png"); // 16x16
public static final Icon TestCustom = IconLoader.getIcon("/runConfigurations/testCustom.png"); // 16x16
public static final Icon TestError = IconLoader.getIcon("/runConfigurations/testError.png"); // 16x16
public static final Icon TestFailed = IconLoader.getIcon("/runConfigurations/testFailed.png"); // 16x16
public static final Icon TestIgnored = IconLoader.getIcon("/runConfigurations/testIgnored.png"); // 16x16
public static final Icon TestInProgress1 = IconLoader.getIcon("/runConfigurations/testInProgress1.png"); // 16x16
public static final Icon TestInProgress2 = IconLoader.getIcon("/runConfigurations/testInProgress2.png"); // 16x16
public static final Icon TestInProgress3 = IconLoader.getIcon("/runConfigurations/testInProgress3.png"); // 16x16
public static final Icon TestInProgress4 = IconLoader.getIcon("/runConfigurations/testInProgress4.png"); // 16x16
public static final Icon TestInProgress5 = IconLoader.getIcon("/runConfigurations/testInProgress5.png"); // 16x16
public static final Icon TestInProgress6 = IconLoader.getIcon("/runConfigurations/testInProgress6.png"); // 16x16
public static final Icon TestInProgress7 = IconLoader.getIcon("/runConfigurations/testInProgress7.png"); // 16x16
public static final Icon TestInProgress8 = IconLoader.getIcon("/runConfigurations/testInProgress8.png"); // 16x16
public static final Icon TestMark = IconLoader.getIcon("/runConfigurations/testMark.png"); // 16x16
public static final Icon TestNotRan = IconLoader.getIcon("/runConfigurations/testNotRan.png"); // 16x16
public static final Icon TestPassed = IconLoader.getIcon("/runConfigurations/testPassed.png"); // 16x16
public static final Icon TestPaused = IconLoader.getIcon("/runConfigurations/testPaused.png"); // 16x16
public static final Icon TestSkipped = IconLoader.getIcon("/runConfigurations/testSkipped.png"); // 16x16
public static class TestState {
public static final Icon Green2 = IconLoader.getIcon("/runConfigurations/testState/green2.png"); // 12x12
public static final Icon Red2 = IconLoader.getIcon("/runConfigurations/testState/red2.png"); // 12x12
public static final Icon Run = IconLoader.getIcon("/runConfigurations/testState/run.png"); // 12x12
public static final Icon Run_run = IconLoader.getIcon("/runConfigurations/testState/run_run.png"); // 12x12
public static final Icon Yellow2 = IconLoader.getIcon("/runConfigurations/testState/yellow2.png"); // 12x12
}
public static final Icon TestTerminated = IconLoader.getIcon("/runConfigurations/testTerminated.png"); // 16x16
public static final Icon TestUnknown = IconLoader.getIcon("/runConfigurations/testUnknown.png"); // 16x16
public static final Icon Tomcat = IconLoader.getIcon("/runConfigurations/tomcat.png"); // 16x16
public static final Icon TrackCoverage = IconLoader.getIcon("/runConfigurations/trackCoverage.png"); // 16x16
public static final Icon TrackTests = IconLoader.getIcon("/runConfigurations/trackTests.png"); // 16x16
public static final Icon Unknown = IconLoader.getIcon("/runConfigurations/unknown.png"); // 16x16
public static final Icon Variables = IconLoader.getIcon("/runConfigurations/variables.png"); // 16x16
public static final Icon Web_app = IconLoader.getIcon("/runConfigurations/web_app.png"); // 16x16
public static final Icon WithCoverageLayer = IconLoader.getIcon("/runConfigurations/withCoverageLayer.png"); // 16x16
}
public static class Toolbar {
public static final Icon Filterdups = IconLoader.getIcon("/toolbar/filterdups.png"); // 16x16
public static final Icon Folders = IconLoader.getIcon("/toolbar/folders.png"); // 16x16
public static final Icon Unknown = IconLoader.getIcon("/toolbar/unknown.png"); // 16x16
}
public static class ToolbarDecorator {
public static final Icon Add = IconLoader.getIcon("/toolbarDecorator/add.png"); // 14x14
public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/addBlankLine.png"); // 16x16
public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/addClass.png"); // 16x16
public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/addFolder.png"); // 16x16
public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/addIcon.png"); // 16x16
public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/addJira.png"); // 16x16
public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/addLink.png"); // 16x16
public static final Icon AddPackage = IconLoader.getIcon("/toolbarDecorator/addPackage.png"); // 16x16
public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/addPattern.png"); // 16x16
public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/addRemoteDatasource.png"); // 16x16
public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/addYouTrack.png"); // 16x16
public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/analyze.png"); // 14x14
public static final Icon Edit = IconLoader.getIcon("/toolbarDecorator/edit.png"); // 14x14
public static final Icon Export = IconLoader.getIcon("/toolbarDecorator/export.png"); // 16x16
public static final Icon Import = IconLoader.getIcon("/toolbarDecorator/import.png"); // 16x16
public static class Mac {
public static final Icon Add = IconLoader.getIcon("/toolbarDecorator/mac/add.png"); // 14x14
public static final Icon AddBlankLine = IconLoader.getIcon("/toolbarDecorator/mac/addBlankLine.png"); // 16x16
public static final Icon AddClass = IconLoader.getIcon("/toolbarDecorator/mac/addClass.png"); // 16x16
public static final Icon AddFolder = IconLoader.getIcon("/toolbarDecorator/mac/addFolder.png"); // 16x16
public static final Icon AddIcon = IconLoader.getIcon("/toolbarDecorator/mac/addIcon.png"); // 16x16
public static final Icon AddJira = IconLoader.getIcon("/toolbarDecorator/mac/addJira.png"); // 16x16
public static final Icon AddLink = IconLoader.getIcon("/toolbarDecorator/mac/addLink.png"); // 16x16
public static final Icon AddPackage = IconLoader.getIcon("/toolbarDecorator/mac/addPackage.png"); // 16x16
public static final Icon AddPattern = IconLoader.getIcon("/toolbarDecorator/mac/addPattern.png"); // 16x16
public static final Icon AddRemoteDatasource = IconLoader.getIcon("/toolbarDecorator/mac/addRemoteDatasource.png"); // 16x16
public static final Icon AddYouTrack = IconLoader.getIcon("/toolbarDecorator/mac/addYouTrack.png"); // 16x16
public static final Icon Analyze = IconLoader.getIcon("/toolbarDecorator/mac/analyze.png"); // 14x14
public static final Icon Edit = IconLoader.getIcon("/toolbarDecorator/mac/edit.png"); // 14x14
public static final Icon MoveDown = IconLoader.getIcon("/toolbarDecorator/mac/moveDown.png"); // 14x14
public static final Icon MoveUp = IconLoader.getIcon("/toolbarDecorator/mac/moveUp.png"); // 14x14
public static final Icon Remove = IconLoader.getIcon("/toolbarDecorator/mac/remove.png"); // 14x14
}
public static final Icon MoveDown = IconLoader.getIcon("/toolbarDecorator/moveDown.png"); // 14x14
public static final Icon MoveUp = IconLoader.getIcon("/toolbarDecorator/moveUp.png"); // 14x14
public static final Icon Remove = IconLoader.getIcon("/toolbarDecorator/remove.png"); // 14x14
}
public static class Toolwindows {
public static final Icon Documentation = IconLoader.getIcon("/toolwindows/documentation.png"); // 13x13
public static final Icon Problems = IconLoader.getIcon("/toolwindows/problems.png"); // 13x13
public static final Icon ToolWindowAnt = IconLoader.getIcon("/toolwindows/toolWindowAnt.png"); // 13x13
public static final Icon ToolWindowBuild = IconLoader.getIcon("/toolwindows/toolWindowBuild.png"); // 13x13
public static final Icon ToolWindowChanges = IconLoader.getIcon("/toolwindows/toolWindowChanges.png"); // 13x13
public static final Icon ToolWindowCommander = IconLoader.getIcon("/toolwindows/toolWindowCommander.png"); // 13x13
public static final Icon ToolWindowCoverage = IconLoader.getIcon("/toolwindows/toolWindowCoverage.png"); // 13x13
public static final Icon ToolWindowCvs = IconLoader.getIcon("/toolwindows/toolWindowCvs.png"); // 13x13
public static final Icon ToolWindowDebugger = IconLoader.getIcon("/toolwindows/toolWindowDebugger.png"); // 13x13
public static final Icon ToolWindowFavorites = IconLoader.getIcon("/toolwindows/toolWindowFavorites.png"); // 13x13
public static final Icon ToolWindowFind = IconLoader.getIcon("/toolwindows/toolWindowFind.png"); // 13x13
public static final Icon ToolWindowHierarchy = IconLoader.getIcon("/toolwindows/toolWindowHierarchy.png"); // 13x13
public static final Icon ToolWindowInspection = IconLoader.getIcon("/toolwindows/toolWindowInspection.png"); // 13x13
public static final Icon ToolWindowMessages = IconLoader.getIcon("/toolwindows/toolWindowMessages.png"); // 13x13
public static final Icon ToolWindowModuleDependencies = IconLoader.getIcon("/toolwindows/toolWindowModuleDependencies.png"); // 13x13
public static final Icon ToolWindowPalette = IconLoader.getIcon("/toolwindows/toolWindowPalette.png"); // 13x13
public static final Icon ToolWindowPreview = IconLoader.getIcon("/toolwindows/toolWindowPreview.png"); // 13x13
public static final Icon ToolWindowProject = IconLoader.getIcon("/toolwindows/toolWindowProject.png"); // 13x13
public static final Icon ToolWindowRun = IconLoader.getIcon("/toolwindows/toolWindowRun.png"); // 13x13
public static final Icon ToolWindowStructure = IconLoader.getIcon("/toolwindows/toolWindowStructure.png"); // 13x13
public static final Icon ToolWindowTodo = IconLoader.getIcon("/toolwindows/toolWindowTodo.png"); // 13x13
public static final Icon WebToolWindow = IconLoader.getIcon("/toolwindows/webToolWindow.png"); // 13x13
}
public static class Vcs {
public static final Icon Arrow_left = IconLoader.getIcon("/vcs/arrow_left.png"); // 16x16
public static final Icon Arrow_right = IconLoader.getIcon("/vcs/arrow_right.png"); // 16x16
public static final Icon CheckSpelling = IconLoader.getIcon("/vcs/checkSpelling.png"); // 16x16
public static final Icon Equal = IconLoader.getIcon("/vcs/equal.png"); // 16x16
public static final Icon Favorite = IconLoader.getIcon("/vcs/favorite.png"); // 16x16
public static final Icon FavoriteOnHover = IconLoader.getIcon("/vcs/favoriteOnHover.png"); // 16x16
public static final Icon History = IconLoader.getIcon("/vcs/history.png"); // 16x16
public static final Icon MapBase = IconLoader.getIcon("/vcs/mapBase.png"); // 16x16
public static final Icon Merge = IconLoader.getIcon("/vcs/merge.png"); // 12x12
public static final Icon MergeSourcesTree = IconLoader.getIcon("/vcs/mergeSourcesTree.png"); // 16x16
public static final Icon Not_equal = IconLoader.getIcon("/vcs/not_equal.png"); // 16x16
public static final Icon NotFavoriteOnHover = IconLoader.getIcon("/vcs/notFavoriteOnHover.png"); // 16x16
public static final Icon Patch = IconLoader.getIcon("/vcs/patch.png"); // 16x16
public static final Icon Patch_applied = IconLoader.getIcon("/vcs/patch_applied.png"); // 16x16
public static final Icon Push = IconLoader.getIcon("/vcs/push.png"); // 16x16
public static final Icon Remove = IconLoader.getIcon("/vcs/remove.png"); // 16x16
public static final Icon ResetStrip = IconLoader.getIcon("/vcs/resetStrip.png"); // 16x16
public static final Icon RestoreDefaultSize = IconLoader.getIcon("/vcs/restoreDefaultSize.png"); // 16x16
public static final Icon Shelve = IconLoader.getIcon("/vcs/Shelve.png"); // 16x16
public static final Icon ShelveSilent = IconLoader.getIcon("/vcs/shelveSilent.png"); // 16x16
public static final Icon ShowUnversionedFiles = IconLoader.getIcon("/vcs/ShowUnversionedFiles.png"); // 16x16
public static final Icon StripDown = IconLoader.getIcon("/vcs/stripDown.png"); // 16x16
public static final Icon StripNull = IconLoader.getIcon("/vcs/stripNull.png"); // 16x16
public static final Icon StripUp = IconLoader.getIcon("/vcs/stripUp.png"); // 16x16
public static final Icon Unshelve = IconLoader.getIcon("/vcs/Unshelve.png"); // 16x16
public static final Icon UnshelveSilent = IconLoader.getIcon("/vcs/unshelveSilent.png"); // 16x16
}
public static class Webreferences {
public static final Icon Server = IconLoader.getIcon("/webreferences/server.png"); // 16x16
}
public static class Welcome {
public static final Icon CreateDesktopEntry = IconLoader.getIcon("/welcome/createDesktopEntry.png"); // 32x32
public static final Icon CreateNewProject = IconLoader.getIcon("/welcome/createNewProject.png"); // 16x16
public static final Icon CreateNewProjectfromExistingFiles = IconLoader.getIcon("/welcome/CreateNewProjectfromExistingFiles.png"); // 16x16
public static final Icon FromVCS = IconLoader.getIcon("/welcome/fromVCS.png"); // 16x16
public static final Icon ImportProject = IconLoader.getIcon("/welcome/importProject.png"); // 16x16
public static final Icon OpenProject = IconLoader.getIcon("/welcome/openProject.png"); // 16x16
public static class Project {
public static final Icon Remove_hover = IconLoader.getIcon("/welcome/project/remove-hover.png"); // 10x10
public static final Icon Remove = IconLoader.getIcon("/welcome/project/remove.png"); // 10x10
}
public static final Icon Register = IconLoader.getIcon("/welcome/register.png"); // 32x32
}
public static class Windows {
public static final Icon CloseActive = IconLoader.getIcon("/windows/closeActive.png"); // 16x16
public static final Icon CloseHover = IconLoader.getIcon("/windows/closeHover.png"); // 16x16
public static final Icon CloseInactive = IconLoader.getIcon("/windows/closeInactive.png"); // 16x16
public static final Icon HelpButton = IconLoader.getIcon("/windows/helpButton.png"); // 16x16
public static final Icon Maximize = IconLoader.getIcon("/windows/maximize.png"); // 16x16
public static final Icon MaximizeInactive = IconLoader.getIcon("/windows/maximizeInactive.png"); // 16x16
public static final Icon Minimize = IconLoader.getIcon("/windows/minimize.png"); // 16x16
public static final Icon MinimizeInactive = IconLoader.getIcon("/windows/minimizeInactive.png"); // 16x16
public static final Icon Restore = IconLoader.getIcon("/windows/restore.png"); // 16x16
public static final Icon RestoreInactive = IconLoader.getIcon("/windows/restoreInactive.png"); // 16x16
public static class Shadow {
public static final Icon Bottom = IconLoader.getIcon("/windows/shadow/bottom.png"); // 1x13
public static final Icon BottomLeft = IconLoader.getIcon("/windows/shadow/bottomLeft.png"); // 24x24
public static final Icon BottomRight = IconLoader.getIcon("/windows/shadow/bottomRight.png"); // 24x24
public static final Icon Left = IconLoader.getIcon("/windows/shadow/left.png"); // 13x1
public static final Icon Right = IconLoader.getIcon("/windows/shadow/right.png"); // 13x1
public static final Icon Top = IconLoader.getIcon("/windows/shadow/top.png"); // 1x13
public static final Icon TopLeft = IconLoader.getIcon("/windows/shadow/topLeft.png"); // 24x24
public static final Icon TopRight = IconLoader.getIcon("/windows/shadow/topRight.png"); // 24x24
}
public static final Icon WinHelp = IconLoader.getIcon("/windows/winHelp.png"); // 16x16
}
public static class Xml {
public static class Browsers {
public static final Icon Canary16 = IconLoader.getIcon("/xml/browsers/canary16.png"); // 16x16
public static final Icon Chrome16 = IconLoader.getIcon("/xml/browsers/chrome16.png"); // 16x16
public static final Icon Chromium16 = IconLoader.getIcon("/xml/browsers/chromium16.png"); // 16x16
public static final Icon Edge16 = IconLoader.getIcon("/xml/browsers/edge16.png"); // 16x16
public static final Icon Explorer16 = IconLoader.getIcon("/xml/browsers/explorer16.png"); // 16x16
public static final Icon Firefox16 = IconLoader.getIcon("/xml/browsers/firefox16.png"); // 16x16
public static final Icon Nwjs16 = IconLoader.getIcon("/xml/browsers/nwjs16.png"); // 16x16
public static final Icon Opera16 = IconLoader.getIcon("/xml/browsers/opera16.png"); // 16x16
public static final Icon Safari16 = IconLoader.getIcon("/xml/browsers/safari16.png"); // 16x16
public static final Icon Yandex16 = IconLoader.getIcon("/xml/browsers/yandex16.png"); // 16x16
}
public static final Icon Css_class = IconLoader.getIcon("/xml/css_class.png"); // 16x16
public static final Icon Html5 = IconLoader.getIcon("/xml/html5.png"); // 16x16
public static final Icon Html_id = IconLoader.getIcon("/xml/html_id.png"); // 16x16
}
} |
package cz.ivoa.vocloud.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import javax.enterprise.inject.Vetoed;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
/**
*
* @author radio.koza
*/
@Vetoed
@Entity
@NamedQueries({
@NamedQuery(name = "Worker.findAllByIdOrdered", query = "SELECT w FROM Worker w ORDER BY w.id"),
@NamedQuery(name = "Worker.findWorkersWithUwsType", query = "SELECT DISTINCT u.worker FROM UWS u WHERE :uwsType = u.uwsType AND u.enabled = TRUE"),
@NamedQuery(name = "Worker.countWorkerJobsInPhase", query = "SELECT COUNT(j) FROM Job j WHERE j.uws.worker = :worker AND j.phase = :phase")
})
public class Worker implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(nullable = false, length = 255)
private String resourceUrl;
@Column(nullable = false, length = 100)
private String shortDescription;
@Column(nullable = true, length = 1000)
private String description;
@Column(nullable = false)
private Integer maxJobs;
//relation definition
@OneToMany(mappedBy = "worker")
private List<UWS> uwsList = new ArrayList<>();
public Worker() {
//nothing to do here
}
public Worker(String resourceUrl, String shortDescription, String description, Integer maxJobs) {
this.resourceUrl = resourceUrl;
this.shortDescription = shortDescription;
this.description = description;
this.maxJobs = maxJobs;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getResourceUrl() {
return resourceUrl;
}
public void setResourceUrl(String resourceUrl) {
this.resourceUrl = cleanUrl(resourceUrl);
}
public String getShortDescription() {
return shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getMaxJobs() {
return maxJobs;
}
public void setMaxJobs(Integer maxJobs) {
this.maxJobs = maxJobs;
}
public List<UWS> getUwsList() {
return uwsList;
}
public void setUwsList(List<UWS> uwsList) {
this.uwsList = uwsList;
}
/**
* Get out trailing whitespaces and slashes at the end of url
*
* @param urlAddress Url address to be cleaned
* @return Cleaned url address
*/
private static String cleanUrl(String urlAddress) {
urlAddress = urlAddress.trim();
while (urlAddress.charAt(urlAddress.length() - 1) == '/') {
//there can be possibly more
urlAddress = urlAddress.substring(0, urlAddress.length() - 1);
}
return urlAddress;
}
@Override
public int hashCode() {
int hash = 3;
hash = 37 * hash + Objects.hashCode(this.id);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Worker other = (Worker) obj;
return Objects.equals(this.id, other.id);
}
@Override
public String toString() {
return "Worker{" + "id=" + id + ", resourceUrl=" + resourceUrl + ", shortDescription=" + shortDescription + ", description=" + description + ", maxJobs=" + maxJobs + ", uwsList=" + uwsList + '}';
}
} |
package com.mikepenz.materialdrawer;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import com.mikepenz.iconics.typeface.IIcon;
import com.mikepenz.iconics.utils.Utils;
import com.mikepenz.materialdrawer.accountswitcher.AccountHeader;
import com.mikepenz.materialdrawer.adapter.BaseDrawerAdapter;
import com.mikepenz.materialdrawer.adapter.DrawerAdapter;
import com.mikepenz.materialdrawer.model.interfaces.Badgeable;
import com.mikepenz.materialdrawer.model.interfaces.Checkable;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.Iconable;
import com.mikepenz.materialdrawer.model.interfaces.Nameable;
import java.util.ArrayList;
import java.util.Collections;
public class Drawer {
private static final String BUNDLE_SELECTION = "bundle_selection";
// some internal vars
// variable to check if a builder is only used once
protected boolean mUsed = false;
protected int mCurrentSelection = -1;
// the activity to use
protected Activity mActivity;
protected ViewGroup mRootView;
/**
* Pass the activity you use the drawer in ;)
*
* @param activity
* @return
*/
public Drawer withActivity(Activity activity) {
this.mRootView = (ViewGroup) activity.findViewById(android.R.id.content);
this.mActivity = activity;
return this;
}
// set actionbar Compatibility mode
protected boolean mTranslucentActionBarCompatibility = false;
/**
* Just use this parameter if you really want to use a translucent statusbar with an
* actionbar
*
* @param translucentActionBarCompatibility
* @return
*/
public Drawer withTranslucentActionBarCompatibility(boolean translucentActionBarCompatibility) {
this.mTranslucentActionBarCompatibility = translucentActionBarCompatibility;
return this;
}
// set non translucent statusbar mode
protected boolean mTranslucentStatusBar = true;
/**
* Set or disable this if you use a translucent statusbar
*
* @param translucentStatusBar
* @return
*/
public Drawer withTranslucentStatusBar(boolean translucentStatusBar) {
this.mTranslucentStatusBar = translucentStatusBar;
return this;
}
/**
* Set or disable this if you want to show the drawer below the toolbar.
* Note this will add a margin above the drawer
*
* @param displayBelowToolbar
* @return
*/
public Drawer withDisplayBelowToolbar(boolean displayBelowToolbar) {
this.mTranslucentStatusBar = displayBelowToolbar;
return this;
}
// the toolbar of the activity
protected Toolbar mToolbar;
/**
* Pass the toolbar you would love to use with this drawer
*
* @param toolbar
* @return
*/
public Drawer withToolbar(Toolbar toolbar) {
this.mToolbar = toolbar;
return this;
}
// the drawerLayout to use
protected DrawerLayout mDrawerLayout;
protected LinearLayout mSliderLayout;
/**
* You can pass a custom view for the drawer lib. note this requires the same structure as the drawer.xml
*
* @param drawerLayout
* @return
*/
public Drawer withDrawerLayout(DrawerLayout drawerLayout) {
this.mDrawerLayout = drawerLayout;
return this;
}
/**
* You can pass a custom layout for the drawer lib. see the drawer.xml in layouts of this lib on GitHub
*
* @param resLayout
* @return
*/
public Drawer withDrawerLayout(int resLayout) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (resLayout != -1) {
this.mDrawerLayout = (DrawerLayout) mActivity.getLayoutInflater().inflate(resLayout, mRootView, false);
} else {
this.mDrawerLayout = (DrawerLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer, mRootView, false);
}
return this;
}
//the background color for the slider
protected int mSliderBackgroundColor = -1;
protected int mSliderBackgroundColorRes = -1;
/**
* set the background for the slider as color
*
* @param sliderBackgroundColor
* @return
*/
public Drawer withSliderBackgroundColor(int sliderBackgroundColor) {
this.mSliderBackgroundColor = sliderBackgroundColor;
return this;
}
/**
* set the background for the slider as resource
*
* @param sliderBackgroundColorRes
* @return
*/
public Drawer withSliderBackgroundColorRes(int sliderBackgroundColorRes) {
this.mSliderBackgroundColorRes = sliderBackgroundColorRes;
return this;
}
//the width of the drawer
protected int mDrawerWidth = -1;
/**
* set the drawer width as px
*
* @param drawerWidthPx
* @return
*/
public Drawer withDrawerWidthPx(int drawerWidthPx) {
this.mDrawerWidth = drawerWidthPx;
return this;
}
/**
* set the drawer width as dp
*
* @param drawerWidthDp
* @return
*/
public Drawer withDrawerWidthDp(int drawerWidthDp) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
this.mDrawerWidth = Utils.convertDpToPx(mActivity, drawerWidthDp);
return this;
}
/**
* set the drawer width from resource
*
* @param drawerWidthRes
* @return
*/
public Drawer withDrawerWidthRes(int drawerWidthRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
this.mDrawerWidth = mActivity.getResources().getDimensionPixelSize(drawerWidthRes);
return this;
}
//the gravity of the drawer
protected Integer mDrawerGravity = null;
public Drawer withDrawerGravity(int gravity) {
this.mDrawerGravity = gravity;
return this;
}
//the account selection header to use
protected AccountHeader.Result mAccountHeader;
/**
* set the accountHeader to use for this drawer instance
* not this will overwrite the mHeaderView if set
*
* @param accountHeader
* @return
*/
public Drawer withAccountHeader(AccountHeader.Result accountHeader) {
this.mAccountHeader = accountHeader;
//set the header offset
mHeaderOffset = 1;
return this;
}
// enable/disable the actionBarDrawerToggle animation
protected boolean mAnimateActionBarDrawerToggle = false;
/**
* set this to enable/disable the actionBarDrawerToggle animation
*
* @param actionBarDrawerToggleAnimated
* @return
*/
public Drawer withActionBarDrawerToggleAnimated(boolean actionBarDrawerToggleAnimated) {
this.mAnimateActionBarDrawerToggle = actionBarDrawerToggleAnimated;
return this;
}
// enable the drawer toggle / if withActionBarDrawerToggle we will autoGenerate it
protected boolean mActionBarDrawerToggleEnabled = true;
/**
* set to true if you want a ActionBarDrawerToggle handled by the lib
*
* @param actionBarDrawerToggleEnabled
* @return
*/
public Drawer withActionBarDrawerToggle(boolean actionBarDrawerToggleEnabled) {
this.mActionBarDrawerToggleEnabled = actionBarDrawerToggleEnabled;
return this;
}
// drawer toggle
protected ActionBarDrawerToggle mActionBarDrawerToggle;
/**
* pass an ActionBarDrawerToggle you would love to use with this drawer
*
* @param actionBarDrawerToggle
* @return
*/
public Drawer withActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) {
this.mActionBarDrawerToggleEnabled = true;
this.mActionBarDrawerToggle = actionBarDrawerToggle;
return this;
}
// header view
protected View mHeaderView;
protected int mHeaderOffset = 0;
protected boolean mHeaderDivider = true;
protected boolean mHeaderClickable = false;
/**
* add a header layout from view
*
* @param headerView
* @return
*/
public Drawer withHeader(View headerView) {
this.mHeaderView = headerView;
//set the header offset
mHeaderOffset = 1;
return this;
}
/**
* add a header layout from res
*
* @param headerViewRes
* @return
*/
public Drawer withHeader(int headerViewRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (headerViewRes != -1) {
//i know there should be a root, bit i got none here
this.mHeaderView = mActivity.getLayoutInflater().inflate(headerViewRes, null, false);
//set the headerOffset :D
mHeaderOffset = 1;
}
return this;
}
/**
* set if the header is clickable
*
* @param headerClickable
* @return
*/
public Drawer withHeaderClickable(boolean headerClickable) {
this.mHeaderClickable = headerClickable;
return this;
}
/**
* this method allows you to disable the divider on the bottom of the header
*
* @param headerDivider
* @return
*/
public Drawer withHeaderDivider(boolean headerDivider) {
this.mHeaderDivider = headerDivider;
return this;
}
// footer view
protected View mFooterView;
protected boolean mFooterDivider = true;
protected boolean mFooterClickable = false;
/**
* add a footer layout from view
*
* @param footerView
* @return
*/
public Drawer withFooter(View footerView) {
this.mFooterView = footerView;
return this;
}
/**
* add a footer layout from res
*
* @param footerViewRes
* @return
*/
public Drawer withFooter(int footerViewRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (footerViewRes != -1) {
//i know there should be a root, bit i got none here
this.mFooterView = mActivity.getLayoutInflater().inflate(footerViewRes, null, false);
}
return this;
}
/**
* set if the footer is clickable
*
* @param footerClickable
* @return
*/
public Drawer withFooterClickable(boolean footerClickable) {
this.mFooterClickable = footerClickable;
return this;
}
/**
* this method allows you to disable the divider on top of the footer
*
* @param footerDivider
* @return
*/
public Drawer withFooterDivider(boolean footerDivider) {
this.mFooterDivider = footerDivider;
return this;
}
// sticky view
protected View mStickyFooterView;
/**
* add a sticky footer layout from view
* this view will be always visible on the bottom
*
* @param stickyFooter
* @return
*/
public Drawer withStickyFooter(View stickyFooter) {
this.mStickyFooterView = stickyFooter;
return this;
}
/**
* add a sticky footer layout from res
* this view will be always visible on the bottom
*
* @param stickyFooterRes
* @return
*/
public Drawer withStickyFooter(int stickyFooterRes) {
if (mActivity == null) {
throw new RuntimeException("please pass an activity first to use this call");
}
if (stickyFooterRes != -1) {
//i know there should be a root, bit i got none here
this.mStickyFooterView = mActivity.getLayoutInflater().inflate(stickyFooterRes, null, false);
}
return this;
}
// fire onClick after build
protected boolean mFireInitialOnClick = false;
/**
* enable this if you would love to receive a onClick event after the build method is called
* to be able to show the initial layout.
*
* @param fireOnInitialOnClick
* @return
*/
public Drawer withFireOnInitialOnClick(boolean fireOnInitialOnClick) {
this.mFireInitialOnClick = fireOnInitialOnClick;
return this;
}
// item to select
protected int mSelectedItem = 0;
/**
* pass the item which should be selected on start
*
* @param selectedItem
* @return
*/
public Drawer withSelectedItem(int selectedItem) {
this.mSelectedItem = selectedItem;
return this;
}
// an ListView to use within the drawer :D
protected ListView mListView;
/**
* Set the list which is added within the slider
*
* @param listView
* @return
*/
public Drawer withListView(ListView listView) {
this.mListView = listView;
return this;
}
// an adapter to use for the list
protected BaseDrawerAdapter mAdapter;
/**
* Set the adapter to be used with the list
*
* @param adapter
* @return
*/
public Drawer withAdapter(BaseDrawerAdapter adapter) {
this.mAdapter = adapter;
return this;
}
// list in drawer
protected ArrayList<IDrawerItem> mDrawerItems;
/**
* set the arrayList of DrawerItems for the drawer
*
* @param drawerItems
* @return
*/
public Drawer withDrawerItems(ArrayList<IDrawerItem> drawerItems) {
this.mDrawerItems = drawerItems;
return this;
}
/**
* add single ore more DrawerItems to the Drawer
*
* @param drawerItems
* @return
*/
public Drawer addDrawerItems(IDrawerItem... drawerItems) {
if (this.mDrawerItems == null) {
this.mDrawerItems = new ArrayList<>();
}
if (drawerItems != null) {
Collections.addAll(this.mDrawerItems, drawerItems);
}
return this;
}
// close drawer on click
protected boolean mCloseOnClick = true;
/**
* set if the drawer should autoClose if an item is clicked
*
* @param closeOnClick
* @return this
*/
public Drawer withCloseOnClick(boolean closeOnClick) {
this.mCloseOnClick = closeOnClick;
return this;
}
// delay drawer close to prevent lag
protected int mDelayOnDrawerClose = 150;
/**
* set the delay for the drawer close operation
* this is a small hack to improve the responsivness if you open a new activity within the drawer onClick
* else you will see some lag
* you can disable this by passing -1
*
* @param delayOnDrawerClose -1 to disable
* @return this
*/
public Drawer withDelayOnDrawerClose(int delayOnDrawerClose) {
this.mDelayOnDrawerClose = delayOnDrawerClose;
return this;
}
// onDrawerListener
protected OnDrawerListener mOnDrawerListener;
/**
* set the drawerListener
*
* @param onDrawerListener
* @return this
*/
public Drawer withOnDrawerListener(OnDrawerListener onDrawerListener) {
this.mOnDrawerListener = onDrawerListener;
return this;
}
// onDrawerItemClickListeners
protected OnDrawerItemClickListener mOnDrawerItemClickListener;
/**
* set the DrawerItemClickListener
*
* @param onDrawerItemClickListener
* @return
*/
public Drawer withOnDrawerItemClickListener(OnDrawerItemClickListener onDrawerItemClickListener) {
this.mOnDrawerItemClickListener = onDrawerItemClickListener;
return this;
}
// onDrawerItemClickListeners
protected OnDrawerItemLongClickListener mOnDrawerItemLongClickListener;
/**
* set the DrawerItemLongClickListener
*
* @param onDrawerItemLongClickListener
* @return
*/
public Drawer withOnDrawerItemLongClickListener(OnDrawerItemLongClickListener onDrawerItemLongClickListener) {
this.mOnDrawerItemLongClickListener = onDrawerItemLongClickListener;
return this;
}
// onDrawerItemClickListeners
protected OnDrawerItemSelectedListener mOnDrawerItemSelectedListener;
/**
* set the ItemSelectedListener
*
* @param onDrawerItemSelectedListener
* @return
*/
public Drawer withOnDrawerItemSelectedListener(OnDrawerItemSelectedListener onDrawerItemSelectedListener) {
this.mOnDrawerItemSelectedListener = onDrawerItemSelectedListener;
return this;
}
// savedInstance to restore state
protected Bundle mSavedInstance;
/**
* create the drawer with the values of a savedInstance
*
* @param savedInstance
* @return
*/
public Drawer withSavedInstance(Bundle savedInstance) {
this.mSavedInstance = savedInstance;
return this;
}
/**
* Build everything and get a Result
*
* @return
*/
public Result build() {
if (mUsed) {
throw new RuntimeException("you must not reuse a Drawer builder");
}
if (mActivity == null) {
throw new RuntimeException("please pass an activity");
}
//set that this builder was used. now you have to create a new one
mUsed = true;
// if the user has not set a drawerLayout use the default one :D
if (mDrawerLayout == null) {
withDrawerLayout(-1);
}
//get the drawer root
ViewGroup drawerContentRoot = (ViewGroup) mDrawerLayout.getChildAt(0);
//get the content view
View contentView = mRootView.getChildAt(0);
// remove the contentView
mRootView.removeView(contentView);
//add the contentView to the drawer content frameLayout
drawerContentRoot.addView(contentView, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
//add the drawerLayout to the root
mRootView.addView(mDrawerLayout, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
// create the ActionBarDrawerToggle if not set and enabled and if we have a toolbar
if (mActionBarDrawerToggleEnabled && mActionBarDrawerToggle == null && mToolbar != null) {
this.mActionBarDrawerToggle = new ActionBarDrawerToggle(mActivity, mDrawerLayout, mToolbar, R.string.drawer_open, R.string.drawer_close) {
@Override
public void onDrawerOpened(View drawerView) {
if (mOnDrawerListener != null) {
mOnDrawerListener.onDrawerOpened(drawerView);
}
super.onDrawerOpened(drawerView);
}
@Override
public void onDrawerClosed(View drawerView) {
if (mOnDrawerListener != null) {
mOnDrawerListener.onDrawerClosed(drawerView);
}
super.onDrawerClosed(drawerView);
}
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
if (!mAnimateActionBarDrawerToggle) {
super.onDrawerSlide(drawerView, 0);
} else {
super.onDrawerSlide(drawerView, slideOffset);
}
}
};
this.mActionBarDrawerToggle.syncState();
}
//handle the ActionBarDrawerToggle
if (mActionBarDrawerToggle != null) {
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
}
// get the slider view
mSliderLayout = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_slider, mDrawerLayout, false);
// get the layout params
DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mSliderLayout.getLayoutParams();
// if we've set a custom gravity set it
if (mDrawerGravity != null) {
params.gravity = mDrawerGravity;
}
// if this is a drawer from the right, change the margins :D
params = processDrawerLayoutParams(params);
// set the new layout params
mSliderLayout.setLayoutParams(params);
// set the background
if (mSliderBackgroundColor != -1) {
mSliderLayout.setBackgroundColor(mSliderBackgroundColor);
} else if (mSliderBackgroundColorRes != -1) {
mSliderLayout.setBackgroundColor(mActivity.getResources().getColor(mSliderBackgroundColorRes));
}
// add the slider to the drawer
mDrawerLayout.addView(mSliderLayout, 1);
//create the content
createContent();
//forget the reference to the activity
mActivity = null;
//create the result object
Result result = new Result(this);
//set the drawer for the accountHeader if set
if (mAccountHeader != null) {
mAccountHeader.setDrawer(result);
}
return result;
}
/**
* the builder method to append a new drawer to an existing Drawer
*
* @param result the Drawer.Result of an existing Drawer
* @return
*/
public Result append(Result result) {
if (mUsed) {
throw new RuntimeException("you must not reuse a Drawer builder");
}
if (mDrawerGravity == null) {
throw new RuntimeException("please set the gravity for the drawer");
}
//set that this builder was used. now you have to create a new one
mUsed = true;
//get the drawer layout from the previous drawer
mDrawerLayout = result.getDrawerLayout();
// get the slider view
mSliderLayout = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_slider, mDrawerLayout, false);
// get the layout params
DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) mSliderLayout.getLayoutParams();
// set the gravity of this drawerGravity
params.gravity = mDrawerGravity;
// if this is a drawer from the right, change the margins :D
params = processDrawerLayoutParams(params);
// set the new params
mSliderLayout.setLayoutParams(params);
// add the slider to the drawer
mDrawerLayout.addView(mSliderLayout, 1);
//create the content
createContent();
//forget the reference to the activity
mActivity = null;
return new Result(this);
}
/**
* the helper method to create the content for the drawer
*/
private void createContent() {
// if we have an adapter (either by defining a custom one or the included one add a list :D
if (mListView == null) {
mListView = new ListView(mActivity);
mListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
mListView.setDivider(null);
mListView.setDrawSelectorOnTop(true);
mListView.setClipToPadding(false);
if (mTranslucentStatusBar) {
mListView.setPadding(0, mActivity.getResources().getDimensionPixelSize(R.dimen.tool_bar_top_padding), 0, 0);
}
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
);
params.weight = 1f;
mSliderLayout.addView(mListView, params);
// initialize list if there is an adapter or set items
if (mDrawerItems != null && mAdapter == null) {
mAdapter = new DrawerAdapter(mActivity, mDrawerItems);
}
//sticky footer view
if (mStickyFooterView != null) {
mSliderLayout.addView(mStickyFooterView);
}
//use the AccountHeader if set
if (mAccountHeader != null) {
mHeaderView = mAccountHeader.getView();
}
// set the header (do this before the setAdapter because some devices will crash else
if (mHeaderView != null) {
if (mListView == null) {
throw new RuntimeException("can't use a headerView without a listView");
}
if (mHeaderDivider) {
LinearLayout headerContainer = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_item_header, mListView, false);
headerContainer.addView(mHeaderView, 0);
mListView.addHeaderView(headerContainer, null, mHeaderClickable);
mListView.setPadding(0, 0, 0, 0);
//link the view including the container to the headerView field
mHeaderView = headerContainer;
} else {
mListView.addHeaderView(mHeaderView, null, mHeaderClickable);
mListView.setPadding(0, 0, 0, 0);
}
}
// set the footer (do this before the setAdapter because some devices will crash else
if (mFooterView != null) {
if (mListView == null) {
throw new RuntimeException("can't use a footerView without a listView");
}
if (mFooterDivider) {
LinearLayout footerContainer = (LinearLayout) mActivity.getLayoutInflater().inflate(R.layout.material_drawer_item_footer, mListView, false);
footerContainer.addView(mFooterView, 1);
mListView.addFooterView(footerContainer, null, mFooterClickable);
//link the view including the container to the footerView field
mFooterView = footerContainer;
} else {
mListView.addFooterView(mFooterView, null, mFooterClickable);
}
}
//after adding the header do the setAdapter and set the selection
if (mAdapter != null) {
//set the adapter on the listView
mListView.setAdapter(mAdapter);
//predefine selection (should be the first element
if (mListView != null && (mSelectedItem + mHeaderOffset) > -1) {
mListView.setSelection(mSelectedItem + mHeaderOffset);
mListView.setItemChecked(mSelectedItem + mHeaderOffset, true);
mCurrentSelection = mSelectedItem;
}
}
// add the onDrawerItemClickListener if set
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
IDrawerItem i = getDrawerItem(position, true);
if (mCloseOnClick) {
if (mDelayOnDrawerClose > -1) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
mDrawerLayout.closeDrawers();
}
}, mDelayOnDrawerClose);
} else {
mDrawerLayout.closeDrawers();
}
}
if (i != null && i instanceof Checkable && !((Checkable) i).isCheckable()) {
mListView.setSelection(mCurrentSelection + mHeaderOffset);
mListView.setItemChecked(mCurrentSelection + mHeaderOffset, true);
} else {
mCurrentSelection = position - mHeaderOffset;
}
if (mOnDrawerItemClickListener != null) {
mOnDrawerItemClickListener.onItemClick(parent, view, position, id, i);
}
}
});
// add the onDrawerItemLongClickListener if set
if (mOnDrawerItemLongClickListener != null) {
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
return mOnDrawerItemLongClickListener.onItemLongClick(parent, view, position, id, getDrawerItem(position, true));
}
});
}
// add the onDrawerItemSelectedListener if set
if (mOnDrawerItemSelectedListener != null) {
mListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mOnDrawerItemSelectedListener.onItemSelected(parent, view, position, id, getDrawerItem(position, true));
mCurrentSelection = position - mHeaderOffset;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
mOnDrawerItemSelectedListener.onNothingSelected(parent);
}
});
}
if (mListView != null) {
mListView.smoothScrollToPosition(0);
}
// try to restore all saved values again
if (mSavedInstance != null) {
int selection = mSavedInstance.getInt(BUNDLE_SELECTION, -1);
if (selection != -1) {
//predefine selection (should be the first element
if (mListView != null && (selection) > -1) {
mListView.setSelection(selection);
mListView.setItemChecked(selection, true);
mCurrentSelection = selection - mHeaderOffset;
}
}
}
// call initial onClick event to allow the dev to init the first view
if (mFireInitialOnClick && mOnDrawerItemClickListener != null) {
mOnDrawerItemClickListener.onItemClick(null, null, mCurrentSelection, mCurrentSelection, getDrawerItem(mCurrentSelection, false));
}
}
/**
* get the drawerItem at a specific position
*
* @param position
* @return
*/
private IDrawerItem getDrawerItem(int position, boolean includeOffset) {
if (includeOffset) {
if (mDrawerItems != null && mDrawerItems.size() > (position - mHeaderOffset) && (position - mHeaderOffset) > -1) {
return mDrawerItems.get(position - mHeaderOffset);
}
} else {
if (mDrawerItems != null && mDrawerItems.size() > position && position > -1) {
return mDrawerItems.get(position);
}
}
return null;
}
/**
* check if the item is within the bounds of the list
*
* @param position
* @param includeOffset
* @return
*/
private boolean checkDrawerItem(int position, boolean includeOffset) {
if (includeOffset) {
if (mDrawerItems != null && mDrawerItems.size() > (position - mHeaderOffset) && (position - mHeaderOffset) > -1) {
return true;
}
} else {
if (mDrawerItems != null && mDrawerItems.size() > position && position > -1) {
return true;
}
}
return false;
}
/**
* helper to extend the layoutParams of the drawer
*
* @param params
* @return
*/
private DrawerLayout.LayoutParams processDrawerLayoutParams(DrawerLayout.LayoutParams params) {
if (mDrawerGravity != null && (mDrawerGravity == Gravity.RIGHT || mDrawerGravity == Gravity.END)) {
params.rightMargin = 0;
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(0);
}
params.leftMargin = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin);
if (Build.VERSION.SDK_INT >= 17) {
params.setMarginEnd(mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_margin));
}
}
if (mTranslucentActionBarCompatibility) {
TypedValue tv = new TypedValue();
if (mActivity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
params.topMargin = TypedValue.complexToDimensionPixelSize(tv.data, mActivity.getResources().getDisplayMetrics());
}
}
if (mDrawerWidth > -1) {
params.width = mDrawerWidth;
} else {
params.width = mActivity.getResources().getDimensionPixelSize(R.dimen.material_drawer_width);
}
return params;
}
public static class Result {
private final Drawer mDrawer;
private FrameLayout mContentView;
/**
* the protected Constructor for the result
*
* @param drawer
*/
protected Result(Drawer drawer) {
this.mDrawer = drawer;
}
/**
* get the drawerLayout of the current drawer
*
* @return
*/
public DrawerLayout getDrawerLayout() {
return this.mDrawer.mDrawerLayout;
}
/**
* open the drawer
*/
public void openDrawer() {
if (mDrawer.mDrawerLayout != null && mDrawer.mSliderLayout != null) {
mDrawer.mDrawerLayout.openDrawer(mDrawer.mSliderLayout);
}
}
/**
* close the drawer
*/
public void closeDrawer() {
if (mDrawer.mDrawerLayout != null) {
mDrawer.mDrawerLayout.closeDrawers();
}
}
/**
* get the current state if the drawer is open
*
* @return
*/
public boolean isDrawerOpen() {
if (mDrawer.mDrawerLayout != null && mDrawer.mSliderLayout != null) {
return mDrawer.mDrawerLayout.isDrawerOpen(mDrawer.mSliderLayout);
}
return false;
}
/**
* get the slider layout of the current drawer
*
* @return
*/
public LinearLayout getSlider() {
return mDrawer.mSliderLayout;
}
/**
* get the cootainer frameLayout of the current drawer
*
* @return
*/
public FrameLayout getContent() {
if (mContentView == null) {
mContentView = (FrameLayout) this.mDrawer.mDrawerLayout.findViewById(R.id.content_layout);
}
return mContentView;
}
/**
* get the listView of the current drawer
*
* @return
*/
public ListView getListView() {
return mDrawer.mListView;
}
/**
* get the BaseDrawerAdapter of the current drawer
*
* @return
*/
public BaseDrawerAdapter getAdapter() {
return mDrawer.mAdapter;
}
/**
* get all drawerItems of the current drawer
*
* @return
*/
public ArrayList<IDrawerItem> getDrawerItems() {
return mDrawer.mDrawerItems;
}
/**
* get the Header View if set else NULL
*
* @return
*/
public View getHeader() {
return mDrawer.mHeaderView;
}
/**
* method to replace a previous set header
*
* @param view
*/
public void setHeader(View view) {
if (getListView() != null) {
BaseDrawerAdapter adapter = getAdapter();
getListView().setAdapter(null);
if (getHeader() != null) {
getListView().removeHeaderView(getHeader());
}
getListView().addHeaderView(view);
getListView().setAdapter(adapter);
}
}
/**
* get the Footer View if set else NULL
*
* @return
*/
public View getFooter() {
return mDrawer.mFooterView;
}
/**
* get the StickyFooter View if set else NULL
*
* @return
*/
public View getStickyFooter() {
return mDrawer.mStickyFooterView;
}
/**
* get the ActionBarDrawerToggle
*
* @return
*/
public ActionBarDrawerToggle getActionBarDrawerToggle() {
return mDrawer.mActionBarDrawerToggle;
}
/**
* calculates the position of an drawerItem. searching by it's identifier
*
* @param drawerItem
* @return
*/
public int getPositionFromIdentifier(IDrawerItem drawerItem) {
return getPositionFromIdentifier(drawerItem.getIdentifier());
}
/**
* calculates the position of an drawerItem. searching by it's identifier
*
* @param identifier
* @return
*/
public int getPositionFromIdentifier(int identifier) {
if (identifier >= 0) {
if (mDrawer.mDrawerItems != null) {
int position = 0;
for (IDrawerItem i : mDrawer.mDrawerItems) {
if (i.getIdentifier() == identifier) {
return position;
}
position = position + 1;
}
}
} else {
throw new RuntimeException("the item requires a unique identifier to use this method");
}
return -1;
}
/**
* get the current selection
*
* @return
*/
public int getCurrentSelection() {
return mDrawer.mCurrentSelection;
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view!
*
* @param identifier
*/
public void setSelectionByIdentifier(int identifier) {
setSelection(getPositionFromIdentifier(identifier), true);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*
* @param identifier
* @param fireOnClick
*/
public void setSelectionByIdentifier(int identifier, boolean fireOnClick) {
setSelection(getPositionFromIdentifier(identifier), fireOnClick);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view!
*
* @param drawerItem
*/
public void setSelection(IDrawerItem drawerItem) {
setSelection(getPositionFromIdentifier(drawerItem), true);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*
* @param drawerItem
* @param fireOnClick
*/
public void setSelection(IDrawerItem drawerItem, boolean fireOnClick) {
setSelection(getPositionFromIdentifier(drawerItem), fireOnClick);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view!
*
* @param position the position to select
*/
public void setSelection(int position) {
setSelection(position, true);
}
/**
* set the current selection in the drawer
* NOTE: This will trigger onDrawerItemSelected without a view if you pass fireOnClick = true;
*
* @param position
* @param fireOnClick
*/
public void setSelection(int position, boolean fireOnClick) {
if (mDrawer.mListView != null) {
mDrawer.mListView.setSelection(position + mDrawer.mHeaderOffset);
mDrawer.mListView.setItemChecked(position + mDrawer.mHeaderOffset, true);
if (fireOnClick && mDrawer.mOnDrawerItemClickListener != null) {
mDrawer.mOnDrawerItemClickListener.onItemClick(null, null, position, position, mDrawer.getDrawerItem(position, false));
}
mDrawer.mCurrentSelection = position;
}
}
/**
* update a specific drawer item :D
* automatically identified by its id
*
* @param drawerItem
*/
public void updateItem(IDrawerItem drawerItem) {
updateItem(drawerItem, getPositionFromIdentifier(drawerItem));
}
/**
* Update a drawerItem at a specific position
*
* @param drawerItem
* @param position
*/
public void updateItem(IDrawerItem drawerItem, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Add a drawerItem at the end
*
* @param drawerItem
*/
public void addItem(IDrawerItem drawerItem) {
if (mDrawer.mDrawerItems != null) {
mDrawer.mDrawerItems.add(drawerItem);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Add a drawerItem at a specific position
*
* @param drawerItem
* @param position
*/
public void addItem(IDrawerItem drawerItem, int position) {
if (mDrawer.mDrawerItems != null) {
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Remove a drawerItem at a specific position
*
* @param position
*/
public void removeItem(int position) {
if (mDrawer.checkDrawerItem(position, false)) {
mDrawer.mDrawerItems.remove(position);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Removes all items from drawer
*/
public void removeAllItems() {
mDrawer.mDrawerItems.clear();
mDrawer.mAdapter.dataUpdated();
}
/**
* add new Items to the current DrawerItem List
*
* @param drawerItems
*/
public void addItems(IDrawerItem... drawerItems) {
if (mDrawer.mDrawerItems != null) {
Collections.addAll(mDrawer.mDrawerItems, drawerItems);
mDrawer.mAdapter.dataUpdated();
}
}
/**
* Replace the current DrawerItems with a new ArrayList of items
*
* @param drawerItems
*/
public void setItems(ArrayList<IDrawerItem> drawerItems) {
mDrawer.mDrawerItems = drawerItems;
mDrawer.mAdapter.setDrawerItems(mDrawer.mDrawerItems);
mDrawer.mAdapter.dataUpdated();
}
/**
* Update the name of a drawer item if its an instance of nameable
*
* @param nameRes
* @param position
*/
public void updateName(int nameRes, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Nameable) {
((Nameable) drawerItem).setNameRes(nameRes);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the name of a drawer item if its an instance of nameable
*
* @param name
* @param position
*/
public void updateName(String name, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Nameable) {
((Nameable) drawerItem).setName(name);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the badge of a drawer item if its an instance of badgeable
*
* @param badge
* @param position
*/
public void updateBadge(String badge, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Badgeable) {
((Badgeable) drawerItem).setBadge(badge);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the icon of a drawer item if its an instance of iconable
*
* @param icon
* @param position
*/
public void updateIcon(Drawable icon, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Iconable) {
((Iconable) drawerItem).setIcon(icon);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the icon of a drawer item from an iconRes
*
* @param iconRes
* @param position
*/
public void updateIcon(int iconRes, int position) {
if (mDrawer.mRootView != null && mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Iconable) {
((Iconable) drawerItem).setIcon(mDrawer.mRootView.getContext().getResources().getDrawable(iconRes));
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* Update the icon of a drawer item if its an instance of iconable
*
* @param icon
* @param position
*/
public void updateIcon(IIcon icon, int position) {
if (mDrawer.checkDrawerItem(position, false)) {
IDrawerItem drawerItem = mDrawer.mDrawerItems.get(position);
if (drawerItem instanceof Iconable) {
((Iconable) drawerItem).setIIcon(icon);
}
mDrawer.mDrawerItems.set(position, drawerItem);
mDrawer.mAdapter.notifyDataSetChanged();
}
}
/**
* setter for the OnDrawerItemClickListener
*
* @param onDrawerItemClickListener
*/
public void setOnDrawerItemClickListener(OnDrawerItemClickListener onDrawerItemClickListener) {
mDrawer.mOnDrawerItemClickListener = onDrawerItemClickListener;
}
/**
* method to get the OnDrawerItemClickListener
*
* @return
*/
public OnDrawerItemClickListener getOnDrawerItemClickListener() {
return mDrawer.mOnDrawerItemClickListener;
}
/**
* setter for the OnDrawerItemLongClickListener
*
* @param onDrawerItemLongClickListener
*/
public void setOnDrawerItemLongClickListener(OnDrawerItemLongClickListener onDrawerItemLongClickListener) {
mDrawer.mOnDrawerItemLongClickListener = onDrawerItemLongClickListener;
}
/**
* method to get the OnDrawerItemLongClickListener
*
* @return
*/
public OnDrawerItemLongClickListener getOnDrawerItemLongClickListener() {
return mDrawer.mOnDrawerItemLongClickListener;
}
/**
* add the values to the bundle for saveInstanceState
*
* @param savedInstanceState
* @return
*/
public Bundle saveInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
if (getListView() != null) {
savedInstanceState.putInt(BUNDLE_SELECTION, mDrawer.mCurrentSelection);
}
}
return savedInstanceState;
}
}
public interface OnDrawerItemClickListener {
public void onItemClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem);
}
public interface OnDrawerItemLongClickListener {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem);
}
public interface OnDrawerListener {
public void onDrawerOpened(View drawerView);
public void onDrawerClosed(View drawerView);
}
public interface OnDrawerItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id, IDrawerItem drawerItem);
public void onNothingSelected(AdapterView<?> parent);
}
} |
package org.mskcc.portal.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.mskcc.cgds.dao.DaoCancerStudy;
import org.mskcc.cgds.dao.DaoClinicalFreeForm;
import org.mskcc.cgds.dao.DaoException;
import org.mskcc.cgds.model.CancerStudy;
import org.mskcc.cgds.model.CaseList;
import org.mskcc.portal.remote.GetCaseSets;
/**
* Utility class for validation of the user-defined case sets.
*
* @author Selcuk Onur Sumer
*/
public class CaseSetValidator
{
/**
* Checks whether the provided case IDs are valid for a specific
* cancer study. This method returns a list of invalid cases if
* any, or returns an empty list if all the cases are valid.
*
* @param studyId stable cancer study id
* @param caseIds case IDs as a single string
* @return list of invalid cases
* @throws DaoException if a DB error occurs
*/
public static List<String> validateCaseSet(String studyId,
String caseIds) throws DaoException
{
ArrayList<String> invalidCases = new ArrayList<String>();
DaoClinicalFreeForm daoFreeForm = new DaoClinicalFreeForm();
// get list of all case sets for the given cancer study
ArrayList<CaseList> caseLists = GetCaseSets.getCaseSets(studyId);
// get cancer study for the given stable id
CancerStudy study = DaoCancerStudy.getCancerStudyByStableId(studyId);
// get all cases in the clinical free form table for the given cancer study
Set<String> freeFormCases = daoFreeForm.getAllCases(study.getInternalId());
if (!caseLists.isEmpty() &&
caseIds != null)
{
// validate each case ID
for(String caseId: caseIds.trim().split(" "))
{
boolean valid = false;
// search all lists for the current case
for (CaseList caseList: caseLists)
{
// if the case is found in any of the lists,
// then it is valid, no need to search further
if(caseList.getCaseList().contains(caseId))
{
valid = true;
break;
}
}
// search also clinical free form table for the current case
if (freeFormCases.contains(caseId))
{
valid = true;
}
// if the case cannot be found in any of the lists,
// then it is an invalid case for this cancer study
if (!valid)
{
invalidCases.add(caseId);
}
}
}
return invalidCases;
}
} |
package org.javarosa.core.model;
import org.javarosa.core.log.WrappedException;
import org.javarosa.core.model.condition.Condition;
import org.javarosa.core.model.condition.Constraint;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IConditionExpr;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.core.model.condition.Recalculate;
import org.javarosa.core.model.condition.Triggerable;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.IntegerData;
import org.javarosa.core.model.data.SelectMultiData;
import org.javarosa.core.model.data.SelectOneData;
import org.javarosa.core.model.data.helper.Selection;
import org.javarosa.core.model.instance.AbstractTreeElement;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.model.instance.FormInstance;
import org.javarosa.core.model.instance.InstanceInitializationFactory;
import org.javarosa.core.model.instance.InvalidReferenceException;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.trace.EvaluationTrace;
import org.javarosa.core.model.util.restorable.RestoreUtils;
import org.javarosa.core.model.utils.QuestionPreloader;
import org.javarosa.core.services.locale.Localizable;
import org.javarosa.core.services.locale.Localizer;
import org.javarosa.core.services.storage.IMetaData;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.core.util.CacheTable;
import org.javarosa.core.util.DataUtil;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapList;
import org.javarosa.core.util.externalizable.ExtWrapListPoly;
import org.javarosa.core.util.externalizable.ExtWrapMap;
import org.javarosa.core.util.externalizable.ExtWrapNullable;
import org.javarosa.core.util.externalizable.ExtWrapTagged;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.model.xform.XPathReference;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathTypeMismatchException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.NoSuchElementException;
import java.util.Vector;
/**
* Definition of a form. This has some meta data about the form definition and a
* collection of groups together with question branching or skipping rules.
*
* @author Daniel Kayiwa, Drew Roos
*/
public class FormDef implements IFormElement, Localizable, Persistable, IMetaData {
public static final String STORAGE_KEY = "FORMDEF";
public static final int TEMPLATING_RECURSION_LIMIT = 10;
/**
* Hierarchy of questions, groups and repeats in the form
*/
private Vector<IFormElement> children;
/**
* A collection of group definitions.
*/
private int id;
/**
* The numeric unique identifier of the form definition on the local device
*/
private String title;
/**
* The display title of the form.
*/
private String name;
private Vector<XFormExtension> extensions;
/**
* A unique external name that is used to identify the form between machines
*/
private Localizer localizer;
// This list is topologically ordered, meaning for any tA
// and tB in the list, where tA comes before tB, evaluating tA cannot
// depend on any result from evaluating tB
private Vector<Triggerable> triggerables;
// true if triggerables has been ordered topologically (DON'T DELETE ME
// EVEN THOUGH I'M UNUSED)
private boolean triggerablesInOrder;
// <IConditionExpr> contents of <output> tags that serve as parameterized
// arguments to captions
private Vector outputFragments;
/**
* Map references to the calculate/relevancy conditions that depend on that
* reference's value. Used to trigger re-evaluation of those conditionals
* when the reference is updated.
*/
private Hashtable<TreeReference, Vector<Triggerable>> triggerIndex;
/**
* Associates repeatable nodes with the Condition that determines their
* relevancy.
*/
private Hashtable<TreeReference, Condition> conditionRepeatTargetIndex;
public EvaluationContext exprEvalContext;
private QuestionPreloader preloader = new QuestionPreloader();
// XML ID's cannot start with numbers, so this should never conflict
private static String DEFAULT_SUBMISSION_PROFILE = "1";
private Hashtable<String, SubmissionProfile> submissionProfiles;
/**
* Secondary and external instance pointers
*/
private Hashtable<String, DataInstance> formInstances;
private FormInstance mainInstance = null;
Hashtable<String, Vector<Action>> eventListeners;
boolean mDebugModeEnabled = false;
/**
* Cache children that trigger target will cascade to. For speeding up
* calculations that determine what needs to be triggered when a value
* changes.
*/
private final CacheTable<TreeReference, Vector<TreeReference>> cachedCascadingChildren =
new CacheTable<TreeReference, Vector<TreeReference>>();
public FormDef() {
setID(-1);
setChildren(null);
triggerables = new Vector<Triggerable>();
triggerablesInOrder = true;
triggerIndex = new Hashtable<TreeReference, Vector<Triggerable>>();
//This is kind of a wreck...
setEvaluationContext(new EvaluationContext(null));
outputFragments = new Vector();
submissionProfiles = new Hashtable<String, SubmissionProfile>();
formInstances = new Hashtable<String, DataInstance>();
eventListeners = new Hashtable<String, Vector<Action>>();
extensions = new Vector<XFormExtension>();
}
/**
* Getters and setters for the vectors tha
*/
public void addNonMainInstance(DataInstance instance) {
formInstances.put(instance.getInstanceId(), instance);
this.setEvaluationContext(new EvaluationContext(null));
}
/**
* Get an instance based on a name
*/
public DataInstance getNonMainInstance(String name) {
if (!formInstances.containsKey(name)) {
return null;
}
return formInstances.get(name);
}
public Enumeration getNonMainInstances() {
return formInstances.elements();
}
/**
* Set the main instance
*/
public void setInstance(FormInstance fi) {
mainInstance = fi;
fi.setFormId(getID());
this.setEvaluationContext(new EvaluationContext(null));
attachControlsToInstanceData();
}
/**
* Get the main instance
*/
public FormInstance getMainInstance() {
return mainInstance;
}
public FormInstance getInstance() {
return getMainInstance();
}
public void fireEvent() {
}
public void addChild(IFormElement fe) {
this.children.addElement(fe);
}
public IFormElement getChild(int i) {
if (i < this.children.size())
return (IFormElement)this.children.elementAt(i);
throw new ArrayIndexOutOfBoundsException(
"FormDef: invalid child index: " + i + " only "
+ children.size() + " children");
}
public IFormElement getChild(FormIndex index) {
IFormElement element = this;
while (index != null && index.isInForm()) {
element = element.getChild(index.getLocalIndex());
index = index.getNextLevel();
}
return element;
}
/**
* Dereference the form index and return a Vector of all interstitial nodes
* (top-level parent first; index target last)
*
* Ignore 'new-repeat' node for now; just return/stop at ref to
* yet-to-be-created repeat node (similar to repeats that already exist)
*/
public Vector explodeIndex(FormIndex index) {
Vector<Integer> indexes = new Vector();
Vector<Integer> multiplicities = new Vector();
Vector<IFormElement> elements = new Vector();
collapseIndex(index, indexes, multiplicities, elements);
return elements;
}
// take a reference, find the instance node it refers to (factoring in
// multiplicities)
public TreeReference getChildInstanceRef(FormIndex index) {
Vector<Integer> indexes = new Vector();
Vector<Integer> multiplicities = new Vector();
Vector<IFormElement> elements = new Vector();
collapseIndex(index, indexes, multiplicities, elements);
return getChildInstanceRef(elements, multiplicities);
}
/**
* Return a tree reference which follows the path down the concrete elements provided
* along with the multiplicities provided.
*/
public TreeReference getChildInstanceRef(Vector<IFormElement> elements,
Vector<Integer> multiplicities) {
if (elements.size() == 0) {
return null;
}
// get reference for target element
TreeReference ref = FormInstance.unpackReference(((IFormElement)elements.lastElement()).getBind()).clone();
for (int i = 0; i < ref.size(); i++) {
//There has to be a better way to encapsulate this
if (ref.getMultiplicity(i) != TreeReference.INDEX_ATTRIBUTE) {
ref.setMultiplicity(i, 0);
}
}
// fill in multiplicities for repeats along the way
for (int i = 0; i < elements.size(); i++) {
IFormElement temp = (IFormElement)elements.elementAt(i);
if (temp instanceof GroupDef && ((GroupDef)temp).getRepeat()) {
TreeReference repRef = FormInstance.unpackReference(temp.getBind());
if (repRef.isParentOf(ref, false)) {
int repMult = ((Integer)multiplicities.elementAt(i)).intValue();
ref.setMultiplicity(repRef.size() - 1, repMult);
} else {
// question/repeat hierarchy is not consistent with
// instance instance and bindings
return null;
}
}
}
return ref;
}
public void setLocalizer(Localizer l) {
if (this.localizer != null) {
this.localizer.unregisterLocalizable(this);
}
this.localizer = l;
if (this.localizer != null) {
this.localizer.registerLocalizable(this);
}
}
// don't think this should ever be called(!)
public XPathReference getBind() {
throw new RuntimeException("method not implemented");
}
public void setValue(IAnswerData data, TreeReference ref) {
setValue(data, ref, mainInstance.resolveReference(ref));
}
public void setValue(IAnswerData data, TreeReference ref, TreeElement node) {
setAnswer(data, node);
triggerTriggerables(ref);
//TODO: pre-populate fix-count repeats here?
}
public void setAnswer(IAnswerData data, TreeReference ref) {
setAnswer(data, mainInstance.resolveReference(ref));
}
public void setAnswer(IAnswerData data, TreeElement node) {
node.setAnswer(data);
}
/**
* Deletes the inner-most repeat that this node belongs to and returns the
* corresponding FormIndex. Behavior is currently undefined if you call this
* method on a node that is not contained within a repeat.
*/
public FormIndex deleteRepeat(FormIndex index) {
Vector indexes = new Vector();
Vector multiplicities = new Vector();
Vector elements = new Vector();
collapseIndex(index, indexes, multiplicities, elements);
// loop backwards through the elements, removing objects from each
// vector, until we find a repeat
// TODO: should probably check to make sure size > 0
for (int i = elements.size() - 1; i >= 0; i
IFormElement e = (IFormElement)elements.elementAt(i);
if (e instanceof GroupDef && ((GroupDef)e).getRepeat()) {
break;
} else {
indexes.removeElementAt(i);
multiplicities.removeElementAt(i);
elements.removeElementAt(i);
}
}
// build new formIndex which includes everything
// up to the node we're going to remove
FormIndex newIndex = buildIndex(indexes, multiplicities, elements);
TreeReference deleteRef = getChildInstanceRef(newIndex);
TreeElement deleteElement = mainInstance.resolveReference(deleteRef);
TreeReference parentRef = deleteRef.getParentRef();
TreeElement parentElement = mainInstance.resolveReference(parentRef);
int childMult = deleteElement.getMult();
parentElement.removeChild(deleteElement);
// update multiplicities of other child nodes
for (int i = 0; i < parentElement.getNumChildren(); i++) {
TreeElement child = parentElement.getChildAt(i);
if (child.getMult() > childMult) {
child.setMult(child.getMult() - 1);
}
}
this.getMainInstance().cleanCache();
triggerTriggerables(deleteRef);
return newIndex;
}
public void createNewRepeat(FormIndex index) throws InvalidReferenceException {
TreeReference destRef = getChildInstanceRef(index);
TreeElement template = mainInstance.getTemplate(destRef);
mainInstance.copyNode(template, destRef);
preloadInstance(mainInstance.resolveReference(destRef));
// Fire jr-insert events before "calculate"s
Vector<Triggerable> triggeredDuringInsert = new Vector<Triggerable>();
processInsertAction(destRef, triggeredDuringInsert);
// trigger conditions that depend on the creation of this new node
triggerTriggerables(destRef);
// trigger conditions for the node (and sub-nodes)
initTriggerablesRootedBy(destRef, triggeredDuringInsert);
}
/**
* Fire insert actions for repeat entry, storing triggerables that were
* triggered so we can avoid triggering them during trigger initialization
* for the new repeat entry later on.
*
* @param triggeredDuringInsert collect triggerables that were directly
* fired while processing the action. Used to prevent duplicate triggering
* later on.
*/
private void processInsertAction(TreeReference newRepeatEntryRef,
Vector<Triggerable> triggeredDuringInsert) {
Vector<Action> listeners = getEventListeners(Action.EVENT_JR_INSERT);
for (Action a : listeners) {
TreeReference refSetByAction = a.processAction(this, newRepeatEntryRef);
if (refSetByAction != null) {
Vector<Triggerable> triggerables =
triggerIndex.get(refSetByAction.genericize());
if (triggerables != null) {
for (Triggerable elem : triggerables) {
triggeredDuringInsert.addElement(elem);
}
}
}
}
}
public boolean isRepeatRelevant(TreeReference repeatRef) {
boolean relev = true;
Condition c = (Condition)conditionRepeatTargetIndex.get(repeatRef.genericize());
if (c != null) {
relev = c.evalBool(mainInstance, new EvaluationContext(exprEvalContext, repeatRef));
}
//check the relevancy of the immediate parent
if (relev) {
TreeElement templNode = mainInstance.getTemplate(repeatRef);
TreeReference parentPath = templNode.getParent().getRef().genericize();
TreeElement parentNode = mainInstance.resolveReference(parentPath.contextualize(repeatRef));
relev = parentNode.isRelevant();
}
return relev;
}
/**
* Does the repeat group at the given index enable users to add more items,
* and if so, has the user reached the item limit?
*
* @param repeatRef Reference pointing to a particular repeat item
* @param repeatIndex Id for looking up the repeat group
* @return Do the current constraints on the repeat group allow for adding
* more children?
*/
public boolean canCreateRepeat(TreeReference repeatRef, FormIndex repeatIndex) {
GroupDef repeat = (GroupDef)this.getChild(repeatIndex);
//Check to see if this repeat can have children added by the user
if (repeat.noAddRemove) {
//Check to see if there's a count to use to determine how many children this repeat
//should have
if (repeat.getCountReference() != null) {
int currentMultiplicity = repeatIndex.getElementMultiplicity();
TreeReference absPathToCount = repeat.getConextualizedCountReference(repeatRef);
AbstractTreeElement countNode = this.getMainInstance().resolveReference(absPathToCount);
if (countNode == null) {
throw new XPathTypeMismatchException("Could not find the location " +
absPathToCount.toString() + " where the repeat at " +
repeatRef.toString(false) + " is looking for its count");
}
//get the total multiplicity possible
IAnswerData boxedCount = countNode.getValue();
int count;
if (boxedCount == null) {
count = 0;
} else {
try {
count = ((Integer)new IntegerData().cast(boxedCount.uncast()).getValue()).intValue();
} catch (IllegalArgumentException iae) {
throw new XPathTypeMismatchException("The repeat count value \"" +
boxedCount.uncast().getString() +
"\" at " + absPathToCount.toString() +
" must be a number!");
}
}
if (count <= currentMultiplicity) {
return false;
}
} else {
//Otherwise the user can never add repeat instances
return false;
}
}
//TODO: If we think the node is still relevant, we also need to figure out a way to test that assumption against
//the repeat's constraints.
return true;
}
public void copyItemsetAnswer(QuestionDef q, TreeElement targetNode, IAnswerData data) throws InvalidReferenceException {
ItemsetBinding itemset = q.getDynamicChoices();
TreeReference targetRef = targetNode.getRef();
TreeReference destRef = itemset.getDestRef().contextualize(targetRef);
Vector<Selection> selections = null;
Vector<String> selectedValues = new Vector<String>();
if (data instanceof SelectMultiData) {
selections = (Vector<Selection>)data.getValue();
} else if (data instanceof SelectOneData) {
selections = new Vector<Selection>();
selections.addElement((Selection)data.getValue());
}
if (itemset.valueRef != null) {
for (int i = 0; i < selections.size(); i++) {
selectedValues.addElement(selections.elementAt(i).choice.getValue());
}
}
//delete existing dest nodes that are not in the answer selection
Hashtable<String, TreeElement> existingValues = new Hashtable<String, TreeElement>();
Vector<TreeReference> existingNodes = exprEvalContext.expandReference(destRef);
for (int i = 0; i < existingNodes.size(); i++) {
TreeElement node = getMainInstance().resolveReference(existingNodes.elementAt(i));
if (itemset.valueRef != null) {
String value = itemset.getRelativeValue().evalReadable(this.getMainInstance(), new EvaluationContext(exprEvalContext, node.getRef()));
if (selectedValues.contains(value)) {
existingValues.put(value, node); //cache node if in selection and already exists
}
}
//delete from target
targetNode.removeChild(node);
}
//copy in nodes for new answer; preserve ordering in answer
for (int i = 0; i < selections.size(); i++) {
Selection s = selections.elementAt(i);
SelectChoice ch = s.choice;
TreeElement cachedNode = null;
if (itemset.valueRef != null) {
String value = ch.getValue();
if (existingValues.containsKey(value)) {
cachedNode = existingValues.get(value);
}
}
if (cachedNode != null) {
cachedNode.setMult(i);
targetNode.addChild(cachedNode);
} else {
getMainInstance().copyItemsetNode(ch.copyNode, destRef, this);
}
}
// trigger conditions that depend on the creation of these new nodes
triggerTriggerables(destRef);
// initialize conditions for the node (and sub-nodes)
// NOTE PLM: the following trigger initialization doesn't cascade to
// children because it is behaving like trigger initalization for new
// repeat entries. If we begin actually using this method, the trigger
// cascading logic should be fixed.
initTriggerablesRootedBy(destRef, new Vector<Triggerable>());
// not 100% sure this will work since destRef is ambiguous as the last
// step, but i think it's supposed to work
}
/**
* Add a Condition to the form's Collection.
*/
public Triggerable addTriggerable(Triggerable t) {
int existingIx = triggerables.indexOf(t);
if (existingIx != -1) {
// One node may control access to many nodes; this means many nodes
// effectively have the same condition. Let's identify when
// conditions are the same, and store and calculate it only once.
// nov-2-2011: ctsims - We need to merge the context nodes together
// whenever we do this (finding the highest common ground between
// the two), otherwise we can end up failing to trigger when the
// ignored context exists and the used one doesn't
Triggerable existingTriggerable = (Triggerable)triggerables.elementAt(existingIx);
existingTriggerable.contextRef = existingTriggerable.contextRef.intersect(t.contextRef);
return existingTriggerable;
// NOTE: if the contextRef is unnecessarily deep, the condition
// will be evaluated more times than needed. Perhaps detect when
// 'identical' condition has a shorter contextRef, and use that one
// instead?
} else {
triggerables.addElement(t);
triggerablesInOrder = false;
for (TreeReference trigger : t.getTriggers()) {
if (!triggerIndex.containsKey(trigger)) {
triggerIndex.put(trigger.clone(), new Vector<Triggerable>());
}
Vector<Triggerable> triggered = (Vector<Triggerable>)triggerIndex.get(trigger);
if (!triggered.contains(t)) {
triggered.addElement(t);
}
}
return t;
}
}
/**
* Dependency-sorted enumerator for the triggerables present in the form.
*
* @return Enumerator of triggerables such that when an element X precedes
* Y then X doesn't have any references that are dependent on Y.
*/
public Enumeration getTriggerables() {
return triggerables.elements();
}
/**
* @return All references in the form that are depended on by
* calculate/relevancy conditions.
*/
public Enumeration refWithTriggerDependencies() {
return triggerIndex.keys();
}
/**
* Get the triggerable conditions, like relevancy/calculate, that depend on
* the given reference.
*
* @param ref An absolute reference that is used in relevancy/calculate
* expressions.
* @return All the triggerables that depend on the given reference.
*/
public Vector conditionsTriggeredByRef(TreeReference ref) {
return triggerIndex.get(ref);
}
public void finalizeTriggerables() throws IllegalStateException {
//DAGify the triggerables based on dependencies and sort them so that
//trigbles come only after the trigbles they depend on
Vector<Triggerable[]> partialOrdering = new Vector<Triggerable[]>();
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = (Triggerable)triggerables.elementAt(i);
Vector<Triggerable> deps = new Vector<Triggerable>();
fillTriggeredElements(t, deps, false);
for (int j = 0; j < deps.size(); j++) {
Triggerable u = (Triggerable)deps.elementAt(j);
Triggerable[] edge = {t, u};
partialOrdering.addElement(edge);
}
}
Vector<Triggerable> vertices = new Vector<Triggerable>();
for (int i = 0; i < triggerables.size(); i++)
vertices.addElement(triggerables.elementAt(i));
triggerables.removeAllElements();
while (vertices.size() > 0) {
//determine root nodes
Vector<Triggerable> roots = new Vector<Triggerable>();
for (int i = 0; i < vertices.size(); i++) {
roots.addElement(vertices.elementAt(i));
}
for (int i = 0; i < partialOrdering.size(); i++) {
Triggerable[] edge = (Triggerable[])partialOrdering.elementAt(i);
roots.removeElement(edge[1]);
}
//if no root nodes while graph still has nodes, graph has cycles
if (roots.size() == 0) {
String hints = "";
for (Triggerable t : vertices) {
for (TreeReference r : t.getTargets()) {
hints += "\n" + r.toString(true);
}
}
String message = "Cycle detected in form's relevant and calculation logic!";
if (!hints.equals("")) {
message += "\nThe following nodes are likely involved in the loop:" + hints;
}
throw new IllegalStateException(message);
}
//remove root nodes and edges originating from them
for (int i = 0; i < roots.size(); i++) {
Triggerable root = (Triggerable)roots.elementAt(i);
triggerables.addElement(root);
vertices.removeElement(root);
}
for (int i = partialOrdering.size() - 1; i >= 0; i
Triggerable[] edge = (Triggerable[])partialOrdering.elementAt(i);
if (roots.contains(edge[0]))
partialOrdering.removeElementAt(i);
}
}
triggerablesInOrder = true;
//build the condition index for repeatable nodes
conditionRepeatTargetIndex = new Hashtable<TreeReference, Condition>();
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = (Triggerable)triggerables.elementAt(i);
if (t instanceof Condition) {
Vector targets = t.getTargets();
for (int j = 0; j < targets.size(); j++) {
TreeReference target = (TreeReference)targets.elementAt(j);
if (mainInstance.getTemplate(target) != null) {
conditionRepeatTargetIndex.put(target, (Condition)t);
}
}
}
}
}
/**
* Get all of the elements which will need to be evaluated (in order) when
* the triggerable is fired.
*
* @param destination (mutated) Will have triggerables added to it.
* @param isRepeatEntryInit Don't cascade triggers to children when
* initializing a new repeat entry. Repeat entry
* children have already been queued to be
* triggered.
*/
private void fillTriggeredElements(Triggerable t,
Vector<Triggerable> destination,
boolean isRepeatEntryInit) {
if (t.canCascade()) {
for (TreeReference target : t.getTargets()) {
Vector<TreeReference> updatedNodes = new Vector<TreeReference>();
updatedNodes.addElement(target);
// Repeat sub-elements have already been added to 'destination'
// when we grabbed all triggerables that target children of the
// repeat entry (via initTriggerablesRootedBy). Hence skip them
if (!isRepeatEntryInit && t.isCascadingToChildren()) {
updatedNodes = findCascadeReferences(target, updatedNodes);
}
addTriggerablesTargetingNodes(updatedNodes, destination);
}
}
}
/**
* Gather list of generic references to children of a target reference for
* a triggerable that cascades to its children. This is needed when, for
* example, changing the relevancy of the target will require the triggers
* pointing to children be recalcualted.
*
* @param target Gather children of this by using a template or
* manually traversing the tree
* @param updatedNodes (potentially mutated) Gets generic child references
* added to it.
* @return Potentially cached version of updatedNodes argument that
* contains the target and generic references to the children it might
* cascade to.
*/
private Vector<TreeReference> findCascadeReferences(TreeReference target,
Vector<TreeReference> updatedNodes) {
Vector<TreeReference> cachedNodes = cachedCascadingChildren.retrieve(target);
if (cachedNodes == null) {
if (target.getMultLast() == TreeReference.INDEX_ATTRIBUTE) {
// attributes don't have children that might change under
// contextualization
cachedCascadingChildren.register(target, updatedNodes);
} else {
Vector<TreeReference> expandedRefs = exprEvalContext.expandReference(target);
if (expandedRefs.size() > 0) {
AbstractTreeElement template = mainInstance.getTemplatePath(target);
if (template != null) {
addChildrenOfElement(template, updatedNodes);
cachedCascadingChildren.register(target, updatedNodes);
} else {
// NOTE PLM: entirely possible this can be removed if
// the getTemplatePath code is updated to handle
// heterogeneous paths. Set a breakpoint here and run
// the test suite to see an example
// NOTE PLM: Though I'm pretty sure we could cache
// this, I'm going to avoid doing so because I'm unsure
// whether it is possible for children that are
// cascaded to will change when expandedRefs changes
// due to new data being added.
addChildrenOfReference(expandedRefs, updatedNodes);
}
}
}
} else {
updatedNodes = cachedNodes;
}
return updatedNodes;
}
/**
* Resolve the expanded references and gather their generic children and
* attributes into the genericRefs list.
*/
private void addChildrenOfReference(Vector<TreeReference> expandedRefs,
Vector<TreeReference> genericRefs) {
for (TreeReference ref : expandedRefs) {
addChildrenOfElement(exprEvalContext.resolveReference(ref), genericRefs);
}
}
/**
* Gathers generic children and attribute references for the provided
* element into the genericRefs list.
*/
private static void addChildrenOfElement(AbstractTreeElement treeElem,
Vector<TreeReference> genericRefs) {
// recursively add children of element
for (int i = 0; i < treeElem.getNumChildren(); ++i) {
AbstractTreeElement child = treeElem.getChildAt(i);
TreeReference genericChild = child.getRef().genericize();
if (!genericRefs.contains(genericChild)) {
genericRefs.addElement(genericChild);
}
addChildrenOfElement(child, genericRefs);
}
// add all the attributes of this element
for (int i = 0; i < treeElem.getAttributeCount(); ++i) {
AbstractTreeElement child =
treeElem.getAttribute(treeElem.getAttributeNamespace(i),
treeElem.getAttributeName(i));
TreeReference genericChild = child.getRef().genericize();
if (!genericRefs.contains(genericChild)) {
genericRefs.addElement(genericChild);
}
}
}
private void addTriggerablesTargetingNodes(Vector<TreeReference> updatedNodes,
Vector<Triggerable> destination) {
//Now go through each of these updated nodes (generally just 1 for a normal calculation,
//multiple nodes if there's a relevance cascade.
for (TreeReference ref : updatedNodes) {
//Check our index to see if that target is a Trigger for other conditions
//IE: if they are an element of a different calculation or relevancy calc
//We can't make this reference generic before now or we'll lose the target information,
//so we'll be more inclusive than needed and see if any of our triggers are keyed on
//the predicate-less path of this ref
TreeReference predicatelessRef = ref;
if (ref.hasPredicates()) {
predicatelessRef = ref.removePredicates();
}
Vector<Triggerable> triggered =
(Vector<Triggerable>)triggerIndex.get(predicatelessRef);
if (triggered != null) {
//If so, walk all of these triggerables that we found
for (Triggerable triggerable : triggered) {
//And add them to the queue if they aren't there already
if (!destination.contains(triggerable)) {
destination.addElement(triggerable);
}
}
}
}
}
/**
* Enables debug traces in this form, which can be requested as a map after
* this call has been performed. Debug traces will be available until they
* are explicitly disabled.
*
* This call also re-executes all triggerables in debug mode to make their
* current traces available.
*
* Must be called after this form is initialized.
*/
public void enableDebugTraces() {
if (!mDebugModeEnabled) {
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = (Triggerable)triggerables.elementAt(i);
t.setDebug(true);
}
// Re-execute all triggerables to collect traces
initAllTriggerables();
mDebugModeEnabled = true;
}
}
/**
* Disable debug tracing for this form. Debug traces will no longer be
* available after this call.
*/
public void disableDebugTraces() {
if (mDebugModeEnabled) {
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = (Triggerable)triggerables.elementAt(i);
t.setDebug(false);
}
mDebugModeEnabled = false;
}
}
public Hashtable<TreeReference, Hashtable<String, EvaluationTrace>> getDebugTraceMap()
throws IllegalStateException {
if (!mDebugModeEnabled) {
throw new IllegalStateException("Debugging is not enabled");
}
// TODO: sure would be nice to be able to cache this at some point, but
// will have to have a way to invalidate by trigger or something
Hashtable<TreeReference, Hashtable<String, EvaluationTrace>> debugInfo =
new Hashtable<TreeReference, Hashtable<String, EvaluationTrace>>();
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = (Triggerable)triggerables.elementAt(i);
Hashtable<TreeReference, EvaluationTrace> triggerOutputs = t.getEvaluationTraces();
for (Enumeration e = triggerOutputs.keys(); e.hasMoreElements(); ) {
TreeReference elementRef = (TreeReference)e.nextElement();
String label = t.getDebugLabel();
Hashtable<String, EvaluationTrace> traces = debugInfo.get(elementRef);
if (traces == null) {
traces = new Hashtable<String, EvaluationTrace>();
}
traces.put(label, triggerOutputs.get(elementRef));
debugInfo.put(elementRef, traces);
}
}
return debugInfo;
}
private void initAllTriggerables() {
// Use all triggerables because we can assume they are rooted by rootRef
TreeReference rootRef = TreeReference.rootRef();
Vector<Triggerable> applicable = new Vector<Triggerable>();
for (Triggerable triggerable : triggerables) {
applicable.addElement(triggerable);
}
evaluateTriggerables(applicable, rootRef, false);
}
/**
* Evaluate triggerables targeting references that are children of the
* provided newly created (repeat instance) ref. Ignore all triggerables
* that were already fired by processing the jr-insert action. Ignored
* triggerables can still be fired if a dependency is modified.
*
* @param triggeredDuringInsert Triggerables that don't need to be fired
* because they have already been fired while processing insert events
*/
private void initTriggerablesRootedBy(TreeReference rootRef,
Vector<Triggerable> triggeredDuringInsert) {
TreeReference genericRoot = rootRef.genericize();
Vector<Triggerable> applicable = new Vector<Triggerable>();
for (Triggerable triggerable : triggerables) {
for (TreeReference target : triggerable.getTargets()) {
if (genericRoot.isParentOf(target, false)) {
if (!triggeredDuringInsert.contains(triggerable)) {
applicable.addElement(triggerable);
break;
}
}
}
}
evaluateTriggerables(applicable, rootRef, true);
}
/**
* The entry point for the DAG cascade after a value is changed in the model.
*
* @param ref The full contextualized unambiguous reference of the value that was
* changed.
*/
public void triggerTriggerables(TreeReference ref) {
//turn unambiguous ref into a generic ref
//to identify what nodes should be triggered by this
//reference changing
TreeReference genericRef = ref.genericize();
//get triggerables which are activated by the generic reference
Vector<Triggerable> triggered = (Vector<Triggerable>)triggerIndex.get(genericRef);
if (triggered == null) {
return;
}
//Our vector doesn't have a shallow copy op, so make one
Vector<Triggerable> triggeredCopy = new Vector<Triggerable>();
for (int i = 0; i < triggered.size(); i++) {
triggeredCopy.addElement(triggered.elementAt(i));
}
//Evaluate all of the triggerables in our new vector
evaluateTriggerables(triggeredCopy, ref, false);
}
/**
* Step 2 in evaluating DAG computation updates from a value being changed
* in the instance. This step is responsible for taking the root set of
* directly triggered conditions, identifying which conditions should
* further be triggered due to their update, and then dispatching all of
* the evaluations.
*
* @param tv A vector of all of the trigerrables directly
* triggered by the value changed. Will be mutated
* by this method.
* @param anchorRef The reference to original value that was updated
* @param isRepeatEntryInit Don't cascade triggers to children when
* initializing a new repeat entry. Repeat entry
* children have already been queued to be
* triggered.
*/
private void evaluateTriggerables(Vector<Triggerable> tv,
TreeReference anchorRef,
boolean isRepeatEntryInit) {
// Update the list of triggerables that need to be evaluated.
for (int i = 0; i < tv.size(); i++) {
// NOTE PLM: tv may grow in size through iteration.
Triggerable t = (Triggerable)tv.elementAt(i);
fillTriggeredElements(t, tv, isRepeatEntryInit);
}
// tv should now contain all of the triggerable components which are
// going to need to be addressed by this update.
// 'triggerables' is topologically-ordered by dependencies, so evaluate
// the triggerables in 'tv' in the order they appear in 'triggerables'
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = (Triggerable)triggerables.elementAt(i);
if (tv.contains(t)) {
evaluateTriggerable(t, anchorRef);
}
}
}
/**
* Step 3 in DAG cascade. evaluate the individual triggerable expressions
* against the anchor (the value that changed which triggered
* recomputation)
*
* @param t The triggerable to be updated
* @param anchorRef The reference to the value which was changed.
*/
private void evaluateTriggerable(Triggerable t, TreeReference anchorRef) {
// Contextualize the reference used by the triggerable against the anchor
TreeReference contextRef = t.contextRef.contextualize(anchorRef);
// Now identify all of the fully qualified nodes which this triggerable
// updates. (Multiple nodes can be updated by the same trigger)
Vector<TreeReference> v = exprEvalContext.expandReference(contextRef);
// Go through each one and evaluate the trigger expresion
for (int i = 0; i < v.size(); i++) {
try {
t.apply(mainInstance, exprEvalContext, v.elementAt(i), this);
} catch (RuntimeException e) {
throw e;
}
}
}
public boolean evaluateConstraint(TreeReference ref, IAnswerData data) {
if (data == null) {
return true;
}
TreeElement node = mainInstance.resolveReference(ref);
Constraint c = node.getConstraint();
if (c == null) {
return true;
}
EvaluationContext ec = new EvaluationContext(exprEvalContext, ref);
ec.isConstraint = true;
ec.candidateValue = data;
return c.constraint.eval(mainInstance, ec);
}
public void setEvaluationContext(EvaluationContext ec) {
ec = new EvaluationContext(mainInstance, formInstances, ec);
initEvalContext(ec);
this.exprEvalContext = ec;
}
public EvaluationContext getEvaluationContext() {
return this.exprEvalContext;
}
private void initEvalContext(EvaluationContext ec) {
if (!ec.getFunctionHandlers().containsKey("jr:itext")) {
final FormDef f = this;
ec.addFunctionHandler(new IFunctionHandler() {
public String getName() {
return "jr:itext";
}
public Object eval(Object[] args, EvaluationContext ec) {
String textID = (String)args[0];
try {
//SUUUUPER HACKY
String form = ec.getOutputTextForm();
if (form != null) {
textID = textID + ";" + form;
String result = f.getLocalizer().getRawText(f.getLocalizer().getLocale(), textID);
return result == null ? "" : result;
} else {
String text = f.getLocalizer().getText(textID);
return text == null ? "[itext:" + textID + "]" : text;
}
} catch (NoSuchElementException nsee) {
return "[nolocale]";
}
}
public Vector getPrototypes() {
Class[] proto = {String.class};
Vector v = new Vector();
v.addElement(proto);
return v;
}
public boolean rawArgs() {
return false;
}
public boolean realTime() {
return false;
}
});
}
/* function to reverse a select value into the display label for that choice in the question it came from
*
* arg 1: select value
* arg 2: string xpath referring to origin question; must be absolute path
*
* this won't work at all if the original label needed to be processed/calculated in some way (<output>s, etc.) (is this even allowed?)
* likely won't work with multi-media labels
* _might_ work for itemsets, but probably not very well or at all; could potentially work better if we had some context info
* DOES work with localization
*
* it's mainly intended for the simple case of reversing a question with compile-time-static fields, for use inside an <output>
*/
if (!ec.getFunctionHandlers().containsKey("jr:choice-name")) {
final FormDef f = this;
ec.addFunctionHandler(new IFunctionHandler() {
public String getName() {
return "jr:choice-name";
}
public Object eval(Object[] args, EvaluationContext ec) {
try {
String value = (String)args[0];
String questionXpath = (String)args[1];
TreeReference ref = RestoreUtils.xfFact.ref(questionXpath);
QuestionDef q = f.findQuestionByRef(ref, f);
if (q == null || (q.getControlType() != Constants.CONTROL_SELECT_ONE &&
q.getControlType() != Constants.CONTROL_SELECT_MULTI)) {
return "";
}
System.out.println("here!!");
Vector<SelectChoice> choices = q.getChoices();
for (SelectChoice ch : choices) {
if (ch.getValue().equals(value)) {
//this is really not ideal. we should hook into the existing code (FormEntryPrompt) for pulling
//display text for select choices. however, it's hard, because we don't really have
//any context to work with, and all the situations where that context would be used
//don't make sense for trying to reverse a select value back to a label in an unrelated
//expression
String textID = ch.getTextID();
if (textID != null) {
return f.getLocalizer().getText(textID);
} else {
return ch.getLabelInnerText();
}
}
}
return "";
} catch (Exception e) {
throw new WrappedException("error in evaluation of xpath function [choice-name]", e);
}
}
public Vector getPrototypes() {
Class[] proto = {String.class, String.class};
Vector v = new Vector();
v.addElement(proto);
return v;
}
public boolean rawArgs() {
return false;
}
public boolean realTime() {
return false;
}
});
}
}
public String fillTemplateString(String template, TreeReference contextRef) {
return fillTemplateString(template, contextRef, new Hashtable());
}
/**
* Performs substitutions on place-holder template from form text by
* evaluating args in template using the current context.
*
* @param template String
* @param contextRef TreeReference
* @param variables Hashtable<String, ?>
* @return String with the all args in the template filled with appropriate
* context values.
*/
public String fillTemplateString(String template, TreeReference contextRef, Hashtable<String, ?> variables) {
// argument to value mapping
Hashtable<String, String> args = new Hashtable<String, String>();
int depth = 0;
// grab all template arguments that need to have substitutions performed
Vector outstandingArgs = Localizer.getArgs(template);
String templateAfterSubstitution;
// Step through outstandingArgs from the template, looking up the value
// they map to, evaluating that under the evaluation context and
// storing in the local args mapping.
// Then perform substitutions over the template until a fixpoint is found
while (outstandingArgs.size() > 0) {
for (int i = 0; i < outstandingArgs.size(); i++) {
String argName = (String)outstandingArgs.elementAt(i);
// lookup value an arg points to if it isn't in our local mapping
if (!args.containsKey(argName)) {
int ix = -1;
try {
ix = Integer.parseInt(argName);
} catch (NumberFormatException nfe) {
System.err.println("Warning: expect arguments to be numeric [" + argName + "]");
}
if (ix < 0 || ix >= outputFragments.size()) {
continue;
}
IConditionExpr expr = (IConditionExpr)outputFragments.elementAt(ix);
EvaluationContext ec = new EvaluationContext(exprEvalContext, contextRef);
ec.setOriginalContext(contextRef);
ec.setVariables(variables);
String value = expr.evalReadable(this.getMainInstance(), ec);
args.put(argName, value);
}
}
templateAfterSubstitution = Localizer.processArguments(template, args);
// The last substitution made no progress, probably because the
// argument isn't in outputFragments, so stop looping and
// attempting more subs!
if (template.equals(templateAfterSubstitution)) {
return template;
}
template = templateAfterSubstitution;
// Since strings being substituted might themselves have arguments that
// need to be further substituted, we must recompute the unperformed
// substitutions and continue to loop.
outstandingArgs = Localizer.getArgs(template);
if (depth++ >= TEMPLATING_RECURSION_LIMIT) {
throw new RuntimeException("Dependency cycle in <output>s; recursion limit exceeded!!");
}
}
return template;
}
/**
* Identify the itemset in the backend model, and create a set of SelectChoice
* objects at the current question reference based on the data in the model.
*
* Will modify the itemset binding to contain the relevant choices
*
* @param itemset The binding for an itemset, where the choices will be populated
* @param curQRef A reference to the current question's element, which will be
* used to determine the values to be chosen from.
*/
public void populateDynamicChoices(ItemsetBinding itemset, TreeReference curQRef) {
Vector<SelectChoice> choices = new Vector<SelectChoice>();
Vector<TreeReference> matches = itemset.nodesetExpr.evalNodeset(this.getMainInstance(),
new EvaluationContext(exprEvalContext, itemset.contextRef.contextualize(curQRef)));
DataInstance fi = null;
if (itemset.nodesetRef.getInstanceName() != null) //We're not dealing with the default instance
{
fi = getNonMainInstance(itemset.nodesetRef.getInstanceName());
if (fi == null) {
throw new XPathException("Instance " + itemset.nodesetRef.getInstanceName() + " not found");
}
} else {
fi = getMainInstance();
}
if (matches == null) {
throw new XPathException("Could not find references depended on by " + itemset.nodesetRef.getInstanceName());
}
for (int i = 0; i < matches.size(); i++) {
TreeReference item = matches.elementAt(i);
//String label = itemset.labelExpr.evalReadable(this.getMainInstance(), new EvaluationContext(exprEvalContext, item));
String label = itemset.labelExpr.evalReadable(fi, new EvaluationContext(exprEvalContext, item));
String value = null;
TreeElement copyNode = null;
if (itemset.copyMode) {
copyNode = this.getMainInstance().resolveReference(itemset.copyRef.contextualize(item));
}
if (itemset.valueRef != null) {
//value = itemset.valueExpr.evalReadable(this.getMainInstance(), new EvaluationContext(exprEvalContext, item));
value = itemset.valueExpr.evalReadable(fi, new EvaluationContext(exprEvalContext, item));
}
// SelectChoice choice = new SelectChoice(labelID,labelInnerText,value,isLocalizable);
SelectChoice choice = new SelectChoice(label, value != null ? value : "dynamic:" + i, itemset.labelIsItext);
choice.setIndex(i);
if (itemset.copyMode)
choice.copyNode = copyNode;
choices.addElement(choice);
}
if (choices.size() == 0) {
//throw new RuntimeException("dynamic select question has no choices! [" + itemset.nodesetRef + "]");
//When you exit a survey mid way through and want to save it, it seems that Collect wants to
//go through all the questions. Well of course not all the questions are going to have answers
//to chose from if the user hasn't filled them out. So I'm just going to make a note of this
//and not throw an exception.
System.out.println("dynamic multiple choice question has no choices! [" + itemset.nodesetRef + "]. If this didn't occure durring saving an incomplete form, you've got a problem.");
}
itemset.setChoices(choices, this.getLocalizer());
}
public QuestionPreloader getPreloader() {
return preloader;
}
public void setPreloader(QuestionPreloader preloads) {
this.preloader = preloads;
}
/*
* (non-Javadoc)
*
* @see
* org.javarosa.core.model.utils.Localizable#localeChanged(java.lang.String,
* org.javarosa.core.model.utils.Localizer)
*/
public void localeChanged(String locale, Localizer localizer) {
for (Enumeration e = children.elements(); e.hasMoreElements(); ) {
((IFormElement)e.nextElement()).localeChanged(locale, localizer);
}
}
public String toString() {
return getTitle();
}
/**
* Preload the Data Model with the preload values that are enumerated in the
* data bindings.
*/
public void preloadInstance(TreeElement node) {
// if (node.isLeaf()) {
IAnswerData preload = null;
if (node.getPreloadHandler() != null) {
preload = preloader.getQuestionPreload(node.getPreloadHandler(),
node.getPreloadParams());
}
if (preload != null) { // what if we want to wipe out a value in the
// instance?
node.setAnswer(preload);
}
// } else {
if (!node.isLeaf()) {
for (int i = 0; i < node.getNumChildren(); i++) {
TreeElement child = node.getChildAt(i);
if (child.getMult() != TreeReference.INDEX_TEMPLATE)
// don't preload templates; new repeats are preloaded as they're created
preloadInstance(child);
}
}
}
public boolean postProcessInstance() {
dispatchFormEvent(Action.EVENT_XFORMS_REVALIDATE);
return postProcessInstance(mainInstance.getRoot());
}
/**
* Iterate over the form's data bindings, and evaluate all post procesing
* calls.
*
* @return true if the instance was modified in any way. false otherwise.
*/
private boolean postProcessInstance(TreeElement node) {
// we might have issues with ordering, for example, a handler that writes a value to a node,
// and a handler that does something external with the node. if both handlers are bound to the
// same node, we need to make sure the one that alters the node executes first. deal with that later.
// can we even bind multiple handlers to the same node currently?
// also have issues with conditions. it is hard to detect what conditions are affected by the actions
// of the post-processor. normally, it wouldn't matter because we only post-process when we are exiting
// the form, so the result of any triggered conditions is irrelevant. however, if we save a form in the
// interim, post-processing occurs, and then we continue to edit the form. it seems like having conditions
// dependent on data written during post-processing is a bad practice anyway, and maybe we shouldn't support it.
if (node.isLeaf()) {
if (node.getPreloadHandler() != null) {
return preloader.questionPostProcess(node, node.getPreloadHandler(), node.getPreloadParams());
} else {
return false;
}
} else {
boolean instanceModified = false;
for (int i = 0; i < node.getNumChildren(); i++) {
TreeElement child = node.getChildAt(i);
if (child.getMult() != TreeReference.INDEX_TEMPLATE)
instanceModified |= postProcessInstance(child);
}
return instanceModified;
}
}
/**
* Reads the form definition object from the supplied stream.
*
* Requires that the instance has been set to a prototype of the instance that
* should be used for deserialization.
*
* @param dis - the stream to read from.
*/
public void readExternal(DataInputStream dis, PrototypeFactory pf) throws IOException, DeserializationException {
setID(ExtUtil.readInt(dis));
setName(ExtUtil.nullIfEmpty(ExtUtil.readString(dis)));
setTitle((String)ExtUtil.read(dis, new ExtWrapNullable(String.class), pf));
setChildren((Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf));
setInstance((FormInstance)ExtUtil.read(dis, FormInstance.class, pf));
setLocalizer((Localizer)ExtUtil.read(dis, new ExtWrapNullable(Localizer.class), pf));
Vector vcond = (Vector)ExtUtil.read(dis, new ExtWrapList(Condition.class), pf);
for (Enumeration e = vcond.elements(); e.hasMoreElements(); ) {
addTriggerable((Condition)e.nextElement());
}
Vector vcalc = (Vector)ExtUtil.read(dis, new ExtWrapList(Recalculate.class), pf);
for (Enumeration e = vcalc.elements(); e.hasMoreElements(); ) {
addTriggerable((Recalculate)e.nextElement());
}
finalizeTriggerables();
outputFragments = (Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf);
submissionProfiles = (Hashtable<String, SubmissionProfile>)ExtUtil.read(dis, new ExtWrapMap(String.class, SubmissionProfile.class), pf);
formInstances = (Hashtable<String, DataInstance>)ExtUtil.read(dis, new ExtWrapMap(String.class, new ExtWrapTagged()), pf);
eventListeners = (Hashtable<String, Vector<Action>>)ExtUtil.read(dis, new ExtWrapMap(String.class, new ExtWrapListPoly()), pf);
extensions = (Vector)ExtUtil.read(dis, new ExtWrapListPoly(), pf);
setEvaluationContext(new EvaluationContext(null));
}
/**
* meant to be called after deserialization and initialization of handlers
*
* @param newInstance true if the form is to be used for a new entry interaction,
* false if it is using an existing IDataModel
*/
public void initialize(boolean newInstance, InstanceInitializationFactory factory) {
for (Enumeration en = formInstances.keys(); en.hasMoreElements(); ) {
String instanceId = (String)en.nextElement();
DataInstance instance = formInstances.get(instanceId);
formInstances.put(instanceId, instance.initialize(factory, instanceId));
}
if (newInstance) {
// only preload new forms (we may have to revisit this)
preloadInstance(mainInstance.getRoot());
}
if (getLocalizer() != null && getLocalizer().getLocale() == null) {
getLocalizer().setToDefault();
}
if (newInstance) {
// only dispatch on a form's first opening, not subsequent loadings
// of saved instances. Ensures setvalues triggered by xform-ready,
// useful for recording form start dates.
dispatchFormEvent(Action.EVENT_XFORMS_READY);
}
initAllTriggerables();
}
/**
* Writes the form definition object to the supplied stream.
*
* @param dos - the stream to write to.
* @throws IOException
*/
public void writeExternal(DataOutputStream dos) throws IOException {
ExtUtil.writeNumeric(dos, getID());
ExtUtil.writeString(dos, ExtUtil.emptyIfNull(getName()));
ExtUtil.write(dos, new ExtWrapNullable(getTitle()));
ExtUtil.write(dos, new ExtWrapListPoly(getChildren()));
ExtUtil.write(dos, getMainInstance());
ExtUtil.write(dos, new ExtWrapNullable(localizer));
Vector<Condition> conditions = new Vector<Condition>();
Vector<Recalculate> recalcs = new Vector<Recalculate>();
for (int i = 0; i < triggerables.size(); i++) {
Triggerable t = (Triggerable)triggerables.elementAt(i);
if (t instanceof Condition) {
conditions.addElement((Condition)t);
} else if (t instanceof Recalculate) {
recalcs.addElement((Recalculate)t);
}
}
ExtUtil.write(dos, new ExtWrapList(conditions));
ExtUtil.write(dos, new ExtWrapList(recalcs));
ExtUtil.write(dos, new ExtWrapListPoly(outputFragments));
ExtUtil.write(dos, new ExtWrapMap(submissionProfiles));
//for support of multi-instance forms
ExtUtil.write(dos, new ExtWrapMap(formInstances, new ExtWrapTagged()));
ExtUtil.write(dos, new ExtWrapMap(eventListeners, new ExtWrapListPoly()));
ExtUtil.write(dos, new ExtWrapListPoly(extensions));
}
public void collapseIndex(FormIndex index,
Vector<Integer> indexes,
Vector<Integer> multiplicities,
Vector<IFormElement> elements) {
if (!index.isInForm()) {
return;
}
IFormElement element = this;
while (index != null) {
int i = index.getLocalIndex();
element = element.getChild(i);
indexes.addElement(DataUtil.integer(i));
multiplicities.addElement(DataUtil.integer(index.getInstanceIndex() == -1 ? 0 : index.getInstanceIndex()));
elements.addElement(element);
index = index.getNextLevel();
}
}
public FormIndex buildIndex(Vector indexes, Vector multiplicities, Vector elements) {
FormIndex cur = null;
Vector curMultiplicities = new Vector();
for (int j = 0; j < multiplicities.size(); ++j) {
curMultiplicities.addElement(multiplicities.elementAt(j));
}
Vector curElements = new Vector();
for (int j = 0; j < elements.size(); ++j) {
curElements.addElement(elements.elementAt(j));
}
for (int i = indexes.size() - 1; i >= 0; i
int ix = ((Integer)indexes.elementAt(i)).intValue();
int mult = ((Integer)multiplicities.elementAt(i)).intValue();
if (!(elements.elementAt(i) instanceof GroupDef && ((GroupDef)elements.elementAt(i)).getRepeat())) {
mult = -1;
}
cur = new FormIndex(cur, ix, mult, getChildInstanceRef(curElements, curMultiplicities));
curMultiplicities.removeElementAt(curMultiplicities.size() - 1);
curElements.removeElementAt(curElements.size() - 1);
}
return cur;
}
public int getNumRepetitions(FormIndex index) {
Vector<Integer> indexes = new Vector();
Vector<Integer> multiplicities = new Vector();
Vector<IFormElement> elements = new Vector();
if (!index.isInForm()) {
throw new RuntimeException("not an in-form index");
}
collapseIndex(index, indexes, multiplicities, elements);
if (!(elements.lastElement() instanceof GroupDef) || !((GroupDef)elements.lastElement()).getRepeat()) {
throw new RuntimeException("current element not a repeat");
}
//so painful
TreeElement templNode = mainInstance.getTemplate(index.getReference());
TreeReference parentPath = templNode.getParent().getRef().genericize();
TreeElement parentNode = mainInstance.resolveReference(parentPath.contextualize(index.getReference()));
return parentNode.getChildMultiplicity(templNode.getName());
}
//repIndex == -1 => next repetition about to be created
public FormIndex descendIntoRepeat(FormIndex index, int repIndex) {
int numRepetitions = getNumRepetitions(index);
Vector<Integer> indexes = new Vector();
Vector<Integer> multiplicities = new Vector();
Vector<IFormElement> elements = new Vector();
collapseIndex(index, indexes, multiplicities, elements);
if (repIndex == -1) {
repIndex = numRepetitions;
} else {
if (repIndex < 0 || repIndex >= numRepetitions) {
throw new RuntimeException("selection exceeds current number of repetitions");
}
}
multiplicities.setElementAt(DataUtil.integer(repIndex), multiplicities.size() - 1);
return buildIndex(indexes, multiplicities, elements);
}
/*
* (non-Javadoc)
*
* @see org.javarosa.core.model.IFormElement#getDeepChildCount()
*/
public int getDeepChildCount() {
int total = 0;
Enumeration e = children.elements();
while (e.hasMoreElements()) {
total += ((IFormElement)e.nextElement()).getDeepChildCount();
}
return total;
}
public void registerStateObserver(FormElementStateListener qsl) {
// NO. (Or at least not yet).
}
public void unregisterStateObserver(FormElementStateListener qsl) {
// NO. (Or at least not yet).
}
public Vector getChildren() {
return children;
}
public void setChildren(Vector children) {
this.children = (children == null ? new Vector() : children);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Localizer getLocalizer() {
return localizer;
}
public Vector getOutputFragments() {
return outputFragments;
}
public void setOutputFragments(Vector outputFragments) {
this.outputFragments = outputFragments;
}
public Hashtable getMetaData() {
Hashtable metadata = new Hashtable();
String[] fields = getMetaDataFields();
for (int i = 0; i < fields.length; i++) {
try {
metadata.put(fields[i], getMetaData(fields[i]));
} catch (NullPointerException npe) {
if (getMetaData(fields[i]) == null) {
System.out.println("ERROR! XFORM MUST HAVE A NAME!");
npe.printStackTrace();
}
}
}
return metadata;
}
public Object getMetaData(String fieldName) {
if (fieldName.equals("DESCRIPTOR")) {
return name;
}
if (fieldName.equals("XMLNS")) {
return ExtUtil.emptyIfNull(mainInstance.schema);
} else {
throw new IllegalArgumentException();
}
}
public String[] getMetaDataFields() {
return new String[]{"DESCRIPTOR", "XMLNS"};
}
/**
* Link a deserialized instance back up with its parent FormDef. this allows select/select1 questions to be
* internationalizable in chatterbox, and (if using CHOICE_INDEX mode) allows the instance to be serialized
* to xml
*/
public void attachControlsToInstanceData() {
attachControlsToInstanceData(getMainInstance().getRoot());
}
private void attachControlsToInstanceData(TreeElement node) {
for (int i = 0; i < node.getNumChildren(); i++) {
attachControlsToInstanceData(node.getChildAt(i));
}
IAnswerData val = node.getValue();
Vector selections = null;
if (val instanceof SelectOneData) {
selections = new Vector();
selections.addElement(val.getValue());
} else if (val instanceof SelectMultiData) {
selections = (Vector)val.getValue();
}
if (selections != null) {
QuestionDef q = findQuestionByRef(node.getRef(), this);
if (q == null) {
throw new RuntimeException("FormDef.attachControlsToInstanceData: can't find question to link");
}
if (q.getDynamicChoices() != null) {
//droos: i think we should do something like initializing the itemset here, so that default answers
//can be linked to the selectchoices. however, there are complications. for example, the itemset might
//not be ready to be evaluated at form initialization; it may require certain questions to be answered
//first. e.g., if we evaluate an itemset and it has no choices, the xform engine will throw an error
//itemset TODO
}
for (int i = 0; i < selections.size(); i++) {
Selection s = (Selection)selections.elementAt(i);
s.attachChoice(q);
}
}
}
public static QuestionDef findQuestionByRef(TreeReference ref, IFormElement fe) {
if (fe instanceof FormDef) {
ref = ref.genericize();
}
if (fe instanceof QuestionDef) {
QuestionDef q = (QuestionDef)fe;
TreeReference bind = FormInstance.unpackReference(q.getBind());
return (ref.equals(bind) ? q : null);
} else {
for (int i = 0; i < fe.getChildren().size(); i++) {
QuestionDef ret = findQuestionByRef(ref, fe.getChild(i));
if (ret != null)
return ret;
}
return null;
}
}
/**
* Appearance isn't a valid attribute for form, but this method must be included
* as a result of conforming to the IFormElement interface.
*/
public String getAppearanceAttr() {
throw new RuntimeException("This method call is not relevant for FormDefs getAppearanceAttr ()");
}
/**
* Appearance isn't a valid attribute for form, but this method must be included
* as a result of conforming to the IFormElement interface.
*/
public void setAppearanceAttr(String appearanceAttr) {
throw new RuntimeException("This method call is not relevant for FormDefs setAppearanceAttr()");
}
/**
* Not applicable here.
*/
public String getLabelInnerText() {
return null;
}
/**
* Not applicable
*/
public String getTextID() {
return null;
}
/**
* Not applicable
*/
public void setTextID(String textID) {
throw new RuntimeException("This method call is not relevant for FormDefs [setTextID()]");
}
public void setDefaultSubmission(SubmissionProfile profile) {
submissionProfiles.put(DEFAULT_SUBMISSION_PROFILE, profile);
}
public void addSubmissionProfile(String submissionId, SubmissionProfile profile) {
submissionProfiles.put(submissionId, profile);
}
public SubmissionProfile getSubmissionProfile() {
//At some point these profiles will be set by the <submit> control in the form.
//In the mean time, though, we can only promise that the default one will be used.
return submissionProfiles.get(DEFAULT_SUBMISSION_PROFILE);
}
public Vector<Action> getEventListeners(String event) {
if (this.eventListeners.containsKey(event)) {
return eventListeners.get(event);
}
return new Vector<Action>();
}
public void registerEventListener(String event, Action action) {
Vector<Action> actions;
if (eventListeners.containsKey(event)) {
actions = eventListeners.get(event);
} else {
actions = new Vector<Action>();
eventListeners.put(event, actions);
}
actions.addElement(action);
}
private void dispatchFormEvent(String event) {
for (Action action : getEventListeners(event)) {
action.processAction(this, null);
}
}
public <X extends XFormExtension> X getExtension(Class<X> extension) {
for (XFormExtension ex : extensions) {
if (ex.getClass().isAssignableFrom(extension)) {
return (X)ex;
}
}
X newEx;
try {
newEx = extension.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException("Illegally Structured XForm Extension " + extension.getName());
} catch (IllegalAccessException e) {
throw new RuntimeException("Illegally Structured XForm Extension " + extension.getName());
}
extensions.addElement(newEx);
return newEx;
}
/**
* Frees all of the components of this form which are no longer needed once it is completed.
*
* Once this is called, the form is no longer capable of functioning, but all data should be retained.
*/
public void seal() {
triggerables = null;
triggerIndex = null;
conditionRepeatTargetIndex = null;
//We may need ths one, actually
exprEvalContext = null;
}
} |
import com.github.sarxos.webcam.Webcam;
public class CalculateFPSExample {
public static void main(String[] args) {
long t1;
long t2;
int p = 10;
int r = 5;
Webcam webcam = Webcam.getDefault();
for (int k = 0; k < p; k++) {
webcam.open();
webcam.getImage();
t1 = System.currentTimeMillis();
for (int i = 0; ++i <= r; webcam.getImage()) {
}
t2 = System.currentTimeMillis();
System.out.println("FPS " + k + ": " + (1000 * r / (t2 - t1 + 1)));
webcam.close();
}
}
} |
package com.google.refine.clustering.binning;
public class Metaphone3 {
/** Length of word sent in to be encoded, as
* measured at beginning of encoding. */
int m_length;
/** Length of encoded key string. */
int m_metaphLength;
/** Flag whether or not to encode non-initial vowels. */
boolean m_encodeVowels;
/** Flag whether or not to encode consonants as exactly
* as possible. */
boolean m_encodeExact;
/** Internal copy of word to be encoded, allocated separately
* from string pointed to in incoming parameter. */
String m_inWord;
/** Running copy of primary key. */
StringBuffer m_primary;
/** Running copy of secondary key. */
StringBuffer m_secondary;
/** Index of character in m_inWord currently being
* encoded. */
int m_current;
/** Index of last character in m_inWord. */
int m_last;
/** Flag that an AL inversion has already been done. */
boolean flag_AL_inversion;
/** Default size of key storage allocation */
int MAX_KEY_ALLOCATION = 32;
/** Default maximum length of encoded key. */
int DEFAULT_MAX_KEY_LENGTH = 8;
// Metaphone3 class definition
/**
* Constructor, default. This constructor is most convenient when
* encoding more than one word at a time. New words to encode can
* be set using SetWord(char *).
*
*/
Metaphone3()
{
m_primary = new StringBuffer();
m_secondary = new StringBuffer();
m_metaphLength = DEFAULT_MAX_KEY_LENGTH;
m_encodeVowels = false;
m_encodeExact = false;
}
/**
* Constructor, parameterized. The Metaphone3 object will
* be initialized with the incoming string, and can be called
* on to encode this string. This constructor is most convenient
* when only one word needs to be encoded.
*
* @param in pointer to char string of word to be encoded.
*
*/
Metaphone3(String in)
{
this();
SetWord(in);
}
/**
* Sets word to be encoded.
*
* @param in pointer to EXTERNALLY ALLOCATED char string of
* the word to be encoded.
*
*/
void SetWord(String in)
{
m_inWord = in.toUpperCase();;
m_length = m_inWord.length();
}
/**
* Sets length allocated for output keys.
* If incoming number is greater than maximum allowable
* length returned by GetMaximumKeyLength(), set key length
* to maximum key length and return false; otherwise, set key
* length to parameter value and return true.
*
* @param inKeyLength new length of key.
* @return true if able to set key length to requested value.
*
*/
boolean SetKeyLength(int inKeyLength)
{
if(inKeyLength < 1)
{
// can't have that -
// no room for terminating null
inKeyLength = 1;
}
if(inKeyLength > MAX_KEY_ALLOCATION)
{
m_metaphLength = MAX_KEY_ALLOCATION;
return false;
}
m_metaphLength = inKeyLength;
return true;
}
/**
* Adds an encoding character to the encoded key value string - one parameter version.
*
* @param main primary encoding character to be added to encoded key string.
*/
void MetaphAdd(String in)
{
if(!(in.equals("A")
&& (m_primary.length() > 0)
&& (m_primary.charAt(m_primary.length() - 1) == 'A')))
{
m_primary.append(in);
}
if(!(in.equals("A")
&& (m_secondary.length() > 0)
&& (m_secondary.charAt(m_secondary.length() - 1) == 'A')))
{
m_secondary.append(in);
}
}
/**
* Adds an encoding character to the encoded key value string - two parameter version
*
* @param main primary encoding character to be added to encoded key string
* @param alt alternative encoding character to be added to encoded alternative key string
*
*/
void MetaphAdd(String main, String alt)
{
if(!(main.equals("A")
&& (m_primary.length() > 0)
&& (m_primary.charAt(m_primary.length() - 1) == 'A')))
{
m_primary.append(main);
}
if(!(alt.equals("A")
&& (m_secondary.length() > 0)
&& (m_secondary.charAt(m_secondary.length() - 1) == 'A')))
{
if(!alt.isEmpty())
{
m_secondary.append(alt);
}
}
}
/**
* Adds an encoding character to the encoded key value string - Exact/Approx version
*
* @param mainExact primary encoding character to be added to encoded key string if
* m_encodeExact is set
*
* @param altExact alternative encoding character to be added to encoded alternative
* key string if m_encodeExact is set
*
* @param main primary encoding character to be added to encoded key string
*
* @param alt alternative encoding character to be added to encoded alternative key string
*
*/
void MetaphAddExactApprox(String mainExact, String altExact, String main, String alt)
{
if(m_encodeExact)
{
MetaphAdd(mainExact, altExact);
}
else
{
MetaphAdd(main, alt);
}
}
/**
* Adds an encoding character to the encoded key value string - Exact/Approx version
*
* @param mainExact primary encoding character to be added to encoded key string if
* m_encodeExact is set
*
* @param main primary encoding character to be added to encoded key string
*
*/
void MetaphAddExactApprox(String mainExact, String main)
{
if(m_encodeExact)
{
MetaphAdd(mainExact);
}
else
{
MetaphAdd(main);
}
}
/** Retrieves maximum number of characters currently allocated for encoded key.
*
* @return short integer representing the length allowed for the key.
*/
int GetKeyLength(){return m_metaphLength;}
/** Retrieves maximum number of characters allowed for encoded key.
*
* @return short integer representing the length of allocated storage for the key.
*/
int GetMaximumKeyLength(){return (int)MAX_KEY_ALLOCATION;}
/** Sets flag that causes Metaphone3 to encode non-initial vowels. However, even
* if there are more than one vowel sound in a vowel sequence (i.e.
* vowel diphthong, etc.), only one 'A' will be encoded before the next consonant or the
* end of the word.
*
* @param inEncodeVowels Non-initial vowels encoded if true, not if false.
*/
void SetEncodeVowels(boolean inEncodeVowels){m_encodeVowels = inEncodeVowels;}
/** Retrieves setting determining whether or not non-initial vowels will be encoded.
*
* @return true if the Metaphone3 object has been set to encode non-initial vowels, false if not.
*/
boolean GetEncodeVowels(){return m_encodeVowels;}
/** Sets flag that causes Metaphone3 to encode consonants as exactly as possible.
* This does not include 'S' vs. 'Z', since americans will pronounce 'S' at the
* at the end of many words as 'Z', nor does it include "CH" vs. "SH". It does cause
* a distinction to be made between 'B' and 'P', 'D' and 'T', 'G' and 'K', and 'V'
* and 'F'.
*
* @param inEncodeExact consonants to be encoded "exactly" if true, not if false.
*/
void SetEncodeExact(boolean inEncodeExact){m_encodeExact = inEncodeExact;}
/** Retrieves setting determining whether or not consonants will be encoded "exactly".
*
* @return true if the Metaphone3 object has been set to encode "exactly", false if not.
*/
boolean GetEncodeExact(){return m_encodeExact;}
/** Retrieves primary encoded key.
*
* @return a character pointer to the primary encoded key
*/
String GetMetaph()
{
String primary = new String(m_primary);
return primary;
}
/** Retrieves alternate encoded key, if any.
*
* @return a character pointer to the alternate encoded key
*/
String GetAlternateMetaph()
{
String secondary = new String(m_secondary);
return secondary;
}
/**
* Test for close front vowels
*
* @return true if close front vowel
*/
boolean Front_Vowel(int at)
{
if(((CharAt(at) == 'E') || (CharAt(at) == 'I') || (CharAt(at) == 'Y')))
{
return true;
}
return false;
}
/**
* Detect names or words that begin with spellings
* typical of german or slavic words, for the purpose
* of choosing alternate pronunciations correctly
*
*/
boolean SlavoGermanic()
{
if(StringAt(0, 3, "SCH", "")
|| StringAt(0, 2, "SW", "")
|| (CharAt(0) == 'J')
|| (CharAt(0) == 'W'))
{
return true;
}
return false;
}
/**
* Tests if character is a vowel
*
* @param inChar character to be tested in string to be encoded
* @return true if character is a vowel, false if not
*
*/
boolean IsVowel(char inChar)
{
if((inChar == 'A')
|| (inChar == 'E')
|| (inChar == 'I')
|| (inChar == 'O')
|| (inChar == 'U')
|| (inChar == 'Y')
|| (inChar == 'À')
|| (inChar == 'Á')
|| (inChar == 'Â')
|| (inChar == 'Ã')
|| (inChar == 'Ä')
|| (inChar == 'Å')
|| (inChar == 'Æ')
|| (inChar == 'È')
|| (inChar == 'É')
|| (inChar == 'Ê')
|| (inChar == 'Ë')
|| (inChar == 'Ì')
|| (inChar == 'Í')
|| (inChar == 'Î')
|| (inChar == 'Ï')
|| (inChar == 'Ò')
|| (inChar == 'Ó')
|| (inChar == 'Ô')
|| (inChar == 'Õ')
|| (inChar == 'Ö')
|| (inChar == '')
|| (inChar == 'Ø')
|| (inChar == 'Ù')
|| (inChar == 'Ú')
|| (inChar == 'Û')
|| (inChar == 'Ü')
|| (inChar == 'Ý')
|| (inChar == ''))
{
return true;
}
return false;
}
/**
* Tests if character in the input string is a vowel
*
* @param at position of character to be tested in string to be encoded
* @return true if character is a vowel, false if not
*
*/
boolean IsVowel(int at)
{
if((at < 0) || (at >= m_length))
{
return false;
}
char it = CharAt(at);
if(IsVowel(it))
{
return true;
}
return false;
}
/**
* Skips over vowels in a string. Has exceptions for skipping consonants that
* will not be encoded.
*
* @param at position, in string to be encoded, of character to start skipping from
*
* @return position of next consonant in string to be encoded
*/
int SkipVowels(int at)
{
if(at < 0)
{
return 0;
}
if(at >= m_length)
{
return m_length;
}
char it = CharAt(at);
while(IsVowel(it) || (it == 'W'))
{
if(StringAt(at, 4, "WICZ", "WITZ", "WIAK", "")
|| StringAt((at - 1), 5, "EWSKI", "EWSKY", "OWSKI", "OWSKY", "")
|| (StringAt(at, 5, "WICKI", "WACKI", "") && ((at + 4) == m_last)))
{
break;
}
at++;
if(((CharAt(at - 1) == 'W') && (CharAt(at) == 'H'))
&& !(StringAt(at, 3, "HOP", "")
|| StringAt(at, 4, "HIDE", "HARD", "HEAD", "HAWK", "HERD", "HOOK", "HAND", "HOLE", "")
|| StringAt(at, 5, "HEART", "HOUSE", "HOUND", "")
|| StringAt(at, 6, "HAMMER", "")))
{
at++;
}
if(at > (m_length - 1))
{
break;
}
it = CharAt(at);
}
return at;
}
/**
* Advanced counter m_current so that it indexes the next character to be encoded
*
* @param ifNotEncodeVowels number of characters to advance if not encoding internal vowels
* @param ifEncodeVowels number of characters to advance if encoding internal vowels
*
*/
void AdvanceCounter(int ifNotEncodeVowels, int ifEncodeVowels)
{
if(!m_encodeVowels)
{
m_current += ifNotEncodeVowels;
}
else
{
m_current += ifEncodeVowels;
}
}
/**
* Subscript safe .charAt()
*
* @param at index of character to access
* @return null if index out of bounds, .charAt() otherwise
*/
char CharAt(int at)
{
// check substring bounds
if((at < 0)
|| (at > (m_length - 1)))
{
return '\0';
}
return m_inWord.charAt(at);
}
/**
* Tests whether the word is the root or a regular english inflection
* of it, e.g. "ache", "achy", "aches", "ached", "aching", "achingly"
* This is for cases where we want to match only the root and corresponding
* inflected forms, and not completely different words which may have the
* same substring in them.
*/
boolean RootOrInflections(String inWord, String root)
{
int len = root.length();
String test;
test = root + "S";
if((inWord.equals(root))
|| (inWord.equals(test)))
{
return true;
}
if(root.charAt(len - 1) != 'E')
{
test = root + "ES";
}
if(inWord.equals(test))
{
return true;
}
if(root.charAt(len - 1) != 'E')
{
test = root + "ED";
}
else
{
test = root + "D";
}
if(inWord.equals(test))
{
return true;
}
if(root.charAt(len - 1) == 'E')
{
root = root.substring(0, len - 1);
}
test = root + "ING";
if(inWord.equals(test))
{
return true;
}
test = root + "INGLY";
if(inWord.equals(test))
{
return true;
}
test = root + "Y";
if(inWord.equals(test))
{
return true;
}
return false;
}
/**
* Determines if one of the substrings sent in is the same as
* what is at the specified position in the string being encoded.
*
* @param start
* @param length
* @param compareStrings
* @return
*/
boolean StringAt(int start, int length, String... compareStrings)
{
// check substring bounds
if((start < 0)
|| (start > (m_length - 1))
|| ((start + length - 1) > (m_length - 1)))
{
return false;
}
String target = m_inWord.substring(start, (start + length));
for(String strFragment : compareStrings)
{
if(target.equals(strFragment))
{
return true;
}
}
return false;
}
/**
* Encodes input string to one or two key values according to Metaphone 3 rules.
*
*/
void Encode()
{
flag_AL_inversion = false;
m_current = 0;
m_primary.setLength(0);
m_secondary.setLength(0);
if(m_length < 1)
{
return;
}
//zero based index
m_last = m_length - 1;
///////////main loop//////////////////////////
while(!(m_primary.length() > m_metaphLength) && !(m_secondary.length() > m_metaphLength))
{
if(m_current >= m_length)
{
break;
}
switch(CharAt(m_current))
{
case 'B':
Encode_B();
break;
case 'ß':
case 'Ç':
MetaphAdd("S");
m_current++;
break;
case 'C':
Encode_C();
break;
case 'D':
Encode_D();
break;
case 'F':
Encode_F();
break;
case 'G':
Encode_G();
break;
case 'H':
Encode_H();
break;
case 'J':
Encode_J();
break;
case 'K':
Encode_K();
break;
case 'L':
Encode_L();
break;
case 'M':
Encode_M();
break;
case 'N':
Encode_N();
break;
case 'Ñ':
MetaphAdd("N");
m_current++;
break;
case 'P':
Encode_P();
break;
case 'Q':
Encode_Q();
break;
case 'R':
Encode_R();
break;
case 'S':
Encode_S();
break;
case 'T':
Encode_T();
break;
case 'Ð': // eth
case 'Þ': // thorn
MetaphAdd("0");
m_current++;
break;
case 'V':
Encode_V();
break;
case 'W':
Encode_W();
break;
case 'X':
Encode_X();
break;
case '':
MetaphAdd("X");
m_current++;
break;
case '':
MetaphAdd("S");
m_current++;
break;
case 'Z':
Encode_Z();
break;
default:
if(IsVowel(CharAt(m_current)))
{
Encode_Vowels();
break;
}
m_current++;
}
}
//only give back m_metaphLength number of chars in m_metaph
if(m_primary.length() > m_metaphLength)
{
m_primary.setLength(m_metaphLength);
}
if(m_secondary.length() > m_metaphLength)
{
m_secondary.setLength(m_metaphLength);
}
// it is possible for the two metaphs to be the same
// after truncation. lose the second one if so
if((m_primary.toString()).equals(m_secondary.toString()))
{
m_secondary.setLength(0);
}
}
/**
* Encodes all initial vowels to A.
*
* Encodes non-initial vowels to A if m_encodeVowels is true
*
*
*/
void Encode_Vowels()
{
if(m_current == 0)
{
// all init vowels map to 'A'
// as of Double Metaphone
MetaphAdd("A");
}
else if(m_encodeVowels)
{
if(CharAt(m_current) != 'E')
{
if(Skip_Silent_UE())
{
return;
}
if (O_Silent())
{
m_current++;
return;
}
// encode all vowels and
// diphthongs to the same value
MetaphAdd("A");
}
else
{
Encode_E_Pronounced();
}
}
if(!(!IsVowel(m_current - 2) && StringAt((m_current - 1), 4, "LEWA", "LEWO", "LEWI", "")))
{
m_current = SkipVowels(m_current);
}
else
{
m_current++;
}
}
/**
* Encodes cases where non-initial 'e' is pronounced, taking
* care to detect unusual cases from the greek.
*
* Only executed if non initial vowel encoding is turned on
*
*
*/
void Encode_E_Pronounced()
{
// special cases with two pronunciations
// 'agape' 'lame' 'resume'
if((StringAt(0, 4, "LAME", "SAKE", "PATE", "") && (m_length == 4))
|| (StringAt(0, 5, "AGAPE", "") && (m_length == 5))
|| ((m_current == 5) && StringAt(0, 6, "RESUME", "")))
{
MetaphAdd("", "A");
return;
}
// special case "inge" => 'INGA', 'INJ'
if(StringAt(0, 4, "INGE", "")
&& (m_length == 4))
{
MetaphAdd("A", "");
return;
}
// special cases with two pronunciations
// special handling due to the difference in
// the pronunciation of the '-D'
if((m_current == 5) && StringAt(0, 7, "BLESSED", "LEARNED", ""))
{
MetaphAddExactApprox("D", "AD", "T", "AT");
m_current += 2;
return;
}
// encode all vowels and diphthongs to the same value
if((!E_Silent()
&& !flag_AL_inversion
&& !Silent_Internal_E())
|| E_Pronounced_Exceptions())
{
MetaphAdd("A");
}
// now that we've visited the vowel in question
flag_AL_inversion = false;
}
/**
* Tests for cases where non-initial 'o' is not pronounced
* Only executed if non initial vowel encoding is turned on
*
* @return true if encoded as silent - no addition to m_metaph key
*
*/
boolean O_Silent()
{
// if "iron" at beginning or end of word and not "irony"
if ((CharAt(m_current) == 'O')
&& StringAt((m_current - 2), 4, "IRON", ""))
{
if ((StringAt(0, 4, "IRON", "")
|| (StringAt((m_current - 2), 4, "IRON", "")
&& (m_last == (m_current + 1))))
&& !StringAt((m_current - 2), 6, "IRONIC", ""))
{
return true;
}
}
return false;
}
/**
* Tests and encodes cases where non-initial 'e' is never pronounced
* Only executed if non initial vowel encoding is turned on
*
* @return true if encoded as silent - no addition to m_metaph key
*
*/
boolean E_Silent()
{
if(E_Pronounced_At_End())
{
return false;
}
// 'e' silent when last letter, altho
if((m_current == m_last)
// also silent if before plural 's'
// or past tense or participle 'd', e.g.
// 'grapes' and 'banished' => PNXT
|| ((StringAt(m_last, 1, "S", "D", "")
&& (m_current > 1)
&& ((m_current + 1) == m_last)
// and not e.g. "nested", "rises", or "pieces" => RASAS
&& !(StringAt((m_current - 1), 3, "TED", "SES", "CES", "")
|| StringAt(0, 9, "ANTIPODES", "ANOPHELES", "")
|| StringAt(0, 8, "MOHAMMED", "MUHAMMED", "MOUHAMED", "")
|| StringAt(0, 7, "MOHAMED", "")
|| StringAt(0, 6, "NORRED", "MEDVED", "MERCED", "ALLRED", "KHALED", "RASHED", "MASJED", "")
|| StringAt(0, 5, "JARED", "AHMED", "HAMED", "JAVED", "")
|| StringAt(0, 4, "ABED", "IMED", ""))))
// e.g. 'wholeness', 'boneless', 'barely'
|| (StringAt((m_current + 1), 4, "NESS", "LESS", "") && ((m_current + 4) == m_last))
|| (StringAt((m_current + 1), 2, "LY", "") && ((m_current + 2) == m_last)
&& !StringAt(0, 6, "CICELY", "")))
{
return true;
}
return false;
}
/**
* Tests for words where an 'E' at the end of the word
* is pronounced
*
* special cases, mostly from the greek, spanish, japanese,
* italian, and french words normally having an acute accent.
* also, pronouns and articles
*
* Many Thanks to ali, QuentinCompson, JeffCO, ToonScribe, Xan,
* Trafalz, and VictorLaszlo, all of them atriots from the Eschaton,
* for all their fine contributions!
*
* @return true if 'E' at end is pronounced
*
*/
boolean E_Pronounced_At_End()
{
if((m_current == m_last)
&& (StringAt((m_current - 6), 7, "STROPHE", "")
// if a vowel is before the 'E', vowel eater will have eaten it.
//otherwise, consonant + 'E' will need 'E' pronounced
|| (m_length == 2)
|| ((m_length == 3) && !IsVowel(0))
// these german name endings can be relied on to have the 'e' pronounced
|| (StringAt((m_last - 2), 3, "BKE", "DKE", "FKE", "KKE", "LKE",
"NKE", "MKE", "PKE", "TKE", "VKE", "ZKE", "")
&& !StringAt(0, 5, "FINKE", "FUNKE", "")
&& !StringAt(0, 6, "FRANKE", ""))
|| StringAt((m_last - 4), 5, "SCHKE", "")
|| (StringAt(0, 4, "ACME", "NIKE", "CAFE", "RENE", "LUPE", "JOSE", "ESME", "") && (m_length == 4))
|| (StringAt(0, 5, "LETHE", "CADRE", "TILDE", "SIGNE", "POSSE", "LATTE", "ANIME", "DOLCE", "CROCE",
"ADOBE", "OUTRE", "JESSE", "JAIME", "JAFFE", "BENGE", "RUNGE",
"CHILE", "DESME", "CONDE", "URIBE", "LIBRE", "ANDRE", "") && (m_length == 5))
|| (StringAt(0, 6, "HECATE", "PSYCHE", "DAPHNE", "PENSKE", "CLICHE", "RECIPE",
"TAMALE", "SESAME", "SIMILE", "FINALE", "KARATE", "RENATE", "SHANTE",
"OBERLE", "COYOTE", "KRESGE", "STONGE", "STANGE", "SWAYZE", "FUENTE",
"SALOME", "URRIBE", "") && (m_length == 6))
|| (StringAt(0, 7, "ECHIDNE", "ARIADNE", "MEINEKE", "PORSCHE", "ANEMONE", "EPITOME",
"SYNCOPE", "SOUFFLE", "ATTACHE", "MACHETE", "KARAOKE", "BUKKAKE",
"VICENTE", "ELLERBE", "VERSACE", "") && (m_length == 7))
|| (StringAt(0, 8, "PENELOPE", "CALLIOPE", "CHIPOTLE", "ANTIGONE", "KAMIKAZE", "EURIDICE",
"YOSEMITE", "FERRANTE", "") && (m_length == 8))
|| (StringAt(0, 9, "HYPERBOLE", "GUACAMOLE", "XANTHIPPE", "") && (m_length == 9))
|| (StringAt(0, 10, "SYNECDOCHE", "") && (m_length == 10))))
{
return true;
}
return false;
}
/**
* Detect internal silent 'E's e.g. "roseman",
* "firestone"
*
*/
boolean Silent_Internal_E()
{
// 'olesen' but not 'olen' RAKE BLAKE
if((StringAt(0, 3, "OLE", "")
&& E_Silent_Suffix(3) && !E_Pronouncing_Suffix(3))
|| (StringAt(0, 4, "BARE", "FIRE", "FORE", "GATE", "HAGE", "HAVE",
"HAZE", "HOLE", "CAPE", "HUSE", "LACE", "LINE",
"LIVE", "LOVE", "MORE", "MOSE", "MORE", "NICE",
"RAKE", "ROBE", "ROSE", "SISE", "SIZE", "WARE",
"WAKE", "WISE", "WINE", "")
&& E_Silent_Suffix(4) && !E_Pronouncing_Suffix(4))
|| (StringAt(0, 5, "BLAKE", "BRAKE", "BRINE", "CARLE", "CLEVE", "DUNNE",
"HEDGE", "HOUSE", "JEFFE", "LUNCE", "STOKE", "STONE",
"THORE", "WEDGE", "WHITE", "")
&& E_Silent_Suffix(5) && !E_Pronouncing_Suffix(5))
|| (StringAt(0, 6, "BRIDGE", "CHEESE", "")
&& E_Silent_Suffix(6) && !E_Pronouncing_Suffix(6))
|| StringAt((m_current - 5), 7, "CHARLES", ""))
{
return true;
}
return false;
}
/**
* Detect conditions required
* for the 'E' not to be pronounced
*
*/
boolean E_Silent_Suffix(int at)
{
if((m_current == (at - 1))
&& (m_length > (at + 1))
&& (IsVowel((at + 1))
|| (StringAt(at, 2, "ST", "SL", "")
&& (m_length > (at + 2)))))
{
return true;
}
return false;
}
/**
* Detect endings that will
* cause the 'e' to be pronounced
*
*/
boolean E_Pronouncing_Suffix(int at)
{
// e.g. 'bridgewood' - the other vowels will get eaten
// up so we need to put one in here
if((m_length == (at + 4)) && StringAt(at, 4, "WOOD", ""))
{
return true;
}
// same as above
if((m_length == (at + 5)) && StringAt(at, 5, "WATER", "WORTH", ""))
{
return true;
}
// e.g. 'bridgette'
if((m_length == (at + 3)) && StringAt(at, 3, "TTE", "LIA", "NOW", "ROS", "RAS", ""))
{
return true;
}
// e.g. 'olena'
if((m_length == (at + 2)) && StringAt(at, 2, "TA", "TT", "NA", "NO", "NE",
"RS", "RE", "LA", "AU", "RO", "RA", ""))
{
return true;
}
// e.g. 'bridget'
if((m_length == (at + 1)) && StringAt(at, 1, "T", "R", ""))
{
return true;
}
return false;
}
/**
* Exceptions where 'E' is pronounced where it
* usually wouldn't be, and also some cases
* where 'LE' transposition rules don't apply
* and the vowel needs to be encoded here
*
* @return true if 'E' pronounced
*
*/
boolean E_Pronounced_Exceptions()
{
// greek names e.g. "herakles" or hispanic names e.g. "robles", where 'e' is pronounced, other exceptions
if((((m_current + 1) == m_last)
&& (StringAt((m_current - 3), 5, "OCLES", "ACLES", "AKLES", "")
|| StringAt(0, 4, "INES", "")
|| StringAt(0, 5, "LOPES", "ESTES", "GOMES", "NUNES", "ALVES", "ICKES",
"INNES", "PERES", "WAGES", "NEVES", "BENES", "DONES", "")
|| StringAt(0, 6, "CORTES", "CHAVES", "VALDES", "ROBLES", "TORRES", "FLORES", "BORGES",
"NIEVES", "MONTES", "SOARES", "VALLES", "GEDDES", "ANDRES", "VIAJES",
"CALLES", "FONTES", "HERMES", "ACEVES", "BATRES", "MATHES", "")
|| StringAt(0, 7, "DELORES", "MORALES", "DOLORES", "ANGELES", "ROSALES", "MIRELES", "LINARES",
"PERALES", "PAREDES", "BRIONES", "SANCHES", "CAZARES", "REVELES", "ESTEVES",
"ALVARES", "MATTHES", "SOLARES", "CASARES", "CACERES", "STURGES", "RAMIRES",
"FUNCHES", "BENITES", "FUENTES", "PUENTES", "TABARES", "HENTGES", "VALORES", "")
|| StringAt(0, 8, "GONZALES", "MERCEDES", "FAGUNDES", "JOHANNES", "GONSALES", "BERMUDES",
"CESPEDES", "BETANCES", "TERRONES", "DIOGENES", "CORRALES", "CABRALES",
"MARTINES", "GRAJALES", "")
|| StringAt(0, 9, "CERVANTES", "FERNANDES", "GONCALVES", "BENEVIDES", "CIFUENTES", "SIFUENTES",
"SERVANTES", "HERNANDES", "BENAVIDES", "")
|| StringAt(0, 10, "ARCHIMEDES", "CARRIZALES", "MAGALLANES", "")))
|| StringAt(m_current - 2, 4, "FRED", "DGES", "DRED", "GNES", "")
|| StringAt((m_current - 5), 7, "PROBLEM", "RESPLEN", "")
|| StringAt((m_current - 4), 6, "REPLEN", "")
|| StringAt((m_current - 3), 4, "SPLE", ""))
{
return true;
}
return false;
}
/**
* Encodes "-UE".
*
* @return true if encoding handled in this routine, false if not
*/
boolean Skip_Silent_UE()
{
// always silent except for cases listed below
if((StringAt((m_current - 1), 3, "QUE", "GUE", "")
&& !StringAt(0, 8, "BARBEQUE", "PALENQUE", "APPLIQUE", "")
// '-que' cases usually french but missing the acute accent
&& !StringAt(0, 6, "RISQUE", "")
&& !StringAt((m_current - 3), 5, "ARGUE", "SEGUE", "")
&& !StringAt(0, 7, "PIROGUE", "ENRIQUE", "")
&& !StringAt(0, 10, "COMMUNIQUE", ""))
&& (m_current > 1)
&& (((m_current + 1) == m_last)
|| StringAt(0, 7, "JACQUES", "")))
{
m_current = SkipVowels(m_current);
return true;
}
return false;
}
/**
* Encodes 'B'
*
*
*/
void Encode_B()
{
if(Encode_Silent_B())
{
return;
}
// "-mb", e.g", "dumb", already skipped over under
// 'M', altho it should really be handled here...
MetaphAddExactApprox("B", "P");
if((CharAt(m_current + 1) == 'B')
|| ((CharAt(m_current + 1) == 'P')
&& ((m_current + 1 < m_last) && (CharAt(m_current + 2) != 'H'))))
{
m_current += 2;
}
else
{
m_current++;
}
}
/**
* Encodes silent 'B' for cases not covered under "-mb-"
*
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_B()
{
//'debt', 'doubt', 'subtle'
if(StringAt((m_current - 2), 4, "DEBT", "")
|| StringAt((m_current - 2), 5, "SUBTL", "")
|| StringAt((m_current - 2), 6, "SUBTIL", "")
|| StringAt((m_current - 3), 5, "DOUBT", ""))
{
MetaphAdd("T");
m_current += 2;
return true;
}
return false;
}
/**
* Encodes 'C'
*
*/
void Encode_C()
{
if(Encode_Silent_C_At_Beginning()
|| Encode_CA_To_S()
|| Encode_CO_To_S()
|| Encode_CH()
|| Encode_CCIA()
|| Encode_CC()
|| Encode_CK_CG_CQ()
|| Encode_C_Front_Vowel()
|| Encode_Silent_C()
|| Encode_CZ()
|| Encode_CS())
{
return;
}
//else
if(!StringAt((m_current - 1), 1, "C", "K", "G", "Q", ""))
{
MetaphAdd("K");
}
//name sent in 'mac caffrey', 'mac gregor
if(StringAt((m_current + 1), 2, " C", " Q", " G", ""))
{
m_current += 2;
}
else
{
if(StringAt((m_current + 1), 1, "C", "K", "Q", "")
&& !StringAt((m_current + 1), 2, "CE", "CI", ""))
{
m_current += 2;
// account for combinations such as Ro-ckc-liffe
if(StringAt((m_current), 1, "C", "K", "Q", "")
&& !StringAt((m_current + 1), 2, "CE", "CI", ""))
{
m_current++;
}
}
else
{
m_current++;
}
}
}
/**
* Encodes cases where 'C' is silent at beginning of word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_C_At_Beginning()
{
//skip these when at start of word
if((m_current == 0)
&& StringAt(m_current, 2, "CT", "CN", ""))
{
m_current += 1;
return true;
}
return false;
}
/**
* Encodes exceptions where "-CA-" should encode to S
* instead of K including cases where the cedilla has not been used
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CA_To_S()
{
// Special case: 'caesar'.
// Also, where cedilla not used, as in "linguica" => LNKS
if(((m_current == 0) && StringAt(m_current, 4, "CAES", "CAEC", "CAEM", ""))
|| StringAt(0, 8, "FRANCAIS", "FRANCAIX", "LINGUICA", "")
|| StringAt(0, 6, "FACADE", "")
|| StringAt(0, 9, "GONCALVES", "PROVENCAL", ""))
{
MetaphAdd("S");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encodes exceptions where "-CO-" encodes to S instead of K
* including cases where the cedilla has not been used
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CO_To_S()
{
// e.g. 'coelecanth' => SLKN0
if((StringAt(m_current, 4, "COEL", "")
&& (IsVowel(m_current + 4) || ((m_current + 3) == m_last)))
|| StringAt(m_current, 5, "COENA", "COENO", "")
|| StringAt(0, 8, "FRANCOIS", "MELANCON", "")
|| StringAt(0, 6, "GARCON", ""))
{
MetaphAdd("S");
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encode "-CH-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CH()
{
if(StringAt(m_current, 2, "CH", ""))
{
if(Encode_CHAE()
|| Encode_CH_To_H()
|| Encode_Silent_CH()
|| Encode_ARCH()
// Encode_CH_To_X() should be
// called before the germanic
// and greek encoding functions
|| Encode_CH_To_X()
|| Encode_English_CH_To_K()
|| Encode_Germanic_CH_To_K()
|| Encode_Greek_CH_Initial()
|| Encode_Greek_CH_Non_Initial())
{
return true;
}
if(m_current > 0)
{
if(StringAt(0, 2, "MC", "")
&& (m_current == 1))
{
//e.g., "McHugh"
MetaphAdd("K");
}
else
{
MetaphAdd("X", "K");
}
}
else
{
MetaphAdd("X");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encodes "-CHAE-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CHAE()
{
// e.g. 'michael'
if(((m_current > 0) && StringAt((m_current + 2), 2, "AE", "")))
{
if(StringAt(0, 7, "RACHAEL", ""))
{
MetaphAdd("X");
}
else if(!StringAt((m_current - 1), 1, "C", "K", "G", "Q", ""))
{
MetaphAdd("K");
}
AdvanceCounter(4, 2);
return true;
}
return false;
}
/**
* Encdoes transliterations from the hebrew where the
* sound 'kh' is represented as "-CH-". The normal pronounciation
* of this in english is either 'h' or 'kh', and alternate
* spellings most often use "-H-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CH_To_H()
{
// hebrew => 'H', e.g. 'channukah', 'chabad'
if(((m_current == 0)
&& (StringAt((m_current + 2), 3, "AIM", "ETH", "ELM", "")
|| StringAt((m_current + 2), 4, "ASID", "AZAN", "")
|| StringAt((m_current + 2), 5, "UPPAH", "UTZPA", "ALLAH", "ALUTZ", "AMETZ", "")
|| StringAt((m_current + 2), 6, "ESHVAN", "ADARIM", "ANUKAH", "")
|| StringAt((m_current + 2), 7, "ALLLOTH", "ANNUKAH", "AROSETH", "")))
// and an irish name with the same encoding
|| StringAt((m_current - 3), 7, "CLACHAN", ""))
{
MetaphAdd("H");
AdvanceCounter(3, 2);
return true;
}
return false;
}
/**
* Encodes cases where "-CH-" is not pronounced
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_CH()
{
// '-ch-' not pronounced
if(StringAt((m_current - 2), 7, "FUCHSIA", "")
|| StringAt((m_current - 2), 5, "YACHT", "")
|| StringAt(0, 8, "STRACHAN", "")
|| StringAt(0, 8, "CRICHTON", "")
|| (StringAt((m_current - 3), 6, "DRACHM", ""))
&& !StringAt((m_current - 3), 7, "DRACHMA", ""))
{
m_current += 2;
return true;
}
return false;
}
/**
* Encodes "-CH-" to X
* English language patterns
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CH_To_X()
{
// e.g. 'approach', 'beach'
if((StringAt((m_current - 2), 4, "OACH", "EACH", "EECH", "OUCH", "OOCH", "MUCH", "SUCH", "")
&& !StringAt((m_current - 3), 5, "JOACH", ""))
// e.g. 'dacha', 'macho'
|| (((m_current + 2) == m_last ) && StringAt((m_current - 1), 4, "ACHA", "ACHO", ""))
|| (StringAt(m_current, 4, "CHOT", "CHOD", "CHAT", "") && ((m_current + 3) == m_last))
|| ((StringAt((m_current - 1), 4, "OCHE", "") && ((m_current + 2) == m_last))
&& !StringAt((m_current - 2), 5, "DOCHE", ""))
|| StringAt((m_current - 4), 6, "ATTACH", "DETACH", "KOVACH", "")
|| StringAt((m_current - 5), 7, "SPINACH", "")
|| StringAt(0, 6, "MACHAU", "")
|| StringAt((m_current - 4), 8, "PARACHUT", "")
|| StringAt((m_current - 5), 8, "MASSACHU", "")
|| (StringAt((m_current - 3), 5, "THACH", "") && !StringAt((m_current - 1), 4, "ACHE", ""))
|| StringAt((m_current - 2), 6, "VACHON", "") )
{
MetaphAdd("X");
m_current += 2;
return true;
}
return false;
}
/**
* Encodes "-CH-" to K in contexts of
* initial "A" or "E" follwed by "CH"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_English_CH_To_K()
{
//'ache', 'echo', alternate spelling of 'michael'
if(((m_current == 1) && RootOrInflections(m_inWord, "ACHE"))
|| (((m_current > 3) && RootOrInflections(m_inWord.substring(m_current - 1), "ACHE"))
&& (StringAt(0, 3, "EAR", "")
|| StringAt(0, 4, "HEAD", "BACK", "")
|| StringAt(0, 5, "HEART", "BELLY", "TOOTH", "")))
|| StringAt((m_current - 1), 4, "ECHO", "")
|| StringAt((m_current - 2), 7, "MICHEAL", "")
|| StringAt((m_current - 4), 7, "JERICHO", "")
|| StringAt((m_current - 5), 7, "LEPRECH", ""))
{
MetaphAdd("K", "X");
m_current += 2;
return true;
}
return false;
}
/**
* Encodes "-CH-" to K in mostly germanic context
* of internal "-ACH-", with exceptions
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Germanic_CH_To_K()
{
// various germanic
// "<consonant><vowel>CH-"implies a german word where 'ch' => K
if(((m_current > 1)
&& !IsVowel(m_current - 2)
&& StringAt((m_current - 1), 3, "ACH", "")
&& !StringAt((m_current - 2), 7, "MACHADO", "MACHUCA", "LACHANC", "LACHAPE", "KACHATU", "")
&& !StringAt((m_current - 3), 7, "KHACHAT", "")
&& ((CharAt(m_current + 2) != 'I')
&& ((CharAt(m_current + 2) != 'E')
|| StringAt((m_current - 2), 6, "BACHER", "MACHER", "MACHEN", "LACHER", "")) )
// e.g. 'brecht', 'fuchs'
|| (StringAt((m_current + 2), 1, "T", "S", "")
&& !(StringAt(0, 11, "WHICHSOEVER", "") || StringAt(0, 9, "LUNCHTIME", "") ))
// e.g. 'andromache'
|| StringAt(0, 4, "SCHR", "")
|| ((m_current > 2) && StringAt((m_current - 2), 5, "MACHE", ""))
|| ((m_current == 2) && StringAt((m_current - 2), 4, "ZACH", ""))
|| StringAt((m_current - 4), 6, "SCHACH", "")
|| StringAt((m_current - 1), 5, "ACHEN", "")
|| StringAt((m_current - 3), 5, "SPICH", "ZURCH", "BUECH", "")
|| (StringAt((m_current - 3), 5, "KIRCH", "JOACH", "BLECH", "MALCH", "")
// "kirch" and "blech" both get 'X'
&& !(StringAt((m_current - 3), 8, "KIRCHNER", "") || ((m_current + 1) == m_last)))
|| (((m_current + 1) == m_last) && StringAt((m_current - 2), 4, "NICH", "LICH", "BACH", ""))
|| (((m_current + 1) == m_last)
&& StringAt((m_current - 3), 5, "URICH", "BRICH", "ERICH", "DRICH", "NRICH", "")
&& !StringAt((m_current - 5), 7, "ALDRICH", "")
&& !StringAt((m_current - 6), 8, "GOODRICH", "")
&& !StringAt((m_current - 7), 9, "GINGERICH", "")))
|| (((m_current + 1) == m_last) && StringAt((m_current - 4), 6, "ULRICH", "LFRICH", "LLRICH",
"EMRICH", "ZURICH", "EYRICH", ""))
// e.g., 'wachtler', 'wechsler', but not 'tichner'
|| ((StringAt((m_current - 1), 1, "A", "O", "U", "E", "") || (m_current == 0))
&& StringAt((m_current + 2), 1, "L", "R", "N", "M", "B", "H", "F", "V", "W", " ", "")))
{
// "CHR/L-" e.g. 'chris' do not get
// alt pronunciation of 'X'
if(StringAt((m_current + 2), 1, "R", "L", "")
|| SlavoGermanic())
{
MetaphAdd("K");
}
else
{
MetaphAdd("K", "X");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-ARCH-". Some occurances are from greek roots and therefore encode
* to 'K', others are from english words and therefore encode to 'X'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_ARCH()
{
if(StringAt((m_current - 2), 4, "ARCH", ""))
{
// "-ARCH-" has many combining forms where "-CH-" => K because of its
// derivation from the greek
if(((IsVowel(m_current + 2) && StringAt((m_current - 2), 5, "ARCHA", "ARCHI", "ARCHO", "ARCHU", "ARCHY", ""))
|| StringAt((m_current - 2), 6, "ARCHEA", "ARCHEG", "ARCHEO", "ARCHET", "ARCHEL", "ARCHES", "ARCHEP",
"ARCHEM", "ARCHEN", "")
|| (StringAt((m_current - 2), 4, "ARCH", "") && (((m_current + 1) == m_last)))
|| StringAt(0, 7, "MENARCH", ""))
&& (!RootOrInflections(m_inWord, "ARCH")
&& !StringAt((m_current - 4), 6, "SEARCH", "POARCH", "")
&& !StringAt(0, 9, "ARCHENEMY", "ARCHIBALD", "ARCHULETA", "ARCHAMBAU", "")
&& !StringAt(0, 6, "ARCHER", "ARCHIE", "")
&& !((((StringAt((m_current - 3), 5, "LARCH", "MARCH", "PARCH", "")
|| StringAt((m_current - 4), 6, "STARCH", ""))
&& !(StringAt(0, 6, "EPARCH", "")
|| StringAt(0, 7, "NOMARCH", "")
|| StringAt(0, 8, "EXILARCH", "HIPPARCH", "MARCHESE", "")
|| StringAt(0, 9, "ARISTARCH", "")
|| StringAt(0, 9, "MARCHETTI", "")) )
|| RootOrInflections(m_inWord, "STARCH"))
&& (!StringAt((m_current - 2), 5, "ARCHU", "ARCHY", "")
|| StringAt(0, 7, "STARCHY", "")))))
{
MetaphAdd("K", "X");
}
else
{
MetaphAdd("X");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-CH-" to K when from greek roots
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Greek_CH_Initial()
{
// greek roots e.g. 'chemistry', 'chorus', ch at beginning of root
if((StringAt(m_current, 6, "CHAMOM", "CHARAC", "CHARIS", "CHARTO", "CHARTU", "CHARYB", "CHRIST", "CHEMIC", "CHILIA", "")
|| (StringAt(m_current, 5, "CHEMI", "CHEMO", "CHEMU", "CHEMY", "CHOND", "CHONA", "CHONI", "CHOIR", "CHASM",
"CHARO", "CHROM", "CHROI", "CHAMA", "CHALC", "CHALD", "CHAET","CHIRO", "CHILO", "CHELA", "CHOUS",
"CHEIL", "CHEIR", "CHEIM", "CHITI", "CHEOP", "")
&& !(StringAt(m_current, 6, "CHEMIN", "") || StringAt((m_current - 2), 8, "ANCHONDO", "")))
|| (StringAt(m_current, 5, "CHISM", "CHELI", "")
// exclude spanish "machismo"
&& !(StringAt(0, 8, "MACHISMO", "")
// exclude some french words
|| StringAt(0, 10, "REVANCHISM", "")
|| StringAt(0, 9, "RICHELIEU", "")
|| (StringAt(0, 5, "CHISM", "") && (m_length == 5))
|| StringAt(0, 6, "MICHEL", "")))
// include e.g. "chorus", "chyme", "chaos"
|| (StringAt(m_current, 4, "CHOR", "CHOL", "CHYM", "CHYL", "CHLO", "CHOS", "CHUS", "CHOE", "")
&& !StringAt(0, 6, "CHOLLO", "CHOLLA", "CHORIZ", ""))
// "chaos" => K but not "chao"
|| (StringAt(m_current, 4, "CHAO", "") && ((m_current + 3) != m_last))
// e.g. "abranchiate"
|| (StringAt(m_current, 4, "CHIA", "") && !(StringAt(0, 10, "APPALACHIA", "") || StringAt(0, 7, "CHIAPAS", "")))
// e.g. "chimera"
|| StringAt(m_current, 7, "CHIMERA", "CHIMAER", "CHIMERI", "")
// e.g. "chameleon"
|| ((m_current == 0) && StringAt(m_current, 5, "CHAME", "CHELO", "CHITO", "") )
// e.g. "spirochete"
|| ((((m_current + 4) == m_last) || ((m_current + 5) == m_last)) && StringAt((m_current - 1), 6, "OCHETE", "")))
// more exceptions where "-CH-" => X e.g. "chortle", "crocheter"
&& !((StringAt(0, 5, "CHORE", "CHOLO", "CHOLA", "") && (m_length == 5))
|| StringAt(m_current, 5, "CHORT", "CHOSE", "")
|| StringAt((m_current - 3), 7, "CROCHET", "")
|| StringAt(0, 7, "CHEMISE", "CHARISE", "CHARISS", "CHAROLE", "")) )
{
// "CHR/L-" e.g. 'christ', 'chlorine' do not get
// alt pronunciation of 'X'
if(StringAt((m_current + 2), 1, "R", "L", ""))
{
MetaphAdd("K");
}
else
{
MetaphAdd("K", "X");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode a variety of greek and some german roots where "-CH-" => K
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Greek_CH_Non_Initial()
{
//greek & other roots e.g. 'tachometer', 'orchid', ch in middle or end of root
if(StringAt((m_current - 2), 6, "ORCHID", "NICHOL", "MECHAN", "LICHEN", "MACHIC", "PACHEL", "RACHIF", "RACHID",
"RACHIS", "RACHIC", "MICHAL", "")
|| StringAt((m_current - 3), 5, "MELCH", "GLOCH", "TRACH", "TROCH", "BRACH", "SYNCH", "PSYCH",
"STICH", "PULCH", "EPOCH", "")
|| (StringAt((m_current - 3), 5, "TRICH", "") && !StringAt((m_current - 5), 7, "OSTRICH", ""))
|| (StringAt((m_current - 2), 4, "TYCH", "TOCH", "BUCH", "MOCH", "CICH", "DICH", "NUCH", "EICH", "LOCH",
"DOCH", "ZECH", "WYCH", "")
&& !(StringAt((m_current - 4), 9, "INDOCHINA", "") || StringAt((m_current - 2), 6, "BUCHON", "")))
|| StringAt((m_current - 2), 5, "LYCHN", "TACHO", "ORCHO", "ORCHI", "LICHO", "")
|| (StringAt((m_current - 1), 5, "OCHER", "ECHIN", "ECHID", "") && ((m_current == 1) || (m_current == 2)))
|| StringAt((m_current - 4), 6, "BRONCH", "STOICH", "STRYCH", "TELECH", "PLANCH", "CATECH", "MANICH", "MALACH",
"BIANCH", "DIDACH", "")
|| (StringAt((m_current - 1), 4, "ICHA", "ICHN","") && (m_current == 1))
|| StringAt((m_current - 2), 8, "ORCHESTR", "")
|| StringAt((m_current - 4), 8, "BRANCHIO", "BRANCHIF", "")
|| (StringAt((m_current - 1), 5, "ACHAB", "ACHAD", "ACHAN", "ACHAZ", "")
&& !StringAt((m_current - 2), 7, "MACHADO", "LACHANC", ""))
|| StringAt((m_current - 1), 6, "ACHISH", "ACHILL", "ACHAIA", "ACHENE", "")
|| StringAt((m_current - 1), 7, "ACHAIAN", "ACHATES", "ACHIRAL", "ACHERON", "")
|| StringAt((m_current - 1), 8, "ACHILLEA", "ACHIMAAS", "ACHILARY", "ACHELOUS", "ACHENIAL", "ACHERNAR", "")
|| StringAt((m_current - 1), 9, "ACHALASIA", "ACHILLEAN", "ACHIMENES", "")
|| StringAt((m_current - 1), 10, "ACHIMELECH", "ACHITOPHEL", "")
// e.g. 'inchoate'
|| (((m_current - 2) == 0) && (StringAt((m_current - 2), 6, "INCHOA", "")
// e.g. 'ischemia'
|| StringAt(0, 4, "ISCH", "")) )
// e.g. 'ablimelech', 'antioch', 'pentateuch'
|| (((m_current + 1) == m_last) && StringAt((m_current - 1), 1, "A", "O", "U", "E", "")
&& !(StringAt(0, 7, "DEBAUCH", "")
|| StringAt((m_current - 2), 4, "MUCH", "SUCH", "KOCH", "")
|| StringAt((m_current - 5), 7, "OODRICH", "ALDRICH", ""))))
{
MetaphAdd("K", "X");
m_current += 2;
return true;
}
return false;
}
/**
* Encodes reliably italian "-CCIA-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CCIA()
{
//e.g., 'focaccia'
if(StringAt((m_current + 1), 3, "CIA", ""))
{
MetaphAdd("X", "S");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-CC-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CC()
{
//double 'C', but not if e.g. 'McClellan'
if(StringAt(m_current, 2, "CC", "") && !((m_current == 1) && (CharAt(0) == 'M')))
{
// exception
if (StringAt((m_current - 3), 7, "FLACCID", ""))
{
MetaphAdd("S");
AdvanceCounter(3, 2);
return true;
}
//'bacci', 'bertucci', other italian
if((((m_current + 2) == m_last) && StringAt((m_current + 2), 1, "I", ""))
|| StringAt((m_current + 2), 2, "IO", "")
|| (((m_current + 4) == m_last) && StringAt((m_current + 2), 3, "INO", "INI", "")))
{
MetaphAdd("X");
AdvanceCounter(3, 2);
return true;
}
//'accident', 'accede' 'succeed'
if(StringAt((m_current + 2), 1, "I", "E", "Y", "")
//except 'bellocchio','bacchus', 'soccer' get K
&& !((CharAt(m_current + 2) == 'H')
|| StringAt((m_current - 2), 6, "SOCCER", "")))
{
MetaphAdd("KS");
AdvanceCounter(3, 2);
return true;
}
else
{
//Pierce's rule
MetaphAdd("K");
m_current += 2;
return true;
}
}
return false;
}
/**
* Encode cases where the consonant following "C" is redundant
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CK_CG_CQ()
{
if(StringAt(m_current, 2, "CK", "CG", "CQ", ""))
{
// eastern european spelling e.g. 'gorecki' == 'goresky'
if(StringAt(m_current, 3, "CKI", "CKY", "")
&& ((m_current + 2) == m_last)
&& (m_length > 6))
{
MetaphAdd("K", "SK");
}
else
{
MetaphAdd("K");
}
m_current += 2;
if(StringAt(m_current, 1, "K", "G", "Q", ""))
{
m_current++;
}
return true;
}
return false;
}
/**
* Encode cases where "C" preceeds a front vowel such as "E", "I", or "Y".
* These cases most likely => S or X
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_C_Front_Vowel()
{
if(StringAt(m_current, 2, "CI", "CE", "CY", ""))
{
if(Encode_British_Silent_CE()
|| Encode_CE()
|| Encode_CI()
|| Encode_Latinate_Suffixes())
{
AdvanceCounter(2, 1);
return true;
}
MetaphAdd("S");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_British_Silent_CE()
{
// english place names like e.g.'gloucester' pronounced glo-ster
if((StringAt((m_current + 1), 5, "ESTER", "") && ((m_current + 5) == m_last))
|| StringAt((m_current + 1), 10, "ESTERSHIRE", ""))
{
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CE()
{
// 'ocean', 'commercial', 'provincial', 'cello', 'fettucini', 'medici'
if((StringAt((m_current + 1), 3, "EAN", "") && IsVowel(m_current - 1))
// e.g. 'rosacea'
|| (StringAt((m_current - 1), 4, "ACEA", "")
&& ((m_current + 2) == m_last)
&& !StringAt(0, 7, "PANACEA", ""))
// e.g. 'botticelli', 'concerto'
|| StringAt((m_current + 1), 4, "ELLI", "ERTO", "EORL", "")
// some italian names familiar to americans
|| (StringAt((m_current - 3), 5, "CROCE", "") && ((m_current + 1) == m_last))
|| StringAt((m_current - 3), 5, "DOLCE", "")
// e.g. 'cello'
|| (StringAt((m_current + 1), 4, "ELLO", "")
&& ((m_current + 4) == m_last)))
{
MetaphAdd("X", "S");
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CI()
{
// with consonant before C
// e.g. 'fettucini', but exception for the americanized pronunciation of 'mancini'
if(((StringAt((m_current + 1), 3, "INI", "") && !StringAt(0, 7, "MANCINI", "")) && ((m_current + 3) == m_last))
// e.g. 'medici'
|| (StringAt((m_current - 1), 3, "ICI", "") && ((m_current + 1) == m_last))
// e.g. "commercial', 'provincial', 'cistercian'
|| StringAt((m_current - 1), 5, "RCIAL", "NCIAL", "RCIAN", "UCIUS", "")
// special cases
|| StringAt((m_current - 3), 6, "MARCIA", "")
|| StringAt((m_current - 2), 7, "ANCIENT", ""))
{
MetaphAdd("X", "S");
return true;
}
// with vowel before C (or at beginning?)
if(((StringAt(m_current, 3, "CIO", "CIE", "CIA", "")
&& IsVowel(m_current - 1))
// e.g. "ciao"
|| StringAt((m_current + 1), 3, "IAO", ""))
&& !StringAt((m_current - 4), 8, "COERCION", ""))
{
if((StringAt(m_current, 4, "CIAN", "CIAL", "CIAO", "CIES", "CIOL", "CION", "")
// exception - "glacier" => 'X' but "spacier" = > 'S'
|| StringAt((m_current - 3), 7, "GLACIER", "")
|| StringAt(m_current, 5, "CIENT", "CIENC", "CIOUS", "CIATE", "CIATI", "CIATO", "CIABL", "CIARY", "")
|| (((m_current + 2) == m_last) && StringAt(m_current, 3, "CIA", "CIO", ""))
|| (((m_current + 3) == m_last) && StringAt(m_current, 3, "CIAS", "CIOS", "")))
// exceptions
&& !(StringAt((m_current - 4), 11, "ASSOCIATION", "")
|| StringAt(0, 4, "OCIE", "")
// exceptions mostly because these names are usually from
// the spanish rather than the italian in america
|| StringAt((m_current - 2), 5, "LUCIO", "")
|| StringAt((m_current - 2), 6, "MACIAS", "")
|| StringAt((m_current - 3), 6, "GRACIE", "GRACIA", "")
|| StringAt((m_current - 2), 7, "LUCIANO", "")
|| StringAt((m_current - 3), 8, "MARCIANO", "")
|| StringAt((m_current - 4), 7, "PALACIO", "")
|| StringAt((m_current - 4), 9, "FELICIANO", "")
|| StringAt((m_current - 5), 8, "MAURICIO", "")
|| StringAt((m_current - 7), 11, "ENCARNACION", "")
|| StringAt((m_current - 4), 8, "POLICIES", "")
|| StringAt((m_current - 2), 8, "HACIENDA", "")
|| StringAt((m_current - 6), 9, "ANDALUCIA", "")
|| StringAt((m_current - 2), 5, "SOCIO", "SOCIE", "")))
{
MetaphAdd("X", "S");
}
else
{
MetaphAdd("S", "X");
}
return true;
}
// exception
if(StringAt((m_current - 4), 8, "COERCION", ""))
{
MetaphAdd("J");
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Latinate_Suffixes()
{
if(StringAt((m_current + 1), 4, "EOUS", "IOUS", ""))
{
MetaphAdd("X", "S");
return true;
}
return false;
}
/**
* Encodes some exceptions where "C" is silent
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_C()
{
if(StringAt((m_current + 1), 1, "T", "S", ""))
{
if (StringAt(0, 11, "CONNECTICUT", "")
|| StringAt(0, 6, "INDICT", "TUCSON", ""))
{
m_current++;
return true;
}
}
return false;
}
/**
* Encodes slavic spellings or transliterations
* written as "-CZ-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CZ()
{
if(StringAt((m_current + 1), 1, "Z", "")
&& !StringAt((m_current - 1), 6, "ECZEMA", ""))
{
if(StringAt(m_current, 4, "CZAR", ""))
{
MetaphAdd("S");
}
// otherwise most likely a czech word...
else
{
MetaphAdd("X");
}
m_current += 2;
return true;
}
return false;
}
/**
* "-CS" special cases
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_CS()
{
// give an 'etymological' 2nd
// encoding for "kovacs" so
// that it matches "kovach"
if(StringAt(0, 6, "KOVACS", ""))
{
MetaphAdd("KS", "X");
m_current += 2;
return true;
}
if(StringAt((m_current - 1), 3, "ACS", "")
&& ((m_current + 1) == m_last)
&& !StringAt((m_current - 4), 6, "ISAACS", ""))
{
MetaphAdd("X");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-D-"
*
*/
void Encode_D()
{
if(Encode_DG()
|| Encode_DJ()
|| Encode_DT_DD()
|| Encode_D_To_J()
|| Encode_DOUS()
|| Encode_Silent_D())
{
return;
}
if(m_encodeExact)
{
// "final de-voicing" in this case
// e.g. 'missed' == 'mist'
if((m_current == m_last)
&& StringAt((m_current - 3), 4, "SSED", ""))
{
MetaphAdd("T");
}
else
{
MetaphAdd("D");
}
}
else
{
MetaphAdd("T");
}
m_current++;
}
/**
* Encode "-DG-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_DG()
{
if(StringAt(m_current, 2, "DG", ""))
{
// excludes exceptions e.g. 'edgar',
// or cases where 'g' is first letter of combining form
// e.g. 'handgun', 'waldglas'
if(StringAt((m_current + 2), 1, "A", "O", "")
// e.g. "midgut"
|| StringAt((m_current + 1), 3, "GUN", "GUT", "")
// e.g. "handgrip"
|| StringAt((m_current + 1), 4, "GEAR", "GLAS", "GRIP", "GREN", "GILL", "GRAF", "")
// e.g. "mudgard"
|| StringAt((m_current + 1), 5, "GUARD", "GUILT", "GRAVE", "GRASS", "")
// e.g. "woodgrouse"
|| StringAt((m_current + 1), 6, "GROUSE", ""))
{
MetaphAddExactApprox("DG", "TK");
}
else
{
//e.g. "edge", "abridgment"
MetaphAdd("J");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-DJ-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_DJ()
{
// e.g. "adjacent"
if(StringAt(m_current, 2, "DJ", ""))
{
MetaphAdd("J");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-DD-" and "-DT-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_DT_DD()
{
// eat redundant 'T' or 'D'
if(StringAt(m_current, 2, "DT", "DD", ""))
{
if(StringAt(m_current, 3, "DTH", ""))
{
MetaphAddExactApprox("D0", "T0");
m_current += 3;
}
else
{
if(m_encodeExact)
{
// devoice it
if(StringAt(m_current, 2, "DT", ""))
{
MetaphAdd("T");
}
else
{
MetaphAdd("D");
}
}
else
{
MetaphAdd("T");
}
m_current += 2;
}
return true;
}
return false;
}
/**
* Encode cases where "-DU-" "-DI-", and "-DI-" => J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_D_To_J()
{
// e.g. "module", "adulate"
if((StringAt(m_current, 3, "DUL", "")
&& (IsVowel(m_current - 1) && IsVowel(m_current + 3)))
// e.g. "soldier", "grandeur", "procedure"
|| (((m_current + 3) == m_last)
&& StringAt((m_current - 1) , 5, "LDIER", "NDEUR", "EDURE", "RDURE", ""))
|| StringAt((m_current - 3), 7, "CORDIAL", "")
// e.g. "pendulum", "education"
|| StringAt((m_current - 1), 5, "NDULA", "NDULU", "EDUCA", "")
// e.g. "individual", "individual", "residuum"
|| StringAt((m_current - 1), 4, "ADUA", "IDUA", "IDUU", ""))
{
MetaphAddExactApprox("J", "D", "J", "T");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode latinate suffix "-DOUS" where 'D' is pronounced as J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_DOUS()
{
// e.g. "assiduous", "arduous"
if(StringAt((m_current + 1), 4, "UOUS", ""))
{
MetaphAddExactApprox("J", "D", "J", "T");
AdvanceCounter(4, 1);
return true;
}
return false;
}
/**
* Encode silent "-D-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_D()
{
// silent 'D' e.g. 'wednesday', 'handsome'
if(StringAt((m_current - 2), 9, "WEDNESDAY", "")
|| StringAt((m_current - 3), 7, "HANDKER", "HANDSOM", "WINDSOR", "")
// french silent D at end in words or names familiar to americans
|| StringAt((m_current - 5), 6, "PERNOD", "ARTAUD", "RENAUD", "")
|| StringAt((m_current - 6), 7, "RIMBAUD", "MICHAUD", "BICHAUD", ""))
{
m_current++;
return true;
}
return false;
}
/**
* Encode "-F-"
*
*/
void Encode_F()
{
// Encode cases where "-FT-" => "T" is usually silent
// e.g. 'often', 'soften'
// This should really be covered under "T"!
if(StringAt((m_current - 1), 5, "OFTEN", ""))
{
MetaphAdd("F", "FT");
m_current += 2;
return;
}
// eat redundant 'F'
if(CharAt(m_current + 1) == 'F')
{
m_current += 2;
}
else
{
m_current++;
}
MetaphAdd("F");
}
/**
* Encode "-G-"
*
*/
void Encode_G()
{
if(Encode_Silent_G_At_Beginning()
|| Encode_GG()
|| Encode_GK()
|| Encode_GH()
|| Encode_Silent_G()
|| Encode_GN()
|| Encode_GL()
|| Encode_Initial_G_Front_Vowel()
|| Encode_NGER()
|| Encode_GER()
|| Encode_GEL()
|| Encode_Non_Initial_G_Front_Vowel()
|| Encode_GA_To_J())
{
return;
}
if(!StringAt((m_current - 1), 1, "C", "K", "G", "Q", ""))
{
MetaphAddExactApprox("G", "K");
}
m_current++;
}
/**
* Encode cases where 'G' is silent at beginning of word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_G_At_Beginning()
{
//skip these when at start of word
if((m_current == 0)
&& StringAt(m_current, 2, "GN", ""))
{
m_current += 1;
return true;
}
return false;
}
/**
* Encode "-GG-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GG()
{
if(CharAt(m_current + 1) == 'G')
{
// italian e.g, 'loggia', 'caraveggio', also 'suggest' and 'exaggerate'
if(StringAt((m_current - 1), 5, "AGGIA", "OGGIA", "AGGIO", "EGGIO", "EGGIA", "IGGIO", "")
// 'ruggiero' but not 'snuggies'
|| (StringAt((m_current - 1), 5, "UGGIE", "") && !(((m_current + 3) == m_last) || ((m_current + 4) == m_last)))
|| (((m_current + 2) == m_last) && StringAt((m_current - 1), 4, "AGGI", "OGGI", ""))
|| StringAt((m_current - 2), 6, "SUGGES", "XAGGER", "REGGIE", ""))
{
// expection where "-GG-" => KJ
if (StringAt((m_current - 2), 7, "SUGGEST", ""))
{
MetaphAddExactApprox("G", "K");
}
MetaphAdd("J");
AdvanceCounter(3, 2);
}
else
{
MetaphAddExactApprox("G", "K");
m_current += 2;
}
return true;
}
return false;
}
/**
* Encode "-GK-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GK()
{
// 'gingko'
if(CharAt(m_current + 1) == 'K')
{
MetaphAdd("K");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-GH-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GH()
{
if(CharAt(m_current + 1) == 'H')
{
if(Encode_GH_After_Consonant()
|| Encode_Initial_GH()
|| Encode_GH_To_J()
|| Encode_GH_To_H()
|| Encode_UGHT()
|| Encode_GH_H_Part_Of_Other_Word()
|| Encode_Silent_GH()
|| Encode_GH_To_F())
{
return true;
}
MetaphAddExactApprox("G", "K");
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GH_After_Consonant()
{
// e.g. 'burgher', 'bingham'
if((m_current > 0)
&& !IsVowel(m_current - 1)
// not e.g. 'greenhalgh'
&& !(StringAt((m_current - 3), 5, "HALGH", "")
&& ((m_current + 1) == m_last)))
{
MetaphAddExactApprox("G", "K");
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Initial_GH()
{
if(m_current < 3)
{
// e.g. "ghislane", "ghiradelli"
if(m_current == 0)
{
if(CharAt(m_current + 2) == 'I')
{
MetaphAdd("J");
}
else
{
MetaphAddExactApprox("G", "K");
}
m_current += 2;
return true;
}
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GH_To_J()
{
// e.g., 'greenhalgh', 'dunkenhalgh', english names
if(StringAt((m_current - 2), 4, "ALGH", "") && ((m_current + 1) == m_last))
{
MetaphAdd("J", "");
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GH_To_H()
{
// special cases
// e.g., 'donoghue', 'donaghy'
if((StringAt((m_current - 4), 4, "DONO", "DONA", "") && IsVowel(m_current + 2))
|| StringAt((m_current - 5), 9, "CALLAGHAN", ""))
{
MetaphAdd("H");
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_UGHT()
{
//e.g. "ought", "aught", "daughter", "slaughter"
if(StringAt((m_current - 1), 4, "UGHT", ""))
{
if ((StringAt((m_current - 3), 5, "LAUGH", "")
&& !(StringAt((m_current - 4), 7, "SLAUGHT", "")
|| StringAt((m_current - 3), 7, "LAUGHTO", "")))
|| StringAt((m_current - 4), 6, "DRAUGH", ""))
{
MetaphAdd("FT");
}
else
{
MetaphAdd("T");
}
m_current += 3;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GH_H_Part_Of_Other_Word()
{
// if the 'H' is the beginning of another word or syllable
if (StringAt((m_current + 1), 4, "HOUS", "HEAD", "HOLE", "HORN", "HARN", ""))
{
MetaphAddExactApprox("G", "K");
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_GH()
{
//Parker's rule (with some further refinements) - e.g., 'hugh'
if(((((m_current > 1) && StringAt((m_current - 2), 1, "B", "H", "D", "G", "L", "") )
//e.g., 'bough'
|| ((m_current > 2)
&& StringAt((m_current - 3), 1, "B", "H", "D", "K", "W", "N", "P", "V", "")
&& !StringAt(0, 6, "ENOUGH", ""))
//e.g., 'broughton'
|| ((m_current > 3) && StringAt((m_current - 4), 1, "B", "H", "") )
//'plough', 'slaugh'
|| ((m_current > 3) && StringAt((m_current - 4), 2, "PL", "SL", "") )
|| ((m_current > 0)
// 'sigh', 'light'
&& ((CharAt(m_current - 1) == 'I')
|| StringAt(0, 4, "PUGH", "")
// e.g. 'MCDONAGH', 'MURTAGH', 'CREAGH'
|| (StringAt((m_current - 1), 3, "AGH", "")
&& ((m_current + 1) == m_last))
|| StringAt((m_current - 4), 6, "GERAGH", "DRAUGH", "")
|| (StringAt((m_current - 3), 5, "GAUGH", "GEOGH", "MAUGH", "")
&& !StringAt(0, 9, "MCGAUGHEY", ""))
// exceptions to 'tough', 'rough', 'lough'
|| (StringAt((m_current - 2), 4, "OUGH", "")
&& (m_current > 3)
&& !StringAt((m_current - 4), 6, "CCOUGH", "ENOUGH", "TROUGH", "CLOUGH", "")))))
// suffixes starting w/ vowel where "-GH-" is usually silent
&& (StringAt((m_current - 3), 5, "VAUGH", "FEIGH", "LEIGH", "")
|| StringAt((m_current - 2), 4, "HIGH", "TIGH", "")
|| ((m_current + 1) == m_last)
|| (StringAt((m_current + 2), 2, "IE", "EY", "ES", "ER", "ED", "TY", "")
&& ((m_current + 3) == m_last)
&& !StringAt((m_current - 5), 9, "GALLAGHER", ""))
|| (StringAt((m_current + 2), 1, "Y", "") && ((m_current + 2) == m_last))
|| (StringAt((m_current + 2), 3, "ING", "OUT", "") && ((m_current + 4) == m_last))
|| (StringAt((m_current + 2), 4, "ERTY", "") && ((m_current + 5) == m_last))
|| (!IsVowel(m_current + 2)
|| StringAt((m_current - 3), 5, "GAUGH", "GEOGH", "MAUGH", "")
|| StringAt((m_current - 4), 8, "BROUGHAM", ""))))
// exceptions where '-g-' pronounced
&& !(StringAt(0, 6, "BALOGH", "SABAGH", "")
|| StringAt((m_current - 2), 7, "BAGHDAD", "")
|| StringAt((m_current - 3), 5, "WHIGH", "")
|| StringAt((m_current - 5), 7, "SABBAGH", "AKHLAGH", "")))
{
// silent - do nothing
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GH_Special_Cases()
{
boolean handled = false;
// special case: 'hiccough' == 'hiccup'
if(StringAt((m_current - 6), 8, "HICCOUGH", ""))
{
MetaphAdd("P");
handled = true;
}
// special case: 'lough' alt spelling for scots 'loch'
else if(StringAt(0, 5, "LOUGH", ""))
{
MetaphAdd("K");
handled = true;
}
// hungarian
else if(StringAt(0, 6, "BALOGH", ""))
{
MetaphAddExactApprox("G", "", "K", "");
handled = true;
}
// "maclaughlin"
else if(StringAt((m_current - 3), 8, "LAUGHLIN", "COUGHLAN", "LOUGHLIN", ""))
{
MetaphAdd("K", "F");
handled = true;
}
else if(StringAt((m_current - 3), 5, "GOUGH", "")
|| StringAt((m_current - 7), 9, "COLCLOUGH", ""))
{
MetaphAdd("", "F");
handled = true;
}
if(handled)
{
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GH_To_F()
{
// the cases covered here would fall under
// the GH_To_F rule below otherwise
if(Encode_GH_Special_Cases())
{
return true;
}
else
{
//e.g., 'laugh', 'cough', 'rough', 'tough'
if((m_current > 2)
&& (CharAt(m_current - 1) == 'U')
&& IsVowel(m_current - 2)
&& StringAt((m_current - 3), 1, "C", "G", "L", "R", "T", "N", "S", "")
&& !StringAt((m_current - 4), 8, "BREUGHEL", "FLAUGHER", ""))
{
MetaphAdd("F");
m_current += 2;
return true;
}
}
return false;
}
/**
* Encode some contexts where "g" is silent
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_G()
{
// e.g. "phlegm", "apothegm", "voigt"
if((((m_current + 1) == m_last)
&& (StringAt((m_current - 1), 3, "EGM", "IGM", "AGM", "")
|| StringAt(m_current, 2, "GT", "")))
|| (StringAt(0, 5, "HUGES", "") && (m_length == 5)))
{
m_current++;
return true;
}
// vietnamese names e.g. "Nguyen" but not "Ng"
if(StringAt(0, 2, "NG", "") && (m_current != m_last))
{
m_current++;
return true;
}
return false;
}
/**
* ENcode "-GN-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GN()
{
if(CharAt(m_current + 1) == 'N')
{
// 'align' 'sign', 'resign' but not 'resignation'
// also 'impugn', 'impugnable', but not 'repugnant'
if(((m_current > 1)
&& ((StringAt((m_current - 1), 1, "I", "U", "E", "")
|| StringAt((m_current - 3), 9, "LORGNETTE", "")
|| StringAt((m_current - 2), 9, "LAGNIAPPE", "")
|| StringAt((m_current - 2), 6, "COGNAC", "")
|| StringAt((m_current - 3), 7, "CHAGNON", "")
|| StringAt((m_current - 5), 9, "COMPAGNIE", "")
|| StringAt((m_current - 4), 6, "BOLOGN", ""))
// Exceptions: following are cases where 'G' is pronounced
// in "assign" 'g' is silent, but not in "assignation"
&& !(StringAt((m_current + 2), 5, "ATION", "")
|| StringAt((m_current + 2), 4, "ATOR", "")
|| StringAt((m_current + 2), 3, "ATE", "ITY", "")
// exception to exceptions, not pronounced:
|| (StringAt((m_current + 2), 2, "AN", "AC", "IA", "UM", "")
&& !(StringAt((m_current - 3), 8, "POIGNANT", "")
|| StringAt((m_current - 2), 6, "COGNAC", "")))
|| StringAt(0, 7, "SPIGNER", "STEGNER", "")
|| (StringAt(0, 5, "SIGNE", "") && (m_length == 5))
|| StringAt((m_current - 2), 5, "LIGNI", "LIGNO", "REGNA", "DIGNI", "WEGNE",
"TIGNE", "RIGNE", "REGNE", "TIGNO", "")
|| StringAt((m_current - 2), 6, "SIGNAL", "SIGNIF", "SIGNAT", "")
|| StringAt((m_current - 1), 5, "IGNIT", ""))
&& !StringAt((m_current - 2), 6, "SIGNET", "LIGNEO", "") ))
//not e.g. 'cagney', 'magna'
|| (((m_current + 2) == m_last)
&& StringAt(m_current, 3, "GNE", "GNA", "")
&& !StringAt((m_current - 2), 5, "SIGNA", "MAGNA", "SIGNE", "")))
{
MetaphAddExactApprox("N", "GN", "N", "KN");
}
else
{
MetaphAddExactApprox("GN", "KN");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-GL-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GL()
{
//'tagliaro', 'puglia' BUT add K in alternative
// since americans sometimes do this
if(StringAt((m_current + 1), 3, "LIA", "LIO", "LIE", "")
&& IsVowel(m_current - 1))
{
MetaphAddExactApprox("L", "GL", "L", "KL");
m_current += 2;
return true;
}
return false;
}
/**
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Initial_G_Soft()
{
if(((StringAt((m_current + 1), 2, "EL", "EM", "EN", "EO", "ER", "ES", "IA", "IN", "IO", "IP", "IU", "YM", "YN", "YP", "YR", "EE", "")
|| StringAt((m_current + 1), 3, "IRA", "IRO", ""))
// except for smaller set of cases where => K, e.g. "gerber"
&& !(StringAt((m_current + 1), 3, "ELD", "ELT", "ERT", "INZ", "ERH", "ITE", "ERD", "ERL", "ERN",
"INT", "EES", "EEK", "ELB", "EER", "")
|| StringAt((m_current + 1), 4, "ERSH", "ERST", "INSB", "INGR", "EROW", "ERKE", "EREN", "")
|| StringAt((m_current + 1), 5, "ELLER", "ERDIE", "ERBER", "ESUND", "ESNER", "INGKO", "INKGO",
"IPPER", "ESELL", "IPSON", "EEZER", "ERSON", "ELMAN", "")
|| StringAt((m_current + 1), 6, "ESTALT", "ESTAPO", "INGHAM", "ERRITY", "ERRISH", "ESSNER", "ENGLER", "")
|| StringAt((m_current + 1), 7, "YNAECOL", "YNECOLO", "ENTHNER", "ERAGHTY", "")
|| StringAt((m_current + 1), 8, "INGERICH", "EOGHEGAN", "")))
||(IsVowel(m_current + 1)
&& (StringAt((m_current + 1), 3, "EE ", "EEW", "")
|| (StringAt((m_current + 1), 3, "IGI", "IRA", "IBE", "AOL", "IDE", "IGL", "")
&& !StringAt((m_current + 1), 5, "IDEON", "") )
|| StringAt((m_current + 1), 4, "ILES", "INGI", "ISEL", "")
|| (StringAt((m_current + 1), 5, "INGER", "") && !StringAt((m_current + 1), 8, "INGERICH", ""))
|| StringAt((m_current + 1), 5, "IBBER", "IBBET", "IBLET", "IBRAN", "IGOLO", "IRARD", "IGANT", "")
|| StringAt((m_current + 1), 6, "IRAFFE", "EEWHIZ","")
|| StringAt((m_current + 1), 7, "ILLETTE", "IBRALTA", ""))))
{
return true;
}
return false;
}
/**
* Encode cases where 'G' is at start of word followed
* by a "front" vowel e.g. 'E', 'I', 'Y'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Initial_G_Front_Vowel()
{
// 'g' followed by vowel at beginning
if((m_current == 0) && Front_Vowel(m_current + 1))
{
// special case "gila" as in "gila monster"
if(StringAt((m_current + 1), 3, "ILA", "")
&& (m_length == 4))
{
MetaphAdd("H");
}
else if(Initial_G_Soft())
{
MetaphAddExactApprox("J", "G", "J", "K");
}
else
{
// only code alternate 'J' if front vowel
if((m_inWord.charAt(m_current + 1) == 'E') || (m_inWord.charAt(m_current + 1) == 'I'))
{
MetaphAddExactApprox("G", "J", "K", "J");
}
else
{
MetaphAddExactApprox("G", "K");
}
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode "-NGER-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_NGER()
{
if((m_current > 1)
&& StringAt((m_current - 1), 4, "NGER", ""))
{
// default 'G' => J such as 'ranger', 'stranger', 'manger', 'messenger', 'orangery', 'granger'
// 'boulanger', 'challenger', 'danger', 'changer', 'harbinger', 'lounger', 'ginger', 'passenger'
// except for these the following
if(!(RootOrInflections(m_inWord, "ANGER")
|| RootOrInflections(m_inWord, "LINGER")
|| RootOrInflections(m_inWord, "MALINGER")
|| RootOrInflections(m_inWord, "FINGER")
|| (StringAt((m_current - 3), 4, "HUNG", "FING", "BUNG", "WING", "RING", "DING", "ZENG",
"ZING", "JUNG", "LONG", "PING", "CONG", "MONG", "BANG",
"GANG", "HANG", "LANG", "SANG", "SING", "WANG", "ZANG", "")
// exceptions to above where 'G' => J
&& !(StringAt((m_current - 6), 7, "BOULANG", "SLESING", "KISSING", "DERRING", "")
|| StringAt((m_current - 8), 9, "SCHLESING", "")
|| StringAt((m_current - 5), 6, "SALING", "BELANG", "")
|| StringAt((m_current - 6), 7, "BARRING", "")
|| StringAt((m_current - 6), 9, "PHALANGER", "")
|| StringAt((m_current - 4), 5, "CHANG", "")))
|| StringAt((m_current - 4), 5, "STING", "YOUNG", "")
|| StringAt((m_current - 5), 6, "STRONG", "")
|| StringAt(0, 3, "UNG", "ENG", "ING", "")
|| StringAt(m_current, 6, "GERICH", "")
|| StringAt(0, 6, "SENGER", "")
|| StringAt((m_current - 3), 6, "WENGER", "MUNGER", "SONGER", "KINGER", "")
|| StringAt((m_current - 4), 7, "FLINGER", "SLINGER", "STANGER", "STENGER", "KLINGER", "CLINGER", "")
|| StringAt((m_current - 5), 8, "SPRINGER", "SPRENGER", "")
|| StringAt((m_current - 3), 7, "LINGERF", "")
|| StringAt((m_current - 2), 7, "ANGERLY", "ANGERBO", "INGERSO", "") ))
{
MetaphAddExactApprox("J", "G", "J", "K");
}
else
{
MetaphAddExactApprox("G", "J", "K", "J");
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode "-GER-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GER()
{
if((m_current > 0)
&& StringAt((m_current + 1), 2, "ER", ""))
{
// Exceptions to 'GE' where 'G' => K
// e.g. "JAGER", "TIGER", "LIGER", "LAGER", "LUGER", "AUGER", "EAGER", "HAGER", "SAGER"
if((((m_current == 2) && IsVowel(m_current - 1) && !IsVowel(m_current - 2)
&& !(StringAt((m_current - 2), 5, "PAGER", "WAGER", "NIGER", "ROGER", "LEGER", "CAGER", ""))
|| StringAt((m_current - 2), 5, "AUGER", "EAGER", "INGER", "YAGER", ""))
|| StringAt((m_current - 3), 6, "SEEGER", "JAEGER", "GEIGER", "KRUGER", "SAUGER", "BURGER",
"MEAGER", "MARGER", "RIEGER", "YAEGER", "STEGER", "PRAGER", "SWIGER",
"YERGER", "TORGER", "FERGER", "HILGER", "ZEIGER", "YARGER",
"COWGER", "CREGER", "KROGER", "KREGER", "GRAGER", "STIGER", "BERGER", "")
// 'berger' but not 'bergerac'
|| (StringAt((m_current - 3), 6, "BERGER", "") && ((m_current + 2) == m_last))
|| StringAt((m_current - 4), 7, "KREIGER", "KRUEGER", "METZGER", "KRIEGER", "KROEGER", "STEIGER",
"DRAEGER", "BUERGER", "BOERGER", "FIBIGER", "")
// e.g. 'harshbarger', 'winebarger'
|| (StringAt((m_current - 3), 6, "BARGER", "") && (m_current > 4))
// e.g. 'weisgerber'
|| (StringAt(m_current, 6, "GERBER", "") && (m_current > 0))
|| StringAt((m_current - 5), 8, "SCHWAGER", "LYBARGER", "SPRENGER", "GALLAGER", "WILLIGER", "")
|| StringAt(0, 4, "HARGER", "")
|| (StringAt(0, 4, "AGER", "EGER", "") && (m_length == 4))
|| StringAt((m_current - 1), 6, "YGERNE", "")
|| StringAt((m_current - 6), 9, "SCHWEIGER", ""))
&& !(StringAt((m_current - 5), 10, "BELLIGEREN", "")
|| StringAt(0, 7, "MARGERY", "")
|| StringAt((m_current - 3), 8, "BERGERAC", "")))
{
if(SlavoGermanic())
{
MetaphAddExactApprox("G", "K");
}
else
{
MetaphAddExactApprox("G", "J", "K", "J");
}
}
else
{
MetaphAddExactApprox("J", "G", "J", "K");
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* ENcode "-GEL-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GEL()
{
// more likely to be "-GEL-" => JL
if(StringAt((m_current + 1), 2, "EL", "")
&& (m_current > 0))
{
// except for
// "BAGEL", "HEGEL", "HUGEL", "KUGEL", "NAGEL", "VOGEL", "FOGEL", "PAGEL"
if(((m_length == 5)
&& IsVowel(m_current - 1)
&& !IsVowel(m_current - 2)
&& !StringAt((m_current - 2), 5, "NIGEL", "RIGEL", ""))
// or the following as combining forms
|| StringAt((m_current - 2), 5, "ENGEL", "HEGEL", "NAGEL", "VOGEL", "")
|| StringAt((m_current - 3), 6, "MANGEL", "WEIGEL", "FLUGEL", "RANGEL", "HAUGEN", "RIEGEL", "VOEGEL", "")
|| StringAt((m_current - 4), 7, "SPEIGEL", "STEIGEL", "WRANGEL", "SPIEGEL", "")
|| StringAt((m_current - 4), 8, "DANEGELD", ""))
{
if(SlavoGermanic())
{
MetaphAddExactApprox("G", "K");
}
else
{
MetaphAddExactApprox("G", "J", "K", "J");
}
}
else
{
MetaphAddExactApprox("J", "G", "J", "K");
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode "-G-" followed by a vowel when non-initial leter.
* Default for this is a 'J' sound, so check exceptions where
* it is pronounced 'G'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Non_Initial_G_Front_Vowel()
{
// -gy-, gi-, ge-
if(StringAt((m_current + 1), 1, "E", "I", "Y", ""))
{
// '-ge' at end
// almost always 'j 'sound
if(StringAt(m_current, 2, "GE", "") && (m_current == (m_last - 1)))
{
if(Hard_GE_At_End())
{
if(SlavoGermanic())
{
MetaphAddExactApprox("G", "K");
}
else
{
MetaphAddExactApprox("G", "J", "K", "J");
}
}
else
{
MetaphAdd("J");
}
}
else
{
if(Internal_Hard_G())
{
// don't encode KG or KK if e.g. "mcgill"
if(!((m_current == 2) && StringAt(0, 2, "MC", ""))
|| ((m_current == 3) && StringAt(0, 3, "MAC", "")))
{
if(SlavoGermanic())
{
MetaphAddExactApprox("G", "K");
}
else
{
MetaphAddExactApprox("G", "J", "K", "J");
}
}
}
else
{
MetaphAddExactApprox("J", "G", "J", "K");
}
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/*
* Detect german names and other words that have
* a 'hard' 'g' in the context of "-ge" at end
*
* @return true if encoding handled in this routine, false if not
*/
boolean Hard_GE_At_End()
{
if(StringAt(0, 6, "RENEGE", "STONGE", "STANGE", "PRANGE", "KRESGE", "")
|| StringAt(0, 5, "BYRGE", "BIRGE", "BERGE", "HAUGE", "")
|| StringAt(0, 4, "HAGE", "")
|| StringAt(0, 5, "LANGE", "SYNGE", "BENGE", "RUNGE", "HELGE", "")
|| StringAt(0, 4, "INGE", "LAGE", ""))
{
return true;
}
return false;
}
/**
* Exceptions to default encoding to 'J':
* encode "-G-" to 'G' in "-g<frontvowel>-" words
* where we are not at "-GE" at the end of the word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Internal_Hard_G()
{
// if not "-GE" at end
if(!(((m_current + 1) == m_last) && (CharAt(m_current + 1) == 'E') )
&& (Internal_Hard_NG()
|| Internal_Hard_GEN_GIN_GET_GIT()
|| Internal_Hard_G_Open_Syllable()
|| Internal_Hard_G_Other()))
{
return true;
}
return false;
}
/**
* Detect words where "-ge-" or "-gi-" get a 'hard' 'g'
* even though this is usually a 'soft' 'g' context
*
* @return true if 'hard' 'g' detected
*
*/
boolean Internal_Hard_G_Other()
{
if((StringAt(m_current, 4, "GETH", "GEAR", "GEIS", "GIRL", "GIVI", "GIVE", "GIFT",
"GIRD", "GIRT", "GILV", "GILD", "GELD", "")
&& !StringAt((m_current - 3), 6, "GINGIV", "") )
// "gish" but not "largish"
|| (StringAt((m_current + 1), 3, "ISH", "") && (m_current > 0) && !StringAt(0, 4, "LARG", ""))
|| (StringAt((m_current - 2), 5, "MAGED", "MEGID", "") && !((m_current + 2) == m_last))
|| StringAt(m_current, 3, "GEZ", "")
|| StringAt(0, 4, "WEGE", "HAGE", "")
|| (StringAt((m_current - 2), 6, "ONGEST", "UNGEST", "")
&& ((m_current + 3) == m_last)
&& !StringAt((m_current - 3), 7, "CONGEST", ""))
|| StringAt(0, 5, "VOEGE", "BERGE", "HELGE", "")
|| (StringAt(0, 4, "ENGE", "BOGY", "") && (m_length == 4))
|| StringAt(m_current, 6, "GIBBON", "")
|| StringAt(0, 10, "CORREGIDOR", "")
|| StringAt(0, 8, "INGEBORG", "")
|| (StringAt(m_current, 4, "GILL", "")
&& (((m_current + 3) == m_last) || ((m_current + 4) == m_last))
&& !StringAt(0, 8, "STURGILL", "")))
{
return true;
}
return false;
}
/**
* Detect words where "-gy-", "-gie-", "-gee-",
* or "-gio-" get a 'hard' 'g' even though this is
* usually a 'soft' 'g' context
*
* @return true if 'hard' 'g' detected
*
*/
boolean Internal_Hard_G_Open_Syllable()
{
if(StringAt((m_current + 1), 3, "EYE", "")
|| StringAt((m_current - 2), 4, "FOGY", "POGY", "YOGI", "")
|| StringAt((m_current - 2), 5, "MAGEE", "MCGEE", "HAGIO", "")
|| StringAt((m_current - 1), 4, "RGEY", "OGEY", "")
|| StringAt((m_current - 3), 5, "HOAGY", "STOGY", "PORGY", "")
|| StringAt((m_current - 5), 8, "CARNEGIE", "")
|| (StringAt((m_current - 1), 4, "OGEY", "OGIE", "") && ((m_current + 2) == m_last)))
{
return true;
}
return false;
}
/**
* Detect a number of contexts, mostly german names, that
* take a 'hard' 'g'.
*
* @return true if 'hard' 'g' detected, false if not
*
*/
boolean Internal_Hard_GEN_GIN_GET_GIT()
{
if((StringAt((m_current - 3), 6, "FORGET", "TARGET", "MARGIT", "MARGET", "TURGEN",
"BERGEN", "MORGEN", "JORGEN", "HAUGEN", "JERGEN",
"JURGEN", "LINGEN", "BORGEN", "LANGEN", "KLAGEN", "STIGER", "BERGER", "")
&& !StringAt(m_current, 7, "GENETIC", "GENESIS", "")
&& !StringAt((m_current - 4), 8, "PLANGENT", ""))
|| (StringAt((m_current - 3), 6, "BERGIN", "FEAGIN", "DURGIN", "") && ((m_current + 2) == m_last))
|| (StringAt((m_current - 2), 5, "ENGEN", "") && !StringAt((m_current + 3), 3, "DER", "ETI", "ESI", ""))
|| StringAt((m_current - 4), 7, "JUERGEN", "")
|| StringAt(0, 5, "NAGIN", "MAGIN", "HAGIN", "")
|| (StringAt(0, 5, "ENGIN", "DEGEN", "LAGEN", "MAGEN", "NAGIN", "") && (m_length == 5))
|| (StringAt((m_current - 2), 5, "BEGET", "BEGIN", "HAGEN", "FAGIN",
"BOGEN", "WIGIN", "NTGEN", "EIGEN",
"WEGEN", "WAGEN", "")
&& !StringAt((m_current - 5), 8, "OSPHAGEN", "")))
{
return true;
}
return false;
}
/**
* Detect a number of contexts of '-ng-' that will
* take a 'hard' 'g' despite being followed by a
* front vowel.
*
* @return true if 'hard' 'g' detected, false if not
*
*/
boolean Internal_Hard_NG()
{
if((StringAt((m_current - 3), 4, "DANG", "FANG", "SING", "")
// exception to exception
&& !StringAt((m_current - 5), 8, "DISINGEN", "") )
|| StringAt(0, 5, "INGEB", "ENGEB", "")
|| (StringAt((m_current - 3), 4, "RING", "WING", "HANG", "LONG", "")
&& !(StringAt((m_current - 4), 5, "CRING", "FRING", "ORANG", "TWING", "CHANG", "PHANG", "")
|| StringAt((m_current - 5), 6, "SYRING", "")
|| StringAt((m_current - 3), 7, "RINGENC", "RINGENT", "LONGITU", "LONGEVI", "")
// e.g. 'longino', 'mastrangelo'
|| (StringAt(m_current, 4, "GELO", "GINO", "") && ((m_current + 3) == m_last))))
|| (StringAt((m_current - 1), 3, "NGY", "")
// exceptions to exception
&& !(StringAt((m_current - 3), 5, "RANGY", "MANGY", "MINGY", "")
|| StringAt((m_current - 4), 6, "SPONGY", "STINGY", ""))))
{
return true;
}
return false;
}
/**
* Encode special case where "-GA-" => J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_GA_To_J()
{
// 'margary', 'margarine'
if((StringAt((m_current - 3), 7, "MARGARY", "MARGARI", "")
// but not in spanish forms such as "margatita"
&& !StringAt((m_current - 3), 8, "MARGARIT", ""))
|| StringAt(0, 4, "GAOL", "")
|| StringAt((m_current - 2), 5, "ALGAE", ""))
{
MetaphAddExactApprox("J", "G", "J", "K");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode 'H'
*
*
*/
void Encode_H()
{
if(Encode_Initial_Silent_H()
|| Encode_Initial_HS()
|| Encode_Initial_HU_HW()
|| Encode_Non_Initial_Silent_H())
{
return;
}
//only keep if first & before vowel or btw. 2 vowels
if(!Encode_H_Pronounced())
{
//also takes care of 'HH'
m_current++;
}
}
/**
* Encode cases where initial 'H' is not pronounced (in American)
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Initial_Silent_H()
{
//'hour', 'herb', 'heir', 'honor'
if(StringAt((m_current + 1), 3, "OUR", "ERB", "EIR", "")
|| StringAt((m_current + 1), 4, "ONOR", "")
|| StringAt((m_current + 1), 5, "ONOUR", "ONEST", ""))
{
// british pronounce H in this word
// americans give it 'H' for the name,
// no 'H' for the plant
if((m_current == 0) && StringAt(m_current, 4, "HERB", ""))
{
if(m_encodeVowels)
{
MetaphAdd("HA", "A");
}
else
{
MetaphAdd("H", "A");
}
}
else if((m_current == 0) || m_encodeVowels)
{
MetaphAdd("A");
}
m_current++;
// don't encode vowels twice
m_current = SkipVowels(m_current);
return true;
}
return false;
}
/**
* Encode "HS-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Initial_HS()
{
// old chinese pinyin transliteration
// e.g., 'HSIAO'
if ((m_current == 0) && StringAt(0, 2, "HS", ""))
{
MetaphAdd("X");
m_current += 2;
return true;
}
return false;
}
/**
* Encode cases where "HU-" is pronounced as part of a vowel dipthong
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Initial_HU_HW()
{
// spanish spellings and chinese pinyin transliteration
if (StringAt(0, 3, "HUA", "HUE", "HWA", ""))
{
if(!StringAt(m_current, 4, "HUEY", ""))
{
MetaphAdd("A");
if(!m_encodeVowels)
{
m_current += 3;
}
else
{
m_current++;
// don't encode vowels twice
while(IsVowel(m_current) || (CharAt(m_current) == 'W'))
{
m_current++;
}
}
return true;
}
}
return false;
}
/**
* Encode cases where 'H' is silent between vowels
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Non_Initial_Silent_H()
{
//exceptions - 'h' not pronounced
// "PROHIB" BUT NOT "PROHIBIT"
if(StringAt((m_current - 2), 5, "NIHIL", "VEHEM", "LOHEN", "NEHEM",
"MAHON", "MAHAN", "COHEN", "GAHAN", "")
|| StringAt((m_current - 3), 6, "GRAHAM", "PROHIB", "FRAHER",
"TOOHEY", "TOUHEY", "")
|| StringAt((m_current - 3), 5, "TOUHY", "")
|| StringAt(0, 9, "CHIHUAHUA", ""))
{
if(!m_encodeVowels)
{
m_current += 2;
}
else
{
m_current++;
// don't encode vowels twice
m_current = SkipVowels(m_current);
}
return true;
}
return false;
}
/**
* Encode cases where 'H' is pronounced
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_H_Pronounced()
{
if((((m_current == 0)
|| IsVowel(m_current - 1)
|| ((m_current > 0)
&& (CharAt(m_current - 1) == 'W')))
&& IsVowel(m_current + 1))
// e.g. 'alWahhab'
|| ((CharAt(m_current + 1) == 'H') && IsVowel(m_current + 2)))
{
MetaphAdd("H");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode 'J'
*
*/
void Encode_J()
{
if(Encode_Spanish_J()
|| Encode_Spanish_OJ_UJ())
{
return;
}
Encode_Other_J();
}
/**
* Encode cases where initial or medial "j" is in a spanish word or name
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Spanish_J()
{
//obvious spanish, e.g. "jose", "san jacinto"
if((StringAt((m_current + 1), 3, "UAN", "ACI", "ALI", "EFE", "ICA", "IME", "OAQ", "UAR", "")
&& !StringAt(m_current, 8, "JIMERSON", "JIMERSEN", ""))
|| (StringAt((m_current + 1), 3, "OSE", "") && ((m_current + 3) == m_last))
|| StringAt((m_current + 1), 4, "EREZ", "UNTA", "AIME", "AVIE", "AVIA", "")
|| StringAt((m_current + 1), 6, "IMINEZ", "ARAMIL", "")
|| (((m_current + 2) == m_last) && StringAt((m_current - 2), 5, "MEJIA", ""))
|| StringAt((m_current - 2), 5, "TEJED", "TEJAD", "LUJAN", "FAJAR", "BEJAR", "BOJOR", "CAJIG",
"DEJAS", "DUJAR", "DUJAN", "MIJAR", "MEJOR", "NAJAR",
"NOJOS", "RAJED", "RIJAL", "REJON", "TEJAN", "UIJAN", "")
|| StringAt((m_current - 3), 8, "ALEJANDR", "GUAJARDO", "TRUJILLO", "")
|| (StringAt((m_current - 2), 5, "RAJAS", "") && (m_current > 2))
|| (StringAt((m_current - 2), 5, "MEJIA", "") && !StringAt((m_current - 2), 6, "MEJIAN", ""))
|| StringAt((m_current - 1), 5, "OJEDA", "")
|| StringAt((m_current - 3), 5, "LEIJA", "MINJA", "")
|| StringAt((m_current - 3), 6, "VIAJES", "GRAJAL", "")
|| StringAt(m_current, 8, "JAUREGUI", "")
|| StringAt((m_current - 4), 8, "HINOJOSA", "")
|| StringAt(0, 4, "SAN ", "")
|| (((m_current + 1) == m_last)
&& (CharAt(m_current + 1) == 'O')
// exceptions
&& !(StringAt(0, 4, "TOJO", "")
|| StringAt(0, 5, "BANJO", "")
|| StringAt(0, 6, "MARYJO", ""))))
{
// americans pronounce "juan" as 'wan'
// and "marijuana" and "tijuana" also
// do not get the 'H' as in spanish, so
// just treat it like a vowel in these cases
if(!(StringAt(m_current, 4, "JUAN", "") || StringAt(m_current, 4, "JOAQ", "")))
{
MetaphAdd("H");
}
else
{
if(m_current == 0)
{
MetaphAdd("A");
}
}
AdvanceCounter(2, 1);
return true;
}
// Jorge gets 2nd HARHA. also JULIO, JESUS
if(StringAt((m_current + 1), 4, "ORGE", "ULIO", "ESUS", "")
&& !StringAt(0, 6, "JORGEN", ""))
{
// get both consonants for "jorge"
if(((m_current + 4) == m_last) && StringAt((m_current + 1), 4, "ORGE", ""))
{
if(m_encodeVowels)
{
MetaphAdd("JARJ", "HARHA");
}
else
{
MetaphAdd("JRJ", "HRH");
}
AdvanceCounter(5, 5);
return true;
}
MetaphAdd("J", "H");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode cases where 'J' is clearly in a german word or name
* that americans pronounce in the german fashion
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_German_J()
{
if(StringAt((m_current + 1), 2, "AH", "")
|| (StringAt((m_current + 1), 5, "OHANN", "") && ((m_current + 5) == m_last))
|| (StringAt((m_current + 1), 3, "UNG", "") && !StringAt((m_current + 1), 4, "UNGL", ""))
|| StringAt((m_current + 1), 3, "UGO", ""))
{
MetaphAdd("A");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode "-JOJ-" and "-JUJ-" as spanish words
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Spanish_OJ_UJ()
{
if(StringAt((m_current + 1), 5, "OJOBA", "UJUY ", ""))
{
if(m_encodeVowels)
{
MetaphAdd("HAH");
}
else
{
MetaphAdd("HH");
}
AdvanceCounter(4, 3);
return true;
}
return false;
}
/**
* Encode 'J' => J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_J_To_J()
{
if(IsVowel(m_current + 1))
{
if((m_current == 0)
&& Names_Beginning_With_J_That_Get_Alt_Y())
{
// 'Y' is a vowel so encode
// is as 'A'
if(m_encodeVowels)
{
MetaphAdd("JA", "A");
}
else
{
MetaphAdd("J", "A");
}
}
else
{
if(m_encodeVowels)
{
MetaphAdd("JA");
}
else
{
MetaphAdd("J");
}
}
m_current++;
m_current = SkipVowels(m_current);
return false;
}
else
{
MetaphAdd("J");
m_current++;
return true;
}
// return false;
}
/**
* Encode 'J' toward end in spanish words
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Spanish_J_2()
{
// spanish forms e.g. "brujo", "badajoz"
if((((m_current - 2) == 0)
&& StringAt((m_current - 2), 4, "BOJA", "BAJA", "BEJA", "BOJO", "MOJA", "MOJI", "MEJI", ""))
|| (((m_current - 3) == 0)
&& StringAt((m_current - 3), 5, "FRIJO", "BRUJO", "BRUJA", "GRAJE", "GRIJA", "LEIJA", "QUIJA", ""))
|| (((m_current + 3) == m_last)
&& StringAt((m_current - 1), 5, "AJARA", ""))
|| (((m_current + 2) == m_last)
&& StringAt((m_current - 1), 4, "AJOS", "EJOS", "OJAS", "OJOS", "UJON", "AJOZ", "AJAL", "UJAR", "EJON", "EJAN", ""))
|| (((m_current + 1) == m_last)
&& (StringAt((m_current - 1), 3, "OJA", "EJA", "") && !StringAt(0, 4, "DEJA", ""))))
{
MetaphAdd("H");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode 'J' as vowel in some exception cases
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_J_As_Vowel()
{
if(StringAt(m_current, 5, "JEWSK", ""))
{
MetaphAdd("J", "");
return true;
}
// e.g. "stijl", "sejm" - dutch, scandanavian, and eastern european spellings
if((StringAt((m_current + 1), 1, "L", "T", "K", "S", "N", "M", "")
// except words from hindi and arabic
&& !StringAt((m_current + 2), 1, "A", ""))
|| StringAt(0, 9, "HALLELUJA", "LJUBLJANA", "")
|| StringAt(0, 4, "LJUB", "BJOR", "")
|| StringAt(0, 5, "HAJEK", "")
|| StringAt(0, 3, "WOJ", "")
// e.g. 'fjord'
|| StringAt(0, 2, "FJ", "")
// e.g. 'rekjavik', 'blagojevic'
|| StringAt(m_current, 5, "JAVIK", "JEVIC", "")
|| (((m_current + 1) == m_last) && StringAt(0, 5, "SONJA", "TANJA", "TONJA", "")))
{
return true;
}
return false;
}
/**
* Call routines to encode 'J', in proper order
*
*/
void Encode_Other_J()
{
if(m_current == 0)
{
if(Encode_German_J())
{
return;
}
else
{
if(Encode_J_To_J())
{
return;
}
}
}
else
{
if(Encode_Spanish_J_2())
{
return;
}
else if(!Encode_J_As_Vowel())
{
MetaphAdd("J");
}
//it could happen! e.g. "hajj"
// eat redundant 'J'
if(CharAt(m_current + 1) == 'J')
{
m_current += 2;
}
else
{
m_current++;
}
}
}
/**
* Encode 'K'
*
*
*/
void Encode_K()
{
if(!Encode_Silent_K())
{
MetaphAdd("K");
// eat redundant 'K's and 'Q's
if((CharAt(m_current + 1) == 'K')
|| (CharAt(m_current + 1) == 'Q'))
{
m_current += 2;
}
else
{
m_current++;
}
}
}
/**
* Encode cases where 'K' is not pronounced
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_K()
{
//skip this except for special cases
if((m_current == 0)
&& StringAt(m_current, 2, "KN", ""))
{
if(!(StringAt((m_current + 2), 5, "ESSET", "IEVEL", "") || StringAt((m_current + 2), 3, "ISH", "") ))
{
m_current += 1;
return true;
}
}
// e.g. "know", "knit", "knob"
if((StringAt((m_current + 1), 3, "NOW", "NIT", "NOT", "NOB", "")
// exception, "slipknot" => SLPNT but "banknote" => PNKNT
&& !StringAt(0, 8, "BANKNOTE", ""))
|| StringAt((m_current + 1), 4, "NOCK", "NUCK", "NIFE", "NACK", "")
|| StringAt((m_current + 1), 5, "NIGHT", ""))
{
// N already encoded before
// e.g. "penknife"
if ((m_current > 0) && CharAt(m_current - 1) == 'N')
{
m_current += 2;
}
else
{
m_current++;
}
return true;
}
return false;
}
/**
* Encode 'L'
*
* Includes special vowel transposition
* encoding, where 'LE' => AL
*
*/
void Encode_L()
{
// logic below needs to know this
// after 'm_current' variable changed
int save_current = m_current;
Interpolate_Vowel_When_Cons_L_At_End();
if(Encode_LELY_To_L()
|| Encode_COLONEL()
|| Encode_French_AULT()
|| Encode_French_EUIL()
|| Encode_French_OULX()
|| Encode_Silent_L_In_LM()
|| Encode_Silent_L_In_LK_LV()
|| Encode_Silent_L_In_OULD())
{
return;
}
if(Encode_LL_As_Vowel_Cases())
{
return;
}
Encode_LE_Cases(save_current);
}
/**
* Cases where an L follows D, G, or T at the
* end have a schwa pronounced before the L
*
*/
void Interpolate_Vowel_When_Cons_L_At_End()
{
if(m_encodeVowels == true)
{
// e.g. "ertl", "vogl"
if((m_current == m_last)
&& StringAt((m_current - 1), 1, "D", "G", "T", ""))
{
MetaphAdd("A");
}
}
}
/**
* Catch cases where 'L' spelled twice but pronounced
* once, e.g., 'DOCILELY' => TSL
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_LELY_To_L()
{
// e.g. "agilely", "docilely"
if(StringAt((m_current - 1), 5, "ILELY", "")
&& ((m_current + 3) == m_last))
{
MetaphAdd("L");
m_current += 3;
return true;
}
return false;
}
/**
* Encode special case "colonel" => KRNL. Can somebody tell
* me how this pronounciation came to be?
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_COLONEL()
{
if(StringAt((m_current - 2), 7, "COLONEL", ""))
{
MetaphAdd("R");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-AULT-", found in a french names
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_French_AULT()
{
// e.g. "renault" and "foucault", well known to americans, but not "fault"
if((m_current > 3)
&& (StringAt((m_current - 3), 5, "RAULT", "NAULT", "BAULT", "SAULT", "GAULT", "CAULT", "")
|| StringAt((m_current - 4), 6, "REAULT", "RIAULT", "NEAULT", "BEAULT", ""))
&& !(RootOrInflections(m_inWord, "ASSAULT")
|| StringAt((m_current - 8), 10, "SOMERSAULT","")
|| StringAt((m_current - 9), 11, "SUMMERSAULT", "")))
{
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-EUIL-", always found in a french word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_French_EUIL()
{
// e.g. "auteuil"
if(StringAt((m_current - 3), 4, "EUIL", "") && (m_current == m_last))
{
m_current++;
return true;
}
return false;
}
/**
* Encode "-OULX", always found in a french word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_French_OULX()
{
// e.g. "proulx"
if(StringAt((m_current - 2), 4, "OULX", "") && ((m_current + 1) == m_last))
{
m_current += 2;
return true;
}
return false;
}
/**
* Encodes contexts where 'L' is not pronounced in "-LM-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_L_In_LM()
{
if(StringAt(m_current, 2, "LM", "LN", ""))
{
// e.g. "lincoln", "holmes", "psalm", "salmon"
if((StringAt((m_current - 2), 4, "COLN", "CALM", "BALM", "MALM", "PALM", "")
|| (StringAt((m_current - 1), 3, "OLM", "") && ((m_current + 1) == m_last))
|| StringAt((m_current - 3), 5, "PSALM", "QUALM", "")
|| StringAt((m_current - 2), 6, "SALMON", "HOLMES", "")
|| StringAt((m_current - 1), 6, "ALMOND", "")
|| ((m_current == 1) && StringAt((m_current - 1), 4, "ALMS", "") ))
&& (!StringAt((m_current + 2), 1, "A", "")
&& !StringAt((m_current - 2), 5, "BALMO", "")
&& !StringAt((m_current - 2), 6, "PALMER", "PALMOR", "BALMER", "")
&& !StringAt((m_current - 3), 5, "THALM", "")))
{
m_current++;
return true;
}
else
{
MetaphAdd("L");
m_current++;
return true;
}
}
return false;
}
/**
* Encodes contexts where '-L-' is silent in 'LK', 'LV'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_L_In_LK_LV()
{
if((StringAt((m_current - 2), 4, "WALK", "YOLK", "FOLK", "HALF", "TALK", "CALF", "BALK", "CALK", "")
|| (StringAt((m_current - 2), 4, "POLK", "")
&& !StringAt((m_current - 2), 5, "POLKA", "WALKO", ""))
|| (StringAt((m_current - 2), 4, "HALV", "")
&& !StringAt((m_current - 2), 5, "HALVA", "HALVO", ""))
|| (StringAt((m_current - 3), 5, "CAULK", "CHALK", "BAULK", "FAULK", "")
&& !StringAt((m_current - 4), 6, "SCHALK", ""))
|| (StringAt((m_current - 2), 5, "SALVE", "CALVE", "")
|| StringAt((m_current - 2), 6, "SOLDER", ""))
// exceptions to above cases where 'L' is usually pronounced
&& !StringAt((m_current - 2), 6, "SALVER", "CALVER", ""))
&& !StringAt((m_current - 5), 9, "GONSALVES", "GONCALVES", "")
&& !StringAt((m_current - 2), 6, "BALKAN", "TALKAL", "")
&& !StringAt((m_current - 3), 5, "PAULK", "CHALF", ""))
{
m_current++;
return true;
}
return false;
}
/**
* Encode 'L' in contexts of "-OULD-" where it is silent
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_L_In_OULD()
{
//'would', 'could'
if(StringAt((m_current - 3), 5, "WOULD", "COULD", "")
|| (StringAt((m_current - 4), 6, "SHOULD", "")
&& !StringAt((m_current - 4), 8, "SHOULDER", "")))
{
MetaphAddExactApprox("D", "T");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-ILLA-" and "-ILLE-" in spanish and french
* contexts were americans know to pronounce it as a 'Y'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_LL_As_Vowel_Special_Cases()
{
if(StringAt((m_current - 5), 8, "TORTILLA", "")
|| StringAt((m_current - 8), 11, "RATATOUILLE", "")
// e.g. 'guillermo', "veillard"
|| (StringAt(0, 5, "GUILL", "VEILL", "GAILL", "")
// 'guillotine' usually has '-ll-' pronounced as 'L' in english
&& !(StringAt((m_current - 3), 7, "GUILLOT", "GUILLOR", "GUILLEN", "")
|| (StringAt(0, 5, "GUILL", "") && (m_length == 5))))
// e.g. "brouillard", "gremillion"
|| StringAt(0, 7, "BROUILL", "GREMILL", "ROBILL", "")
// e.g. 'mireille'
|| (StringAt((m_current - 2), 5, "EILLE", "")
&& ((m_current + 2) == m_last)
// exception "reveille" usually pronounced as 're-vil-lee'
&& !StringAt((m_current - 5), 8, "REVEILLE", "")))
{
m_current += 2;
return true;
}
return false;
}
/**
* Encode other spanish cases where "-LL-" is pronounced as 'Y'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_LL_As_Vowel()
{
//spanish e.g. "cabrillo", "gallegos" but also "gorilla", "ballerina" -
// give both pronounciations since an american might pronounce "cabrillo"
// in the spanish or the american fashion.
if((((m_current + 3) == m_length)
&& StringAt((m_current - 1), 4, "ILLO", "ILLA", "ALLE", ""))
|| (((StringAt((m_last - 1), 2, "AS", "OS", "")
|| StringAt(m_last, 2, "AS", "OS", "")
|| StringAt(m_last, 1, "A", "O", ""))
&& StringAt((m_current - 1), 2, "AL", "IL", ""))
&& !StringAt((m_current - 1), 4, "ALLA", ""))
|| StringAt(0, 5, "VILLE", "VILLA", "")
|| StringAt(0, 8, "GALLARDO", "VALLADAR", "MAGALLAN", "CAVALLAR", "BALLASTE", "")
|| StringAt(0, 3, "LLA", ""))
{
MetaphAdd("L", "");
m_current += 2;
return true;
}
return false;
}
/**
* Call routines to encode "-LL-", in proper order
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_LL_As_Vowel_Cases()
{
if(CharAt(m_current + 1) == 'L')
{
if(Encode_LL_As_Vowel_Special_Cases())
{
return true;
}
else if(Encode_LL_As_Vowel())
{
return true;
}
m_current += 2;
}
else
{
m_current++;
}
return false;
}
/**
* Encode vowel-encoding cases where "-LE-" is pronounced "-EL-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Vowel_LE_Transposition(int save_current)
{
// transposition of vowel sound and L occurs in many words,
// e.g. "bristle", "dazzle", "goggle" => KAKAL
if(m_encodeVowels
&& (save_current > 1)
&& !IsVowel(save_current - 1)
&& (CharAt(save_current + 1) == 'E')
&& (CharAt(save_current - 1) != 'L')
&& (CharAt(save_current - 1) != 'R')
// lots of exceptions to this:
&& !IsVowel(save_current + 2)
&& !StringAt(0, 7, "ECCLESI", "COMPLEC", "COMPLEJ", "ROBLEDO", "")
&& !StringAt(0, 5, "MCCLE", "MCLEL", "")
&& !StringAt(0, 6, "EMBLEM", "KADLEC", "")
&& !(((save_current + 2) == m_last) && StringAt(save_current, 3, "LET", ""))
&& !StringAt(save_current, 7, "LETTING", "")
&& !StringAt(save_current, 6, "LETELY", "LETTER", "LETION", "LETIAN", "LETING", "LETORY", "")
&& !StringAt(save_current, 5, "LETUS", "LETIV", "")
&& !StringAt(save_current, 4, "LESS", "LESQ", "LECT", "LEDG", "LETE", "LETH", "LETS", "LETT", "")
&& !StringAt(save_current, 3, "LEG", "LER", "LEX", "")
// e.g. "complement" !=> KAMPALMENT
&& !(StringAt(save_current, 6, "LEMENT", "")
&& !(StringAt((m_current - 5), 6, "BATTLE", "TANGLE", "PUZZLE", "RABBLE", "BABBLE", "")
|| StringAt((m_current - 4), 5, "TABLE", "")))
&& !(((save_current + 2) == m_last) && StringAt((save_current - 2), 5, "OCLES", "ACLES", "AKLES", ""))
&& !StringAt((save_current - 3), 5, "LISLE", "AISLE", "")
&& !StringAt(0, 4, "ISLE", "")
&& !StringAt(0, 6, "ROBLES", "")
&& !StringAt((save_current - 4), 7, "PROBLEM", "RESPLEN", "")
&& !StringAt((save_current - 3), 6, "REPLEN", "")
&& !StringAt((save_current - 2), 4, "SPLE", "")
&& (CharAt(save_current - 1) != 'H')
&& (CharAt(save_current - 1) != 'W'))
{
MetaphAdd("AL");
flag_AL_inversion = true;
// eat redundant 'L'
if(CharAt(save_current + 2) == 'L')
{
m_current = save_current + 3;
}
return true;
}
return false;
}
/**
* Encode special vowel-encoding cases where 'E' is not
* silent at the end of a word as is the usual case
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Vowel_Preserve_Vowel_After_L(int save_current)
{
// an example of where the vowel would NOT need to be preserved
// would be, say, "hustled", where there is no vowel pronounced
// between the 'l' and the 'd'
if(m_encodeVowels
&& !IsVowel(save_current - 1)
&& (CharAt(save_current + 1) == 'E')
&& (save_current > 1)
&& ((save_current + 1) != m_last)
&& !(StringAt((save_current + 1), 2, "ES", "ED", "")
&& ((save_current + 2) == m_last))
&& !StringAt((save_current - 1), 5, "RLEST", "") )
{
MetaphAdd("LA");
m_current = SkipVowels(m_current);
return true;
}
return false;
}
/**
* Call routines to encode "-LE-", in proper order
*
* @param save_current index of actual current letter
*
*/
void Encode_LE_Cases(int save_current)
{
if(Encode_Vowel_LE_Transposition(save_current))
{
return;
}
else
{
if(Encode_Vowel_Preserve_Vowel_After_L(save_current))
{
return;
}
else
{
MetaphAdd("L");
}
}
}
/**
* Encode "-M-"
*
*/
void Encode_M()
{
if(Encode_Silent_M_At_Beginning()
|| Encode_MR_And_MRS()
|| Encode_MAC()
|| Encode_MPT())
{
return;
}
// Silent 'B' should really be handled
// under 'B", not here under 'M'!
Encode_MB();
MetaphAdd("M");
}
/**
* Encode cases where 'M' is silent at beginning of word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_M_At_Beginning()
{
//skip these when at start of word
if((m_current == 0)
&& StringAt(m_current, 2, "MN", ""))
{
m_current += 1;
return true;
}
return false;
}
/**
* Encode special cases "Mr." and "Mrs."
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_MR_And_MRS()
{
if((m_current == 0) && StringAt(m_current, 2, "MR", ""))
{
// exceptions for "mr." and "mrs."
if((m_length == 2) && StringAt(m_current, 2, "MR", ""))
{
if(m_encodeVowels)
{
MetaphAdd("MASTAR");
}
else
{
MetaphAdd("MSTR");
}
m_current += 2;
return true;
}
else if((m_length == 3) && StringAt(m_current, 3, "MRS", ""))
{
if(m_encodeVowels)
{
MetaphAdd("MASAS");
}
else
{
MetaphAdd("MSS");
}
m_current += 3;
return true;
}
}
return false;
}
/**
* Encode "Mac-" and "Mc-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_MAC()
{
// should only find irish and
// scottish names e.g. 'macintosh'
if((m_current == 0)
&& (StringAt(0, 7, "MACIVER", "MACEWEN", "")
|| StringAt(0, 8, "MACELROY", "MACILROY", "")
|| StringAt(0, 9, "MACINTOSH", "")
|| StringAt(0, 2, "MC", "") ))
{
if(m_encodeVowels)
{
MetaphAdd("MAK");
}
else
{
MetaphAdd("MK");
}
if(StringAt(0, 2, "MC", ""))
{
if(StringAt((m_current + 2), 1, "K", "G", "Q", "")
// watch out for e.g. "McGeorge"
&& !StringAt((m_current + 2), 4, "GEOR", ""))
{
m_current += 3;
}
else
{
m_current += 2;
}
}
else
{
m_current += 3;
}
return true;
}
return false;
}
/**
* Encode silent 'M' in context of "-MPT-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_MPT()
{
if(StringAt((m_current - 2), 8, "COMPTROL", "")
|| StringAt((m_current - 4), 7, "ACCOMPT", ""))
{
MetaphAdd("N");
m_current += 2;
return true;
}
return false;
}
/**
* Test if 'B' is silent in these contexts
*
* @return true if 'B' is silent in this context
*
*/
boolean Test_Silent_MB_1()
{
// e.g. "LAMB", "COMB", "LIMB", "DUMB", "BOMB"
// Handle combining roots first
if (((m_current == 3)
&& StringAt((m_current - 3), 5, "THUMB", ""))
|| ((m_current == 2)
&& StringAt((m_current - 2), 4, "DUMB", "BOMB", "DAMN", "LAMB", "NUMB", "TOMB", "") ))
{
return true;
}
return false;
}
/**
* Test if 'B' is pronounced in this context
*
* @return true if 'B' is pronounced in this context
*
*/
boolean Test_Pronounced_MB()
{
if (StringAt((m_current - 2), 6, "NUMBER", "")
|| (StringAt((m_current + 2), 1, "A", "")
&& !StringAt((m_current - 2), 7, "DUMBASS", ""))
|| StringAt((m_current + 2), 1, "O", "")
|| StringAt((m_current - 2), 6, "LAMBEN", "LAMBER", "LAMBET", "TOMBIG", "LAMBRE", ""))
{
return true;
}
return false;
}
/**
* Test whether "-B-" is silent in these contexts
*
* @return true if 'B' is silent in this context
*
*/
boolean Test_Silent_MB_2()
{
// 'M' is the current letter
if ((CharAt(m_current + 1) == 'B') && (m_current > 1)
&& (((m_current + 1) == m_last)
// other situations where "-MB-" is at end of root
// but not at end of word. The tests are for standard
// noun suffixes.
// e.g. "climbing" => KLMNK
|| StringAt((m_current + 2), 3, "ING", "ABL", "")
|| StringAt((m_current + 2), 4, "LIKE", "")
|| ((CharAt(m_current + 2) == 'S') && ((m_current + 2) == m_last))
|| StringAt((m_current - 5), 7, "BUNCOMB", "")
// e.g. "bomber",
|| (StringAt((m_current + 2), 2, "ED", "ER", "")
&& ((m_current + 3) == m_last)
&& (StringAt(0, 5, "CLIMB", "PLUMB", "")
// e.g. "beachcomber"
|| !StringAt((m_current - 1), 5, "IMBER", "AMBER", "EMBER", "UMBER", ""))
// exceptions
&& !StringAt((m_current - 2), 6, "CUMBER", "SOMBER", "") ) ) )
{
return true;
}
return false;
}
/**
* Test if 'B' is pronounced in these "-MB-" contexts
*
* @return true if "-B-" is pronounced in these contexts
*
*/
boolean Test_Pronounced_MB_2()
{
// e.g. "bombastic", "umbrage", "flamboyant"
if (StringAt((m_current - 1), 5, "OMBAS", "OMBAD", "UMBRA", "")
|| StringAt((m_current - 3), 4, "FLAM", "") )
{
return true;
}
return false;
}
/**
* Tests for contexts where "-N-" is silent when after "-M-"
*
* @return true if "-N-" is silent in these contexts
*
*/
boolean Test_MN()
{
if ((CharAt(m_current + 1) == 'N')
&& (((m_current + 1) == m_last)
// or at the end of a word but followed by suffixes
|| (StringAt((m_current + 2), 3, "ING", "EST", "") && ((m_current + 4) == m_last))
|| ((CharAt(m_current + 2) == 'S') && ((m_current + 2) == m_last))
|| (StringAt((m_current + 2), 2, "LY", "ER", "ED", "")
&& ((m_current + 3) == m_last))
|| StringAt((m_current - 2), 9, "DAMNEDEST", "")
|| StringAt((m_current - 5), 9, "GODDAMNIT", "") ))
{
return true;
}
return false;
}
/**
* Call routines to encode "-MB-", in proper order
*
*/
void Encode_MB()
{
if(Test_Silent_MB_1())
{
if(Test_Pronounced_MB())
{
m_current++;
}
else
{
m_current += 2;
}
}
else if(Test_Silent_MB_2())
{
if(Test_Pronounced_MB_2())
{
m_current++;
}
else
{
m_current += 2;
}
}
else if(Test_MN())
{
m_current += 2;
}
else
{
// eat redundant 'M'
if (CharAt(m_current + 1) == 'M')
{
m_current += 2;
}
else
{
m_current++;
}
}
}
/**
* Encode "-N-"
*
*/
void Encode_N()
{
if(Encode_NCE())
{
return;
}
// eat redundant 'N'
if(CharAt(m_current + 1) == 'N')
{
m_current += 2;
}
else
{
m_current++;
}
if (!StringAt((m_current - 3), 8, "MONSIEUR", "")
// e.g. "aloneness",
&& !StringAt((m_current - 3), 6, "NENESS", ""))
{
MetaphAdd("N");
}
}
/**
* Encode "-NCE-" and "-NSE-"
* "entrance" is pronounced exactly the same as "entrants"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_NCE()
{
//'acceptance', 'accountancy'
if(StringAt((m_current + 1), 1, "C", "S", "")
&& StringAt((m_current + 2), 1, "E", "Y", "I", "")
&& (((m_current + 2) == m_last)
|| (((m_current + 3) == m_last))
&& (CharAt(m_current + 3) == 'S')))
{
MetaphAdd("NTS");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-P-"
*
*/
void Encode_P()
{
if(Encode_Silent_P_At_Beginning()
|| Encode_PT()
|| Encode_PH()
|| Encode_PPH()
|| Encode_RPS()
|| Encode_COUP()
|| Encode_PNEUM()
|| Encode_PSYCH()
|| Encode_PSALM())
{
return;
}
Encode_PB();
MetaphAdd("P");
}
/**
* Encode cases where "-P-" is silent at the start of a word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_P_At_Beginning()
{
//skip these when at start of word
if((m_current == 0)
&& StringAt(m_current, 2, "PN", "PF", "PS", "PT", ""))
{
m_current += 1;
return true;
}
return false;
}
/**
* Encode cases where "-P-" is silent before "-T-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_PT()
{
// 'pterodactyl', 'receipt', 'asymptote'
if((CharAt(m_current + 1) == 'T'))
{
if (((m_current == 0) && StringAt(m_current, 5, "PTERO", ""))
|| StringAt((m_current - 5), 7, "RECEIPT", "")
|| StringAt((m_current - 4), 8, "ASYMPTOT", ""))
{
MetaphAdd("T");
m_current += 2;
return true;
}
}
return false;
}
/**
* Encode "-PH-", usually as F, with exceptions for
* cases where it is silent, or where the 'P' and 'T'
* are pronounced seperately because they belong to
* two different words in a combining form
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_PH()
{
if(CharAt(m_current + 1) == 'H')
{
// 'PH' silent in these contexts
if (StringAt(m_current, 9, "PHTHALEIN", "")
|| ((m_current == 0) && StringAt(m_current, 4, "PHTH", ""))
|| StringAt((m_current - 3), 10, "APOPHTHEGM", ""))
{
MetaphAdd("0");
m_current += 4;
}
// combining forms
//'sheepherd', 'upheaval', 'cupholder'
else if((m_current > 0)
&& (StringAt((m_current + 2), 3, "EAD", "OLE", "ELD", "ILL", "OLD", "EAP", "ERD",
"ARD", "ANG", "ORN", "EAV", "ART", "")
|| StringAt((m_current + 2), 4, "OUSE", "")
|| (StringAt((m_current + 2), 2, "AM", "") && !StringAt((m_current -1), 5, "LPHAM", ""))
|| StringAt((m_current + 2), 5, "AMMER", "AZARD", "UGGER", "")
|| StringAt((m_current + 2), 6, "OLSTER", ""))
&& !StringAt((m_current - 3), 5, "LYMPH", "NYMPH", ""))
{
MetaphAdd("P");
AdvanceCounter(3, 2);
}
else
{
MetaphAdd("F");
m_current += 2;
}
return true;
}
return false;
}
/**
* Encode "-PPH-". I don't know why the greek poet's
* name is transliterated this way...
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_PPH()
{
// 'sappho'
if((CharAt(m_current + 1) == 'P')
&& ((m_current + 2) < m_length) && (CharAt(m_current + 2) == 'H'))
{
MetaphAdd("F");
m_current += 3;
return true;
}
return false;
}
/**
* Encode "-CORPS-" where "-PS-" not pronounced
* since the cognate is here from the french
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_RPS()
{
//'-corps-', 'corpsman'
if(StringAt((m_current - 3), 5, "CORPS", "")
&& !StringAt((m_current - 3), 6, "CORPSE", ""))
{
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-COUP-" where "-P-" is not pronounced
* since the word is from the french
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_COUP()
{
//'coup'
if((m_current == m_last)
&& StringAt((m_current - 3), 4, "COUP", "")
&& !StringAt((m_current - 5), 6, "RECOUP", ""))
{
m_current++;
return true;
}
return false;
}
/**
* Encode 'P' in non-initial contexts of "-PNEUM-"
* where is also silent
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_PNEUM()
{
//'-pneum-'
if(StringAt((m_current + 1), 4, "NEUM", ""))
{
MetaphAdd("N");
m_current += 2;
return true;
}
return false;
}
/**
* Encode special case "-PSYCH-" where two encodings need to be
* accounted for in one syllable, one for the 'PS' and one for
* the 'CH'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_PSYCH()
{
//'-psych-'
if(StringAt((m_current + 1), 4, "SYCH", ""))
{
if(m_encodeVowels)
{
MetaphAdd("SAK");
}
else
{
MetaphAdd("SK");
}
m_current += 5;
return true;
}
return false;
}
/**
* Encode 'P' in context of "-PSALM-", where it has
* become silent
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_PSALM()
{
//'-psalm-'
if(StringAt((m_current + 1), 4, "SALM", ""))
{
// go ahead and encode entire word
if(m_encodeVowels)
{
MetaphAdd("SAM");
}
else
{
MetaphAdd("SM");
}
m_current += 5;
return true;
}
return false;
}
/**
* Eat redundant 'B' or 'P'
*
*/
void Encode_PB()
{
// e.g. "campbell", "raspberry"
// eat redundant 'P' or 'B'
if(StringAt((m_current + 1), 1, "P", "B", ""))
{
m_current += 2;
}
else
{
m_current++;
}
}
/**
* Encode "-Q-"
*
*/
void Encode_Q()
{
// current pinyin
if(StringAt(m_current, 3, "QIN", ""))
{
MetaphAdd("X");
m_current++;
return;
}
// eat redundant 'Q'
if(CharAt(m_current + 1) == 'Q')
{
m_current += 2;
}
else
{
m_current++;
}
MetaphAdd("K");
}
/**
* Encode "-R-"
*
*/
void Encode_R()
{
if(Encode_RZ())
{
return;
}
if(!Test_Silent_R())
{
if(!Encode_Vowel_RE_Transposition())
{
MetaphAdd("R");
}
}
// eat redundant 'R'; also skip 'S' as well as 'R' in "poitiers"
if((CharAt(m_current + 1) == 'R') || StringAt((m_current - 6), 8, "POITIERS", ""))
{
m_current += 2;
}
else
{
m_current++;
}
}
/**
* Encode "-RZ-" according
* to american and polish pronunciations
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_RZ()
{
if(StringAt((m_current - 2), 4, "GARZ", "KURZ", "MARZ", "MERZ", "HERZ", "PERZ", "WARZ", "")
|| StringAt(m_current, 5, "RZANO", "RZOLA", "")
|| StringAt((m_current - 1), 4, "ARZA", "ARZN", ""))
{
return false;
}
// 'yastrzemski' usually has 'z' silent in
// united states, but should get 'X' in poland
if(StringAt((m_current - 4), 11, "YASTRZEMSKI", ""))
{
MetaphAdd("R", "X");
m_current += 2;
return true;
}
// 'BRZEZINSKI' gets two pronunciations
// in the united states, neither of which
// are authentically polish
if(StringAt((m_current - 1), 10, "BRZEZINSKI", ""))
{
MetaphAdd("RS", "RJ");
// skip over 2nd 'Z'
m_current += 4;
return true;
}
// 'z' in 'rz after voiceless consonant gets 'X'
// in alternate polish style pronunciation
else if(StringAt((m_current - 1), 3, "TRZ", "PRZ", "KRZ", "")
|| (StringAt(m_current, 2, "RZ", "")
&& (IsVowel(m_current - 1) || (m_current == 0))))
{
MetaphAdd("RS", "X");
m_current += 2;
return true;
}
// 'z' in 'rz after voiceled consonant, vowel, or at
// beginning gets 'J' in alternate polish style pronunciation
else if(StringAt((m_current - 1), 3, "BRZ", "DRZ", "GRZ", ""))
{
MetaphAdd("RS", "J");
m_current += 2;
return true;
}
return false;
}
/**
* Test whether 'R' is silent in this context
*
* @return true if 'R' is silent in this context
*
*/
boolean Test_Silent_R()
{
// test cases where 'R' is silent, either because the
// word is from the french or because it is no longer pronounced.
// e.g. "rogier", "monsieur", "surburban"
if(((m_current == m_last)
// reliably french word ending
&& StringAt((m_current - 2), 3, "IER", "")
// e.g. "metier"
&& (StringAt((m_current - 5), 3, "MET", "VIV", "LUC", "")
// e.g. "cartier", "bustier"
|| StringAt((m_current - 6), 4, "CART", "DOSS", "FOUR", "OLIV", "BUST", "DAUM", "ATEL",
"SONN", "CORM", "MERC", "PELT", "POIR", "BERN", "FORT", "GREN",
"SAUC", "GAGN", "GAUT", "GRAN", "FORC", "MESS", "LUSS", "MEUN",
"POTH", "HOLL", "CHEN", "")
// e.g. "croupier"
|| StringAt((m_current - 7), 5, "CROUP", "TORCH", "CLOUT", "FOURN", "GAUTH", "TROTT",
"DEROS", "CHART", "")
// e.g. "chevalier"
|| StringAt((m_current - 8), 6, "CHEVAL", "LAVOIS", "PELLET", "SOMMEL", "TREPAN", "LETELL", "COLOMB", "")
|| StringAt((m_current - 9), 7, "CHARCUT", "")
|| StringAt((m_current - 10), 8, "CHARPENT", "")))
|| StringAt((m_current - 2), 7, "SURBURB", "WORSTED", "")
|| StringAt((m_current - 2), 9, "WORCESTER", "")
|| StringAt((m_current - 7), 8, "MONSIEUR", "")
|| StringAt((m_current - 6), 8, "POITIERS", "") )
{
return true;
}
return false;
}
/**
* Encode '-re-" as 'AR' in contexts
* where this is the correct pronunciation
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Vowel_RE_Transposition()
{
// -re inversion is just like
// -le inversion
// e.g. "fibre" => FABAR or "centre" => SANTAR
if((m_encodeVowels)
&& (CharAt(m_current + 1) == 'E')
&& (m_length > 3)
&& !StringAt(0, 5, "OUTRE", "LIBRE", "ANDRE", "")
&& !(StringAt(0, 4, "FRED", "TRES", "") && (m_length == 4))
&& !StringAt((m_current - 2), 5, "LDRED", "LFRED", "NDRED", "NFRED", "NDRES", "TRES", "IFRED", "")
&& !IsVowel(m_current - 1)
&& (((m_current + 1) == m_last)
|| (((m_current + 2) == m_last)
&& StringAt((m_current + 2), 1, "D", "S", ""))))
{
MetaphAdd("AR");
return true;
}
return false;
}
/**
* Encode "-S-"
*
*/
void Encode_S()
{
if(Encode_SKJ()
|| Encode_Special_SW()
|| Encode_SJ()
|| Encode_Silent_French_S_Final()
|| Encode_Silent_French_S_Internal()
|| Encode_ISL()
|| Encode_STL()
|| Encode_Christmas()
|| Encode_STHM()
|| Encode_ISTEN()
|| Encode_Sugar()
|| Encode_SH()
|| Encode_SCH()
|| Encode_SUR()
|| Encode_SU()
|| Encode_SSIO()
|| Encode_SS()
|| Encode_SIA()
|| Encode_SIO()
|| Encode_Anglicisations()
|| Encode_SC()
|| Encode_SEA_SUI_SIER()
|| Encode_SEA())
{
return;
}
MetaphAdd("S");
if(StringAt((m_current + 1), 1, "S", "Z", "")
&& !StringAt((m_current + 1), 2, "SH", ""))
{
m_current += 2;
}
else
{
m_current++;
}
}
/**
* Encode a couple of contexts where scandinavian, slavic
* or german names should get an alternate, native
* pronunciation of 'SV' or 'XV'
*
* @return true if handled
*
*/
boolean Encode_Special_SW()
{
if(m_current == 0)
{
if(Names_Beginning_With_SW_That_Get_Alt_SV())
{
MetaphAdd("S", "SV");
m_current += 2;
return true;
}
if(Names_Beginning_With_SW_That_Get_Alt_XV())
{
MetaphAdd("S", "XV");
m_current += 2;
return true;
}
}
return false;
}
/**
* Encode "-SKJ-" as X ("sh"), since americans pronounce
* the name Dag Hammerskjold as "hammer-shold"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SKJ()
{
// scandinavian
if(StringAt(m_current, 4, "SKJO", "SKJU", "")
&& IsVowel(m_current + 3))
{
MetaphAdd("X");
m_current += 3;
return true;
}
return false;
}
/**
* Encode initial swedish "SJ-" as X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SJ()
{
if(StringAt(0, 2, "SJ", ""))
{
MetaphAdd("X");
m_current += 2;
return true;
}
return false;
}
/**
* Encode final 'S' in words from the french, where they
* are not pronounced
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_French_S_Final()
{
// "louis" is an exception because it gets two pronuncuations
if(StringAt(0, 5, "LOUIS", "") && (m_current == m_last))
{
MetaphAdd("S", "");
m_current++;
return true;
}
// french words familiar to americans where final s is silent
if((m_current == m_last)
&& (StringAt(0, 4, "YVES", "")
|| (StringAt(0, 4, "HORS", "") && (m_current == 3))
|| StringAt((m_current - 4), 5, "CAMUS", "YPRES", "")
|| StringAt((m_current - 5), 6, "MESNES", "DEBRIS", "BLANCS", "INGRES", "CANNES", "")
|| StringAt((m_current - 6), 7, "CHABLIS", "APROPOS", "JACQUES", "ELYSEES", "OEUVRES",
"GEORGES", "DESPRES", "")
|| StringAt(0, 8, "ARKANSAS", "FRANCAIS", "CRUDITES", "BRUYERES", "")
|| StringAt(0, 9, "DESCARTES", "DESCHUTES", "DESCHAMPS", "DESROCHES", "DESCHENES", "")
|| StringAt(0, 10, "RENDEZVOUS", "")
|| StringAt(0, 11, "CONTRETEMPS", "DESLAURIERS", ""))
|| ((m_current == m_last)
&& StringAt((m_current - 2), 2, "AI", "OI", "UI", "")
&& !StringAt(0, 4, "LOIS", "LUIS", "")))
{
m_current++;
return true;
}
return false;
}
/**
* Encode non-final 'S' in words from the french where they
* are not pronounced.
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_French_S_Internal()
{
// french words familiar to americans where internal s is silent
if(StringAt((m_current - 2), 9, "DESCARTES", "")
|| StringAt((m_current - 2), 7, "DESCHAM", "DESPRES", "DESROCH", "DESROSI", "DESJARD", "DESMARA",
"DESCHEN", "DESHOTE", "DESLAUR", "")
|| StringAt((m_current - 2), 6, "MESNES", "")
|| StringAt((m_current - 5), 8, "DUQUESNE", "DUCHESNE", "")
|| StringAt((m_current - 7), 10, "BEAUCHESNE", "")
|| StringAt((m_current - 3), 7, "FRESNEL", "")
|| StringAt((m_current - 3), 9, "GROSVENOR", "")
|| StringAt((m_current - 4), 10, "LOUISVILLE", "")
|| StringAt((m_current - 7), 10, "ILLINOISAN", ""))
{
m_current++;
return true;
}
return false;
}
/**
* Encode silent 'S' in context of "-ISL-"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_ISL()
{
//special cases 'island', 'isle', 'carlisle', 'carlysle'
if((StringAt((m_current - 2), 4, "LISL", "LYSL", "AISL", "")
&& !StringAt((m_current - 3), 7, "PAISLEY", "BAISLEY", "ALISLAM", "ALISLAH", "ALISLAA", ""))
|| ((m_current == 1)
&& ((StringAt((m_current - 1), 4, "ISLE", "")
|| StringAt((m_current - 1), 5, "ISLAN", ""))
&& !StringAt((m_current - 1), 5, "ISLEY", "ISLER", ""))))
{
m_current++;
return true;
}
return false;
}
/**
* Encode "-STL-" in contexts where the 'T' is silent. Also
* encode "-USCLE-" in contexts where the 'C' is silent
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_STL()
{
//'hustle', 'bustle', 'whistle'
if((StringAt(m_current, 4, "STLE", "STLI", "")
&& !StringAt((m_current + 2), 4, "LESS", "LIKE", "LINE", ""))
|| StringAt((m_current - 3), 7, "THISTLY", "BRISTLY", "GRISTLY", "")
// e.g. "corpuscle"
|| StringAt((m_current - 1), 5, "USCLE", ""))
{
// KRISTEN, KRYSTLE, CRYSTLE, KRISTLE all pronounce the 't'
// also, exceptions where "-LING" is a nominalizing suffix
if(StringAt(0, 7, "KRISTEN", "KRYSTLE", "CRYSTLE", "KRISTLE", "")
|| StringAt(0, 11, "CHRISTENSEN", "CHRISTENSON", "")
|| StringAt((m_current - 3), 9, "FIRSTLING", "")
|| StringAt((m_current - 2), 8, "NESTLING", "WESTLING", ""))
{
MetaphAdd("ST");
m_current += 2;
}
else
{
if(m_encodeVowels
&& (CharAt(m_current + 3) == 'E')
&& (CharAt(m_current + 4) != 'R')
&& !StringAt((m_current + 3), 4, "ETTE", "ETTA", "")
&& !StringAt((m_current + 3), 2, "EY", ""))
{
MetaphAdd("SAL");
flag_AL_inversion = true;
}
else
{
MetaphAdd("SL");
}
m_current += 3;
}
return true;
}
return false;
}
/**
* Encode "christmas". Americans always pronounce this as "krissmuss"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Christmas()
{
//'christmas'
if(StringAt((m_current - 4), 8, "CHRISTMA", ""))
{
MetaphAdd("SM");
m_current += 3;
return true;
}
return false;
}
/**
* Encode "-STHM-" in contexts where the 'TH'
* is silent.
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_STHM()
{
//'asthma', 'isthmus'
if(StringAt(m_current, 4, "STHM", ""))
{
MetaphAdd("SM");
m_current += 4;
return true;
}
return false;
}
/**
* Encode "-ISTEN-" and "-STNT-" in contexts
* where the 'T' is silent
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_ISTEN()
{
// 't' is silent in verb, pronounced in name
if(StringAt(0, 8, "CHRISTEN", ""))
{
// the word itself
if(RootOrInflections(m_inWord, "CHRISTEN")
|| StringAt(0, 11, "CHRISTENDOM", ""))
{
MetaphAdd("S", "ST");
}
else
{
// e.g. 'christenson', 'christene'
MetaphAdd("ST");
}
m_current += 2;
return true;
}
//e.g. 'glisten', 'listen'
if(StringAt((m_current - 2), 6, "LISTEN", "RISTEN", "HASTEN", "FASTEN", "MUSTNT", "")
|| StringAt((m_current - 3), 7, "MOISTEN", ""))
{
MetaphAdd("S");
m_current += 2;
return true;
}
return false;
}
/**
* Encode special case "sugar"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Sugar()
{
//special case 'sugar-'
if(StringAt(m_current, 5, "SUGAR", ""))
{
MetaphAdd("X");
m_current++;
return true;
}
return false;
}
/**
* Encode "-SH-" as X ("sh"), except in cases
* where the 'S' and 'H' belong to different combining
* roots and are therefore pronounced seperately
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SH()
{
if(StringAt(m_current, 2, "SH", ""))
{
// exception
if(StringAt((m_current - 2), 8, "CASHMERE", ""))
{
MetaphAdd("J");
m_current += 2;
return true;
}
//combining forms, e.g. 'clotheshorse', 'woodshole'
if((m_current > 0)
// e.g. "mishap"
&& ((StringAt((m_current + 1), 3, "HAP", "") && ((m_current + 3) == m_last))
// e.g. "hartsheim", "clothshorse"
|| StringAt((m_current + 1), 4, "HEIM", "HOEK", "HOLM", "HOLZ", "HOOD", "HEAD", "HEID",
"HAAR", "HORS", "HOLE", "HUND", "HELM", "HAWK", "HILL", "")
// e.g. "dishonor"
|| StringAt((m_current + 1), 5, "HEART", "HATCH", "HOUSE", "HOUND", "HONOR", "")
// e.g. "mishear"
|| (StringAt((m_current + 2), 3, "EAR", "") && ((m_current + 4) == m_last))
// e.g. "hartshorn"
|| (StringAt((m_current + 2), 3, "ORN", "") && !StringAt((m_current - 2), 7, "UNSHORN", ""))
// e.g. "newshour" but not "bashour", "manshour"
|| (StringAt((m_current + 1), 4, "HOUR", "")
&& !(StringAt(0, 7, "BASHOUR", "") || StringAt(0, 8, "MANSHOUR", "") || StringAt(0, 6, "ASHOUR", "") ))
// e.g. "dishonest", "grasshopper"
|| StringAt((m_current + 2), 5, "ARMON", "ONEST", "ALLOW", "OLDER", "OPPER", "EIMER", "ANDLE", "ONOUR", "")
// e.g. "dishabille", "transhumance"
|| StringAt((m_current + 2), 6, "ABILLE", "UMANCE", "ABITUA", "")))
{
if (!StringAt((m_current - 1), 1, "S", ""))
MetaphAdd("S");
}
else
{
MetaphAdd("X");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-SCH-" in cases where the 'S' is pronounced
* seperately from the "CH", in words from the dutch, italian,
* and greek where it can be pronounced SK, and german words
* where it is pronounced X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SCH()
{
// these words were combining forms many centuries ago
if(StringAt((m_current + 1), 2, "CH", ""))
{
if((m_current > 0)
// e.g. "mischief", "escheat"
&& (StringAt((m_current + 3), 3, "IEF", "EAT", "")
// e.g. "mischance"
|| StringAt((m_current + 3), 4, "ANCE", "ARGE", "")
// e.g. "eschew"
|| StringAt(0, 6, "ESCHEW", "")))
{
MetaphAdd("S");
m_current++;
return true;
}
//Schlesinger's rule
//dutch, danish, italian, greek origin, e.g. "school", "schooner", "schiavone", "schiz-"
if((StringAt((m_current + 3), 2, "OO", "ER", "EN", "UY", "ED", "EM", "IA", "IZ", "IS", "OL", "")
&& !StringAt(m_current, 6, "SCHOLT", "SCHISL", "SCHERR", ""))
|| StringAt((m_current + 3), 3, "ISZ", "")
|| (StringAt((m_current - 1), 6, "ESCHAT", "ASCHIN", "ASCHAL", "ISCHAE", "ISCHIA", "")
&& !StringAt((m_current - 2), 8, "FASCHING", ""))
|| (StringAt((m_current - 1), 5, "ESCHI", "") && ((m_current + 3) == m_last))
|| (CharAt(m_current + 3) == 'Y'))
{
// e.g. "schermerhorn", "schenker", "schistose"
if(StringAt((m_current + 3), 2, "ER", "EN", "IS", "")
&& (((m_current + 4) == m_last)
|| StringAt((m_current + 3), 3, "ENK", "ENB", "IST", "")))
{
MetaphAdd("X", "SK");
}
else
{
MetaphAdd("SK");
}
m_current += 3;
return true;
}
else
{
MetaphAdd("X");
m_current += 3;
return true;
}
}
return false;
}
/**
* Encode "-SUR<E,A,Y>-" to J, unless it is at the beginning,
* or preceeded by 'N', 'K', or "NO"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SUR()
{
// 'erasure', 'usury'
if(StringAt((m_current + 1), 3, "URE", "URA", "URY", ""))
{
//'sure', 'ensure'
if ((m_current == 0)
|| StringAt((m_current - 1), 1, "N", "K", "")
|| StringAt((m_current - 2), 2, "NO", ""))
{
MetaphAdd("X");
}
else
{
MetaphAdd("J");
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode "-SU<O,A>-" to X ("sh") unless it is preceeded by
* an 'R', in which case it is encoded to S, or it is
* preceeded by a vowel, in which case it is encoded to J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SU()
{
//'sensuous', 'consensual'
if(StringAt((m_current + 1), 2, "UO", "UA", "") && (m_current != 0))
{
// exceptions e.g. "persuade"
if(StringAt((m_current - 1), 4, "RSUA", ""))
{
MetaphAdd("S");
}
// exceptions e.g. "casual"
else if(IsVowel(m_current - 1))
{
MetaphAdd("J", "S");
}
else
{
MetaphAdd("X", "S");
}
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encodes "-SSIO-" in contexts where it is pronounced
* either J or X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SSIO()
{
if(StringAt((m_current + 1), 4, "SION", ""))
{
//"abcission"
if (StringAt((m_current - 2), 2, "CI", ""))
{
MetaphAdd("J");
}
//'mission'
else
{
if (IsVowel(m_current - 1))
{
MetaphAdd("X");
}
}
AdvanceCounter(4, 2);
return true;
}
return false;
}
/**
* Encode "-SS-" in contexts where it is pronounced X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SS()
{
// e.g. "russian", "pressure"
if(StringAt((m_current - 1), 5, "USSIA", "ESSUR", "ISSUR", "ISSUE", "")
// e.g. "hessian", "assurance"
|| StringAt((m_current - 1), 6, "ESSIAN", "ASSURE", "ASSURA", "ISSUAB", "ISSUAN", "ASSIUS", ""))
{
MetaphAdd("X");
AdvanceCounter(3, 2);
return true;
}
return false;
}
/**
* Encodes "-SIA-" in contexts where it is pronounced
* as X ("sh"), J, or S
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SIA()
{
// e.g. "controversial", also "fuchsia", "ch" is silent
if(StringAt((m_current - 2), 5, "CHSIA", "")
|| StringAt((m_current - 1), 5, "RSIAL", ""))
{
MetaphAdd("X");
AdvanceCounter(3, 1);
return true;
}
// names generally get 'X' where terms, e.g. "aphasia" get 'J'
if((StringAt(0, 6, "ALESIA", "ALYSIA", "ALISIA", "STASIA", "")
&& (m_current == 3)
&& !StringAt(0, 9, "ANASTASIA", ""))
|| StringAt((m_current - 5), 9, "DIONYSIAN", "")
|| StringAt((m_current - 5), 8, "THERESIA", ""))
{
MetaphAdd("X", "S");
AdvanceCounter(3, 1);
return true;
}
if((StringAt(m_current, 3, "SIA", "") && ((m_current + 2) == m_last))
|| (StringAt(m_current, 4, "SIAN", "") && ((m_current + 3) == m_last))
|| StringAt((m_current - 5), 9, "AMBROSIAL", ""))
{
if ((IsVowel(m_current - 1) || StringAt((m_current - 1), 1, "R", ""))
// exclude compounds based on names, or french or greek words
&& !(StringAt(0, 5, "JAMES", "NICOS", "PEGAS", "PEPYS", "")
|| StringAt(0, 6, "HOBBES", "HOLMES", "JAQUES", "KEYNES", "")
|| StringAt(0, 7, "MALTHUS", "HOMOOUS", "")
|| StringAt(0, 8, "MAGLEMOS", "HOMOIOUS", "")
|| StringAt(0, 9, "LEVALLOIS", "TARDENOIS", "")
|| StringAt((m_current - 4), 5, "ALGES", "") ))
{
MetaphAdd("J");
}
else
{
MetaphAdd("S");
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encodes "-SIO-" in contexts where it is pronounced
* as J or X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SIO()
{
// special case, irish name
if(StringAt(0, 7, "SIOBHAN", ""))
{
MetaphAdd("X");
AdvanceCounter(3, 1);
return true;
}
if(StringAt((m_current + 1), 3, "ION", ""))
{
// e.g. "vision", "version"
if (IsVowel(m_current - 1) || StringAt((m_current - 2), 2, "ER", "UR", ""))
{
MetaphAdd("J");
}
else // e.g. "declension"
{
MetaphAdd("X");
}
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encode cases where "-S-" might well be from a german name
* and add encoding of german pronounciation in alternate m_metaph
* so that it can be found in a genealogical search
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Anglicisations()
{
//german & anglicisations, e.g. 'smith' match 'schmidt', 'snider' match 'schneider'
//also, -sz- in slavic language altho in hungarian it is pronounced 's'
if(((m_current == 0)
&& StringAt((m_current + 1), 1, "M", "N", "L", ""))
|| StringAt((m_current + 1), 1, "Z", ""))
{
MetaphAdd("S", "X");
// eat redundant 'Z'
if(StringAt((m_current + 1), 1, "Z", ""))
{
m_current += 2;
}
else
{
m_current++;
}
return true;
}
return false;
}
/**
* Encode "-SC<vowel>-" in contexts where it is silent,
* or pronounced as X ("sh"), S, or SK
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SC()
{
if(StringAt(m_current, 2, "SC", ""))
{
// exception 'viscount'
if(StringAt((m_current - 2), 8, "VISCOUNT", ""))
{
m_current += 1;
return true;
}
// encode "-SC<front vowel>-"
if(StringAt((m_current + 2), 1, "I", "E", "Y", ""))
{
// e.g. "conscious"
if(StringAt((m_current + 2), 4, "IOUS", "")
// e.g. "prosciutto"
|| StringAt((m_current + 2), 3, "IUT", "")
|| StringAt((m_current - 4), 9, "OMNISCIEN", "")
// e.g. "conscious"
|| StringAt((m_current - 3), 8, "CONSCIEN", "CRESCEND", "CONSCION", "")
|| StringAt((m_current - 2), 6, "FASCIS", ""))
{
MetaphAdd("X");
}
else if(StringAt(m_current, 7, "SCEPTIC", "SCEPSIS", "")
|| StringAt(m_current, 5, "SCIVV", "SCIRO", "")
// commonly pronounced this way in u.s.
|| StringAt(m_current, 6, "SCIPIO", "")
|| StringAt((m_current - 2), 10, "PISCITELLI", ""))
{
MetaphAdd("SK");
}
else
{
MetaphAdd("S");
}
m_current += 2;
return true;
}
MetaphAdd("SK");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-S<EA,UI,IER>-" in contexts where it is pronounced
* as J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SEA_SUI_SIER()
{
// "nausea" by itself has => NJ as a more likely encoding. Other forms
// using "nause-" (see Encode_SEA()) have X or S as more familiar pronounciations
if((StringAt((m_current - 3), 6, "NAUSEA", "") && ((m_current + 2) == m_last))
// e.g. "casuistry", "frasier", "hoosier"
|| StringAt((m_current - 2), 5, "CASUI", "")
|| (StringAt((m_current - 1), 5, "OSIER", "ASIER", "")
&& !(StringAt(0, 6, "EASIER","")
|| StringAt(0, 5, "OSIER","")
|| StringAt((m_current - 2), 6, "ROSIER", "MOSIER", ""))))
{
MetaphAdd("J", "X");
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encode cases where "-SE-" is pronounced as X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_SEA()
{
if((StringAt(0, 4, "SEAN", "") && ((m_current + 3) == m_last))
|| (StringAt((m_current - 3), 6, "NAUSEO", "")
&& !StringAt((m_current - 3), 7, "NAUSEAT", "")))
{
MetaphAdd("X");
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encode "-T-"
*
*/
void Encode_T()
{
if(Encode_T_Initial()
|| Encode_TCH()
|| Encode_Silent_French_T()
|| Encode_TUN_TUL_TUA_TUO()
|| Encode_TUE_TEU_TEOU_TUL_TIE()
|| Encode_TUR_TIU_Suffixes()
|| Encode_TI()
|| Encode_TIENT()
|| Encode_TSCH()
|| Encode_TZSCH()
|| Encode_TH_Pronounced_Separately()
|| Encode_TTH()
|| Encode_TH())
{
return;
}
// eat redundant 'T' or 'D'
if(StringAt((m_current + 1), 1, "T", "D", ""))
{
m_current += 2;
}
else
{
m_current++;
}
MetaphAdd("T");
}
/**
* Encode some exceptions for initial 'T'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_T_Initial()
{
if(m_current == 0)
{
// americans usually pronounce "tzar" as "zar"
if (StringAt((m_current + 1), 3, "SAR", "ZAR", ""))
{
m_current++;
return true;
}
if (((m_length == 3) && StringAt((m_current + 1), 2, "SO", "SA", "SU", ""))
|| ((m_length == 4) && StringAt((m_current + 1), 3, "SAO", "SAI", ""))
|| ((m_length == 5) && StringAt((m_current + 1), 4, "SING", "SANG", "")))
{
MetaphAdd("X");
AdvanceCounter(3, 2);
return true;
}
// "TS<vowel>-" at start can be pronounced both with and without 'T'
if (StringAt((m_current + 1), 1, "S", "") && IsVowel(m_current + 2))
{
MetaphAdd("TS", "S");
AdvanceCounter(3, 2);
return true;
}
// e.g. "Tjaarda"
if (StringAt((m_current + 1), 1, "J", ""))
{
MetaphAdd("X");
AdvanceCounter(3, 2);
return true;
}
// cases where initial "TH-" is pronounced as T and not 0 ("th")
if ((StringAt((m_current + 1), 2, "HU", "") && (m_length == 3))
|| StringAt((m_current + 1), 3, "HAI", "HUY", "HAO", "")
|| StringAt((m_current + 1), 4, "HYME", "HYMY", "HANH", "")
|| StringAt((m_current + 1), 5, "HERES", ""))
{
MetaphAdd("T");
AdvanceCounter(3, 2);
return true;
}
}
return false;
}
/**
* Encode "-TCH-", reliably X ("sh", or in this case, "ch")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TCH()
{
if(StringAt((m_current + 1), 2, "CH", ""))
{
MetaphAdd("X");
m_current += 3;
return true;
}
return false;
}
/**
* Encode the many cases where americans are aware that a certain word is
* french and know to not pronounce the 'T'
*
* @return true if encoding handled in this routine, false if not
* TOUCHET CHABOT BENOIT
*/
boolean Encode_Silent_French_T()
{
// french silent T familiar to americans
if(((m_current == m_last) && StringAt((m_current - 4), 5, "MONET", "GENET", "CHAUT", ""))
|| StringAt((m_current - 2), 9, "POTPOURRI", "")
|| StringAt((m_current - 3), 9, "BOATSWAIN", "")
|| StringAt((m_current - 3), 8, "MORTGAGE", "")
|| (StringAt((m_current - 4), 5, "BERET", "BIDET", "FILET", "DEBUT", "DEPOT", "PINOT", "TAROT", "")
|| StringAt((m_current - 5), 6, "BALLET", "BUFFET", "CACHET", "CHALET", "ESPRIT", "RAGOUT", "GOULET",
"CHABOT", "BENOIT", "")
|| StringAt((m_current - 6), 7, "GOURMET", "BOUQUET", "CROCHET", "CROQUET", "PARFAIT", "PINCHOT",
"CABARET", "PARQUET", "RAPPORT", "TOUCHET", "COURBET", "DIDEROT", "")
|| StringAt((m_current - 7), 8, "ENTREPOT", "CABERNET", "DUBONNET", "MASSENET", "MUSCADET", "RICOCHET", "ESCARGOT", "")
|| StringAt((m_current - 8), 9, "SOBRIQUET", "CABRIOLET", "CASSOULET", "OUBRIQUET", "CAMEMBERT", ""))
&& !StringAt((m_current + 1), 2, "AN", "RY", "IC", "OM", "IN", ""))
{
m_current++;
return true;
}
return false;
}
/**
* Encode "-TU<N,L,A,O>-" in cases where it is pronounced
* X ("sh", or in this case, "ch")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TUN_TUL_TUA_TUO()
{
// e.g. "fortune", "fortunate"
if(StringAt((m_current - 3), 6, "FORTUN", "")
// e.g. "capitulate"
|| (StringAt(m_current, 3, "TUL", "")
&& (IsVowel(m_current - 1) && IsVowel(m_current + 3)))
// e.g. "obituary", "barbituate"
|| StringAt((m_current - 2), 5, "BITUA", "BITUE", "")
// e.g. "actual"
|| ((m_current > 1) && StringAt(m_current, 3, "TUA", "TUO", "")))
{
MetaphAdd("X", "T");
m_current++;
return true;
}
return false;
}
/**
* Encode "-T<vowel>-" forms where 'T' is pronounced as X
* ("sh", or in this case "ch")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TUE_TEU_TEOU_TUL_TIE()
{
// 'constituent', 'pasteur'
if(StringAt((m_current + 1), 4, "UENT", "")
|| StringAt((m_current - 4), 9, "RIGHTEOUS", "")
|| StringAt((m_current - 3), 7, "STATUTE", "")
|| StringAt((m_current - 3), 7, "AMATEUR", "")
// e.g. "blastula", "pasteur"
|| (StringAt((m_current - 1), 5, "NTULE", "NTULA", "STULE", "STULA", "STEUR", ""))
// e.g. "statue"
|| (((m_current + 2) == m_last) && StringAt(m_current, 3, "TUE", ""))
// e.g. "constituency"
|| StringAt(m_current, 5, "TUENC", "")
// e.g. "statutory"
|| StringAt((m_current - 3), 8, "STATUTOR", "")
// e.g. "patience"
|| (((m_current + 5) == m_last) && StringAt(m_current, 6, "TIENCE", "")))
{
MetaphAdd("X", "T");
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode "-TU-" forms in suffixes where it is usually
* pronounced as X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TUR_TIU_Suffixes()
{
// 'adventure', 'musculature'
if((m_current > 0) && StringAt((m_current + 1), 3, "URE", "URA", "URI", "URY", "URO", "IUS", ""))
{
// exceptions e.g. 'tessitura', mostly from romance languages
if ((StringAt((m_current + 1), 3, "URA", "URO", "")
//&& !StringAt((m_current + 1), 4, "URIA", "")
&& ((m_current + 3) == m_last))
&& !StringAt((m_current - 3), 7, "VENTURA", "")
// e.g. "kachaturian", "hematuria"
|| StringAt((m_current + 1), 4, "URIA", ""))
{
MetaphAdd("T");
}
else
{
MetaphAdd("X", "T");
}
AdvanceCounter(2, 1);
return true;
}
return false;
}
/**
* Encode "-TI<O,A,U>-" as X ("sh"), except
* in cases where it is part of a combining form,
* or as J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TI()
{
// '-tio-', '-tia-', '-tiu-'
// except combining forms where T already pronounced e.g 'rooseveltian'
if((StringAt((m_current + 1), 2, "IO", "") && !StringAt((m_current - 1), 5, "ETIOL", ""))
|| StringAt((m_current + 1), 3, "IAL", "")
|| StringAt((m_current - 1), 5, "RTIUM", "ATIUM", "")
|| ((StringAt((m_current + 1), 3, "IAN", "") && (m_current > 0))
&& !(StringAt((m_current - 4), 8, "FAUSTIAN", "")
|| StringAt((m_current - 5), 9, "PROUSTIAN", "")
|| StringAt((m_current - 2), 7, "TATIANA", "")
||(StringAt((m_current - 3), 7, "KANTIAN", "GENTIAN", "")
|| StringAt((m_current - 8), 12, "ROOSEVELTIAN", "")))
|| (((m_current + 2) == m_last)
&& StringAt(m_current, 3, "TIA", "")
// exceptions to above rules where the pronounciation is usually X
&& !(StringAt((m_current - 3), 6, "HESTIA", "MASTIA", "")
|| StringAt((m_current - 2), 5, "OSTIA", "")
|| StringAt(0, 3, "TIA", "")
|| StringAt((m_current - 5), 8, "IZVESTIA", "")))
|| StringAt((m_current + 1), 4, "IATE", "IATI", "IABL", "IATO", "IARY", "")
|| StringAt((m_current - 5), 9, "CHRISTIAN", "")))
{
if(((m_current == 2) && StringAt(0, 4, "ANTI", ""))
|| StringAt(0, 5, "PATIO", "PITIA", "DUTIA", ""))
{
MetaphAdd("T");
}
else if(StringAt((m_current - 4), 8, "EQUATION", ""))
{
MetaphAdd("J");
}
else
{
if(StringAt(m_current, 4, "TION", ""))
{
MetaphAdd("X");
}
else if(StringAt(0, 5, "KATIA", "LATIA", ""))
{
MetaphAdd("T", "X");
}
else
{
MetaphAdd("X", "T");
}
}
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encode "-TIENT-" where "TI" is pronounced X ("sh")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TIENT()
{
// e.g. 'patient'
if(StringAt((m_current + 1), 4, "IENT", ""))
{
MetaphAdd("X", "T");
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encode "-TSCH-" as X ("ch")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TSCH()
{
//'deutsch'
if(StringAt(m_current, 4, "TSCH", "")
// combining forms in german where the 'T' is pronounced seperately
&& !StringAt((m_current - 3), 4, "WELT", "KLAT", "FEST", ""))
{
// pronounced the same as "ch" in "chit" => X
MetaphAdd("X");
m_current += 4;
return true;
}
return false;
}
/**
* Encode "-TZSCH-" as X ("ch")
*
* "Neitzsche is peachy"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TZSCH()
{
//'neitzsche'
if(StringAt(m_current, 5, "TZSCH", ""))
{
MetaphAdd("X");
m_current += 5;
return true;
}
return false;
}
/**
* Encodes cases where the 'H' in "-TH-" is the beginning of
* another word in a combining form, special cases where it is
* usually pronounced as 'T', and a special case where it has
* become pronounced as X ("sh", in this case "ch")
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TH_Pronounced_Separately()
{
//'adulthood', 'bithead', 'apartheid'
if(((m_current > 0)
&& StringAt((m_current + 1), 4, "HOOD", "HEAD", "HEID", "HAND", "HILL", "HOLD",
"HAWK", "HEAP", "HERD", "HOLE", "HOOK", "HUNT",
"HUMO", "HAUS", "HOFF", "HARD", "")
&& !StringAt((m_current - 3), 5, "SOUTH", "NORTH", ""))
|| StringAt((m_current + 1), 5, "HOUSE", "HEART", "HASTE", "HYPNO", "HEQUE", "")
// watch out for greek root "-thallic"
|| (StringAt((m_current + 1), 4, "HALL", "")
&& ((m_current + 4) == m_last)
&& !StringAt((m_current - 3), 5, "SOUTH", "NORTH", ""))
|| (StringAt((m_current + 1), 3, "HAM", "")
&& ((m_current + 3) == m_last)
&& !(StringAt(0, 6, "GOTHAM", "WITHAM", "LATHAM", "")
|| StringAt(0, 7, "BENTHAM", "WALTHAM", "WORTHAM", "")
|| StringAt(0, 8, "GRANTHAM", "")))
|| (StringAt((m_current + 1), 5, "HATCH", "")
&& !((m_current == 0) || StringAt((m_current - 2), 8, "UNTHATCH", "")))
|| StringAt((m_current - 3), 7, "WARTHOG", "")
// and some special cases where "-TH-" is usually pronounced 'T'
|| StringAt((m_current - 2), 6, "ESTHER", "")
|| StringAt((m_current - 3), 6, "GOETHE", "")
|| StringAt((m_current - 2), 8, "NATHALIE", ""))
{
// special case
if (StringAt((m_current - 3), 7, "POSTHUM", ""))
{
MetaphAdd("X");
}
else
{
MetaphAdd("T");
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode the "-TTH-" in "matthew", eating the redundant 'T'
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TTH()
{
// 'matthew' vs. 'outthink'
if(StringAt(m_current, 3, "TTH", ""))
{
if (StringAt((m_current - 2), 5, "MATTH", ""))
{
MetaphAdd("0");
}
else
{
MetaphAdd("T0");
}
m_current += 3;
return true;
}
return false;
}
/**
* Encode "-TH-". 0 (zero) is used in Metaphone to encode this sound
* when it is pronounced as a dipthong, either voiced or unvoiced
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_TH()
{
if(StringAt(m_current, 2, "TH", "") )
{
//'-clothes-'
if(StringAt((m_current - 3), 7, "CLOTHES", ""))
{
// vowel already encoded so skip right to S
m_current += 3;
return true;
}
//special case "thomas", "thames", "beethoven" or germanic words
if(StringAt((m_current + 2), 4, "OMAS", "OMPS", "OMPK", "OMSO", "OMSE",
"AMES", "OVEN", "OFEN", "ILDA", "ILDE", "")
|| (StringAt(0, 4, "THOM", "") && (m_length == 4))
|| (StringAt(0, 5, "THOMS", "") && (m_length == 5))
|| StringAt(0, 4, "VAN ", "VON ", "")
|| StringAt(0, 3, "SCH", ""))
{
MetaphAdd("T");
}
else
{
// give an 'etymological' 2nd
// encoding for "smith"
if(StringAt(0, 2, "SM", ""))
{
MetaphAdd("0", "T");
}
else
{
MetaphAdd("0");
}
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-V-"
*
*/
void Encode_V()
{
// eat redundant 'V'
if(CharAt(m_current + 1) == 'V')
{
m_current += 2;
}
else
{
m_current++;
}
MetaphAddExactApprox("V", "F");
}
/**
* Encode "-W-"
*
*/
void Encode_W()
{
if(Encode_Silent_W_At_Beginning()
|| Encode_WITZ_WICZ()
|| Encode_WR()
|| Encode_Initial_W_Vowel()
|| Encode_WH()
|| Encode_Eastern_European_W())
{
return;
}
// e.g. 'zimbabwe'
if(m_encodeVowels
&& StringAt(m_current, 2, "WE", "")
&& ((m_current + 1) == m_last))
{
MetaphAdd("A");
}
//else skip it
m_current++;
}
/**
* Encode cases where 'W' is silent at beginning of word
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Silent_W_At_Beginning()
{
//skip these when at start of word
if((m_current == 0)
&& StringAt(m_current, 2, "WR", ""))
{
m_current += 1;
return true;
}
return false;
}
/**
* Encode polish patronymic suffix, mapping
* alternate spellings to the same encoding,
* and including easern european pronounciation
* to the american so that both forms can
* be found in a genealogy search
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_WITZ_WICZ()
{
//polish e.g. 'filipowicz'
if(((m_current + 3) == m_last) && StringAt(m_current, 4, "WICZ", "WITZ", ""))
{
if(m_encodeVowels)
{
if((m_primary.length() > 0)
&& m_primary.charAt(m_primary.length() - 1) == 'A')
{
MetaphAdd("TS", "FAX");
}
else
{
MetaphAdd("ATS", "FAX");
}
}
else
{
MetaphAdd("TS", "FX");
}
m_current += 4;
return true;
}
return false;
}
/**
* Encode "-WR-" as R ('W' always effectively silent)
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_WR()
{
//can also be in middle of word
if(StringAt(m_current, 2, "WR", ""))
{
MetaphAdd("R");
m_current += 2;
return true;
}
return false;
}
/**
* Encode "W-", adding central and eastern european
* pronounciations so that both forms can be found
* in a genealogy search
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Initial_W_Vowel()
{
if((m_current == 0) && IsVowel(m_current + 1))
{
//Witter should match Vitter
if(Germanic_Or_Slavic_Name_Beginning_With_W())
{
if(m_encodeVowels)
{
MetaphAddExactApprox("A", "VA", "A", "FA");
}
else
{
MetaphAddExactApprox("A", "V", "A", "F");
}
}
else
{
MetaphAdd("A");
}
m_current++;
// don't encode vowels twice
m_current = SkipVowels(m_current);
return true;
}
return false;
}
/**
* Encode "-WH-" either as H, or close enough to 'U' to be
* considered a vowel
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_WH()
{
if(StringAt(m_current, 2, "WH", ""))
{
// cases where it is pronounced as H
// e.g. 'who', 'whole'
if((CharAt(m_current + 2) == 'O')
// exclude cases where it is pronounced like a vowel
&& !(StringAt((m_current + 2), 4, "OOSH", "")
|| StringAt((m_current + 2), 3, "OOP", "OMP", "ORL", "ORT", "")
|| StringAt((m_current + 2), 2, "OA", "OP", "")))
{
MetaphAdd("H");
AdvanceCounter(3, 2);
return true;
}
else
{
// combining forms, e.g. 'hollowhearted', 'rawhide'
if(StringAt((m_current + 2), 3, "IDE", "ARD", "EAD", "AWK", "ERD",
"OOK", "AND", "OLE", "OOD", "")
|| StringAt((m_current + 2), 4, "EART", "OUSE", "OUND", "")
|| StringAt((m_current + 2), 5, "AMMER", ""))
{
MetaphAdd("H");
m_current += 2;
return true;
}
else if(m_current == 0)
{
MetaphAdd("A");
m_current += 2;
// don't encode vowels twice
m_current = SkipVowels(m_current);
return true;
}
}
m_current += 2;
return true;
}
return false;
}
/**
* Encode "-W-" when in eastern european names, adding
* the eastern european pronounciation to the american so
* that both forms can be found in a genealogy search
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Eastern_European_W()
{
//Arnow should match Arnoff
if(((m_current == m_last) && IsVowel(m_current - 1))
|| StringAt((m_current - 1), 5, "EWSKI", "EWSKY", "OWSKI", "OWSKY", "")
|| (StringAt(m_current, 5, "WICKI", "WACKI", "") && ((m_current + 4) == m_last))
|| StringAt(m_current, 4, "WIAK", "") && ((m_current + 3) == m_last)
|| StringAt(0, 3, "SCH", ""))
{
MetaphAddExactApprox("", "V", "", "F");
m_current++;
return true;
}
return false;
}
/**
* Encode "-X-"
*
*/
void Encode_X()
{
if(Encode_Initial_X()
|| Encode_Greek_X()
|| Encode_X_Special_Cases()
|| Encode_X_To_H()
|| Encode_X_Vowel()
|| Encode_French_X_Final())
{
return;
}
// eat redundant 'X' or other redundant cases
if(StringAt((m_current + 1), 1, "X", "Z", "S", "")
// e.g. "excite", "exceed"
|| StringAt((m_current + 1), 2, "CI", "CE", ""))
{
m_current += 2;
}
else
{
m_current++;
}
}
/**
* Encode initial X where it is usually pronounced as S
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Initial_X()
{
// current chinese pinyin spelling
if(StringAt(0, 3, "XIA", "XIO", "XIE", "")
|| StringAt(0, 2, "XU", ""))
{
MetaphAdd("X");
m_current++;
return true;
}
// else
if((m_current == 0))
{
MetaphAdd("S");
m_current++;
return true;
}
return false;
}
/**
* Encode X when from greek roots where it is usually pronounced as S
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_Greek_X()
{
// 'xylophone', xylem', 'xanthoma', 'xeno-'
if(StringAt((m_current + 1), 3, "YLO", "YLE", "ENO", "")
|| StringAt((m_current + 1), 4, "ANTH", ""))
{
MetaphAdd("S");
m_current++;
return true;
}
return false;
}
/**
* Encode special cases, "LUXUR-", "Texeira"
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_X_Special_Cases()
{
// 'luxury'
if(StringAt((m_current - 2), 5, "LUXUR", ""))
{
MetaphAddExactApprox("GJ", "KJ");
m_current++;
return true;
}
// 'texeira' portuguese/galician name
if(StringAt(0, 7, "TEXEIRA", "")
|| StringAt(0, 8, "TEIXEIRA", ""))
{
MetaphAdd("X");
m_current++;
return true;
}
return false;
}
/**
* Encode special case where americans know the
* proper mexican indian pronounciation of this name
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_X_To_H()
{
// TODO: look for other mexican indian words
// where 'X' is usually pronounced this way
if(StringAt((m_current - 2), 6, "OAXACA", "")
|| StringAt((m_current - 3), 7, "QUIXOTE", ""))
{
MetaphAdd("H");
m_current++;
return true;
}
return false;
}
/**
* Encode "-X-" in vowel contexts where it is usually
* pronounced KX ("ksh")
* account also for BBC pronounciation of => KS
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_X_Vowel()
{
// e.g. "sexual", "connexion" (british), "noxious"
if(StringAt((m_current + 1), 3, "UAL", "ION", "IOU", ""))
{
MetaphAdd("KX", "KS");
AdvanceCounter(3, 1);
return true;
}
return false;
}
/**
* Encode cases of "-X", encoding as silent when part
* of a french word where it is not pronounced
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_French_X_Final()
{
//french e.g. "breaux", "paix"
if(!((m_current == m_last)
&& (StringAt((m_current - 3), 3, "IAU", "EAU", "IEU", "")
|| StringAt((m_current - 2), 2, "AI", "AU", "OU", "OI", "EU", ""))) )
{
MetaphAdd("KS");
}
return false;
}
/**
* Encode "-Z-"
*
*/
void Encode_Z()
{
if(Encode_ZZ()
|| Encode_ZU_ZIER_ZS()
|| Encode_French_EZ()
|| Encode_German_Z())
{
return;
}
if(Encode_ZH())
{
return;
}
else
{
MetaphAdd("S");
}
// eat redundant 'Z'
if(CharAt(m_current + 1) == 'Z')
{
m_current += 2;
}
else
{
m_current++;
}
}
/**
* Encode cases of "-ZZ-" where it is obviously part
* of an italian word where "-ZZ-" is pronounced as TS
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_ZZ()
{
// "abruzzi", 'pizza'
if((CharAt(m_current + 1) == 'Z')
&& ((StringAt((m_current + 2), 1, "I", "O", "A", "")
&& ((m_current + 2) == m_last))
|| StringAt((m_current - 2), 9, "MOZZARELL", "PIZZICATO", "PUZZONLAN", "")))
{
MetaphAdd("TS", "S");
m_current += 2;
return true;
}
return false;
}
/**
* Encode special cases where "-Z-" is pronounced as J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_ZU_ZIER_ZS()
{
if(((m_current == 1) && StringAt((m_current - 1), 4, "AZUR", ""))
|| (StringAt(m_current, 4, "ZIER", "")
&& !StringAt((m_current - 2), 6, "VIZIER", ""))
|| StringAt(m_current, 3, "ZSA", ""))
{
MetaphAdd("J", "S");
if(StringAt(m_current, 3, "ZSA", ""))
{
m_current += 2;
}
else
{
m_current++;
}
return true;
}
return false;
}
/**
* Encode cases where americans recognize "-EZ" as part
* of a french word where Z not pronounced
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_French_EZ()
{
if(((m_current == 3) && StringAt((m_current - 3), 4, "CHEZ", ""))
|| StringAt((m_current - 5), 6, "RENDEZ", ""))
{
m_current++;
return true;
}
return false;
}
/**
* Encode cases where "-Z-" is in a german word
* where Z => TS in german
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_German_Z()
{
if(((m_current == 2) && ((m_current + 1) == m_last) && StringAt((m_current - 2), 4, "NAZI", ""))
|| StringAt((m_current - 2), 6, "NAZIFY", "MOZART", "")
|| StringAt((m_current - 3), 4, "HOLZ", "HERZ", "MERZ", "FITZ", "")
|| (StringAt((m_current - 3), 4, "GANZ", "") && !IsVowel(m_current + 1))
|| StringAt((m_current - 4), 5, "STOLZ", "PRINZ", "")
|| StringAt((m_current - 4), 7, "VENEZIA", "")
|| StringAt((m_current - 3), 6, "HERZOG", "")
// german words beginning with "sch-" but not schlimazel, schmooze
|| (m_inWord.contains("SCH") && !(StringAt((m_last - 2), 3, "IZE", "OZE", "ZEL", "")))
|| ((m_current > 0) && StringAt(m_current, 4, "ZEIT", ""))
|| StringAt((m_current - 3), 4, "WEIZ", ""))
{
if((m_current > 0) && m_inWord.charAt(m_current - 1) == 'T')
{
MetaphAdd("S");
}
else
{
MetaphAdd("TS");
}
m_current++;
return true;
}
return false;
}
/**
* Encode "-ZH-" as J
*
* @return true if encoding handled in this routine, false if not
*
*/
boolean Encode_ZH()
{
//chinese pinyin e.g. 'zhao', also english "phonetic spelling"
if(CharAt(m_current + 1) == 'H')
{
MetaphAdd("J");
m_current += 2;
return true;
}
return false;
}
/**
* Test for names derived from the swedish,
* dutch, or slavic that should get an alternate
* pronunciation of 'SV' to match the native
* version
*
* @return true if swedish, dutch, or slavic derived name
*/
boolean Names_Beginning_With_SW_That_Get_Alt_SV()
{
if(StringAt(0, 7, "SWANSON", "SWENSON", "SWINSON", "SWENSEN",
"SWOBODA", "")
|| StringAt(0, 9, "SWIDERSKI", "SWARTHOUT", "")
|| StringAt(0, 10, "SWEARENGIN", ""))
{
return true;
}
return false;
}
/**
* Test for names derived from the german
* that should get an alternate pronunciation
* of 'XV' to match the german version spelled
* "schw-"
*
* @return true if german derived name
*/
boolean Names_Beginning_With_SW_That_Get_Alt_XV()
{
if(StringAt(0, 5, "SWART", "")
|| StringAt(0, 6, "SWARTZ", "SWARTS", "SWIGER", "")
|| StringAt(0, 7, "SWITZER", "SWANGER", "SWIGERT",
"SWIGART", "SWIHART", "")
|| StringAt(0, 8, "SWEITZER", "SWATZELL", "SWINDLER", "")
|| StringAt(0, 9, "SWINEHART", "")
|| StringAt(0, 10, "SWEARINGEN", ""))
{
return true;
}
return false;
}
/**
* Test whether the word in question
* is a name of germanic or slavic origin, for
* the purpose of determining whether to add an
* alternate encoding of 'V'
*
* @return true if germanic or slavic name
*/
boolean Germanic_Or_Slavic_Name_Beginning_With_W()
{
if(StringAt(0, 3, "WEE", "WIX", "WAX", "")
|| StringAt(0, 4, "WOLF", "WEIS", "WAHL", "WALZ", "WEIL", "WERT",
"WINE", "WILK", "WALT", "WOLL", "WADA", "WULF",
"WEHR", "WURM", "WYSE", "WENZ", "WIRT", "WOLK",
"WEIN", "WYSS", "WASS", "WANN", "WINT", "WINK",
"WILE", "WIKE", "WIER", "WELK", "WISE", "")
|| StringAt(0, 5, "WIRTH", "WIESE", "WITTE", "WENTZ", "WOLFF", "WENDT",
"WERTZ", "WILKE", "WALTZ", "WEISE", "WOOLF", "WERTH",
"WEESE", "WURTH", "WINES", "WARGO", "WIMER", "WISER",
"WAGER", "WILLE", "WILDS", "WAGAR", "WERTS", "WITTY",
"WIENS", "WIEBE", "WIRTZ", "WYMER", "WULFF", "WIBLE",
"WINER", "WIEST", "WALKO", "WALLA", "WEBRE", "WEYER",
"WYBLE", "WOMAC", "WILTZ", "WURST", "WOLAK", "WELKE",
"WEDEL", "WEIST", "WYGAN", "WUEST", "WEISZ", "WALCK",
"WEITZ", "WYDRA", "WANDA", "WILMA", "WEBER", "")
|| StringAt(0, 6, "WETZEL", "WEINER", "WENZEL", "WESTER", "WALLEN", "WENGER",
"WALLIN", "WEILER", "WIMMER", "WEIMER", "WYRICK", "WEGNER",
"WINNER", "WESSEL", "WILKIE", "WEIGEL", "WOJCIK", "WENDEL",
"WITTER", "WIENER", "WEISER", "WEXLER", "WACKER", "WISNER",
"WITMER", "WINKLE", "WELTER", "WIDMER", "WITTEN", "WINDLE",
"WASHER", "WOLTER", "WILKEY", "WIDNER", "WARMAN", "WEYANT",
"WEIBEL", "WANNER", "WILKEN", "WILTSE", "WARNKE", "WALSER",
"WEIKEL", "WESNER", "WITZEL", "WROBEL", "WAGNON", "WINANS",
"WENNER", "WOLKEN", "WILNER", "WYSONG", "WYCOFF", "WUNDER",
"WINKEL", "WIDMAN", "WELSCH", "WEHNER", "WEIGLE", "WETTER",
"WUNSCH", "WHITTY", "WAXMAN", "WILKER", "WILHAM", "WITTIG",
"WITMAN", "WESTRA", "WEHRLE", "WASSER", "WILLER", "WEGMAN",
"WARFEL", "WYNTER", "WERNER", "WAGNER", "WISSER", "")
|| StringAt(0, 7, "WISEMAN", "WINKLER", "WILHELM", "WELLMAN", "WAMPLER", "WACHTER",
"WALTHER", "WYCKOFF", "WEIDNER", "WOZNIAK", "WEILAND", "WILFONG",
"WIEGAND", "WILCHER", "WIELAND", "WILDMAN", "WALDMAN", "WORTMAN",
"WYSOCKI", "WEIDMAN", "WITTMAN", "WIDENER", "WOLFSON", "WENDELL",
"WEITZEL", "WILLMAN", "WALDRUP", "WALTMAN", "WALCZAK", "WEIGAND",
"WESSELS", "WIDEMAN", "WOLTERS", "WIREMAN", "WILHOIT", "WEGENER",
"WOTRING", "WINGERT", "WIESNER", "WAYMIRE", "WHETZEL", "WENTZEL",
"WINEGAR", "WESTMAN", "WYNKOOP", "WALLICK", "WURSTER", "WINBUSH",
"WILBERT", "WALLACH", "WYNKOOP", "WALLICK", "WURSTER", "WINBUSH",
"WILBERT", "WALLACH", "WEISSER", "WEISNER", "WINDERS", "WILLMON",
"WILLEMS", "WIERSMA", "WACHTEL", "WARNICK", "WEIDLER", "WALTRIP",
"WHETSEL", "WHELESS", "WELCHER", "WALBORN", "WILLSEY", "WEINMAN",
"WAGAMAN", "WOMMACK", "WINGLER", "WINKLES", "WIEDMAN", "WHITNER",
"WOLFRAM", "WARLICK", "WEEDMAN", "WHISMAN", "WINLAND", "WEESNER",
"WARTHEN", "WETZLER", "WENDLER", "WALLNER", "WOLBERT", "WITTMER",
"WISHART", "WILLIAM", "")
|| StringAt(0, 8, "WESTPHAL", "WICKLUND", "WEISSMAN", "WESTLUND", "WOLFGANG", "WILLHITE",
"WEISBERG", "WALRAVEN", "WOLFGRAM", "WILHOITE", "WECHSLER", "WENDLING",
"WESTBERG", "WENDLAND", "WININGER", "WHISNANT", "WESTRICK", "WESTLING",
"WESTBURY", "WEITZMAN", "WEHMEYER", "WEINMANN", "WISNESKI", "WHELCHEL",
"WEISHAAR", "WAGGENER", "WALDROUP", "WESTHOFF", "WIEDEMAN", "WASINGER",
"WINBORNE", "")
|| StringAt(0, 9, "WHISENANT", "WEINSTEIN", "WESTERMAN", "WASSERMAN", "WITKOWSKI", "WEINTRAUB",
"WINKELMAN", "WINKFIELD", "WANAMAKER", "WIECZOREK", "WIECHMANN", "WOJTOWICZ",
"WALKOWIAK", "WEINSTOCK", "WILLEFORD", "WARKENTIN", "WEISINGER", "WINKLEMAN",
"WILHEMINA", "")
|| StringAt(0, 10, "WISNIEWSKI", "WUNDERLICH", "WHISENHUNT", "WEINBERGER", "WROBLEWSKI",
"WAGUESPACK", "WEISGERBER", "WESTERVELT", "WESTERLUND", "WASILEWSKI",
"WILDERMUTH", "WESTENDORF", "WESOLOWSKI", "WEINGARTEN", "WINEBARGER",
"WESTERBERG", "WANNAMAKER", "WEISSINGER", "")
|| StringAt(0, 11, "WALDSCHMIDT", "WEINGARTNER", "WINEBRENNER", "")
|| StringAt(0, 12, "WOLFENBARGER", "")
|| StringAt(0, 13, "WOJCIECHOWSKI", ""))
{
return true;
}
return false;
}
/**
* Test whether the word in question
* is a name starting with 'J' that should
* match names starting with a 'Y' sound.
* All forms of 'John', 'Jane', etc, get
* and alt to match e.g. 'Ian', 'Yana'. Joelle
* should match 'Yael', 'Joseph' should match
* 'Yusef'. German and slavic last names are
* also included.
*
* @return true if name starting with 'J' that
* should get an alternate encoding as a vowel
*/
boolean Names_Beginning_With_J_That_Get_Alt_Y()
{
if(StringAt(0, 3, "JAN", "JON", "JAN", "JIN", "JEN", "")
|| StringAt(0, 4, "JUHL", "JULY", "JOEL", "JOHN", "JOSH",
"JUDE", "JUNE", "JONI", "JULI", "JENA",
"JUNG", "JINA", "JANA", "JENI", "JOEL",
"JANN", "JONA", "JENE", "JULE", "JANI",
"JONG", "JOHN", "JEAN", "JUNG", "JONE",
"JARA", "JUST", "JOST", "JAHN", "JACO",
"JANG", "JUDE", "JONE", "")
|| StringAt(0, 5, "JOANN", "JANEY", "JANAE", "JOANA", "JUTTA",
"JULEE", "JANAY", "JANEE", "JETTA", "JOHNA",
"JOANE", "JAYNA", "JANES", "JONAS", "JONIE",
"JUSTA", "JUNIE", "JUNKO", "JENAE", "JULIO",
"JINNY", "JOHNS", "JACOB", "JETER", "JAFFE",
"JESKE", "JANKE", "JAGER", "JANIK", "JANDA",
"JOSHI", "JULES", "JANTZ", "JEANS", "JUDAH",
"JANUS", "JENNY", "JENEE", "JONAH", "JONAS",
"JACOB", "JOSUE", "JOSEF", "JULES", "JULIE",
"JULIA", "JANIE", "JANIS", "JENNA", "JANNA",
"JEANA", "JENNI", "JEANE", "JONNA", "")
|| StringAt(0, 6, "JORDAN", "JORDON", "JOSEPH", "JOSHUA", "JOSIAH",
"JOSPEH", "JUDSON", "JULIAN", "JULIUS", "JUNIOR",
"JUDITH", "JOESPH", "JOHNIE", "JOANNE", "JEANNE",
"JOANNA", "JOSEFA", "JULIET", "JANNIE", "JANELL",
"JASMIN", "JANINE", "JOHNNY", "JEANIE", "JEANNA",
"JOHNNA", "JOELLE", "JOVITA", "JOSEPH", "JONNIE",
"JANEEN", "JANINA", "JOANIE", "JAZMIN", "JOHNIE",
"JANENE", "JOHNNY", "JONELL", "JENELL", "JANETT",
"JANETH", "JENINE", "JOELLA", "JOEANN", "JULIAN",
"JOHANA", "JENICE", "JANNET", "JANISE", "JULENE",
"JOSHUA", "JANEAN", "JAIMEE", "JOETTE", "JANYCE",
"JENEVA", "JORDAN", "JACOBS", "JENSEN", "JOSEPH",
"JANSEN", "JORDON", "JULIAN", "JAEGER", "JACOBY",
"JENSON", "JARMAN", "JOSLIN", "JESSEN", "JAHNKE",
"JACOBO", "JULIEN", "JOSHUA", "JEPSON", "JULIUS",
"JANSON", "JACOBI", "JUDSON", "JARBOE", "JOHSON",
"JANZEN", "JETTON", "JUNKER", "JONSON", "JAROSZ",
"JENNER", "JAGGER", "JASMIN", "JEPSEN", "JORDEN",
"JANNEY", "JUHASZ", "JERGEN", "JAKOB", "")
|| StringAt(0, 7, "JOHNSON", "JOHNNIE", "JASMINE", "JEANNIE", "JOHANNA",
"JANELLE", "JANETTE", "JULIANA", "JUSTINA", "JOSETTE",
"JOELLEN", "JENELLE", "JULIETA", "JULIANN", "JULISSA",
"JENETTE", "JANETTA", "JOSELYN", "JONELLE", "JESENIA",
"JANESSA", "JAZMINE", "JEANENE", "JOANNIE", "JADWIGA",
"JOLANDA", "JULIANE", "JANUARY", "JEANICE", "JANELLA",
"JEANETT", "JENNINE", "JOHANNE", "JOHNSIE", "JANIECE",
"JOHNSON", "JENNELL", "JAMISON", "JANSSEN", "JOHNSEN",
"JARDINE", "JAGGERS", "JURGENS", "JOURDAN", "JULIANO",
"JOSEPHS", "JHONSON", "JOZWIAK", "JANICKI", "JELINEK",
"JANSSON", "JOACHIM", "JANELLE", "JACOBUS", "JENNING",
"JANTZEN", "JOHNNIE", "")
|| StringAt(0, 8, "JOSEFINA", "JEANNINE", "JULIANNE", "JULIANNA", "JONATHAN",
"JONATHON", "JEANETTE", "JANNETTE", "JEANETTA", "JOHNETTA",
"JENNEFER", "JULIENNE", "JOSPHINE", "JEANELLE", "JOHNETTE",
"JULIEANN", "JOSEFINE", "JULIETTA", "JOHNSTON", "JACOBSON",
"JACOBSEN", "JOHANSEN", "JOHANSON", "JAWORSKI", "JENNETTE",
"JELLISON", "JOHANNES", "JASINSKI", "JUERGENS", "JARNAGIN",
"JEREMIAH", "JEPPESEN", "JARNIGAN", "JANOUSEK", "")
|| StringAt(0, 9, "JOHNATHAN", "JOHNATHON", "JORGENSEN", "JEANMARIE", "JOSEPHINA",
"JEANNETTE", "JOSEPHINE", "JEANNETTA", "JORGENSON", "JANKOWSKI",
"JOHNSTONE", "JABLONSKI", "JOSEPHSON", "JOHANNSEN", "JURGENSEN",
"JIMMERSON", "JOHANSSON", "")
|| StringAt(0, 10, "JAKUBOWSKI", ""))
{
return true;
}
return false;
}
/**
* @param args
*/
public static void main(String[] args)
{
// example code
Metaphone3 m3 = new Metaphone3();
//m3.SetEncodeVowels(true);
//m3.SetEncodeExact(true);
m3.SetWord("iron");
m3.Encode();
System.out.println("iron : " + m3.GetMetaph());
System.out.println("iron : (alt) " + m3.GetAlternateMetaph());
m3.SetWord("witz");
m3.Encode();
System.out.println("witz : " + m3.GetMetaph());
System.out.println("witz : (alt) " + m3.GetAlternateMetaph());
m3.SetWord("");
m3.Encode();
System.out.println("BLANK : " + m3.GetMetaph());
System.out.println("BLANK : (alt) " + m3.GetAlternateMetaph());
// these settings default to false
m3.SetEncodeExact(true);
m3.SetEncodeVowels(true);
String test = new String("Guillermo");
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "VILLASENOR";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "GUILLERMINA";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "PADILLA";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "BJORK";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "belle";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "ERICH";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "CROCE";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "GLOWACKI";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "qing";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
test = "tsing";
m3.SetWord(test);
m3.Encode();
System.out.println(test + " : " + m3.GetMetaph());
System.out.println(test + " : (alt) " + m3.GetAlternateMetaph());
}
} |
package oasis.model.accounts;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.wordnik.swagger.annotations.ApiModelProperty;
public class AccessToken extends Token {
@JsonProperty
@ApiModelProperty
private String serviceProviderId;
@JsonProperty
@ApiModelProperty
private Set<String> scopeIds;
@JsonProperty
@ApiModelProperty
private String refreshTokenId;
public String getRefreshTokenId() {
return refreshTokenId;
}
public void setRefreshTokenId(String refreshTokenId) {
this.refreshTokenId = refreshTokenId;
}
public String getServiceProviderId() {
return serviceProviderId;
}
public void setServiceProviderId(String serviceProviderId) {
this.serviceProviderId = serviceProviderId;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public void setScopeIds(Set<String> scopeIds) {
this.scopeIds = scopeIds;
}
} |
package com.WildAmazing.marinating.CombatTag;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.*;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Listener;
import org.bukkit.plugin.java.JavaPlugin;
/**
* CombatTag for Bukkit
*
* @author <Your Name>
*/
public class CombatTag extends JavaPlugin {
private final CombatTagPlayerListener playerListener = new CombatTagPlayerListener(this);
private final CombatTagEntityListener entityListener = new CombatTagEntityListener(this);
private HashMap<String, PlayerCombatClass> PLAYERLIST = new HashMap<String, PlayerCombatClass>(); //All players should be in this list.
static String mainDirectory = "plugins/CombatTag";
public static File CONFIG = new File(mainDirectory + File.separator + "CombatTag.properties");
public static File PVPLOG = new File(mainDirectory + File.separator + "CombatTag.Players");
static Properties prop = new Properties();
Properties pvploggers = new Properties();
private long TAGTIME = 15000; //time in milliseconds (1000 is 1)
private long GRACEPERIOD = 45000; //time in milliseconds before players are considered penalized
// private long EXTENDEDGRACEPERIOD = 30000; //grace period for players who accidently disconnect.
private String PENALTY = "DEATH";
private boolean INVENTORYCLEAR = true;
private boolean LIGHTNING = false;
private boolean DEBUG = false;
private int MAXRELOG = 1; //Number of times a player can relog during a tag
private String MSG2PLR = "&d[CombatTag] &c $tagged &6 was executed for logging off while in combat with &c $tagger";
private String MSG1PLR = "&d[CombatTag] &c $tagged &6 was executed for logging off during pvp";
private String ITEMSDROPPEDMSG = "&d[CombatTag] &c $tagged &6 has pvp logged. His/Her items drop at your feet";
public static Logger log = Logger.getLogger("Minecraft");
public CombatTag(){
super();
}
public void onEnable() {
log.info("[CombatTag] Operational.");
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_JOIN, playerListener, Event.Priority.Low, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_QUIT, playerListener, Event.Priority.Low, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_KICK, playerListener, Event.Priority.Normal, this);
getServer().getPluginManager().registerEvent(Event.Type.PLAYER_RESPAWN, playerListener, Event.Priority.Low, this);
getServer().getPluginManager().registerEvent(Event.Type.ENTITY_DAMAGE, (Listener) entityListener, Event.Priority.Monitor, this);
new File(mainDirectory).mkdir(); //directory for the config file
if(!CONFIG.exists()){ //Make config file if it doesn't exist
try {
CONFIG.createNewFile(); //make new file
FileOutputStream out = new FileOutputStream(CONFIG); //for writing the file
// prop.put("Extended_Grace_Period", "30");
prop.put("Debug", "False");
prop.put("Penalty", "DEATH");
prop.put("PvpMessage2plr", "&d[CombatTag] &c $tagged &6 was executed for logging off while in combat with &c $tagger");
prop.put("PvpMessage1plr", "&d[CombatTag] &c $tagged &6 was executed for logging off during pvp");
prop.put("ItemsDroppedMsg", "&d[CombatTag] &c $tagged &6 has pvp logged. His/Her items drop at your feet");
prop.put("TagTime", "15");
prop.put("Grace_period","45");
prop.put("MaxRelog", "1");
prop.put("Lightning","false");
prop.store(out, " TagTime = duration of tag" + "\r\n Grace_period = time the player has to relog (starting from the moment they logout)"
+ "\r\n Debug = enables debug mode (be ready for the spam)" + "\r\n PvpMessage2plr is called upon a pvp logger logging back in.\r\n It supports $tagger (person who hit the pvplogger) and $tagged (Pvplogger).\r\n It also supports color coding using the &(0-9,a-f)"
+ "\r\n PvpMessage1plr is nearly the same as PvpMessage1plr except it is called when the pvp logger did not log back in before the server was reloaded or restarted.\r\n It supports $tagged and &colors only."
+ "\r\n ItemsDroppedMsg is called when the player is considered a pvplogger(when the items would normally drop to the gound)." +
"\r\n It supports $tagger,$tagged and chat colors and only send the message to the person who tagged the pvp logger, as apposed to the entire server." +
"\r\n MaxRelog is the maximum number of times a player can relog during a tag period." +
"\r\n Lightning (true or false) Strikes lightning at players location upon logging back in. \r\n Only works when penalty is set to DEATH");
out.flush();
out.close(); //save and close writer
log.info("[CombatTag] New file created.");
} catch (IOException ex) {
log.warning("[CombatTag] File creation error: "+ex.getMessage());
}
}
if(!PVPLOG.exists()){
try {
PVPLOG.createNewFile();
FileOutputStream badplayers = new FileOutputStream(PVPLOG);
pvploggers.store(badplayers, "Do not edit this file\r\n This file is only for players who have not yet been punished by combattag.");
badplayers.flush();
badplayers.close();
log.info("[CombatTag] BadPlayers file created.");
}
catch (IOException ex){
log.warning("[CombatTag] File creation error: " + ex.getMessage());
}
}
else {
log.info("[CombatTag] Detected existing config file and loading.");
loadProcedure();//added later
logit("Debug is enabled! Be ready for the spam.");
}
loadplayers();//get players currently online here
}
public void loadProcedure(){
try {
FileInputStream in = new FileInputStream(CONFIG); //Creates the input stream
prop.load(in); //loads file
PENALTY = prop.getProperty("Penalty");
// EXTENDEDGRACEPERIOD = Long.parseLong(prop.getProperty("Extended_Grace_Period"))*1000; //To be implemented (will change time depending on disconect type)
TAGTIME = Long.parseLong(prop.getProperty("TagTime"))*1000;
GRACEPERIOD = Long.parseLong(prop.getProperty("Grace_period"))*1000;
LIGHTNING = Boolean.parseBoolean(prop.getProperty("Lightning"));
DEBUG = Boolean.parseBoolean(prop.getProperty("Debug"));
MSG2PLR = prop.getProperty("PvpMessage2plr");
MSG1PLR = prop.getProperty("PvpMessage1plr");
ITEMSDROPPEDMSG = prop.getProperty("ItemsDroppedMsg");
MAXRELOG = Integer.parseInt(prop.getProperty("MaxRelog"));
in.close(); //Closes the input stream.
FileInputStream inplayerfile = new FileInputStream(PVPLOG);
pvploggers.load(inplayerfile);
inplayerfile.close();
}catch (Exception e){
log.severe("[CombatTag] Loading error: "+e.getMessage());
}
}
public void onDisable() {
try {
for (PlayerCombatClass i : PLAYERLIST.values())
{
if(i.hasPvplogged() == true)
{
pvploggers.put(i.getPlayerName(), "logged");
}
}
FileOutputStream badplayers = new FileOutputStream(PVPLOG);
pvploggers.store(badplayers, "Do not edit this file\r\n This file is only for players who have not yet been punished by combattag.");
badplayers.flush();
badplayers.close();
} catch (FileNotFoundException e) {
log.info("Combat tag has encountered error" + e);
} catch (IOException e) {
log.info("Combat tag has encountered error" + e);
}
log.info("[CombatTag] Out.");
}
public boolean checkpvplogger(String Playername)
{
if(pvploggers.containsKey(Playername))
{
return true;
}
else
{
return false;
}
}
public void removepvplogger(String Playername)
{
pvploggers.remove(Playername);
}
public boolean getLightning(){
return LIGHTNING;
}
public int getMaxRelog()
{
return MAXRELOG;
}
public long getGracePeriod(){
return GRACEPERIOD;
}
/* public long getExtendedGracePeriod()
{
return EXTENDEDGRACEPERIOD;
}
*/
public String getPenalty(){
return PENALTY;
}
public void setPenalty(String s){
PENALTY = s;
}
public boolean getInventoryClear(){
return INVENTORYCLEAR;
}
public void setInventoryClear(boolean b){
INVENTORYCLEAR = b;
}
public long getTagTime()
{
return TAGTIME;
}
public boolean isinPlayerList(String PlayerName)
{
return(PLAYERLIST.containsKey(PlayerName));
}
public PlayerCombatClass getPCC(String PlayerName)// Retrieves PlayerCombatClass from HashMap
{
return(PLAYERLIST.get(PlayerName));
}
public void addtoPCC(Player myplayer)// Adds Player to HashMap PlayerList
{
PLAYERLIST.put(myplayer.getName(),new PlayerCombatClass(myplayer));
return;
}
public void logit(String stringlog)
{
if (DEBUG == true){
log.info(stringlog);
}
}
public void loadplayers()//Loads Players upon starting up. Used for reloads and such
{
logit("loading all players currently in world");
//Add all Players currently online to the PLAYERLIST
List<World> myworlds = getServer().getWorlds();
for(int i = 0;myworlds.size() > i; i++)
{
List<Player> myplayers = myworlds.get(i).getPlayers();
for(int k = 0;myplayers.size() > k; k++)
{
addtoPCC(myplayers.get(k));
}
}
return;
}
public void killAndClean(Player p)//Kills Player and cleans inventory
{
if (getPenalty().equalsIgnoreCase("DEATH")){
p.getInventory().clear();
if (getLightning())
{
logit("Lightning struck at " + p.getName() + "'s location");
p.getWorld().strikeLightning(p.getLocation());
}
logit(p.getName() + "'s inventory has been cleared and killed");
p.setHealth(0);
}
}
public void removetaggedfromallplrs(String PlayerName)// Removes Player from all other players tagged list
{
for (PlayerCombatClass i : PLAYERLIST.values()){
i.removeFromTaggedPlayers(PlayerName);
}
logit("Removing " + PlayerName + " from all players taged list");
return;
}
public void dropitemsandclearPCCitems(String Winner, String Loser)// Drops items naturally infront of Player and removes items from ...
{
PlayerCombatClass PCCLoser = getPCC(Loser);
PlayerCombatClass PCCWinner = getPCC(Winner);
if(isPlrOnline(PCCWinner.getPlayerName()))
{
Player PlrWinner = getServer().getPlayer(PCCWinner.getPlayerName());//Winner by default (or by pvp logging)
sendMessageWinner(PlrWinner, PCCLoser.getPlayerName());
if(getPenalty().equalsIgnoreCase("DEATH"))
{
logit("dropping " + Loser + "items at " + Winner + "'s feet");
for(int i = 0;PCCLoser.getItems().size() > i; i++)
{
PlrWinner.getWorld().dropItemNaturally(PlrWinner.getLocation(), PCCLoser.getItems().get(i));
}
}
}
else
{
logit("Unable to get winner null returned. (winner not online)");
}
PCCLoser.clearItems();
return;
}
public void configureTaggerAndTagged(PlayerCombatClass Tagger, PlayerCombatClass Tagged)//Configures Tagged and Tagger appropriately
{
if(!(Tagger.hasTaggedPlayer(Tagged.getPlayerName())))
{
Tagged.setTaggedBy(Tagger.getPlayerName()); //Sets tagger as the tagger for tagged
Tagger.addToTaggedPlayers(Tagged.getPlayerName()); //Adds Tagged player to Taggers player list
}
Tagged.setTagExpiration(getTagTime());// Sets the tag expiration for Tagged
}
public void announcePvPLog(String tagged, String tagger)
{
String Messageout = MSG2PLR;
Messageout = Messageout.replace("$tagged", tagged);
Messageout = Messageout.replace("$tagger", tagger);
Messageout = Messageout.replaceAll("&([0-9a-f])", "\u00A7$1");
getServer().broadcastMessage(Messageout);
}
public void announcePvPLog(String tagged)
{
String Messageout = MSG1PLR;
Messageout = Messageout.replace("$tagged", tagged);
Messageout = Messageout.replaceAll("&([0-9a-f])", "\u00A7$1");
getServer().broadcastMessage(Messageout);
}
public void sendMessageWinner(Player winner, String Loser)
{
String mymessage = ITEMSDROPPEDMSG;
mymessage = mymessage.replace("$tagged", Loser );
mymessage = mymessage.replaceAll("&([0-9a-f])", "\u00A7$1");
winner.sendMessage(mymessage);
}
public boolean isPlrOnline(String Playername)
{
try
{
Player myplayer = getServer().getPlayer(Playername);
return myplayer.isOnline();
}
catch(NullPointerException e)
{
return false;
}
}
public void updateTags(String playername, Boolean Continue_deeper)//Updates tags for players (called from onCommand)
{
PlayerCombatClass Tagged = getPCC(playername); //Player1 (tagged player)
if(Tagged.isTagged())
{
if(Tagged.tagExpired())
{
if(isPlrOnline(Tagged.getPlayerName()))//If tagged is online
{
Tagged.removeTimesReloged();
PlayerCombatClass Tagger = getPCC(Tagged.getTaggedBy());
Tagged.removeTaggedBy();
Tagger.removeFromTaggedPlayers(Tagged.getPlayerName());
//remove tags here
}
}
}
if(Continue_deeper == true)
{
if(Tagged.hasTaggedPlayer())// Check to see if Player has tagged other players
{
logit(Tagged.getPlayerName() + " has tagged players");
ArrayList<String> Myarray = Tagged.getTaggedPlayers();// Temporary arraylist for deep copy
logit("setting up iterator");
//Make a deep copy of Myarray
Iterator<String> itr = Myarray.iterator(); // Setup iterator
ArrayList<String> backup = new ArrayList<String>();
while (itr.hasNext())//Check to see if there is another element in Myarray
{
backup.add(itr.next()); //Copy each element in arraylist
}
//Deep copy finished
Iterator<String> newitr = backup.iterator();//Setup iterator
while(newitr.hasNext())// Check to see if there is another element in backup
{
String currentplayer = newitr.next();
logit("recursive call to update tags using " + currentplayer);
updateTags(currentplayer, false);// Recursive call for tagged player
}
}
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args)
{
if(command.getName().equalsIgnoreCase("ct") || command.getName().equalsIgnoreCase("combattag"))
{
if(sender instanceof Player)
{
if(args.length == 0)
{
Player CmdPlr = (Player)sender;
PlayerCombatClass PCCPlr = getPCC(CmdPlr.getName());
updateTags(PCCPlr.getPlayerName(),true);//Updates tags to represent most recent values
if(PCCPlr.isTagged())
{
CmdPlr.sendMessage(ChatColor.GOLD + "You are tagged by " + ChatColor.RED +PCCPlr.getTaggedBy() + ChatColor.GOLD +" for " + PCCPlr.tagPeriodInSeconds() + " more seconds.");
CmdPlr.sendMessage(ChatColor.GOLD + "You have " + getGracePeriod()/1000 + " seconds to relog");
CmdPlr.sendMessage(ChatColor.GOLD + "You have " + new Integer (getMaxRelog()-PCCPlr.getTimesReloged()).toString() + " relog(s) remaining for this tag");
}
else
{
CmdPlr.sendMessage(ChatColor.GOLD + "You are not tagged.");
}
CmdPlr.sendMessage(ChatColor.GOLD + "You have tagged : " + ChatColor.RED +PCCPlr.TaggedList());//Sends the player a list of players he has tagged
return true;
}
}
else
{
log.info("Only Players can use CombatTag");
return true;
}
}
return false;
}
} |
package org.voovan.tools.buffer;
import org.voovan.Global;
import org.voovan.tools.*;
import org.voovan.tools.collection.ThreadObjectPool;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.atomic.LongAdder;
public class TByteBuffer {
public final static int DEFAULT_BYTE_BUFFER_SIZE = TEnv.getSystemProperty("ByteBufferSize", 1024*8);
public final static int THREAD_BUFFER_POOL_SIZE = TEnv.getSystemProperty("ThreadBufferPoolSize", 64);
public final static LongAdder MALLOC_SIZE = new LongAdder();
public final static LongAdder MALLOC_COUNT = new LongAdder();
public final static LongAdder BYTE_BUFFER_COUNT = new LongAdder();
public final static int BYTE_BUFFER_ANALYSIS = TEnv.getSystemProperty("ByteBufferAnalysis", 0);
public static void malloc(int capacity) {
if(BYTE_BUFFER_ANALYSIS >= 0) {
MALLOC_SIZE.add(capacity);
MALLOC_COUNT.increment();
BYTE_BUFFER_COUNT.increment();
}
}
public static void realloc(int oldCapacity, int newCapacity) {
if(BYTE_BUFFER_ANALYSIS >= 0) {
MALLOC_SIZE.add(newCapacity - oldCapacity);
}
}
public static void free(int capacity) {
if(BYTE_BUFFER_ANALYSIS >= 0) {
MALLOC_SIZE.add(-1 * capacity);
MALLOC_COUNT.decrement();
BYTE_BUFFER_COUNT.decrement();
}
}
public static Map<String, Long> getByteBufferAnalysis() {
return TObject.asMap("Time", TDateTime.now(), "MallocSize", TString.formatBytes(MALLOC_SIZE.longValue()),
"MallocCount", MALLOC_COUNT.longValue(),
"ByteBufferCount", BYTE_BUFFER_COUNT.longValue());
}
static {
if(BYTE_BUFFER_ANALYSIS > 0) {
Global.getHashWheelTimer().addTask(() -> {
Logger.simple(getByteBufferAnalysis());
}, BYTE_BUFFER_ANALYSIS);
}
}
public final static ThreadObjectPool<ByteBuffer> THREAD_BYTE_BUFFER_POOL = new ThreadObjectPool<ByteBuffer>(THREAD_BUFFER_POOL_SIZE, ()->allocateManualReleaseBuffer(DEFAULT_BYTE_BUFFER_SIZE));
static {
System.out.println("[SYTSEM] ThreadBufferPoolSize: " + THREAD_BYTE_BUFFER_POOL.getThreadPoolSize());
System.out.println("[SYTSEM] BufferSize: " + DEFAULT_BYTE_BUFFER_SIZE);
}
public final static ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocateDirect(0);
public final static Class DIRECT_BYTE_BUFFER_CLASS = EMPTY_BYTE_BUFFER.getClass();
public final static Constructor DIRECT_BYTE_BUFFER_CONSTURCTOR = getConsturctor();
static {
DIRECT_BYTE_BUFFER_CONSTURCTOR.setAccessible(true);
}
public final static Field addressField = ByteBufferField("address");
public final static Field capacityField = ByteBufferField("capacity");
public final static Field attField = ByteBufferField("att");
private static Constructor getConsturctor(){
try {
Constructor constructor = DIRECT_BYTE_BUFFER_CLASS.getDeclaredConstructor(long.class, int.class, Object.class);
constructor.setAccessible(true);
return constructor;
} catch (NoSuchMethodException e) {
Logger.error(e);
}
return null;
}
private static Field ByteBufferField(String fieldName){
Field field = TReflect.findField(DIRECT_BYTE_BUFFER_CLASS, fieldName);
field.setAccessible(true);
return field;
}
/**
* ByteBuffer
* @param capacity
* @return ByteBuffer
*/
protected static ByteBuffer allocateManualReleaseBuffer(int capacity){
try {
long address = (TUnsafe.getUnsafe().allocateMemory(capacity));
Deallocator deallocator = new Deallocator(address, capacity);
ByteBuffer byteBuffer = (ByteBuffer) DIRECT_BYTE_BUFFER_CONSTURCTOR.newInstance(address, capacity, deallocator);
Cleaner.create(byteBuffer, deallocator);
malloc(capacity);
return byteBuffer;
} catch (Exception e) {
Logger.error("Allocate ByteBuffer error. ", e);
return null;
}
}
/**
* , ByteBuffer
* @return ByteBuffer
*/
public static ByteBuffer allocateDirect() {
return allocateDirect(DEFAULT_BYTE_BUFFER_SIZE);
}
/**
* , ByteBuffer
* @param capacity
* @return ByteBuffer
*/
public static ByteBuffer allocateDirect(int capacity) {
ByteBuffer byteBuffer = THREAD_BYTE_BUFFER_POOL.get(()->allocateManualReleaseBuffer(capacity));
if(capacity <= byteBuffer.capacity()) {
byteBuffer.limit(capacity);
} else {
reallocate(byteBuffer, capacity);
}
byteBuffer.position(0);
byteBuffer.limit(capacity);
return byteBuffer;
}
/**
* byteBuffer
* @param byteBuffer byteBuffer
* @param newSize
* @return true:, false:
*/
public static boolean reallocate(ByteBuffer byteBuffer, int newSize) {
if(isReleased(byteBuffer)) {
return false;
}
try {
int oldCapacity = byteBuffer.capacity();
if(oldCapacity > newSize){
byteBuffer.limit(newSize);
return true;
}
if(!byteBuffer.hasArray()) {
if(getAtt(byteBuffer) == null){
throw new UnsupportedOperationException("JDK's ByteBuffer can't reallocate");
}
long address = getAddress(byteBuffer);
long newAddress = TUnsafe.getUnsafe().reallocateMemory(address, newSize);
setAddress(byteBuffer, newAddress);
}else{
byte[] hb = byteBuffer.array();
byte[] newHb = Arrays.copyOf(hb, newSize);
TReflect.setFieldValue(byteBuffer, "hb", newHb);
}
capacityField.set(byteBuffer, newSize);
realloc(oldCapacity, newSize);
return true;
}catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.reallocate() Error. ", e);
}
return false;
}
/**
* Bytebuffer
* Bytebuffer.position(), offset
* @param byteBuffer byteBuffer
* @param offset ByteBuffer.position
* @return true:, false:
*/
public static boolean move(ByteBuffer byteBuffer, int offset) {
try {
if(byteBuffer.remaining() == 0) {
byteBuffer.position(0);
byteBuffer.limit(0);
return true;
}
if(offset==0){
return true;
}
int newPosition = byteBuffer.position() + offset;
int newLimit = byteBuffer.limit() + offset;
if(newPosition < 0){
return false;
}
if(newLimit > byteBuffer.capacity()){
reallocate(byteBuffer, newLimit);
}
if(!byteBuffer.hasArray()) {
long address = getAddress(byteBuffer);
if(address!=0) {
long startAddress = address + byteBuffer.position();
long targetAddress = address + newPosition;
if (address > targetAddress) {
targetAddress = address;
}
TUnsafe.getUnsafe().copyMemory(startAddress, targetAddress, byteBuffer.remaining());
}
}else{
byte[] hb = byteBuffer.array();
System.arraycopy(hb, byteBuffer.position(), hb, newPosition, byteBuffer.remaining());
}
byteBuffer.limit(newLimit);
byteBuffer.position(newPosition);
return true;
}catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.moveData() Error.", e);
}
return false;
}
/**
* Bytebuffer
* @param byteBuffer ByteBuffer
* @return
* @throws ReflectiveOperationException
*/
public static ByteBuffer copy(ByteBuffer byteBuffer) throws ReflectiveOperationException {
ByteBuffer newByteBuffer = TByteBuffer.allocateDirect(byteBuffer.capacity());
if(byteBuffer.hasRemaining()) {
long address = getAddress(byteBuffer);
long newAddress = getAddress(newByteBuffer);
TUnsafe.getUnsafe().copyMemory(address, newAddress + byteBuffer.position(), byteBuffer.remaining());
}
newByteBuffer.position(byteBuffer.position());
newByteBuffer.limit(byteBuffer.limit());
return newByteBuffer;
}
/**
* srcBuffer appendBuffer;
* @param srcBuffer srcBuffer
* @param srcPosition
* @param appendBuffer
* @param appendPosition
* @param length
* @return srcBuffer
*/
public static ByteBuffer append(ByteBuffer srcBuffer, int srcPosition, ByteBuffer appendBuffer, int appendPosition, int length) {
try {
int appendSize = appendBuffer.limit() < length ? appendBuffer.limit() : length;
long srcAddress = getAddress(srcBuffer) + srcPosition;
long appendAddress = getAddress(appendBuffer) + appendPosition;
int availableSize = srcBuffer.capacity() - srcBuffer.limit();
if (availableSize < appendSize) {
int newSize = srcBuffer.capacity() + appendSize;
reallocate(srcBuffer, newSize);
}
TUnsafe.getUnsafe().copyMemory(appendAddress, srcAddress, appendSize);
srcBuffer.limit(srcPosition + appendSize);
srcBuffer.position(srcBuffer.limit());
return srcBuffer;
} catch (ReflectiveOperationException e){
Logger.error("TByteBuffer.moveData() Error.", e);
}
return null;
}
/**
* byteBuffer
* bytebuffer
* @param byteBuffer bytebuffer
*/
public static void release(ByteBuffer byteBuffer) {
if(byteBuffer == null){
return;
}
if (byteBuffer != null) {
if(THREAD_BYTE_BUFFER_POOL.getPool().avaliable() > 0 &&
byteBuffer.capacity() > DEFAULT_BYTE_BUFFER_SIZE){
reallocate(byteBuffer, DEFAULT_BYTE_BUFFER_SIZE);
}
THREAD_BYTE_BUFFER_POOL.release(byteBuffer, (buffer)->{
try {
long address = TByteBuffer.getAddress(byteBuffer);
Object att = getAtt(byteBuffer);
if (address!=0 && att!=null && att.getClass() == Deallocator.class) {
if(address!=0) {
byteBuffer.clear();
synchronized (byteBuffer) {
byteBuffer.position(0);
byteBuffer.limit(0);
setCapacity(byteBuffer, 0);
setAddress(byteBuffer, 0);
TUnsafe.getUnsafe().freeMemory(address);
free(byteBuffer.capacity());
}
}
}
} catch (ReflectiveOperationException e) {
Logger.error(e);
}
});
}
}
/**
*
* @param byteBuffer ByteBuffer
* @return true: , false:
*/
public static boolean isReleased(ByteBuffer byteBuffer){
if(byteBuffer==null){
return true;
}
try {
return getAddress(byteBuffer) == 0;
}catch (ReflectiveOperationException e){
return true;
}
}
/**
* ByteBuffer byte
* @param bytebuffer ByteBuffer
* @return byte
*/
public static byte[] toArray(ByteBuffer bytebuffer){
if(!bytebuffer.hasArray()) {
if(isReleased(bytebuffer)) {
return new byte[0];
}
bytebuffer.mark();
int position = bytebuffer.position();
int limit = bytebuffer.limit();
byte[] buffers = new byte[limit-position];
bytebuffer.get(buffers);
bytebuffer.reset();
return buffers;
}else{
return Arrays.copyOfRange(bytebuffer.array(), 0, bytebuffer.limit());
}
}
/**
* Bytebuffer
* @param bytebuffer Bytebuffer
* @param charset
* @return
*/
public static String toString(ByteBuffer bytebuffer,String charset) {
try {
return new String(toArray(bytebuffer), charset);
} catch (UnsupportedEncodingException e) {
Logger.error(charset+" is not supported",e);
return null;
}
}
/**
* Bytebuffer
* @param bytebuffer Bytebuffer
* @return
*/
public static String toString(ByteBuffer bytebuffer) {
return toString(bytebuffer, "UTF-8");
}
/**
* byte
* byte
* @param byteBuffer Bytebuffer
* @param mark byte
* @return
*/
public static int indexOf(ByteBuffer byteBuffer, byte[] mark){
if(isReleased(byteBuffer)) {
return -1;
}
if(byteBuffer.remaining() == 0){
return -1;
}
int originPosition = byteBuffer.position();
int length = byteBuffer.remaining();
if(length < mark.length){
return -1;
}
int index = -1;
int i = byteBuffer.position();
int j = 0;
while(i <= (byteBuffer.limit() - mark.length + j ) ){
if(byteBuffer.get(i) != mark[j] ){
if(i == (byteBuffer.limit() - mark.length + j )){
break;
}
int pos = TByte.byteIndexOf(mark, byteBuffer.get(i+mark.length-j));
if( pos== -1){
i = i + mark.length + 1 - j;
j = 0 ;
}else{
i = i + mark.length - pos - j;
j = 0;
}
}else{
if(j == (mark.length - 1)){
i = i - j + 1 ;
j = 0;
index = i-j - 1;
break;
}else{
i++;
j++;
}
}
}
byteBuffer.position(originPosition);
return index;
}
/**
*
* @param byteBuffer bytebuffer
* @return
* @throws ReflectiveOperationException
*/
public static Long getAddress(ByteBuffer byteBuffer) throws ReflectiveOperationException {
return (Long) addressField.get(byteBuffer);
}
/**
*
* @param byteBuffer bytebuffer
* @param address
* @throws ReflectiveOperationException
*/
public static void setAddress(ByteBuffer byteBuffer, long address) throws ReflectiveOperationException {
addressField.set(byteBuffer, address);
Object att = getAtt(byteBuffer);
if(att!=null && att.getClass() == Deallocator.class){
((Deallocator) att).setAddress(address);
}
}
/**
*
* @param byteBuffer bytebuffer
* @return
* @throws ReflectiveOperationException
*/
public static Object getAtt(ByteBuffer byteBuffer) throws ReflectiveOperationException {
return attField.get(byteBuffer);
}
/**
*
* @param byteBuffer bytebuffer
* @param attr
* @throws ReflectiveOperationException
*/
public static void setAttr(ByteBuffer byteBuffer, Object attr) throws ReflectiveOperationException {
attField.set(byteBuffer, attr);
}
/**
*
* @param byteBuffer bytebuffer
* @param capacity
* @throws ReflectiveOperationException
*/
public static void setCapacity(ByteBuffer byteBuffer, int capacity) throws ReflectiveOperationException {
capacityField.set(byteBuffer, capacity);
Object att = getAtt(byteBuffer);
if(att!=null && att.getClass() == Deallocator.class){
((Deallocator) att).setCapacity(capacity);
}
}
} |
package io.rouz.task.cli;
import io.rouz.task.Task;
import joptsimple.OptionParser;
/**
* Used to create a {@link Task} by parsing arguments from a String array.
*
* Use with {@link Cli}.
*/
public interface TaskConstructor<T> {
/**
* @return The name of the task being created
*/
String name();
/**
* Create an instance of the task by parsing the arguments from a String array
*
* @param args The arguments to parse
* @return an instance of the task
*/
Task<T> create(String... args);
/**
* @return The underlying {@link joptsimple.OptionParser} for this task constructor
*/
OptionParser parser();
} |
// <auto-generated>
// This code was generated by a tool.
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
package com.sharefile.api.entities;
import com.sharefile.api.entities.*;
import com.sharefile.api.models.*;
import com.sharefile.api.models.internal.*;
import com.sharefile.api.SFApiQuery;
import com.sharefile.api.interfaces.ISFQuery;
import java.io.InputStream;
import java.util.ArrayList;
import java.net.URI;
import java.util.Date;
import com.google.gson.annotations.SerializedName;
import com.sharefile.api.enumerations.SFSafeEnum;
public class SFItemsEntity extends SFODataEntityBase
{
public ISFQuery<SFItem> get()
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Item by ID
* Returns a single Item
* @param url
* @param includeDeleted
* @return a single Item
*/
public ISFQuery<SFItem> get(URI url, Boolean includeDeleted)
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("includeDeleted", includeDeleted);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get TreeView
* Retrieves a folder list structure tailored for TreeView navigation - used by clients
* to create folder trees for specific operations.
* This operation will enforce a specific $select and $expand operators. You can provide
* additional $expand, for example Children, which is not added by default. The $select
* operator will apply to the expanded objects as well. You can also specify additional
* $select elements.
* @param url
* @param treeMode
* @param sourceId
* @param canCreateRootFolder
* @param fileBox
* @return A tree root element.
*/
public ISFQuery<SFItem> get(URI url, SFSafeEnum<SFTreeMode> treeMode, String sourceId, Boolean canCreateRootFolder, Boolean fileBox)
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("treeMode", treeMode);
sfApiQuery.addQueryString("sourceId", sourceId);
sfApiQuery.addQueryString("canCreateRootFolder", canCreateRootFolder);
sfApiQuery.addQueryString("fileBox", fileBox);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
public ISFQuery<SFODataFeed<SFItem>> getChildrenByConnectorGroup(URI url)
{
SFApiQuery<SFODataFeed<SFItem>> sfApiQuery = new SFApiQuery<SFODataFeed<SFItem>>();
sfApiQuery.setFrom("ConnectorGroups");
sfApiQuery.setAction("Children");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Stream
* Retrieves the versions of a given Stream.
* An Item represents a single version of a file system object. The stream identifies
* all versions of the same file system object. For example, when users upload or modify an existing file, a new Item
* is created with the same StreamID. All default Item enumerations return only the latest version of a given stream.
* Use this method to retrieve previous versions of a given stream
* @param url
* @param includeDeleted
*/
public ISFQuery<SFODataFeed<SFItem>> stream(URI url, Boolean includeDeleted)
{
SFApiQuery<SFODataFeed<SFItem>> sfApiQuery = new SFApiQuery<SFODataFeed<SFItem>>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Stream");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("includeDeleted", includeDeleted);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Item by Path
* Retrieves an item from its path. The path is of format /foldername/foldername/filename
* This call may redirect the client to another API provider, if the path
* contains a symbolic link.
* @param path
* @return An item identified by a path
*/
public ISFQuery<SFItem> byPath(String path)
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("ByPath");
sfApiQuery.addQueryString("path", path);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Item by relative Path from ID
* Retrieves an item from its path, relative to the provided ID.
* The path is of format /foldername/foldername/filename
* This call may redirect the client to another API provider, if the path
* contains a symbolic link.
* @param url
* @param path
* @return An item identified by a path
*/
public ISFQuery<SFItem> byPath(URI url, String path)
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("ByPath");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("path", path);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Parent Item
* Retrieves the Parent navigation property of a single Item.
* @param url
* @return the Parent Item of the give object ID.
*/
public ISFQuery<SFItem> getParent(URI url)
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Parent");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Children
* Handler for the Children navigation property of a given Item.
* A 302 redirection is returned if the folder is a SymbolicLink. The redirection
* will enumerate the children of the remote connector
* @param url
* @param includeDeleted
* @return the list of children under the given object ID
*/
public ISFQuery<SFODataFeed<SFItem>> getChildren(URI url, Boolean includeDeleted)
{
SFApiQuery<SFODataFeed<SFItem>> sfApiQuery = new SFApiQuery<SFODataFeed<SFItem>>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Children");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("includeDeleted", includeDeleted);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Folder Access Info
* Returns the effective Access Controls for the current authenticated user for the
* selected folder - i.e., the resulting set of Access Controls for the Item/User context.This operation applies to Folders only, will return an error for other Item types.
* @param url
* @return The Folder Access Control Information
*/
public ISFQuery<SFItemInfo> getInfo(URI url)
{
SFApiQuery<SFItemInfo> sfApiQuery = new SFApiQuery<SFItemInfo>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Info");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Download Item Content
* Initiate the download operation for an item. It will return 302 redirection to the
* actual download link. For Folders, the download link will retrieve a ZIP archive
* with the contents of the Folder.
* @param url
* @param redirect
* @return the download link for the provided item content.
*/
public ISFQuery<InputStream> download(URI url, Boolean redirect)
{
SFApiQuery<InputStream> sfApiQuery = new SFApiQuery<InputStream>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Download");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("redirect", redirect);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Create Folder
* {
* "Name":"Folder Name",
* "Description":"Description",
* "Zone":{ "Id":"z014766e-8e96-4615-86aa-57132a69843c" }
* }
* Creates a new Folder.
* The POST body must contain the serialized object.
* For top-level folders, use Items/Folder.
* The Zone object may only be provided for top-level folders. The Zone object must
* contain a zone ID.
* @param parentUrl
* @param folder
* @param overwrite
* @param passthrough
* @return the new Folder
*/
public ISFQuery<SFFolder> createFolder(URI parentUrl, SFFolder folder, Boolean overwrite, Boolean passthrough)
{
SFApiQuery<SFFolder> sfApiQuery = new SFApiQuery<SFFolder>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Folder");
sfApiQuery.addIds(parentUrl);
sfApiQuery.addQueryString("overwrite", overwrite);
sfApiQuery.addQueryString("passthrough", passthrough);
sfApiQuery.setBody(folder);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Create Note
* {
* "Name":"Note Name",
* "Description":"Description"
* }
* Creates a new Note.
* @param parentUrl
* @param note
* @return the new Note
*/
public ISFQuery<SFNote> createNote(URI parentUrl, SFNote note)
{
SFApiQuery<SFNote> sfApiQuery = new SFApiQuery<SFNote>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Note");
sfApiQuery.addIds(parentUrl);
sfApiQuery.setBody(note);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
public ISFQuery<SFLink> createLink(URI parentUrl, SFLink link)
{
SFApiQuery<SFLink> sfApiQuery = new SFApiQuery<SFLink>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Link");
sfApiQuery.addIds(parentUrl);
sfApiQuery.setBody(link);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Create SymbolicLink
* {
* "Name":"RemoteFileName",
* "Description":"Description",
* "Zone":{ "Id":"z014766e-8e96-4615-86aa-57132a69843c" },
* "ConnectorGroup": { "Id":"1" }
* }
* Creates a Symbolic Link
* The body must contain either a "Link" parameter with a fully qualified URI; or use
* FileName + Zone to have sharefile.com attempt to convert the Connector path to an
* URI using a call to the Zone - using ShareFile Hash authentication mode. For active
* clients, it's recommended to make the convertion call to the Zone directly, using
* Items/ByPath=name, retriving the resulting URL, and calling this method with the
* Link parameter.SymbolicLinks must be created as top-level folders - i.e., this call requires
* the parent to be the Item(accountid) element.Zone defines the location of the SymbolicLink target - for example, for
* Network Shares connectors, the SymbolicLink will point to the StorageZone Controller
* that will serve the file browsing requests.The ConnectorGroup parameter indicates the kind of symbolic link - e.g., Network
* Share, or SharePoint.
* @param parentUrl
* @param symlink
* @param overwrite
* @return the new SymbolicLink
*/
public ISFQuery<SFSymbolicLink> createSymbolicLink(URI parentUrl, SFSymbolicLink symlink, Boolean overwrite)
{
SFApiQuery<SFSymbolicLink> sfApiQuery = new SFApiQuery<SFSymbolicLink>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("SymbolicLink");
sfApiQuery.addIds(parentUrl);
sfApiQuery.addQueryString("overwrite", overwrite);
sfApiQuery.setBody(symlink);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
public ISFQuery<SFSymbolicLink> createChildrenByConnectorGroup(URI url, SFSymbolicLink symlink, Boolean overwrite)
{
SFApiQuery<SFSymbolicLink> sfApiQuery = new SFApiQuery<SFSymbolicLink>();
sfApiQuery.setFrom("ConnectorGroups");
sfApiQuery.setAction("Children");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("overwrite", overwrite);
sfApiQuery.setBody(symlink);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Update Item
* {
* "Name":"Name",
* "FileName":"FileName",
* "Description":"Description",
* "ExpirationDate": "date",
* "Parent": { "Id": "parentid" },
* "Zone": { "Id": "zoneid" }
* }
* Updates an Item object
* @param url
* @param item
* @param forceSync
* @return A modified Item object. If the item Zone or Parent Zone is modified, then this method will return an Asynchronous operation record instead. Note: the parameters listed in the body of the request are the only parameters that can be updated through this call.
*/
public ISFQuery<SFItem> update(URI url, SFItem item, String batchid, Long batchSizeInBytes, Boolean forceSync, Boolean scheduleAsync)
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("batchid", batchid);
sfApiQuery.addQueryString("batchSizeInBytes", batchSizeInBytes);
sfApiQuery.addQueryString("forceSync", forceSync);
sfApiQuery.addQueryString("scheduleAsync", scheduleAsync);
sfApiQuery.setBody(item);
sfApiQuery.setHttpMethod("PATCH");
return sfApiQuery;
}
public ISFQuery<SFLink> updateLink(URI url, SFLink link, Boolean notify)
{
SFApiQuery<SFLink> sfApiQuery = new SFApiQuery<SFLink>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Link");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("notify", notify);
sfApiQuery.setBody(link);
sfApiQuery.setHttpMethod("PATCH");
return sfApiQuery;
}
/**
* Update Note
* {
* "Name":"Name",
* "Description":"Description",
* "Parent": { "Id": "parentid" },
* }
* Updates a Note object
* @param url
* @param note
* @param notify
* @return The modified Note object
*/
public ISFQuery<SFNote> updateNote(URI url, SFNote note, Boolean notify)
{
SFApiQuery<SFNote> sfApiQuery = new SFApiQuery<SFNote>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Note");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("notify", notify);
sfApiQuery.setBody(note);
sfApiQuery.setHttpMethod("PATCH");
return sfApiQuery;
}
public ISFQuery<SFSymbolicLink> updateSymbolicLink(URI url, SFSymbolicLink symlink)
{
SFApiQuery<SFSymbolicLink> sfApiQuery = new SFApiQuery<SFSymbolicLink>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("SymbolicLink");
sfApiQuery.addIds(url);
sfApiQuery.setBody(symlink);
sfApiQuery.setHttpMethod("PATCH");
return sfApiQuery;
}
public ISFQuery delete(URI url, Boolean singleversion, Boolean forceSync)
{
SFApiQuery sfApiQuery = new SFApiQuery();
sfApiQuery.setFrom("Items");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("singleversion", singleversion);
sfApiQuery.addQueryString("forceSync", forceSync);
sfApiQuery.setHttpMethod("DELETE");
return sfApiQuery;
}
public ISFQuery bulkDelete(URI url, ArrayList<String> ids, Boolean forceSync, Boolean deletePermanently)
{
SFApiQuery sfApiQuery = new SFApiQuery();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("BulkDelete");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("ids", ids);
sfApiQuery.addQueryString("forceSync", forceSync);
sfApiQuery.addQueryString("deletePermanently", deletePermanently);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
public ISFQuery<InputStream> getThumbnail(URI url, Integer size, Boolean redirect)
{
SFApiQuery<InputStream> sfApiQuery = new SFApiQuery<InputStream>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Thumbnail");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("size", size);
sfApiQuery.addQueryString("redirect", redirect);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Breadcrumbs
* Retrieves the path from an item from the root. The return list is a Feed of Items, with the top-level
* folder at the first position. If this item is in a Connection path, the breadcrumbs may contain URL
* reference back to the parent account - and the Item in the feed will contain just the URL reference.
* @param url
* @param path
* @return A feed containing the path of folders from the specified root to the item, in order
*/
public ISFQuery<SFODataFeed<SFItem>> getBreadcrumbs(URI url, String path)
{
SFApiQuery<SFODataFeed<SFItem>> sfApiQuery = new SFApiQuery<SFODataFeed<SFItem>>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Breadcrumbs");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("path", path);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Copy Item
* Copies an item to a new target Folder. If the target folder is in another zone, the operation will
* return an AsyncOperation record instead. Clients may query the /AsyncOperation Entity to determine
* operation progress and result.
* @param url
* @param targetid
* @param overwrite
* @return the modified source object
*/
public ISFQuery<SFItem> copy(URI url, String targetid, Boolean overwrite)
{
SFApiQuery<SFItem> sfApiQuery = new SFApiQuery<SFItem>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Copy");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("targetid", targetid);
sfApiQuery.addQueryString("overwrite", overwrite);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Upload File
* Prepares the links for uploading files to the target Folder.
* This method returns an Upload Specification object. The fields are
* populated based on the upload method, provider, and resume parameters passed to the
* upload call.
* The Method determines how the URLs must be called.
*
* Standard uploads use a single HTTP POST message to the ChunkUri address provided in
* the response. All other fields will be empty. Standard uploads do not support Resume.
*
* Streamed uploads use multiple HTTP POST calls to the ChunkUri address. The client must
* append the parameters index, offset and hash to the end of the ChunkUri address. Index
* is a sequential number representing the data block (zero-based); Offset represents the
* byte offset for the block; and hash contains the MD5 hash of the block. The last HTTP
* POST must also contain finish=true parameter.
*
* Threaded uploads use multiple HTTP POST calls to ChunkUri, and can have a number of
* threads issuing blocks in parallel. Clients must append index, offset and hash to
* the end of ChunkUri, as explained in Streamed. After all chunks were sent, the client
* must call the FinishUri provided in this spec.
*
* For all uploaders, the contents of the POST Body can either be "raw", if the "Raw" parameter
* was provided to the Uploader, or use MIME multi-part form encoding otherwise. Raw uploads
* simply put the block content in the POST body - Content-Length specifies the size. Multi-part
* form encoding has to pass the File as a Form parameter named "File1".
*
* For streamed and threaded, if Resume options were provided to the Upload call, then the
* fields IsResume, ResumeIndex, ResumeOffset and ResumeFileHash MAY be populated. If they are,
* it indicates that the server has identified a partial upload with that specification, and is
* ready to resume on the provided parameters. The clients can then verify the ResumeFileHash to
* ensure the file has not been modified; and continue issuing ChunkUri calls from the ResumeIndex
* ResumeOffset parameters. If the client decides to restart, it should simply ignore the resume
* parameters and send the blocks from Index 0.
*
* For all uploaders: the result code for the HTTP POST calls to Chunk and Finish Uri can either
* be a 401 - indicating authentication is required; 4xx/5xx indicating some kind of error; or
* 200 with a Content Body of format 'ERROR:message'. Successful calls will return either a 200
* response with no Body, or with Body of format 'OK'.
* @param url
* @param method
* @param raw
* @param fileName
* @param fileSize
* @param batchId
* @param batchLast
* @param canResume
* @param startOver
* @param unzip
* @param tool
* @param overwrite
* @param title
* @param details
* @param isSend
* @param sendGuid
* @param opid
* @param threadCount
* @param responseFormat
* @param notify
* @param clientCreatedDateUTC
* @param clientModifiedDateUTC
* @return an Upload Specification element, containing the links for uploading, and the parameters for resume. The caller must know the protocol for sending the prepare, chunk and finish URLs returned in the spec; as well as negotiate the resume upload.
*/
public ISFQuery<SFUploadSpecification> upload(URI url, SFSafeEnum<SFUploadMethod> method, Boolean raw, String fileName, Long fileSize, String batchId, Boolean batchLast, Boolean canResume, Boolean startOver, Boolean unzip, String tool, Boolean overwrite, String title, String details, Boolean isSend, String sendGuid, String opid, Integer threadCount, String responseFormat, Boolean notify, Date clientCreatedDateUTC, Date clientModifiedDateUTC, Integer expirationDays)
{
SFApiQuery<SFUploadSpecification> sfApiQuery = new SFApiQuery<SFUploadSpecification>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Upload");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("method", method);
sfApiQuery.addQueryString("raw", raw);
sfApiQuery.addQueryString("fileName", fileName);
sfApiQuery.addQueryString("fileSize", fileSize);
sfApiQuery.addQueryString("batchId", batchId);
sfApiQuery.addQueryString("batchLast", batchLast);
sfApiQuery.addQueryString("canResume", canResume);
sfApiQuery.addQueryString("startOver", startOver);
sfApiQuery.addQueryString("unzip", unzip);
sfApiQuery.addQueryString("tool", tool);
sfApiQuery.addQueryString("overwrite", overwrite);
sfApiQuery.addQueryString("title", title);
sfApiQuery.addQueryString("details", details);
sfApiQuery.addQueryString("isSend", isSend);
sfApiQuery.addQueryString("sendGuid", sendGuid);
sfApiQuery.addQueryString("opid", opid);
sfApiQuery.addQueryString("threadCount", threadCount);
sfApiQuery.addQueryString("responseFormat", responseFormat);
sfApiQuery.addQueryString("notify", notify);
sfApiQuery.addQueryString("clientCreatedDateUTC", clientCreatedDateUTC);
sfApiQuery.addQueryString("clientModifiedDateUTC", clientModifiedDateUTC);
sfApiQuery.addQueryString("expirationDays", expirationDays);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Unlock File
* Unlock a locked file.
* This operation is only implemented in Sharepoint providers (/sp)
* @param url
* @param message
*/
public ISFQuery checkIn(URI url, String message)
{
SFApiQuery sfApiQuery = new SFApiQuery();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("CheckIn");
sfApiQuery.addIds(url);
sfApiQuery.addQueryString("message", message);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Lock File
* Locks a file.
* This operation is only implemented in Sharepoint providers (/sp)
* @param url
*/
public ISFQuery checkOut(URI url)
{
SFApiQuery sfApiQuery = new SFApiQuery();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("CheckOut");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Discard CheckOut
* Discards the existing lock on the file
* This operation is only implemented in Sharepoint providers (/sp)
* @param url
*/
public ISFQuery discardCheckOut(URI url)
{
SFApiQuery sfApiQuery = new SFApiQuery();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("DiscardCheckOut");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Search
* Search for Items matching the criteria of the query parameter
* @param query
* @return SearchResults
*/
public ISFQuery<SFSearchResults> search(String query)
{
SFApiQuery<SFSearchResults> sfApiQuery = new SFApiQuery<SFSearchResults>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Search");
sfApiQuery.addQueryString("query", query);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Advanced Simple Search
* {
* "Query":{
* "AuthID":"",
* "ItemType":"",
* "ParentID":"",
* "CreatorID":"",
* "LuceneQuery":"",
* "SearchQuery":"",
* "CreateStartDate":"",
* "CreateEndDate":"",
* "ItemNameOnly":"",
* },
* "Paging":{
* "Key":"",
* "PageNumber":1,
* "PageSize":10,
* },
* "Sort":{
* "SortBy":"",
* "Ascending":false,
* },
* "TimeoutInSeconds":10
* }
* Search for Items matching the criteria of the query parameter
* @param simpleSearchQuery
* @return AdvancedSearchResults
*/
public ISFQuery<SFAdvancedSearchResults> advancedSimpleSearch(SFSimpleSearchQuery simpleSearchQuery)
{
SFApiQuery<SFAdvancedSearchResults> sfApiQuery = new SFApiQuery<SFAdvancedSearchResults>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("AdvancedSimpleSearch");
sfApiQuery.setBody(simpleSearchQuery);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Advanced Search
* {
* "Query":{
* "AuthIDs":["id1", "id2", ...],
* "ItemTypes":["type1", "type2", ...],
* "ParentID":["id1", "id2", ...],
* "CreatorID":["id1", "id2", ...],
* "LuceneQuery":"",
* "SearchQuery":"",
* "CreateStartDate":"",
* "CreateEndDate":"",
* "ItemNameOnly":"",
* },
* "Paging":{
* "Key":"",
* "PageNumber":1,
* "PageSize":10,
* },
* "Sort":{
* "SortBy":"",
* "Ascending":false,
* },
* "TimeoutInSeconds":10
* }
* Search for Items matching the criteria of the query parameter
* @param searchQuery
* @return AdvancedSearchResults
*/
public ISFQuery<SFAdvancedSearchResults> advancedSearch(SFSearchQuery searchQuery)
{
SFApiQuery<SFAdvancedSearchResults> sfApiQuery = new SFApiQuery<SFAdvancedSearchResults>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("AdvancedSimpleSearch");
sfApiQuery.setBody(searchQuery);
sfApiQuery.setHttpMethod("POST");
return sfApiQuery;
}
/**
* Get Web Preview Link
* Redirects the caller to the Web Edit application for the selected item.
* @param url
* @return A redirection message to the Web Edit app for this item. It returns 404 (Not Found) if the Web Preview app doesn't support the file type.
*/
public ISFQuery<SFRedirection> webView(URI url)
{
SFApiQuery<SFRedirection> sfApiQuery = new SFApiQuery<SFRedirection>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("WebView");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get all Item Protocol Link
* This method returns all alternate protocol links supported by ShareFile (such
* as WOPI, FTP, WebDAV).
* @param id
* @return A Feed containing all protocols links supported by the given item
*/
public ISFQuery<SFODataFeed<SFItemProtocolLink>> getProtocolLinks(URI url)
{
SFApiQuery<SFODataFeed<SFItemProtocolLink>> sfApiQuery = new SFApiQuery<SFODataFeed<SFItemProtocolLink>>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("ProtocolLinks");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get an Item Protocol Link
* @param url
* @param protocol
* @return A single protocol link if supported, 404 (Not Found) if not supported by the item
*/
public ISFQuery<SFItemProtocolLink> getProtocolLinks(URI url, String protocol)
{
SFApiQuery<SFItemProtocolLink> sfApiQuery = new SFApiQuery<SFItemProtocolLink>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("ProtocolLinks");
sfApiQuery.addIds(url);
sfApiQuery.addActionIds(protocol);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
/**
* Get Redirection endpoint Information
* Returns the redirection endpoint for this Item.This operation applies to Folders and SymbolicLinks only, will return an error for other Item types.
* @param url
* @return The Redirection endpoint Information
*/
public ISFQuery<SFRedirection> getRedirection(URI url)
{
SFApiQuery<SFRedirection> sfApiQuery = new SFApiQuery<SFRedirection>();
sfApiQuery.setFrom("Items");
sfApiQuery.setAction("Redirection");
sfApiQuery.addIds(url);
sfApiQuery.setHttpMethod("GET");
return sfApiQuery;
}
} |
package com.alexstyl.specialdates.date;
import com.alexstyl.specialdates.Optional;
import com.alexstyl.specialdates.contact.ShortDate;
import org.joda.time.LocalDate;
import static com.alexstyl.specialdates.date.DateConstants.NO_YEAR;
/**
* A specific date on a specific year
*/
public class Date implements ShortDate {
private final LocalDate localDate;
private final Optional<Integer> year;
public static int CURRENT_YEAR;
static {
CURRENT_YEAR = LocalDate.now().getYear();
}
public static Date today() {
LocalDate localDate = LocalDate.now();
return new Date(localDate, new Optional<>(localDate.getYear()));
}
public static Date on(int dayOfMonth, @MonthInt int month) {
LocalDate localDate = new LocalDate(NO_YEAR, month, dayOfMonth);
return new Date(localDate, Optional.<Integer>absent());
}
public static Date on(int dayOfMonth, @MonthInt int month, int year) {
if (year <= 0) {
throw new IllegalArgumentException(
"Do not call DayDate.on() if no year is present. Call the respective method without the year argument instead");
}
LocalDate localDate = new LocalDate(year, month, dayOfMonth);
return new Date(localDate, new Optional<>(year));
}
private Date(LocalDate localDate, Optional<Integer> year) {
this.localDate = localDate;
this.year = year;
}
public Date addDay(int i) {
LocalDate addedDate = localDate.plusDays(i);
return new Date(addedDate, new Optional<>(addedDate.getYear()));
}
public int getDayOfMonth() {
return localDate.getDayOfMonth();
}
@MonthInt
@SuppressWarnings("WrongConstant") // JodaTime follows the same indexing as our project
public int getMonth() {
return localDate.getMonthOfYear();
}
public int getYear() {
return year.get();
}
public Date addMonth(int m) {
LocalDate minusDate = localDate.plusMonths(m);
return new Date(minusDate, new Optional<>(minusDate.getYear()));
}
public Date minusMonth(int m) {
LocalDate minusDate = localDate.minusMonths(m);
return new Date(minusDate, new Optional<>(minusDate.getYear()));
}
@Override
public String toString() {
return DateDisplayStringCreator.getInstance().stringOf(this);
}
public long toMillis() {
return localDate.toDate().getTime();
}
public static Date startOfTheYear(int currentYear) {
return Date.on(1, DateConstants.JANUARY, currentYear);
}
public Date minusDay(int days) {
LocalDate minusDays = localDate.minusDays(days);
return new Date(minusDays, new Optional<>(minusDays.getYear()));
}
public static Date endOfYear(int currentYear) {
return Date.on(31, DateConstants.DECEMBER, currentYear);
}
public int getDayOfWeek() {
return localDate.getDayOfWeek();
}
public Date addWeek(int weeks) {
return addDay(7 * weeks);
}
public int daysDifferenceTo(Date otherEvent) {
int dayOfYear = localDate.dayOfYear().get();
int otherDayOfYear = otherEvent.localDate.dayOfYear().get();
Integer daysOfYearsDifference = (yearOf(this) - yearOf(otherEvent)) * 365;
return (otherDayOfYear - dayOfYear) - daysOfYearsDifference;
}
private Integer yearOf(Date otherEvent) {
return otherEvent.getYear();
}
@Override
public String toShortDate() {
return DateDisplayStringCreator.getInstance().stringOf(this);
}
public boolean hasYear() {
return year.isPresent();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Date date = (Date) o;
if (!localDate.equals(date.localDate)) {
return false;
}
return year.equals(date.year);
}
@Override
public int hashCode() {
int result = localDate.hashCode();
result = 31 * result + year.hashCode();
return result;
}
} |
package edu.teco.dnd.network.tcp;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import edu.teco.dnd.network.ConnectionManager;
import edu.teco.dnd.network.MessageHandler;
import edu.teco.dnd.network.messages.Message;
/**
* <p>
* Manages a set {@link MessageHandler}s for a single Message class.
* </p>
*
* <p>
* A default MessageHandler can be registered as well as handlers for specific Application IDs. When queried with an
* Application ID this class will either return the handler registered for that ID if it exists or the default handler
* otherwise
* </p>
*
* @author Philipp Adolf
*
* @param <T>
* the Message class this class will be used for
*/
// TODO: add methods to remove handlers
public class HandlersByApplicationID<T extends Message> {
private final Map<UUID, MessageHandler<? super T>> handlers = new HashMap<UUID, MessageHandler<? super T>>();
/**
* Sets the default handler.
*
* This handler will be used if no Application specific handler can be found.
*
* @param handler
* the handler that will be the used if no Application specific handler can be found
*/
public void setDefaultHandler(final MessageHandler<? super T> handler) {
setHandler(ConnectionManager.APPID_DEFAULT, handler);
}
/**
* Sets an application specific handler.
*
* @param applicationID
* the ID of the Application the handler should be used for
* @param handler
* the handler to use for that Application
*/
public void setHandler(final UUID applicationID, final MessageHandler<? super T> handler) {
if (applicationID == null) {
throw new IllegalArgumentException("applicationID must not be null");
}
if (handler == null) {
throw new IllegalArgumentException("handler must not be null");
}
handlers.put(applicationID, handler);
}
/**
* Returns the handler that should be used for the given Application.
*
* If a handler was registered for the given Application ID that handler is returned, otherwise the default handler
* is returned.
*
* @param applicationID
* the ID of the Application
* @return the handler that should be used for that Application. May be null.
*/
public MessageHandler<? super T> getHandler(final UUID applicationID) {
final MessageHandler<? super T> applicationSpecificHandler = getApplicationSpecificHandler(applicationID);
if (applicationSpecificHandler == null) {
return getDefaultHandler();
}
return applicationSpecificHandler;
}
/**
* Returns the default handler.
*
* @return the default handler. May be null.
*/
public MessageHandler<? super T> getDefaultHandler() {
return getApplicationSpecificHandler(ConnectionManager.APPID_DEFAULT);
}
/**
* Returns the handler that was registered for the given Application ID.
*
* @param applicationID
* the Application ID to check
* @return the handler for the given Application ID. May be null.
*/
public MessageHandler<? super T> getApplicationSpecificHandler(final UUID applicationID) {
return handlers.get(applicationID);
}
} |
package org.eclipse.sisu.space;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Locale;
/**
* Utility methods for dealing with streams.
*/
public final class Streams
{
// Static initialization
static
{
boolean useCaches;
try
{
String urlCaches = System.getProperty( "sisu.url.caches" );
if ( null != urlCaches && !urlCaches.isEmpty() )
{
useCaches = Boolean.parseBoolean( urlCaches );
}
else
{
String osName = System.getProperty( "os.name" ).toLowerCase( Locale.US );
useCaches = !osName.contains( "windows" );
}
}
catch ( final RuntimeException e )
{
useCaches = true;
}
USE_CACHES = useCaches;
}
// Constants
private static final boolean USE_CACHES;
// Constructors
private Streams()
{
// static utility class, not allowed to create instances
}
// Utility methods
/**
* Opens an input stream to the given URL; disables JAR caching on Windows
* or when the 'sisu.url.caches' system property is set to {@code false}.
*/
public static InputStream open( final URL url )
throws IOException
{
if ( USE_CACHES )
{
return url.openStream();
}
final URLConnection conn = url.openConnection();
conn.setUseCaches( false );
return conn.getInputStream();
}
} |
/**
* AVL tree (Georgy Adelson-Velsky and Landis' tree,
* named after the inventors) is a self-balancing
* binary search tree.
*
*@author Benjamin Sientzoff, Thomas Minier
*@version 0.1
*/
public class AVLTree<T extends Comparable> {
private Node<T> root;
public AVLTree(T root){
this.root = new Node<T>(root);
}
public AVLTree(){
this.root = null;
}
public void add(T element){
if(null == root){
root = new Node<T>(element);
} else {
root.add(element);
}
}
public String toString(){
return root.toString();
}
}
class Node<T extends Comparable> {
private Node<T> leftSon, rightSon;
private T tag;
private int balance;
public Node(T tag){
this.balance = 0;
this.tag = tag;
this.leftSon = null;
this.rightSon = null;
}
public Node(T tag, Node<T> leftSon, Node<T> rightSon){
this(tag);
this.leftSon = leftSon;
this.rightSon = rightSon;
}
/**
* What is a node height ?
*/
private int computeHeight(){
if(null == leftSon){
if(null == rightSon){
// if node, height is 0
return 0;
}
else{
// height is right son height plus 1 (no left son)
return 1 + rightSon.computeHeight();
}
}
else {
if(null == rightSon){
// no right son, height is 1 plus
return 1 + leftSon.computeHeight();
}
else{
// if two sons, height is sons maximum height
return Math.max(leftSon.computeHeight(), rightSon.computeHeight());
}
}
}
public T getTag(){
return tag;
}
/**
* Le Node est-il une feuille ?
* @return retourne vrai si pas de Son, sinon faux
*/
public boolean isLeaf(){
return ( null == leftSon ) && ( null == rightSon );
}
/**
* Mutteur du Son left
* @param nouveauleftSon Nouveau Son gacuhe du Node
*/
public void setLeftSon(Node<T> nouveauleftSon){
this.leftSon = nouveauleftSon;
}
/**
* Mutteur du Son right
* @param nouveaurightSon Nouveau Son right du Node
*/
public void setRightSon(Node<T> nouveaurightSon){
this.leftSon = nouveaurightSon;
}
public Node<T> getRightSon() throws NoSonException{
if( null == rightSon )
throw new NoSonException("Le Node n'a pas de Son right!");
return rightSon;
}
public Node<T> getLeftSon() throws NoSonException{
if( null == leftSon )
throw new NoSonException("Le Node n'a pas de Son left!");
return leftSon;
}
@Override
public String toString(){
String toReturn = "";
if( null != leftSon ){
toReturn += leftSon.toString();
}
toReturn += "," +tag.toString()+ "(" + computeHeight() + ")";
if( null != rightSon ){
toReturn += rightSon.toString();
}
return toReturn;
}
public void add(T element){
// if element is 'less' than tag
if( 0 < tag.compareTo(element) ){
// then add element on the left
// if there is not left son
if( null == leftSon ) {
// then create it
leftSon = new Node<T>(element);
} else {
// else recursive call to the son
leftSon.add(element);
}
} else {
// else add element on the right
// if no right son
if( null == rightSon ) {
// then create it
rightSon = new Node<T>(element);
} else {
// else recursive call to the son
rightSon.add(element);
}
}
}
private Node<T> equilibrer(Node<T> nodeA) {
// If the balance == 2, then the tree is unbalanced to the right
if(nodeA.balance == 2) {
if(nodeA.rightSon.balance >= 0) {
// We perform a simple left rotation
return this.leftRotation(nodeA);
} else { // else, we perform a double left rotation
return this.doubleLeftRotation(nodeA);
}
} else if(nodeA.balance == -2) { // else, if == -2, then the tree is unbalanced to the left
if(nodeA.leftSon.balance <= 0) {
// We perform a simple right rotation
return this.rightRotation(nodeA);
} else { // else, we perform a double right rotation
return this.doubleRightRotation(nodeA);
}
} else { // else, the tree is balanced
return nodeA;
}
}
private Node<T> leftRotation(Node<T> nodeA) {
int a, b;
Node<T> nodeB = nodeA.rightSon;
a = nodeA.balance;
b = nodeB.balance;
// Left rotation
nodeA.rightSon = nodeB.leftSon;
nodeB.leftSon = nodeA;
// Update the balance of the new tree
nodeA.balance = a - Math.max(b,0) - 1;
nodeB.balance = Math.min(a - 2, Math.min(a + b - 2, b - 1));
return nodeB;
}
private Node<T> doubleLeftRotation(Node<T> nodeA) {
nodeA.rightSon = this.leftRotation(nodeA.rightSon);
return this.leftRotation(nodeA);
}
private Node<T> rightRotation(Node<T> nodeA) {
int a, b;
Node<T> nodeB = nodeA.leftSon;
a = nodeA.balance;
b = nodeB.balance;
// Right rotation
nodeA.leftSon = nodeB.rightSon;
nodeB.rightSon = nodeA;
// Update the balance of the new tree
nodeA.balance = a - Math.max(b,0) - 1;
nodeB.balance = Math.min(a - 2, Math.min(a + b - 2, b - 1));
return nodeB;
}
private Node<T> doubleRightRotation(Node<T> nodeA) {
nodeA.leftSon = this.rightRotation(nodeA.leftSon);
return this.rightRotation(nodeA);
}
} |
package com.xpn.xwiki.api;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.lang.StringUtils;
import org.suigeneris.jrcs.diff.DifferentiationFailedException;
import org.suigeneris.jrcs.diff.delta.Delta;
import org.suigeneris.jrcs.rcs.Version;
import com.xpn.xwiki.XWiki;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.criteria.impl.RevisionCriteria;
import com.xpn.xwiki.doc.AttachmentDiff;
import com.xpn.xwiki.doc.MetaDataDiff;
import com.xpn.xwiki.doc.XWikiAttachment;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.doc.XWikiDocumentArchive;
import com.xpn.xwiki.doc.XWikiLink;
import com.xpn.xwiki.doc.XWikiLock;
import com.xpn.xwiki.objects.BaseObject;
import com.xpn.xwiki.objects.BaseProperty;
import com.xpn.xwiki.objects.ObjectDiff;
import com.xpn.xwiki.objects.classes.BaseClass;
import com.xpn.xwiki.plugin.fileupload.FileUploadPlugin;
import com.xpn.xwiki.stats.impl.DocumentStats;
import com.xpn.xwiki.util.TOCGenerator;
import com.xpn.xwiki.util.Util;
public class Document extends Api
{
/**
* The XWikiDocument object wrapped by this API.
*/
protected XWikiDocument doc;
/**
* Indicates if this API wraps a cloned XWikiDocument.
*/
protected boolean cloned = false;
/**
* Convenience object used by object related methods.
*/
protected Object currentObj;
/**
* Document constructor.
*
* @param doc The XWikiDocument object to wrap.
* @param context The current request context.
*/
public Document(XWikiDocument doc, XWikiContext context)
{
super(context);
this.doc = doc;
}
/**
* Get the XWikiDocument wrapped by this API. This function is accessible only if you have the programming rights
* give access to the priviledged API of the Document.
*
* @return The XWikiDocument wrapped by this API.
*/
public XWikiDocument getDocument()
{
if (hasProgrammingRights()) {
return this.doc;
} else {
return null;
}
}
/**
* Get a clone of the XWikiDocument wrapped by this API.
*
* @return A clone of the XWikiDocument wrapped by this API.
*/
protected XWikiDocument getDoc()
{
if (!this.cloned) {
this.doc = (XWikiDocument) this.doc.clone();
this.cloned = true;
}
return this.doc;
}
/**
* return the ID of the document. this ID is unique across the wiki.
*
* @return the id of the document.
*/
public long getId()
{
return this.doc.getId();
}
/**
* return the name of a document. for exemple if the fullName of a document is "MySpace.Mydoc", the name is MyDoc.
*
* @return the name of the document
*/
public String getName()
{
return this.doc.getName();
}
/**
* return the name of the space of the document for example if the fullName of a document is "MySpace.Mydoc", the
* name is MySpace.
*
* @return the name of the space of the document
*/
public String getSpace()
{
return this.doc.getSpace();
}
/**
* Get the name wiki where the document is stored.
*
* @return The name of the wiki where this document is stored.
* @since XWiki Core 1.1.2, XWiki Core 1.2M2
*/
public String getWiki()
{
return this.doc.getDatabase();
}
/**
* Get the name of the space of the document for exemple if the fullName of a document is "MySpace.Mydoc", the name
* is MySpace.
*
* @return The name of the space of the document.
* @deprecated use {@link #getSpace()} instead of this function.
*/
@Deprecated
public String getWeb()
{
return this.doc.getSpace();
}
/**
* Get the fullName of the document. If a document is named "MyDoc" in space "MySpace", the fullname is
* "MySpace.MyDoc". In a wiki, all the documents have a different fullName.
*
* @return fullName of the document.
*/
public String getFullName()
{
return this.doc.getFullName();
}
/**
* Get the complete fullName of the document. The real full name of the document containing the name of the wiki
* where the document is stored. For a document stored in the wiki "xwiki", in space "MySpace", named "MyDoc", its
* complete full name is "xwiki:MySpace.MyDoc".
*
* @return The complete fullName of the document.
* @since XWiki Core 1.1.2, XWiki Core 1.2M2
*/
public String getPrefixedFullName()
{
return (getWiki() != null ? getWiki() + ":" : "") + getFullName();
}
/**
* Get a Version object representing the current version of the document.
*
* @return A Version object representing the current version of the document
*/
public Version getRCSVersion()
{
return this.doc.getRCSVersion();
}
/**
* Get a string representing the current version of the document.
*
* @return A string representing the current version of the document.
*/
public String getVersion()
{
return this.doc.getVersion();
}
/**
* Get a string representing the previous version of the document.
*
* @return A string representing the previous version of the document.
*/
public String getPreviousVersion()
{
return this.doc.getPreviousVersion();
}
/**
* Get the value of the title field of the document.
*
* @return The value of the title field of the document.
*/
public String getTitle()
{
return this.doc.getTitle();
}
/**
* Get document title. If a title has not been provided through the title field, it looks for a section title in the
* document's content and if not found return the page name. The returned title is also interpreted which means it's
* allowed to use Velocity, Groovy, etc syntax within a title.
*
* @return The document title.
*/
public String getDisplayTitle()
{
return this.doc.getDisplayTitle(getXWikiContext());
}
/**
* TODO: document this.
*/
public String getFormat()
{
return this.doc.getFormat();
}
/**
* Get fullName of the profile document of the author of the current version of the document. Example: XWiki.Admin.
*
* @return The fullName of the profile document of the author of the current version of the document.
*/
public String getAuthor()
{
return this.doc.getAuthor();
}
/**
* Get fullName of the profile document of the author of the last content modification in the document. Example:
* XWiki.Admin.
*
* @return The fullName of the profile document of the author of the last content modification in the document.
*/
public String getContentAuthor()
{
return this.doc.getContentAuthor();
}
/**
* Get the date when the current document version has been created, i.e. the date of the last modification of the
* document.
*
* @return The date where the current document version has been created.
*/
public Date getDate()
{
return this.doc.getDate();
}
/**
* Get the date when the last content modification has been done on the document.
*
* @return The date where the last content modification has been done on the document.
*/
public Date getContentUpdateDate()
{
return this.doc.getContentUpdateDate();
}
/**
* Get the date when the document has been created. return The date when the document has been created.
*/
public Date getCreationDate()
{
return this.doc.getCreationDate();
}
/**
* Get the name of the parent of this document.
*
* @return The name of the parent of this document.
*/
public String getParent()
{
return this.doc.getParent();
}
/**
* Get fullName of the profile document of the document creator.
*
* @return The fullName of the profile document of the document creator.
*/
public String getCreator()
{
return this.doc.getCreator();
}
/**
* Get raw content of the document, i.e. the content that is visible through the wiki editor.
*
* @return The raw content of the document.
*/
public String getContent()
{
return this.doc.getContent();
}
/**
* Get the Syntax id representing the syntax used for the document. For example "xwiki/1.0" represents the first
* version XWiki syntax while "xwiki/2.0" represents version 2.0 of the XWiki Syntax.
*
* @return The syntax id representing the syntax used for the document.
*/
public String getSyntaxId()
{
return this.doc.getSyntaxId();
}
/**
* Get the language of the document. If the document is a translation it returns the language set for it, otherwise,
* it returns the default language in the wiki where the document is stored.
*
* @return The language of the document.
*/
public String getLanguage()
{
return this.doc.getLanguage();
}
public String getTemplate()
{
return this.doc.getTemplate();
}
/**
* return the real language of the document
*/
public String getRealLanguage() throws XWikiException
{
return this.doc.getRealLanguage(getXWikiContext());
}
/**
* return the language of the default document
*/
public String getDefaultLanguage()
{
return this.doc.getDefaultLanguage();
}
public String getDefaultTemplate()
{
return this.doc.getDefaultTemplate();
}
/**
* return the comment of the latest update of the document
*/
public String getComment()
{
return this.doc.getComment();
}
public boolean isMinorEdit()
{
return this.doc.isMinorEdit();
}
/**
* Return the list of existing translations for this document.
*/
public List<String> getTranslationList() throws XWikiException
{
return this.doc.getTranslationList(getXWikiContext());
}
/**
* return the translated document's content if the wiki is multilingual, the language is first checked in the URL,
* the cookie, the user profile and finally the wiki configuration if not, the language is the one on the wiki
* configuration
*/
public String getTranslatedContent() throws XWikiException
{
return this.doc.getTranslatedContent(getXWikiContext());
}
/**
* return the translated content in the given language
*/
public String getTranslatedContent(String language) throws XWikiException
{
return this.doc.getTranslatedContent(language, getXWikiContext());
}
/**
* return the translated document in the given document
*/
public Document getTranslatedDocument(String language) throws XWikiException
{
return this.doc.getTranslatedDocument(language, getXWikiContext()).newDocument(getXWikiContext());
}
/**
* return the tranlated Document if the wiki is multilingual, the language is first checked in the URL, the cookie,
* the user profile and finally the wiki configuration if not, the language is the one on the wiki configuration
*/
public Document getTranslatedDocument() throws XWikiException
{
return this.doc.getTranslatedDocument(getXWikiContext()).newDocument(getXWikiContext());
}
/**
* return the content of the document rendererd
*/
public String getRenderedContent() throws XWikiException
{
return this.doc.getRenderedContent(getXWikiContext());
}
/**
* @param text the text to render
* @return the given text rendered in the context of this document
* @deprecated since 1.6M1 use {@link #getRenderedContent(String, String)}
*/
@Deprecated
public String getRenderedContent(String text) throws XWikiException
{
return this.doc.getRenderedContent(text, getXWikiContext());
}
/**
* @param text the text to render
* @param syntaxId the id of the Syntax used by the passed text (for example: "xwiki/1.0")
* @return the given text rendered in the context of this document using the passed Syntax
* @since 1.6M1
*/
public String getRenderedContent(String text, String syntaxId) throws XWikiException
{
return this.doc.getRenderedContent(text, syntaxId, getXWikiContext());
}
/**
* return a escaped version of the content of this document
*/
public String getEscapedContent() throws XWikiException
{
return this.doc.getEscapedContent(getXWikiContext());
}
/**
* return the archive of the document in a string format
*/
public String getArchive() throws XWikiException
{
return this.doc.getDocumentArchive(getXWikiContext()).getArchive(getXWikiContext());
}
/**
* this function is accessible only if you have the programming rights return the archive of the document
*/
public XWikiDocumentArchive getDocumentArchive() throws XWikiException
{
if (hasProgrammingRights()) {
return this.doc.getDocumentArchive(getXWikiContext());
}
return null;
}
/**
* @return true if the document is a new one (ie it has never been saved) or false otherwise
*/
public boolean isNew()
{
return this.doc.isNew();
}
/**
* return the URL of download for the the given attachment name
*
* @param filename the name of the attachment
* @return A String with the URL
*/
public String getAttachmentURL(String filename)
{
return this.doc.getAttachmentURL(filename, "download", getXWikiContext());
}
/**
* return the URL of the given action for the the given attachment name
*
* @return A string with the URL
*/
public String getAttachmentURL(String filename, String action)
{
return this.doc.getAttachmentURL(filename, action, getXWikiContext());
}
/**
* return the URL of the given action for the the given attachment name with "queryString" parameters
*
* @param queryString parameters added to the URL
*/
public String getAttachmentURL(String filename, String action, String queryString)
{
return this.doc.getAttachmentURL(filename, action, queryString, getXWikiContext());
}
/**
* return the URL for accessing to the archive of the attachment "filename" at the version "version"
*/
public String getAttachmentRevisionURL(String filename, String version)
{
return this.doc.getAttachmentRevisionURL(filename, version, getXWikiContext());
}
/**
* return the URL for accessing to the archive of the attachment "filename" at the version "version" and with the
* given queryString parameters
*/
public String getAttachmentRevisionURL(String filename, String version, String querystring)
{
return this.doc.getAttachmentRevisionURL(filename, version, querystring, getXWikiContext());
}
/**
* return the URL of this document in view mode
*/
public String getURL()
{
return this.doc.getURL("view", getXWikiContext());
}
/**
* return the URL of this document with the given action
*/
public String getURL(String action)
{
return this.doc.getURL(action, getXWikiContext());
}
/**
* return the URL of this document with the given action and queryString as parameters
*/
public String getURL(String action, String querystring)
{
return this.doc.getURL(action, querystring, getXWikiContext());
}
/**
* return the full URL of the document
*/
public String getExternalURL()
{
return this.doc.getExternalURL("view", getXWikiContext());
}
/**
* return the full URL of the document for the given action
*/
public String getExternalURL(String action)
{
return this.doc.getExternalURL(action, getXWikiContext());
}
public String getExternalURL(String action, String querystring)
{
return this.doc.getExternalURL(action, querystring, getXWikiContext());
}
public String getParentURL() throws XWikiException
{
return this.doc.getParentURL(getXWikiContext());
}
public Class getxWikiClass()
{
BaseClass bclass = this.doc.getxWikiClass();
if (bclass == null) {
return null;
} else {
return new Class(bclass, getXWikiContext());
}
}
public Class[] getxWikiClasses()
{
List<BaseClass> list = this.doc.getxWikiClasses(getXWikiContext());
if (list == null) {
return null;
}
Class[] result = new Class[list.size()];
for (int i = 0; i < list.size(); i++) {
result[i] = new Class(list.get(i), getXWikiContext());
}
return result;
}
public int createNewObject(String classname) throws XWikiException
{
return getDoc().createNewObject(classname, getXWikiContext());
}
public Object newObject(String classname) throws XWikiException
{
int nb = createNewObject(classname);
return getObject(classname, nb);
}
public boolean isFromCache()
{
return this.doc.isFromCache();
}
public int getObjectNumbers(String classname)
{
return this.doc.getObjectNumbers(classname);
}
public Map<String, Vector<Object>> getxWikiObjects()
{
Map<String, Vector<BaseObject>> map = this.doc.getxWikiObjects();
Map<String, Vector<Object>> resultmap = new HashMap<String, Vector<Object>>();
for (String name : map.keySet()) {
Vector<BaseObject> objects = map.get(name);
if (objects != null) {
resultmap.put(name, getObjects(objects));
}
}
return resultmap;
}
protected Vector<Object> getObjects(Vector<BaseObject> objects)
{
Vector<Object> result = new Vector<Object>();
if (objects == null) {
return result;
}
for (BaseObject bobj : objects) {
if (bobj != null) {
result.add(newObjectApi(bobj, getXWikiContext()));
}
}
return result;
}
public Vector<Object> getObjects(String classname)
{
Vector<BaseObject> objects = this.doc.getObjects(classname);
return getObjects(objects);
}
public Object getFirstObject(String fieldname)
{
try {
BaseObject obj = this.doc.getFirstObject(fieldname, getXWikiContext());
if (obj == null) {
return null;
} else {
return newObjectApi(obj, getXWikiContext());
}
} catch (Exception e) {
return null;
}
}
public Object getObject(String classname, String key, String value, boolean failover)
{
try {
BaseObject obj = this.doc.getObject(classname, key, value, failover);
if (obj == null) {
return null;
} else {
return newObjectApi(obj, getXWikiContext());
}
} catch (Exception e) {
return null;
}
}
/**
* Select a subset of objects from a given class, filtered on a "key = value" criteria.
*
* @param classname The type of objects to return.
* @param key The name of the property used for filtering.
* @param value The required value.
* @return A Vector of {@link Object objects} matching the criteria. If no objects are found, or if the key is an
* empty String, then an empty vector is returned.
*/
public Vector<Object> getObjects(String classname, String key, String value)
{
Vector<Object> result = new Vector<Object>();
if (StringUtils.isBlank(key) || value == null) {
return getObjects(classname);
}
try {
Vector<BaseObject> allObjects = this.doc.getObjects(classname);
if (allObjects == null || allObjects.size() == 0) {
return result;
} else {
for (BaseObject obj : allObjects) {
if (obj != null) {
BaseProperty prop = (BaseProperty) obj.get(key);
if (prop == null || prop.getValue() == null) {
continue;
}
if (value.equals(prop.getValue().toString())) {
result.add(newObjectApi(obj, getXWikiContext()));
}
}
}
}
} catch (Exception e) {
}
return result;
}
public Object getObject(String classname, String key, String value)
{
try {
BaseObject obj = this.doc.getObject(classname, key, value);
if (obj == null) {
return null;
} else {
return newObjectApi(obj, getXWikiContext());
}
} catch (Exception e) {
return null;
}
}
public Object getObject(String classname)
{
return getObject(classname, false);
}
/**
* get the object of the given className. If there is no object of this className and the create parameter at true,
* the object is created.
*/
public Object getObject(String classname, boolean create)
{
try {
BaseObject obj = this.doc.getObject(classname, create, getXWikiContext());
if (obj == null) {
return null;
} else {
return newObjectApi(obj, getXWikiContext());
}
} catch (Exception e) {
return null;
}
}
public Object getObject(String classname, int nb)
{
try {
BaseObject obj = this.doc.getObject(classname, nb);
if (obj == null) {
return null;
} else {
return newObjectApi(obj, getXWikiContext());
}
} catch (Exception e) {
return null;
}
}
private Object newObjectApi(BaseObject obj, XWikiContext context)
{
return obj.newObjectApi(obj, context);
}
public String getXMLContent() throws XWikiException
{
String xml = this.doc.getXMLContent(getXWikiContext());
return getXWikiContext().getUtil().substitute(
"s/<email>.*?<\\/email>/<email>********<\\/email>/goi",
getXWikiContext().getUtil().substitute("s/<password>.*?<\\/password>/<password>********<\\/password>/goi",
xml));
}
public String toXML() throws XWikiException
{
if (hasProgrammingRights()) {
return this.doc.toXML(getXWikiContext());
} else {
return "";
}
}
public org.dom4j.Document toXMLDocument() throws XWikiException
{
if (hasProgrammingRights()) {
return this.doc.toXMLDocument(getXWikiContext());
} else {
return null;
}
}
public Version[] getRevisions() throws XWikiException
{
return this.doc.getRevisions(getXWikiContext());
}
public String[] getRecentRevisions() throws XWikiException
{
return this.doc.getRecentRevisions(5, getXWikiContext());
}
public String[] getRecentRevisions(int nb) throws XWikiException
{
return this.doc.getRecentRevisions(nb, getXWikiContext());
}
/**
* Get document versions matching criterias like author, minimum creation date, etc.
*
* @param criteria criteria used to match versions
* @return a list of matching versions
*/
public List<String> getRevisions(RevisionCriteria criteria) throws XWikiException
{
return this.doc.getRevisions(criteria, this.context);
}
/**
* Get information about a document version : author, date, etc.
*
* @param version the version you want to get information about
* @return a new RevisionInfo object
*/
public RevisionInfo getRevisionInfo(String version) throws XWikiException
{
return new RevisionInfo(this.doc.getRevisionInfo(version, getXWikiContext()), getXWikiContext());
}
public List<Attachment> getAttachmentList()
{
List<Attachment> apis = new ArrayList<Attachment>();
for (XWikiAttachment attachment : this.doc.getAttachmentList()) {
apis.add(new Attachment(this, attachment, getXWikiContext()));
}
return apis;
}
public Vector<Object> getComments()
{
return getComments(true);
}
public Vector<Object> getComments(boolean asc)
{
return getObjects(this.doc.getComments(asc));
}
public void use(Object object)
{
this.currentObj = object;
}
public void use(String className)
{
this.currentObj = getObject(className);
}
public void use(String className, int nb)
{
this.currentObj = getObject(className, nb);
}
public String getActiveClass()
{
if (this.currentObj == null) {
return null;
} else {
return this.currentObj.getName();
}
}
public String displayPrettyName(String fieldname)
{
if (this.currentObj == null) {
return this.doc.displayPrettyName(fieldname, getXWikiContext());
} else {
return this.doc.displayPrettyName(fieldname, this.currentObj.getBaseObject(), getXWikiContext());
}
}
public String displayPrettyName(String fieldname, Object obj)
{
if (obj == null) {
return "";
}
return this.doc.displayPrettyName(fieldname, obj.getBaseObject(), getXWikiContext());
}
public String displayPrettyName(String fieldname, boolean showMandatory)
{
if (this.currentObj == null) {
return this.doc.displayPrettyName(fieldname, showMandatory, getXWikiContext());
} else {
return this.doc.displayPrettyName(fieldname, showMandatory, this.currentObj.getBaseObject(),
getXWikiContext());
}
}
public String displayPrettyName(String fieldname, boolean showMandatory, Object obj)
{
if (obj == null) {
return "";
}
return this.doc.displayPrettyName(fieldname, showMandatory, obj.getBaseObject(), getXWikiContext());
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before)
{
if (this.currentObj == null) {
return this.doc.displayPrettyName(fieldname, showMandatory, before, getXWikiContext());
} else {
return this.doc.displayPrettyName(fieldname, showMandatory, before, this.currentObj.getBaseObject(),
getXWikiContext());
}
}
public String displayPrettyName(String fieldname, boolean showMandatory, boolean before, Object obj)
{
if (obj == null) {
return "";
}
return this.doc.displayPrettyName(fieldname, showMandatory, before, obj.getBaseObject(), getXWikiContext());
}
public String displayTooltip(String fieldname)
{
if (this.currentObj == null) {
return this.doc.displayTooltip(fieldname, getXWikiContext());
} else {
return this.doc.displayTooltip(fieldname, this.currentObj.getBaseObject(), getXWikiContext());
}
}
public String displayTooltip(String fieldname, Object obj)
{
if (obj == null) {
return "";
}
return this.doc.displayTooltip(fieldname, obj.getBaseObject(), getXWikiContext());
}
public String display(String fieldname)
{
if (this.currentObj == null) {
return this.doc.display(fieldname, getXWikiContext());
} else {
return this.doc.display(fieldname, this.currentObj.getBaseObject(), getXWikiContext());
}
}
public String display(String fieldname, String mode)
{
if (this.currentObj == null) {
return this.doc.display(fieldname, mode, getXWikiContext());
} else {
return this.doc.display(fieldname, mode, this.currentObj.getBaseObject(), getXWikiContext());
}
}
public String display(String fieldname, String mode, String prefix)
{
if (this.currentObj == null) {
return this.doc.display(fieldname, mode, prefix, getXWikiContext());
} else {
return this.doc.display(fieldname, mode, prefix, this.currentObj.getBaseObject(), getSyntaxId(),
getXWikiContext());
}
}
public String display(String fieldname, Object obj)
{
if (obj == null) {
return "";
}
return this.doc.display(fieldname, obj.getBaseObject(), getXWikiContext());
}
/**
* Note: We've introduced this signature taking an extra syntaxId parameter to handle the case where Panels are
* written in a syntax other than the main document. The problem is that currently the displayPanel() velocity macro
* in macros.vm calls display() on the main document and not on the panel document. Thus if we don't tell what
* syntax to use the main document syntax will be used to display panels even if they're written in another syntax.
*/
public String display(String fieldname, String type, Object obj, String syntaxId)
{
if (obj == null) {
return "";
}
return this.doc.display(fieldname, type, obj.getBaseObject(), syntaxId, getXWikiContext());
}
public String display(String fieldname, String mode, Object obj)
{
if (obj == null) {
return "";
}
return this.doc.display(fieldname, mode, obj.getBaseObject(), getXWikiContext());
}
public String display(String fieldname, String mode, String prefix, Object obj)
{
if (obj == null) {
return "";
}
return this.doc.display(fieldname, mode, prefix, obj.getBaseObject(), getSyntaxId(), getXWikiContext());
}
public String displayForm(String className, String header, String format)
{
return this.doc.displayForm(className, header, format, getXWikiContext());
}
public String displayForm(String className, String header, String format, boolean linebreak)
{
return this.doc.displayForm(className, header, format, linebreak, getXWikiContext());
}
public String displayForm(String className)
{
return this.doc.displayForm(className, getXWikiContext());
}
public String displayRendered(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object)
throws XWikiException
{
if ((pclass == null) || (object == null)) {
return "";
}
return this.doc.displayRendered(pclass.getBasePropertyClass(), prefix, object.getCollection(),
getXWikiContext());
}
public String displayView(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object)
{
if ((pclass == null) || (object == null)) {
return "";
}
return this.doc.displayView(pclass.getBasePropertyClass(), prefix, object.getCollection(), getXWikiContext());
}
public String displayEdit(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object)
{
if ((pclass == null) || (object == null)) {
return "";
}
return this.doc.displayEdit(pclass.getBasePropertyClass(), prefix, object.getCollection(), getXWikiContext());
}
public String displayHidden(com.xpn.xwiki.api.PropertyClass pclass, String prefix, Collection object)
{
if ((pclass == null) || (object == null)) {
return "";
}
return this.doc.displayHidden(pclass.getBasePropertyClass(), prefix, object.getCollection(), getXWikiContext());
}
public List<String> getIncludedPages()
{
return this.doc.getIncludedPages(getXWikiContext());
}
public List<String> getIncludedMacros()
{
return this.doc.getIncludedMacros(getXWikiContext());
}
public List<String> getLinkedPages()
{
return this.doc.getLinkedPages(getXWikiContext());
}
public Attachment getAttachment(String filename)
{
XWikiAttachment attach = this.doc.getAttachment(filename);
if (attach == null) {
return null;
} else {
return new Attachment(this, attach, getXWikiContext());
}
}
public List<Delta> getContentDiff(Document origdoc, Document newdoc) throws XWikiException,
DifferentiationFailedException
{
try {
if ((origdoc == null) && (newdoc == null)) {
return Collections.emptyList();
}
if (origdoc == null) {
return this.doc.getContentDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc,
getXWikiContext());
}
if (newdoc == null) {
return this.doc.getContentDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()),
getXWikiContext());
}
return this.doc.getContentDiff(origdoc.doc, newdoc.doc, getXWikiContext());
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe =
new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_CONTENT_ERROR,
"Error while making content diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext());
list.add(errormsg);
return list;
}
}
public List<Delta> getXMLDiff(Document origdoc, Document newdoc) throws XWikiException,
DifferentiationFailedException
{
try {
if ((origdoc == null) && (newdoc == null)) {
return Collections.emptyList();
}
if (origdoc == null) {
return this.doc.getXMLDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc,
getXWikiContext());
}
if (newdoc == null) {
return this.doc.getXMLDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()),
getXWikiContext());
}
return this.doc.getXMLDiff(origdoc.doc, newdoc.doc, getXWikiContext());
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe =
new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_XML_ERROR,
"Error while making xml diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext());
list.add(errormsg);
return list;
}
}
public List<Delta> getRenderedContentDiff(Document origdoc, Document newdoc) throws XWikiException,
DifferentiationFailedException
{
try {
if ((origdoc == null) && (newdoc == null)) {
return Collections.emptyList();
}
if (origdoc == null) {
return this.doc.getRenderedContentDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()),
newdoc.doc, getXWikiContext());
}
if (newdoc == null) {
return this.doc.getRenderedContentDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc
.getName()), getXWikiContext());
}
return this.doc.getRenderedContentDiff(origdoc.doc, newdoc.doc, getXWikiContext());
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe =
new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_RENDERED_ERROR,
"Error while making rendered diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext());
list.add(errormsg);
return list;
}
}
public List<MetaDataDiff> getMetaDataDiff(Document origdoc, Document newdoc) throws XWikiException
{
try {
if ((origdoc == null) && (newdoc == null)) {
return Collections.emptyList();
}
if (origdoc == null) {
return this.doc.getMetaDataDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc,
getXWikiContext());
}
if (newdoc == null) {
return this.doc.getMetaDataDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()),
getXWikiContext());
}
return this.doc.getMetaDataDiff(origdoc.doc, newdoc.doc, getXWikiContext());
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe =
new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_METADATA_ERROR,
"Error while making meta data diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext());
list.add(errormsg);
return list;
}
}
public List<List<ObjectDiff>> getObjectDiff(Document origdoc, Document newdoc) throws XWikiException
{
try {
if ((origdoc == null) && (newdoc == null)) {
return Collections.emptyList();
}
if (origdoc == null) {
return this.doc.getObjectDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc,
getXWikiContext());
}
if (newdoc == null) {
return this.doc.getObjectDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()),
getXWikiContext());
}
return this.doc.getObjectDiff(origdoc.doc, newdoc.doc, getXWikiContext());
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe =
new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_OBJECT_ERROR,
"Error while making meta object diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext());
list.add(errormsg);
return list;
}
}
public List<List<ObjectDiff>> getClassDiff(Document origdoc, Document newdoc) throws XWikiException
{
try {
if ((origdoc == null) && (newdoc == null)) {
return Collections.emptyList();
}
if (origdoc == null) {
return this.doc.getClassDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc,
getXWikiContext());
}
if (newdoc == null) {
return this.doc.getClassDiff(origdoc.doc, new XWikiDocument(origdoc.getSpace(), origdoc.getName()),
getXWikiContext());
}
return this.doc.getClassDiff(origdoc.doc, newdoc.doc, getXWikiContext());
} catch (Exception e) {
java.lang.Object[] args = {origdoc.getFullName(), origdoc.getVersion(), newdoc.getVersion()};
List list = new ArrayList();
XWikiException xe =
new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_CLASS_ERROR,
"Error while making class diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext());
list.add(errormsg);
return list;
}
}
public List<AttachmentDiff> getAttachmentDiff(Document origdoc, Document newdoc) throws XWikiException
{
try {
if ((origdoc == null) && (newdoc == null)) {
return Collections.emptyList();
}
if (origdoc == null) {
return this.doc.getAttachmentDiff(new XWikiDocument(newdoc.getSpace(), newdoc.getName()), newdoc.doc,
getXWikiContext());
}
if (newdoc == null) {
return this.doc.getAttachmentDiff(origdoc.doc,
new XWikiDocument(origdoc.getSpace(), origdoc.getName()), getXWikiContext());
}
return this.doc.getAttachmentDiff(origdoc.doc, newdoc.doc, getXWikiContext());
} catch (Exception e) {
java.lang.Object[] args =
{(origdoc != null) ? origdoc.getFullName() : null, (origdoc != null) ? origdoc.getVersion() : null,
(newdoc != null) ? newdoc.getVersion() : null};
List list = new ArrayList();
XWikiException xe =
new XWikiException(XWikiException.MODULE_XWIKI_DIFF, XWikiException.ERROR_XWIKI_DIFF_ATTACHMENT_ERROR,
"Error while making attachment diff of {0} between version {1} and version {2}", e, args);
String errormsg = Util.getHTMLExceptionMessage(xe, getXWikiContext());
list.add(errormsg);
return list;
}
}
public List<Delta> getLastChanges() throws XWikiException, DifferentiationFailedException
{
return this.doc.getLastChanges(getXWikiContext());
}
public DocumentStats getCurrentMonthPageStats(String action)
{
return getXWikiContext().getWiki().getStatsService(getXWikiContext()).getDocMonthStats(this.doc.getFullName(),
action, new Date(), getXWikiContext());
}
public DocumentStats getCurrentMonthWebStats(String action)
{
return getXWikiContext().getWiki().getStatsService(getXWikiContext()).getDocMonthStats(this.doc.getSpace(),
action, new Date(), getXWikiContext());
}
public List getCurrentMonthRefStats() throws XWikiException
{
return getXWikiContext().getWiki().getStatsService(getXWikiContext()).getRefMonthStats(this.doc.getFullName(),
new Date(), getXWikiContext());
}
public boolean checkAccess(String right)
{
try {
return getXWikiContext().getWiki().checkAccess(right, this.doc, getXWikiContext());
} catch (XWikiException e) {
return false;
}
}
public boolean hasAccessLevel(String level)
{
try {
return getXWikiContext().getWiki().getRightService().hasAccessLevel(level, getXWikiContext().getUser(),
this.doc.getFullName(), getXWikiContext());
} catch (Exception e) {
return false;
}
}
@Override
public boolean hasAccessLevel(String level, String user)
{
try {
return getXWikiContext().getWiki().getRightService().hasAccessLevel(level, user, this.doc.getFullName(),
getXWikiContext());
} catch (Exception e) {
return false;
}
}
public boolean getLocked()
{
try {
XWikiLock lock = this.doc.getLock(getXWikiContext());
if (lock != null && !getXWikiContext().getUser().equals(lock.getUserName())) {
return true;
} else {
return false;
}
} catch (Exception e) {
return false;
}
}
public String getLockingUser()
{
try {
XWikiLock lock = this.doc.getLock(getXWikiContext());
if (lock != null && !getXWikiContext().getUser().equals(lock.getUserName())) {
return lock.getUserName();
} else {
return "";
}
} catch (XWikiException e) {
return "";
}
}
public Date getLockingDate()
{
try {
XWikiLock lock = this.doc.getLock(getXWikiContext());
if (lock != null && !getXWikiContext().getUser().equals(lock.getUserName())) {
return lock.getDate();
} else {
return null;
}
} catch (XWikiException e) {
return null;
}
}
public java.lang.Object get(String classOrFieldName)
{
if (this.currentObj != null) {
return this.doc.display(classOrFieldName, this.currentObj.getBaseObject(), getXWikiContext());
}
BaseObject object = this.doc.getFirstObject(classOrFieldName, getXWikiContext());
if (object != null) {
return this.doc.display(classOrFieldName, object, getXWikiContext());
}
return this.doc.getObject(classOrFieldName);
}
public java.lang.Object getValue(String fieldName)
{
Object object;
if (this.currentObj == null) {
object = new Object(this.doc.getFirstObject(fieldName, getXWikiContext()), getXWikiContext());
} else {
object = this.currentObj;
}
return getValue(fieldName, object);
}
public java.lang.Object getValue(String fieldName, Object object)
{
if (object != null) {
try {
return ((BaseProperty) object.getBaseObject().safeget(fieldName)).getValue();
} catch (NullPointerException e) {
return null;
}
}
return null;
}
public String getTextArea()
{
return com.xpn.xwiki.XWiki.getTextArea(this.doc.getContent(), getXWikiContext());
}
/**
* Returns data needed for a generation of Table of Content for this document.
*
* @param init an intial level where the TOC generation should start at
* @param max maximum level TOC is generated for
* @param numbered if should generate numbering for headings
* @return a map where an heading (title) ID is the key and value is another map with two keys: text, level and
* numbering
*/
public Map getTOC(int init, int max, boolean numbered)
{
getXWikiContext().put("tocNumbered", new Boolean(numbered));
return TOCGenerator.generateTOC(getContent(), init, max, numbered, getXWikiContext());
}
public String getTags()
{
return this.doc.getTags(getXWikiContext());
}
public List<String> getTagList()
{
return this.doc.getTagsList(getXWikiContext());
}
public List getTagsPossibleValues()
{
return this.doc.getTagsPossibleValues(getXWikiContext());
}
public void insertText(String text, String marker) throws XWikiException
{
if (hasAccessLevel("edit")) {
getDoc().insertText(text, marker, getXWikiContext());
}
}
@Override
public boolean equals(java.lang.Object arg0)
{
if (!(arg0 instanceof Document)) {
return false;
}
Document d = (Document) arg0;
return d.getXWikiContext().equals(getXWikiContext()) && this.doc.equals(d.doc);
}
public List<String> getBacklinks() throws XWikiException
{
return this.doc.getBackLinkedPages(getXWikiContext());
}
public List<XWikiLink> getLinks() throws XWikiException
{
return this.doc.getWikiLinkedPages(getXWikiContext());
}
/**
* Get document children. Children are document with the current document as parent.
*
* @return The list of children for the current document.
* @since 1.8 Milestone 2
*/
public List<String> getChildren() throws XWikiException
{
return this.doc.getChildren(getXWikiContext());
}
/**
* @return "inline" if the document should be edited in inline mode by default or "edit" otherwise.
* @throws XWikiException if an error happens when computing the edit mode
*/
public String getDefaultEditMode() throws XWikiException
{
return this.doc.getDefaultEditMode(getXWikiContext());
}
public String getDefaultEditURL() throws XWikiException
{
return this.doc.getDefaultEditURL(getXWikiContext());
}
public String getEditURL(String action, String mode) throws XWikiException
{
return this.doc.getEditURL(action, mode, getXWikiContext());
}
public String getEditURL(String action, String mode, String language)
{
return this.doc.getEditURL(action, mode, language, getXWikiContext());
}
public boolean isCurrentUserCreator()
{
return this.doc.isCurrentUserCreator(getXWikiContext());
}
public boolean isCurrentUserPage()
{
return this.doc.isCurrentUserPage(getXWikiContext());
}
public boolean isCurrentLocalUserPage()
{
return this.doc.isCurrentLocalUserPage(getXWikiContext());
}
public boolean isCreator(String username)
{
return this.doc.isCreator(username);
}
public void set(String fieldname, java.lang.Object value)
{
Object obj;
if (this.currentObj != null) {
obj = this.currentObj;
} else {
obj = getFirstObject(fieldname);
}
set(fieldname, value, obj);
}
public void set(String fieldname, java.lang.Object value, Object obj)
{
if (obj == null) {
return;
}
obj.set(fieldname, value);
}
public void setTitle(String title)
{
getDoc().setTitle(title);
}
public void setCustomClass(String customClass)
{
getDoc().setCustomClass(customClass);
}
public void setParent(String parent)
{
getDoc().setParent(parent);
}
public void setContent(String content)
{
getDoc().setContent(content);
}
/**
* @param syntaxId the Syntax id representing the syntax used for the current document. For example "xwiki/1.0"
* represents the first version XWiki syntax while "xwiki/2.0" represents version 2.0 of the XWiki
* Syntax.
*/
public void setSyntaxId(String syntaxId)
{
getDoc().setSyntaxId(syntaxId);
}
public void setDefaultTemplate(String dtemplate)
{
getDoc().setDefaultTemplate(dtemplate);
}
public void setComment(String comment)
{
getDoc().setComment(comment);
}
public void setMinorEdit(boolean isMinor)
{
getDoc().setMinorEdit(isMinor);
}
public void save() throws XWikiException
{
save("", false);
}
public void save(String comment) throws XWikiException
{
save(comment, false);
}
public void save(String comment, boolean minorEdit) throws XWikiException
{
if (hasAccessLevel("edit")) {
saveDocument(comment, minorEdit);
} else {
java.lang.Object[] args = {this.doc.getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied in edit mode on document {0}", null, args);
}
}
public void saveWithProgrammingRights() throws XWikiException
{
saveWithProgrammingRights("", false);
}
public void saveWithProgrammingRights(String comment) throws XWikiException
{
saveWithProgrammingRights(comment, false);
}
public void saveWithProgrammingRights(String comment, boolean minorEdit) throws XWikiException
{
if (hasProgrammingRights()) {
saveDocument(comment, minorEdit);
} else {
java.lang.Object[] args = {this.doc.getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied with no programming rights document {0}", null, args);
}
}
protected void saveDocument(String comment, boolean minorEdit) throws XWikiException
{
XWikiDocument doc = getDoc();
doc.setAuthor(this.context.getUser());
if (doc.isNew()) {
doc.setCreator(this.context.getUser());
}
getXWikiContext().getWiki().saveDocument(doc, comment, minorEdit, getXWikiContext());
this.cloned = false;
}
public com.xpn.xwiki.api.Object addObjectFromRequest() throws XWikiException
{
// Call to getDoc() ensures that we are working on a clone()
return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(getXWikiContext()), getXWikiContext());
}
public com.xpn.xwiki.api.Object addObjectFromRequest(String className) throws XWikiException
{
return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(className, getXWikiContext()),
getXWikiContext());
}
public List<Object> addObjectsFromRequest(String className) throws XWikiException
{
return addObjectsFromRequest(className, "");
}
public com.xpn.xwiki.api.Object addObjectFromRequest(String className, String prefix) throws XWikiException
{
return new com.xpn.xwiki.api.Object(getDoc().addObjectFromRequest(className, prefix, getXWikiContext()),
getXWikiContext());
}
public List<Object> addObjectsFromRequest(String className, String prefix) throws XWikiException
{
List<BaseObject> objs = getDoc().addObjectsFromRequest(className, prefix, getXWikiContext());
List<Object> wrapped = new ArrayList<Object>();
for (BaseObject object : objs) {
wrapped.add(new com.xpn.xwiki.api.Object(object, getXWikiContext()));
}
return wrapped;
}
public com.xpn.xwiki.api.Object updateObjectFromRequest(String className) throws XWikiException
{
return new com.xpn.xwiki.api.Object(getDoc().updateObjectFromRequest(className, getXWikiContext()),
getXWikiContext());
}
public List<Object> updateObjectsFromRequest(String className) throws XWikiException
{
return updateObjectsFromRequest(className, "");
}
public com.xpn.xwiki.api.Object updateObjectFromRequest(String className, String prefix) throws XWikiException
{
return new com.xpn.xwiki.api.Object(getDoc().updateObjectFromRequest(className, prefix, getXWikiContext()),
getXWikiContext());
}
public List<Object> updateObjectsFromRequest(String className, String prefix) throws XWikiException
{
List<BaseObject> objs = getDoc().updateObjectsFromRequest(className, prefix, getXWikiContext());
List<Object> wrapped = new ArrayList<Object>();
for (BaseObject object : objs) {
wrapped.add(new com.xpn.xwiki.api.Object(object, getXWikiContext()));
}
return wrapped;
}
public boolean isAdvancedContent()
{
return this.doc.isAdvancedContent();
}
public boolean isProgrammaticContent()
{
return this.doc.isProgrammaticContent();
}
public boolean removeObject(Object obj)
{
return getDoc().removeObject(obj.getBaseObject());
}
public boolean removeObjects(String className)
{
return getDoc().removeObjects(className);
}
/**
* Remove document from the wiki. Reinit <code>cloned</code>.
*
* @throws XWikiException
*/
protected void deleteDocument() throws XWikiException
{
getXWikiContext().getWiki().deleteDocument(this.doc, getXWikiContext());
this.cloned = false;
}
public void delete() throws XWikiException
{
if (hasAccessLevel("delete")) {
deleteDocument();
} else {
java.lang.Object[] args = {this.doc.getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied in edit mode on document {0}", null, args);
}
}
public void deleteWithProgrammingRights() throws XWikiException
{
if (hasProgrammingRights()) {
deleteDocument();
} else {
java.lang.Object[] args = {this.doc.getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied with no programming rights document {0}", null, args);
}
}
public String getVersionHashCode()
{
return this.doc.getVersionHashCode(getXWikiContext());
}
public int addAttachments() throws XWikiException
{
return addAttachments(null);
}
public int addAttachments(String fieldName) throws XWikiException
{
if (!hasAccessLevel("edit")) {
java.lang.Object[] args = {this.doc.getFullName()};
throw new XWikiException(XWikiException.MODULE_XWIKI_ACCESS, XWikiException.ERROR_XWIKI_ACCESS_DENIED,
"Access denied in edit mode on document {0}", null, args);
}
XWiki xwiki = getXWikiContext().getWiki();
FileUploadPlugin fileupload = (FileUploadPlugin) xwiki.getPlugin("fileupload", getXWikiContext());
List<FileItem> fileuploadlist = fileupload.getFileItems(getXWikiContext());
List<XWikiAttachment> attachments = new ArrayList<XWikiAttachment>();
// adding attachment list to context so we find the names
this.context.put("addedAttachments", attachments);
int nb = 0;
if (fileuploadlist == null) {
return 0;
}
for (FileItem item : fileuploadlist) {
String name = item.getFieldName();
if (fieldName != null && !fieldName.equals(name)) {
continue;
}
if (item.isFormField()) {
continue;
}
byte[] data = fileupload.getFileItemData(name, getXWikiContext());
String filename;
String fname = fileupload.getFileName(name, getXWikiContext());
int i = fname.lastIndexOf("\\");
if (i == -1) {
i = fname.lastIndexOf("/");
}
filename = fname.substring(i + 1);
filename = filename.replaceAll("\\+", " ");
if ((data != null) && (data.length > 0)) {
XWikiAttachment attachment = this.doc.addAttachment(filename, data, getXWikiContext());
getDoc().saveAttachmentContent(attachment, getXWikiContext());
// commenting because this was already done by addAttachment
// getDoc().getAttachmentList().add(attachment);
attachments.add(attachment);
nb++;
}
}
if (nb > 0) {
getXWikiContext().getWiki().saveDocument(getDoc(), getXWikiContext());
this.cloned = false;
}
return nb;
}
public Attachment addAttachment(String fileName, InputStream iStream)
{
try {
return new Attachment(this, this.doc.addAttachment(fileName, iStream, getXWikiContext()), getXWikiContext());
} catch (XWikiException e) {
// TODO Log the error and let the user know about it
} catch (IOException e) {
// TODO Log the error and let the user know about it
}
return null;
}
public Attachment addAttachment(String fileName, byte[] data)
{
try {
return new Attachment(this, this.doc.addAttachment(fileName, data, getXWikiContext()), getXWikiContext());
} catch (XWikiException e) {
// TODO Log the error and let the user know about it
}
return null;
}
public boolean validate() throws XWikiException
{
return this.doc.validate(getXWikiContext());
}
public boolean validate(String[] classNames) throws XWikiException
{
return this.doc.validate(classNames, getXWikiContext());
}
/**
* Retrieves the validation script associated with this document, a Velocity script that is executed when validating
* the document data.
*
* @return A <code>String</code> representation of the validation script, or an empty string if there is no such
* script.
*/
public String getValidationScript()
{
return getDoc().getValidationScript();
}
/**
* Sets a new validation script for this document, a Velocity script that is executed when validating the document
* data.
*
* @param validationScript The new validation script, which can be an empty string or <code>null</code> if the
* script should be removed.
*/
public void setValidationScript(String validationScript)
{
getDoc().setValidationScript(validationScript);
}
/**
* @deprecated use {@link #rename(String)} instead
*/
@Deprecated
public void renameDocument(String newDocumentName) throws XWikiException
{
rename(newDocumentName);
}
/**
* Rename the current document and all the backlinks leading to it. See
* {@link #renameDocument(String, java.util.List)} for more details.
*
* @param newDocumentName the new document name. If the space is not specified then defaults to the current space.
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName) throws XWikiException
{
if (hasAccessLevel("delete")
&& this.context.getWiki().checkAccess("edit",
this.context.getWiki().getDocument(newDocumentName, this.context), this.context)) {
this.doc.rename(newDocumentName, getXWikiContext());
}
}
/**
* @deprecated use {@link #rename(String, java.util.List)} instead
*/
@Deprecated
public void renameDocument(String newDocumentName, List<String> backlinkDocumentNames) throws XWikiException
{
rename(newDocumentName, backlinkDocumentNames);
}
/**
* Rename the current document and all the links pointing to it in the list of passed backlink documents. The
* renaming algorithm takes into account the fact that there are several ways to write a link to a given page and
* all those forms need to be renamed. For example the following links all point to the same page:
* <ul>
* <li>[Page]</li>
* <li>[Page?param=1]</li>
* <li>[currentwiki:Page]</li>
* <li>[CurrentSpace.Page]</li>
* </ul>
* <p>
* Note: links without a space are renamed with the space added.
* </p>
*
* @param newDocumentName the new document name. If the space is not specified then defaults to the current space.
* @param backlinkDocumentNames the list of documents to parse and for which links will be modified to point to the
* new renamed document.
* @throws XWikiException in case of an error
*/
public void rename(String newDocumentName, List<String> backlinkDocumentNames) throws XWikiException
{
this.doc.rename(newDocumentName, backlinkDocumentNames, getXWikiContext());
}
/**
* Allow to easily access any revision of a document
*
* @param revision version to access
* @return Document object
* @throws XWikiException
*/
public Document getDocumentRevision(String revision) throws XWikiException
{
return new Document(this.context.getWiki().getDocument(this.doc, revision, this.context), this.context);
}
/**
* Allow to easily access the previous revision of a document
*
* @return Document
* @throws XWikiException
*/
public Document getPreviousDocument() throws XWikiException
{
return getDocumentRevision(getPreviousVersion());
}
/**
* @return is document most recent. false if and only if there are older versions of this document.
*/
public boolean isMostRecent()
{
return this.doc.isMostRecent();
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return this.doc.toString();
}
/**
* Convert the current document content from its current syntax to the new syntax passed as parameter.
*
* @param targetSyntaxId the syntax to convert to (eg "xwiki/2.0", "xhtml/1.0", etc)
* @throws XWikiException if an exception occurred during the conversion process
*/
public boolean convertSyntax(String targetSyntaxId) throws XWikiException
{
try {
getDoc().convertSyntax(targetSyntaxId, this.context);
} catch (Exception ex) {
return false;
}
return true;
}
} |
package io.spacedog.http;
import java.util.Map;
import java.util.regex.Pattern;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import io.spacedog.utils.Exceptions;
import io.spacedog.utils.Optional7;
import io.spacedog.utils.Utils;
public class SpaceBackend {
// main fields
private String host;
private int port;
private boolean ssl;
// specific multi backend fields
private boolean multi = false;
private String prefix = "";
private String backendId = defaultBackendId();
private boolean webApp = false;
private SpaceBackend() {
}
// Getters, setters and common methods
public String host() {
return multi ? new UrlBuilder().appendHost().toString() : host;
}
public String backendId() {
return backendId;
}
public int port() {
return port;
}
public boolean webApp() {
return webApp;
}
public boolean ssl() {
return ssl;
}
public boolean multi() {
return multi;
}
public String scheme() {
return ssl ? "https" : "http";
}
@Override
public String toString() {
if (multi)
return new UrlBuilder().appendScheme().appendHost("*").appendPort().toString();
else
return url();
}
// URL methods
public StringBuilder urlBuilder() {
return new UrlBuilder().appendScheme().appendHost().appendPort().build();
}
private class UrlBuilder {
private UrlBuilder appendScheme() {
builder.append(scheme()).append(":
return this;
}
private UrlBuilder appendHost() {
if (multi)
appendHost(defaultBackendId());
else
builder.append(host);
return this;
}
private UrlBuilder appendHost(String backendId) {
builder.append(prefix).append(backendId).append(host);
return this;
}
private UrlBuilder appendPort() {
if (port != 80 && port != 443)
builder.append(":").append(port);
return this;
}
public UrlBuilder append(String string) {
builder.append(string);
return this;
}
private StringBuilder build() {
return builder;
}
@Override
public String toString() {
return build().toString();
}
private StringBuilder builder = new StringBuilder();
}
public String url() {
return urlBuilder().toString();
}
public String url(String uri) {
return urlBuilder().append(uri).toString();
}
// Factory methods
public static SpaceBackend fromUrl(String url) {
return fromUrl(url, false);
}
public static SpaceBackend fromUrl(String url, boolean webApp) {
SpaceBackend target = new SpaceBackend();
target.webApp = webApp;
// handle scheme
if (url.startsWith("https:
url = Utils.removePreffix(url, "https:
target.ssl = true;
} else if (url.startsWith("http:
url = Utils.removePreffix(url, "http:
target.ssl = false;
} else
throw Exceptions.illegalArgument("invalid backend url [%s]", url);
// handle multi backend
if (url.indexOf('*') < 0) {
target.multi = false;
target.host = url;
} else {
String[] parts = url.split("\\*", 2);
target.multi = true;
target.host = parts[1];
target.prefix = parts[0];
target.backendId = defaultBackendId();
}
// handle url port
if (target.host.indexOf(':') < 0) {
target.port = target.ssl ? 443 : 80;
} else {
String[] parts = target.host.split(":", 2);
target.host = parts[0];
target.port = Integer.valueOf(parts[1]);
}
return target;
}
public static SpaceBackend fromDefaults(String name) {
return defaultTargets.get(name);
}
public static SpaceBackend valueOf(String string) {
return string.startsWith("http") ? fromUrl(string) : fromDefaults(string);
}
public Optional7<SpaceBackend> checkAndInstantiate(String requestHostAndPort) {
String backendhostAndPort = hostAndPort();
if (multi && requestHostAndPort.startsWith(prefix)
&& requestHostAndPort.endsWith(backendhostAndPort)) {
String backendId = Utils.removeSuffix(
Utils.removePreffix(requestHostAndPort, prefix),
backendhostAndPort);
// check if resulting backing id is well formed
if (backendId.length() > 0 && !backendId.contains("."))
return Optional7.of(instanciate(backendId));
} else if (backendhostAndPort.equalsIgnoreCase(requestHostAndPort))
return Optional7.of(this);
return Optional7.empty();
}
public SpaceBackend instanciate() {
return instanciate(defaultBackendId());
}
public SpaceBackend instanciate(String backendId) {
checkIsMultiple();
SpaceBackend backend = new SpaceBackend();
backend.multi = false;
backend.host = new UrlBuilder().appendHost(backendId).toString();
backend.backendId = backendId;
backend.port = port;
backend.ssl = ssl;
backend.webApp = webApp;
return backend;
}
// Default targets |
package org.yamcs.utils;
import java.net.URI;
import java.util.Base64;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.yamcs.security.UsernamePasswordToken;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpContentDecompressor;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponse;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.CharsetUtil;
public class HttpClient {
URI uri;
Exception exception;
StringBuilder result = new StringBuilder();
// public Future<String> doAsyncRequest(String url, HttpMethod httpMethod, String body) throws Exception {
// return doAsyncRequest(url, httpMethod, body, null);
public Future<String> doAsyncRequest(String url, HttpMethod httpMethod, String body,
UsernamePasswordToken authToken) throws Exception {
uri = new URI(url);
String scheme = uri.getScheme() == null? "http" : uri.getScheme();
String host = uri.getHost() == null? "127.0.0.1" : uri.getHost();
int port = uri.getPort();
if (port == -1) {
port = 80;
}
if (!"http".equalsIgnoreCase(scheme)) {
throw new IllegalArgumentException("Only HTTP is supported.");
}
exception = null;
result.setLength(0);
EventLoopGroup group = new NioEventLoopGroup();
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) {
ChannelPipeline p = ch.pipeline();
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new MyChannelHandler());
}
});
Channel ch = b.connect(host, port).sync().channel();
ByteBuf content = null;
if(body!=null) {
content = Unpooled.copiedBuffer(body, CharsetUtil.UTF_8);
} else {
content = Unpooled.EMPTY_BUFFER;
}
String fullUri = uri.getRawPath();
if (uri.getRawQuery() != null) {
fullUri += "?" + uri.getRawQuery();
}
HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, httpMethod, fullUri, content);
request.headers().set(HttpHeaders.Names.HOST, host);
request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
if(authToken != null) {
String credentialsClear = authToken.getUsername();
if(authToken.getPasswordS() != null)
credentialsClear += ":" + authToken.getPasswordS();
String credentialsB64 = new String(Base64.getEncoder().encode(credentialsClear.getBytes()));
String authorization = "Basic " + credentialsB64;
request.headers().set(HttpHeaders.Names.AUTHORIZATION, authorization);
}
ch.writeAndFlush(request).await(1, TimeUnit.SECONDS);
ResultFuture rf = new ResultFuture(ch.closeFuture());
return rf;
}
/* public String doRequest(String url, HttpMethod httpMethod, String body) throws Exception {
return doRequest(url, httpMethod, body, null);
}*/
public String doRequest(String url, HttpMethod httpMethod, String body, UsernamePasswordToken authToken) throws Exception {
Future<String> f = doAsyncRequest(url, httpMethod, body, authToken);
return f.get(5, TimeUnit.SECONDS);
}
/* public String doGetRequest(String url, String body) throws Exception {
return doGetRequest(url, body, null);
}*/
public String doGetRequest(String url, String body, UsernamePasswordToken authToken) throws Exception {
return doRequest(url, HttpMethod.GET, body, authToken);
}
/* public String doPostRequest(String url, String body) throws Exception {
return doPostRequest(url, body, null);
}*/
public String doPostRequest(String url, String body, UsernamePasswordToken authToken) throws Exception {
return doRequest(url, HttpMethod.POST, body, authToken);
}
class MyChannelHandler extends SimpleChannelInboundHandler<HttpObject> {
@Override
public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
if (msg instanceof HttpResponse) {
// HttpResponse response = (HttpResponse) msg;
}
if (msg instanceof HttpContent) {
HttpContent content = (HttpContent) msg;
result.append(content.content().toString(CharsetUtil.UTF_8));
if (content instanceof LastHttpContent) {
ctx.close();
}
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
if(cause instanceof Exception) {
exception = (Exception)cause;
} else {
exception = new RuntimeException(cause);
}
cause.printStackTrace();
ctx.close();
}
}
class ResultFuture implements Future<String> {
ChannelFuture closeFuture;
public ResultFuture(ChannelFuture closeFuture) {
this.closeFuture = closeFuture;
}
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return closeFuture.cancel(mayInterruptIfRunning);
}
@Override
public boolean isCancelled() {
return closeFuture.isCancelled();
}
@Override
public boolean isDone() {
return closeFuture.isDone();
}
@Override
public String get() throws InterruptedException, ExecutionException {
closeFuture.await();
if(HttpClient.this.exception!=null) {
throw new ExecutionException(HttpClient.this.exception);
}
return HttpClient.this.result.toString();
}
@Override
public String get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
if(closeFuture.await(timeout, unit)) {
if(HttpClient.this.exception!=null) {
throw new ExecutionException(HttpClient.this.exception);
}
} else {
throw new TimeoutException();
}
return HttpClient.this.result.toString();
}
}
} |
package jenkins.python.pwm;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTMatcher;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.TypeDeclaration;
import org.eclipse.jdt.core.dom.PackageDeclaration;
import org.eclipse.jdt.core.dom.ImportDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.Type;
import org.eclipse.jdt.core.dom.SimpleType;
import org.eclipse.jdt.core.dom.ParameterizedType;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.SimpleName;
import org.eclipse.jdt.core.dom.Name;
import org.eclipse.jdt.core.dom.TypeParameter;
import org.eclipse.jdt.core.dom.VariableDeclarationFragment;
import org.eclipse.jdt.core.dom.FieldDeclaration;
import org.eclipse.jdt.core.formatter.DefaultCodeFormatterConstants;
import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.text.edits.TextEdit;
/**
* Makes Python wrappers of given classes for the python-wrapper plugin.
*/
public class WrapperMaker {
private List<List<TypeDeclaration>> declarations;
private File outputDir;
public WrapperMaker(List<List<TypeDeclaration>> declars, File dir) {
declarations = declars;
outputDir = dir;
}
public void makeWrappers() throws WrapperMakerException {
outputDir.mkdirs();
if (!outputDir.isDirectory()) {
throw new WrapperMakerException("cannot create output directory " +
outputDir.getPath());
}
/// TODO declarations.size()
for (int i = 0; i < declarations.size(); i++) {
makeWrapper(declarations.get(i));
}
}
/**
* Saves a document to the output directory.
*/
private void saveFile(Document doc, TypeDeclaration decl) throws WrapperMakerException {
String[] nameParts = NameResolver.getFullName(decl).split("\\.");
String name = nameParts[nameParts.length-1] + "PW.java";
File outputFile = new File(outputDir, name);
try {
FileWriter fw = new FileWriter(outputFile);
fw.write(doc.get());
fw.close();
} catch (IOException e) {
throw new WrapperMakerException("cannot save a file " + outputFile.getPath() +
" caused by " + e.getMessage());
}
Logger.info("wrapper " + outputFile.getPath() + " created");
}
/**
* Makes a wrapper for the given type declaration (and all of its super classes).
*/
private void makeWrapper(List<TypeDeclaration> declars) throws WrapperMakerException {
try {
// init new blank Document, AST and CompilationUnit objecs
Document document = new Document("\n");
ASTParser parser = ASTParser.newParser(AST.JLS4);
parser.setSource(document.get().toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT);
CompilationUnit cu = (CompilationUnit)parser.createAST(null);
cu.recordModifications();
AST ast = cu.getAST();
// add package declaration
addPackage(cu);
// add import declarations
addImports(cu, declars);
// add type declaration
addTypeDeclaration(cu, declars.get(0));
// add fiels declaration
addFieldsDeclarations(cu);
// add method declarations
/// TODO methods
// rewrite changes to the document
Map<String,String> options = (Map<String,String>)JavaCore.getDefaultOptions();
options.put(DefaultCodeFormatterConstants.FORMATTER_LINE_SPLIT, "200");
TextEdit edits = cu.rewrite(document, options);
edits.apply(document);
// save the document as a new wrapper
saveFile(document, declars.get(0));
}
catch (BadLocationException e) {
Logger.error(e.getMessage());
String declName = NameResolver.getFullName(declars.get(0));
throw new WrapperMakerException("internal error while generating wrapper " +
"of the " + declName + " class");
}
}
/**
* Adds a type declaration to the compilation unit cu, which inherits from oldTD.
*/
private void addTypeDeclaration(CompilationUnit cu, TypeDeclaration oldTD) {
AST ast = cu.getAST();
TypeDeclaration td = ast.newTypeDeclaration();
cu.types().add(td);
List<Modifier> modifiers = ast.newModifiers(Modifier.PUBLIC + Modifier.ABSTRACT);
for (int i = 0; i < modifiers.size(); i++) {
td.modifiers().add(modifiers.get(i));
}
td.setName(ast.newSimpleName(oldTD.getName().getFullyQualifiedName() + "PW"));
Name oldName = (Name)ASTNode.copySubtree(ast, oldTD.getName());
if (oldTD.typeParameters().size() == 0) {
td.setSuperclassType(ast.newSimpleType(oldName));
}
else {
Type superType = ast.newSimpleType(oldName);
ParameterizedType superTypeP = ast.newParameterizedType(superType);
td.setSuperclassType(superTypeP);
for (int i = 0; i < oldTD.typeParameters().size(); i++) {
ASTNode param = (ASTNode)oldTD.typeParameters().get(i);
TypeParameter tp = (TypeParameter)ASTNode.copySubtree(ast, param);
td.typeParameters().add(tp);
SimpleName argName = (SimpleName)ASTNode.copySubtree(ast, tp.getName());
superTypeP.typeArguments().add(ast.newSimpleType(argName));
}
}
}
/**
* Adds field declarations to the root type declaration of the given compilation unit.
*/
private void addFieldsDeclarations(CompilationUnit cu) {
TypeDeclaration td = (TypeDeclaration)cu.types().get(0);
AST ast = cu.getAST();
// create new decl fragment
VariableDeclarationFragment vdf = ast.newVariableDeclarationFragment();
SimpleName fieldName = ast.newSimpleName("pexec");
vdf.setName(fieldName);
// create new field
SimpleName fieldTypeName = ast.newSimpleName("PythonExecutor");
Type fieldType = ast.newSimpleType(fieldTypeName);
FieldDeclaration field = ast.newFieldDeclaration(vdf);
field.setType(fieldType);
List<Modifier> modifiers = ast.newModifiers(Modifier.PRIVATE + Modifier.TRANSIENT);
for (int i = 0; i < modifiers.size(); i++) {
field.modifiers().add(modifiers.get(i));
}
// add field to the root type declaration
td.bodyDeclarations().add(field);
}
/**
* Adds a package declaration to the compilation unit cu.
*/
private void addPackage(CompilationUnit cu) {
AST ast = cu.getAST();
PackageDeclaration pd = ast.newPackageDeclaration();
Name name = ast.newName("jenkins.python." + outputDir.getPath());
pd.setName(name);
cu.setPackage(pd);
}
/**
* Determines if the node is in the list by subtreeMatch() method.
*/
private boolean isIn(List<? extends ASTNode> list, ASTNode node) {
boolean found = false;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).subtreeMatch(new ASTMatcher(), node)) {
found = true;
break;
}
}
return found;
}
/**
* Adds import declarations to the compilation unit cu.
*/
private void addImports(CompilationUnit cu, List<TypeDeclaration> declars) {
AST ast = cu.getAST();
List<ImportDeclaration> imports = cu.imports();
// for all original declarations
for (int i = 0; i < declars.size(); i++) {
TypeDeclaration decl = declars.get(i);
String declName = NameResolver.getFullName(decl);
CompilationUnit oldCU = (CompilationUnit)decl.getRoot();
List<ImportDeclaration> oldImports = oldCU.imports();
// for all imports in the CU of the declaration
for (int j = 0; j < oldImports.size(); j++) {
ImportDeclaration oldImportD = oldImports.get(j);
// if not in the list, copy and add an import declaration
if (!isIn(imports, oldImportD)) {
imports.add((ImportDeclaration)ASTNode.copySubtree(ast, oldImportD));
}
}
// add also the original package name as an on-demand import declaration
Name pckgImportName = oldCU.getPackage().getName();
ImportDeclaration pckgImport = ast.newImportDeclaration();
pckgImport.setName((Name)ASTNode.copySubtree(ast, pckgImportName));
pckgImport.setOnDemand(true);
if (!isIn(imports, pckgImport)) {
imports.add(pckgImport);
}
// import also all subtypes of the original type declarations
ImportDeclaration subtypesImport = ast.newImportDeclaration();
subtypesImport.setName(ast.newName(declName));
subtypesImport.setOnDemand(true);
if (!isIn(imports, subtypesImport)) {
imports.add(subtypesImport);
}
// import also all subtypes of the parent type of the original declaration
String[] declNameParts = declName.split("\\.");
String parentTypeName = "";
for (int j = 0; j < declNameParts.length-1; j++) {
parentTypeName += declNameParts[j];
if (j < declNameParts.length-2) {
parentTypeName += ".";
}
}
ImportDeclaration parentSubtypesImport = ast.newImportDeclaration();
parentSubtypesImport.setName(ast.newName(parentTypeName));
parentSubtypesImport.setOnDemand(true);
if (!isIn(imports, parentSubtypesImport)) {
imports.add(parentSubtypesImport);
}
}
// import also jenkins.python.* names
Name iName;
ImportDeclaration pPckgImport;
iName = ast.newName("jenkins.python.DataConvertor");
pPckgImport = ast.newImportDeclaration();
pPckgImport.setName(iName);
imports.add(pPckgImport);
iName = ast.newName("jenkins.python.PythonExecutor");
pPckgImport = ast.newImportDeclaration();
pPckgImport.setName(iName);
imports.add(pPckgImport);
}
} |
package org.yamcs.xtce;
import java.io.PrintStream;
import java.util.Collections;
import java.util.List;
/**
* A type definition used as the base type for a CommandDefinition
*
*
* @author nm
*
*/
public class MetaCommand extends NameDescription {
private static final long serialVersionUID = 1L;
/**
* From XTCE:
* Many commands have one or more options. These are called command arguments. Command arguments may be of any of the standard data types.
* MetaCommand arguments are local to the MetaCommand. Arguments are the visible to the user or processing software.
* This can be somewhat subjective -- for example a checksum that is always part of the command format is probably not an argument.
*/
List<Argument> argumentList;
/**
* From XTCE:
* Tells how to package this command.
* May not be referred to in the EntryList of a SequenceContainer, CommandContainerSet/CommandContainer or another MetaCommandContainer.
* May be extended by another MetaCommand/CommandContainer.
*/
MetaCommandContainer commandContainer;
MetaCommand baseMetaCommand;
//assignment for inheritance
List<ArgumentAssignment> argumentAssignmentList;
/**
* if command is abstract, it cannot be instantiated
*/
boolean abstractCmd = false;
public MetaCommand(String name) {
super(name);
}
/**
* Set the command as abstract or non abstract.
* Abstract commands cannot be instantiated
* @param a
*/
public void setAbstract(boolean a) {
abstractCmd = a;
}
public boolean isAbstract() {
return abstractCmd;
}
public void setMetaCommandContainer(MetaCommandContainer mcc) {
this.commandContainer = mcc;
}
public MetaCommandContainer getCommandContainer() {
return commandContainer;
}
public void setBaseMetaCommand(MetaCommand mc) {
this.baseMetaCommand = mc;
}
public List<Argument> getArgumentList() {
return Collections.unmodifiableList(argumentList);
}
/**
* returns an argument based on name or null if it doesn't exist
* @param argumentName
* @return
*/
public Argument getArgument(String argumentName) {
for(Argument a: argumentList) {
if(a.getName().equals(argumentName)) {
return a;
}
}
return null;
}
public void print(PrintStream out) {
out.print("MetaCommand name: "+name+" abstract:"+abstractCmd);
if(getAliasSet()!=null) out.print(", aliases: "+getAliasSet());
out.println( "." );
commandContainer.print(out);
}
} |
package org.jetel.component;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.connection.DBConnection;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.data.RecordKey;
import org.jetel.database.IConnection;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.TransformException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.TransformationGraph;
import org.jetel.lookup.DBLookupTable;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.ComponentXMLAttributes;
import org.w3c.dom.Element;
public class DBJoin extends Node {
private static final String XML_SQL_QUERY_ATTRIBUTE = "sqlQuery";
private static final String XML_DBCONNECTION_ATTRIBUTE = "dbConnection";
private static final String XML_JOIN_KEY_ATTRIBUTE = "joinKey";
private static final String XML_TRANSFORM_CLASS_ATTRIBUTE = "transformClass";
private static final String XML_TRANSFORM_ATTRIBUTE = "transform";
private static final String XML_DB_METADATA_ATTRIBUTE = "metadata";
private static final String XML_MAX_CASHED_ATTRIBUTE = "maxCashed";
private static final String XML_LEFTOUTERJOIN_ATTRIBUTE = "leftOuterJoin";
public final static String COMPONENT_TYPE = "DBJOIN";
private final static int WRITE_TO_PORT = 0;
private final static int READ_FROM_PORT = 0;
private String transformClassName = null;
private RecordTransform transformation = null;
private String transformSource = null;
private String[] joinKey;
private String connectionName;
private String query;
private String metadataName;
private int maxCashed;
private boolean leftOuterJoin = false;
private Properties transformationParameters=null;
private DBLookupTable lookupTable;
private RecordKey recordKey;
private DataRecordMetadata dbMetadata;
static Log logger = LogFactory.getLog(Reformat.class);
/**
*Constructor
*
* @param id of component
* @param connectionName id of connection used for connecting with database
* @param query for getting data from database
* @param joinKey fields from input port which defines joing records with record from database
*/
public DBJoin(String id,String connectionName,String query,String[] joinKey,
String transform, String transformClass){
super(id);
this.connectionName = connectionName;
this.query = query;
this.joinKey = joinKey;
this.transformClassName = transformClass;
this.transformSource = transform;
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#getType()
*/
public String getType() {
return COMPONENT_TYPE;
}
/* (non-Javadoc)
* @see org.jetel.graph.Node#run()
*/
public void run() {
//initialize in and out records
InputPort inPort=getInputPort(WRITE_TO_PORT);
DataRecord inRecord = new DataRecord(inPort.getMetadata());
inRecord.init();
DataRecord[] outRecord = {new DataRecord(getOutputPort(READ_FROM_PORT).getMetadata())};
outRecord[0].init();
DataRecord[] inRecords = new DataRecord[] {inRecord,null};
while (inRecord!=null && runIt) {
try {
inRecord = inPort.readRecord(inRecord);
if (inRecord!=null) {
//find slave record in database
inRecords[1] = lookupTable.get(inRecord);
if (inRecords[1] == null && leftOuterJoin) {
inRecords[1] = new DataRecord(dbMetadata);
inRecords[1].init();
}
while (inRecords[1]!=null){
if (transformation.transform(inRecords, outRecord)) {
writeRecord(WRITE_TO_PORT,outRecord[0]);
}
//get next record from database with the same key
inRecords[1] = lookupTable.getNext();
}
}
} catch (TransformException ex) {
resultMsg = "Error occurred in nested transformation: " + ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (IOException ex) {
resultMsg = ex.getMessage();
resultCode = Node.RESULT_ERROR;
closeAllOutputPorts();
return;
} catch (Exception ex) {
ex.printStackTrace();
resultMsg = ex.getMessage();
resultCode = Node.RESULT_FATAL_ERROR;
closeAllOutputPorts();
return;
}
}
broadcastEOF();
if (runIt) {
resultMsg = "OK";
} else {
resultMsg = "STOPPED";
}
resultCode = Node.RESULT_OK;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#checkConfig()
*/
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
//TODO
return status;
}
/* (non-Javadoc)
* @see org.jetel.graph.GraphElement#init()
*/
public void init() throws ComponentNotReadyException {
// test that we have one input port and one output
if (inPorts.size() != 1) {
throw new ComponentNotReadyException("Exactly one input port has to be defined!");
} else if (outPorts.size() != 1) {
throw new ComponentNotReadyException("Exactly one output port has to be defined!");
}
//Initializing lookup table
IConnection conn = getGraph().getConnection(connectionName);
if(conn == null) {
throw new ComponentNotReadyException("Can't find DBConnection ID: " + connectionName);
}
if(!(conn instanceof DBConnection)) {
throw new ComponentNotReadyException("Connection with ID: " + connectionName + " isn't instance of the DBConnection class.");
}
dbMetadata = getGraph().getDataRecordMetadata(metadataName);
DataRecordMetadata inMetadata[]={ getInputPort(READ_FROM_PORT).getMetadata(),dbMetadata};
DataRecordMetadata outMetadata[]={getOutputPort(WRITE_TO_PORT).getMetadata()};
lookupTable = new DBLookupTable("LOOKUP_TABLE_FROM_"+this.getId(),(DBConnection) conn,dbMetadata,query,maxCashed);
lookupTable.init();
if (dbMetadata == null){
dbMetadata = lookupTable.getMetadata();
}
try {
recordKey = new RecordKey(joinKey,inMetadata[0]);
recordKey.init();
lookupTable.setLookupKey(recordKey);
transformation = RecordTransformFactory.createTransform(
transformSource, transformClassName, this, inMetadata, outMetadata, transformationParameters);
} catch(Exception e) {
throw new ComponentNotReadyException(this, e);
}
}
public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException {
ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph);
DBJoin dbjoin;
String connectionName;
String query;
String[] joinKey;
//get necessary parameters
try{
connectionName = xattribs.getString(XML_DBCONNECTION_ATTRIBUTE);
query = xattribs.getString(XML_SQL_QUERY_ATTRIBUTE);
joinKey = xattribs.getString(XML_JOIN_KEY_ATTRIBUTE).split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX);
dbjoin = new DBJoin(
xattribs.getString(XML_ID_ATTRIBUTE),
connectionName,query,joinKey,
xattribs.getString(XML_TRANSFORM_ATTRIBUTE, null),
xattribs.getString(XML_TRANSFORM_CLASS_ATTRIBUTE, null));
dbjoin.setTransformationParameters(xattribs.attributes2Properties(new String[]{XML_TRANSFORM_CLASS_ATTRIBUTE}));
if (xattribs.exists(XML_DB_METADATA_ATTRIBUTE)){
dbjoin.setDbMetadata(xattribs.getString(XML_DB_METADATA_ATTRIBUTE));
}
if (xattribs.exists(XML_LEFTOUTERJOIN_ATTRIBUTE)){
dbjoin.setLeftOuterJoin(xattribs.getBoolean(XML_LEFTOUTERJOIN_ATTRIBUTE));
}
dbjoin.setMaxCashed(xattribs.getInteger(XML_MAX_CASHED_ATTRIBUTE,100));
} catch (Exception ex) {
throw new XMLConfigurationException(COMPONENT_TYPE + ":" + xattribs.getString(XML_ID_ATTRIBUTE," unknown ID ") + ":" + ex.getMessage(),ex);
}
return dbjoin;
}
/**
* @param transformationParameters The transformationParameters to set.
*/
public void setTransformationParameters(Properties transformationParameters) {
this.transformationParameters = transformationParameters;
}
/**
* @param dbMetadata The dbMetadata to set.
*/
private void setDbMetadata(String dbMetadata) {
this.metadataName = dbMetadata;
}
private void setMaxCashed(int maxCashed) {
this.maxCashed = maxCashed;
}
private void setLeftOuterJoin(boolean leftOuterJoin) {
this.leftOuterJoin = leftOuterJoin;
}
} |
package org.jetel.logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SafeLogUtils {
/** Pattern for identifying URL with password in a given text */
private static final Pattern URL_PASSWORD_PATTERN = Pattern.compile("\\w+://.*?:([^/]*)@", Pattern.DOTALL);
/*
* a://b:c@d
*
* Input text matches:
* group #0 = a://b:c@d
* group #1 = b
* group #2 = c
*
*/
/**
* Obfuscates passwords in URLs in given text.
* Moreover secure parameters are backward resolved if it is possible.
*
* @param text - text to obfuscate passwords
* @return obfuscated text
*/
public static String obfuscateSensitiveInformation(String text) {
if (text == null) {
return null;
}
StringBuilder result = new StringBuilder();
Matcher m = URL_PASSWORD_PATTERN.matcher(text);
int pointer = 0;
while (m.find()) {
result.append(text.substring(pointer, m.start(1)));
result.append("***");
pointer = m.end(1);
}
result.append(text.substring(pointer, text.length()));
return result.toString();
}
private SafeLogUtils() {
}
} |
package org.jetel.util.file;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLStreamHandler;
import java.nio.channels.Channel;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import org.jetel.component.fileoperation.CloverURI;
import org.jetel.component.fileoperation.FileManager;
import org.jetel.component.fileoperation.Operation;
import org.jetel.component.fileoperation.SimpleParameters.CreateParameters;
import org.jetel.component.fileoperation.URIUtils;
import org.jetel.data.Defaults;
import org.jetel.enums.ArchiveType;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.TransformationGraph;
import org.jetel.logger.SafeLog;
import org.jetel.logger.SafeLogFactory;
import org.jetel.util.MultiOutFile;
import org.jetel.util.Pair;
import org.jetel.util.bytes.SystemOutByteChannel;
import org.jetel.util.exec.PlatformUtils;
import org.jetel.util.protocols.ProxyAuthenticable;
import org.jetel.util.protocols.UserInfo;
import org.jetel.util.protocols.amazon.S3InputStream;
import org.jetel.util.protocols.amazon.S3OutputStream;
import org.jetel.util.protocols.ftp.FTPStreamHandler;
import org.jetel.util.protocols.proxy.ProxyHandler;
import org.jetel.util.protocols.proxy.ProxyProtocolEnum;
import org.jetel.util.protocols.sandbox.SandboxStreamHandler;
import org.jetel.util.protocols.sftp.SFTPConnection;
import org.jetel.util.protocols.sftp.SFTPStreamHandler;
import org.jetel.util.protocols.webdav.WebdavOutputStream;
import org.jetel.util.stream.StreamUtils;
import org.jetel.util.stream.TarInputStream;
import org.jetel.util.string.StringUtils;
import com.ice.tar.TarEntry;
import com.jcraft.jsch.ChannelSftp;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
/**
* Helper class with some useful methods regarding file manipulation
*
* @author dpavlis
* @since May 24, 2002
*/
public class FileUtils {
private final static String DEFAULT_ZIP_FILE = "default_output";
// for embedded source
// "something : ( something ) [#something]?
// ([^:]*) (:) (\\() (.*) (\\)) (((
private final static Pattern INNER_SOURCE = Pattern.compile("(([^:]*)([:])([\\(]))(.*)(\\))(((
// standard input/output source
public final static String STD_CONSOLE = "-";
// sftp protocol handler
public static final SFTPStreamHandler sFtpStreamHandler = new SFTPStreamHandler();
// ftp protocol handler
public static final FTPStreamHandler ftpStreamHandler = new FTPStreamHandler();
// proxy protocol handler
public static final ProxyHandler proxyHandler = new ProxyHandler();
// file protocol name
private static final String FILE_PROTOCOL = "file";
private static final String FILE_PROTOCOL_ABSOLUTE_MARK = "file:./";
// archive protocol names
private static final String TAR_PROTOCOL = "tar";
private static final String GZIP_PROTOCOL = "gzip";
private static final String ZIP_PROTOCOL = "zip";
private static final String TGZ_PROTOCOL = "tgz";
// FTP-like protocol names
private static final String FTP_PROTOCOL = "ftp";
private static final String SFTP_PROTOCOL = "sftp";
private static final String SCP_PROTOCOL = "scp";
private static final ArchiveURLStreamHandler ARCHIVE_URL_STREAM_HANDLER = new ArchiveURLStreamHandler();
private static final URLStreamHandler HTTP_HANDLER = new CredentialsSerializingHandler() {
@Override
protected int getDefaultPort() {
return 80;
}
};
private static final URLStreamHandler HTTPS_HANDLER = new CredentialsSerializingHandler() {
@Override
protected int getDefaultPort() {
return 443;
}
};
private static final SafeLog log = SafeLogFactory.getSafeLog(FileUtils.class);
public static final Map<String, URLStreamHandler> handlers;
private static final String HTTP_PROTOCOL = "http";
private static final String HTTPS_PROTOCOL = "https";
private static final String UTF8 = "UTF-8";
static {
Map<String, URLStreamHandler> h = new HashMap<String, URLStreamHandler>();
h.put(GZIP_PROTOCOL, ARCHIVE_URL_STREAM_HANDLER);
h.put(ZIP_PROTOCOL, ARCHIVE_URL_STREAM_HANDLER);
h.put(TAR_PROTOCOL, ARCHIVE_URL_STREAM_HANDLER);
h.put(TGZ_PROTOCOL, ARCHIVE_URL_STREAM_HANDLER);
h.put(FTP_PROTOCOL, ftpStreamHandler);
h.put(SFTP_PROTOCOL, sFtpStreamHandler);
h.put(SCP_PROTOCOL, sFtpStreamHandler);
h.put(HTTP_PROTOCOL, HTTP_HANDLER);
h.put(HTTPS_PROTOCOL, HTTPS_HANDLER);
for (ProxyProtocolEnum p: ProxyProtocolEnum.values()) {
h.put(p.toString(), proxyHandler);
}
h.put(SandboxUrlUtils.SANDBOX_PROTOCOL, new SandboxStreamHandler());
handlers = Collections.unmodifiableMap(h);
}
/**
* Third-party implementation of path resolving - useful to make possible to run the graph inside of war file.
*/
private static final List<CustomPathResolver> customPathResolvers = new ArrayList<CustomPathResolver>();
private static final String PLUS_CHAR_ENCODED = "%2B";
/**
* Used only to extract the protocol name in a generic manner
*/
private static final URLStreamHandler GENERIC_HANDLER = new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
};
/**
* If the given string is an valid absolute URL
* with a known protocol, returns the URL.
*
* Throws MalformedURLException otherwise.
*
* @param url
* @return URL constructed from <code>url</code>
* @throws MalformedURLException
*/
public static final URL getUrl(String url) throws MalformedURLException {
try {
return new URL(url);
} catch (MalformedURLException e) {
String protocol = new URL(null, url, GENERIC_HANDLER).getProtocol();
URLStreamHandler handler = FileUtils.handlers.get(protocol.toLowerCase());
if (handler != null) {
return new URL(null, url, handler);
} else {
throw e;
}
}
}
public static URL getFileURL(String fileURL) throws MalformedURLException {
return getFileURL((URL) null, fileURL);
}
public static URL getFileURL(String contextURL, String fileURL) throws MalformedURLException {
return getFileURL(getFileURL((URL) null, contextURL), fileURL);
}
/**
* Creates URL object based on specified fileURL string. Handles
* situations when <code>fileURL</code> contains only path to file
* <i>(without "file:" string)</i>.
*
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL string containing file URL
* @return URL object or NULL if object can't be created (due to Malformed URL)
* @throws MalformedURLException
*/
public static URL getFileURL(URL contextURL, String fileURL) throws MalformedURLException {
//FIX CLD-2895
//default value for addStrokePrefix was changed to true
//right now I am not sure if this change can have an impact to other part of project,
//but it seems this changed fix relatively important issue:
//contextURL "file:/c:/project/"
//fileURL "c:/otherProject/data.txt"
//leads to --> "file:/c:/project/c:/otherProject/data.txt"
return getFileURL(contextURL, fileURL, true);
}
private static Pattern DRIVE_LETTER_PATTERN = Pattern.compile("\\A\\p{Alpha}:[/\\\\]");
private static Pattern PROTOCOL_PATTERN = Pattern.compile("\\A(\\p{Alnum}+):");
private static final String PORT_PROTOCOL = "port";
private static final String DICTIONARY_PROTOCOL = "dict";
private static String getProtocol(String fileURL) {
if (fileURL == null) {
throw new NullPointerException("fileURL is null");
}
Matcher m = PROTOCOL_PATTERN.matcher(fileURL);
if (m.find()) {
String protocol = m.group(1);
if ((protocol.length() == 1) && PlatformUtils.isWindowsPlatform() && DRIVE_LETTER_PATTERN.matcher(fileURL).find()) {
return null;
} else {
return protocol;
}
}
return null;
}
/**
* Creates URL object based on specified fileURL string. Handles
* situations when <code>fileURL</code> contains only path to file
* <i>(without "file:" string)</i>.
*
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL string containing file URL
* @return URL object or NULL if object can't be created (due to Malformed URL)
* @throws MalformedURLException
*/
public static URL getFileURL(URL contextURL, String fileURL, boolean addStrokePrefix) throws MalformedURLException {
// remove mark for absolute path
if (contextURL != null && fileURL.startsWith(FILE_PROTOCOL_ABSOLUTE_MARK)) {
fileURL = fileURL.substring((FILE_PROTOCOL+":").length());
}
final String protocol = getProtocol(fileURL);
if (DICTIONARY_PROTOCOL.equalsIgnoreCase(protocol) || PORT_PROTOCOL.equalsIgnoreCase(protocol)) {
return new URL(contextURL, fileURL, GENERIC_HANDLER);
}
//first we try the custom path resolvers
for (CustomPathResolver customPathResolver : customPathResolvers) {
// CLO-978 - call handlesURL(), don't catch any MalformedURLExceptions
if (customPathResolver.handlesURL(contextURL, fileURL)) {
return customPathResolver.getURL(contextURL, fileURL);
}
}
// standard url
try {
if( fileURL.startsWith("/") ){
return new URL(fileURL);
} else {
return getStandardUrlWeblogicHack(contextURL, fileURL);
}
} catch(MalformedURLException ex) {}
// sftp url
try {
// ftp connection is connected via sftp handler, 22 port is ok but 21 is somehow blocked for the same connection
return new URL(contextURL, fileURL, sFtpStreamHandler);
} catch(MalformedURLException e) {}
// proxy url
try {
return new URL(contextURL, fileURL, proxyHandler);
} catch(MalformedURLException e) {}
// sandbox url
if (SandboxUrlUtils.isSandboxUrl(fileURL)){
try {
return new URL(contextURL, fileURL, new SandboxStreamHandler());
} catch(MalformedURLException e) {}
}
// archive url
if (isArchive(fileURL)) {
StringBuilder innerInput = new StringBuilder();
StringBuilder anchor = new StringBuilder();
ArchiveType type = getArchiveType(fileURL, innerInput, anchor);
URL archiveFileUrl = getFileURL(contextURL, innerInput.toString());
return new URL(null, type.getId() + ":(" + archiveFileUrl.toString() + ")#" + anchor, new ArchiveURLStreamHandler(contextURL));
}
if (!StringUtils.isEmpty(protocol)) {
// unknown protocol will throw an exception,
// standard Java protocols will be ignored;
// all Clover-specific protocols must be checked before this call
new URL(fileURL);
}
if (StringUtils.isEmpty(protocol)) {
// file url
String prefix = FILE_PROTOCOL + ":";
if (addStrokePrefix && new File(fileURL).isAbsolute() && !fileURL.startsWith("/")) {
prefix += "/";
}
return new URL(contextURL, prefix + fileURL);
}
return new URL(contextURL, fileURL);
}
private static URL getStandardUrlWeblogicHack(URL contextUrl, String fileUrl) throws MalformedURLException {
if (contextUrl != null || fileUrl != null) {
final URL resolvedInContextUrl = new URL(contextUrl, fileUrl);
String protocol = resolvedInContextUrl.getProtocol();
if (protocol != null) {
protocol = protocol.toLowerCase();
if (protocol.equals(HTTP_PROTOCOL)) {
return new URL(contextUrl, fileUrl, FileUtils.HTTP_HANDLER);
} else if (protocol.equals(HTTPS_PROTOCOL)) {
return new URL(contextUrl, fileUrl, FileUtils.HTTPS_HANDLER);
}
}
}
return new URL(contextUrl, fileUrl);
}
/**
* Converts a list of file URLs to URL objects by calling {@link #getFileURL(URL, String)}.
*
* @param contextUrl URL context for converting relative paths to absolute ones
* @param fileUrls array of string file URLs
*
* @return an array of file URL objects
*
* @throws MalformedURLException if any of the given file URLs is malformed
*/
public static URL[] getFileUrls(URL contextUrl, String[] fileUrls) throws MalformedURLException {
if (fileUrls == null) {
return null;
}
URL[] resultFileUrls = new URL[fileUrls.length];
for (int i = 0; i < fileUrls.length; i++) {
resultFileUrls[i] = getFileURL(contextUrl, fileUrls[i]);
}
return resultFileUrls;
}
/**
* Calculates checksum of specified file.<br>Is suitable for short files (not very much buffered).
*
* @param filename Filename (full path) of file to calculate checksum for
* @return Calculated checksum or -1 if some error (IO) occured
*/
public static long calculateFileCheckSum(String filename) {
byte[] buffer = new byte[1024];
Checksum checksum = new Adler32(); // we use Adler - should be faster
int length = 0;
try {
FileInputStream dataFile = new FileInputStream(filename);
try {
while (length != -1) {
length = dataFile.read(buffer);
if (length > 0) {
checksum.update(buffer, 0, length);
}
}
} finally {
dataFile.close();
}
} catch (IOException ex) {
return -1;
}
return checksum.getValue();
}
/**
* Reads file specified by URL. The content is returned as String
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL URL specifying the location of file from which to read
* @return
*/
public static String getStringFromURL(URL contextURL, String fileURL, String charset){
InputStream source;
String chSet = charset != null ? charset : Defaults.DataParser.DEFAULT_CHARSET_DECODER;
StringBuffer sb = new StringBuffer(2048);
char[] charBuf=new char[256];
try {
source = FileUtils.getInputStream(contextURL, fileURL);
BufferedReader in = new BufferedReader(new InputStreamReader(source, chSet));
try {
int readNum;
while ((readNum = in.read(charBuf, 0, charBuf.length)) != -1) {
sb.append(charBuf, 0, readNum);
}
} finally {
in.close();
}
} catch (IOException ex) {
throw new RuntimeException("Can't get string from file " + fileURL, ex);
}
return sb.toString();
}
/**
* Creates ReadableByteChannel from the url definition.
* <p>
* All standard url format are acceptable plus extended form of url by zip & gzip construction:
* </p>
* Examples:
* <dl>
* <dd>zip:<url_to_zip_file>#<inzip_path_to_file></dd>
* <dd>gzip:<url_to_gzip_file></dd>
* </dl>
*
* @param contextURL
* context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param input
* URL of file to read
* @return
* @throws IOException
*/
public static ReadableByteChannel getReadableChannel(URL contextURL, String input) throws IOException {
InputStream in = getInputStream(contextURL, input);
//incremental reader needs FileChannel:
return in instanceof FileInputStream ? ((FileInputStream)in).getChannel() : Channels.newChannel(in);
}
/**
* Creates InputStream from the url definition.
* <p>
* All standard url format are acceptable plus extended form of url by zip & gzip construction:
* </p>
* Examples:
* <dl>
* <dd>zip:<url_to_zip_file>#<inzip_path_to_file></dd>
* <dd>gzip:<url_to_gzip_file></dd>
* </dl>
* For zip file, if anchor is not set there is return first zip entry.
*
* @param contextURL
* context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param input
* URL of file to read
* @return
* @throws IOException
* @throws IOException
*/
public static InputStream getInputStream(URL contextURL, String input) throws IOException {
InputStream innerStream = null;
// It is important to use the same mechanism (TrueZip) for both reading and writing
// of the local archives!
// The TrueZip library has it's own virtual file system. Even after a stream from TrueZip
// gets closed, the contents are not immediately written to the disc.
// Therefore reading local archive with different library (e.g. java.util.zip) might lead to
// inconsistency if the archive has not been flushed by TrueZip yet.
StringBuilder localArchivePath = new StringBuilder();
if (getLocalArchiveInputPath(contextURL, input, localArchivePath)) {
// apply the contextURL
URL url = FileUtils.getFileURL(contextURL, localArchivePath.toString());
String absolutePath = getUrlFile(url);
registerTrueZipVSFEntry(new de.schlichtherle.io.File(localArchivePath.toString()));
return new de.schlichtherle.io.FileInputStream(absolutePath);
}
//first we try the custom path resolvers
for (CustomPathResolver customPathResolver : customPathResolvers) {
innerStream = customPathResolver.getInputStream(contextURL, input);
if (innerStream != null) {
log.debug("Input stream '" + input + "[" + contextURL + "] was opened by custom path resolver.");
return innerStream; //we found the desired input stream using external resolver method
}
}
// std input (console)
if (input.equals(STD_CONSOLE)) {
return System.in;
}
// get inner source
Matcher matcher = FileURLParser.getURLMatcher(input);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
// get and set proxy and go to inner source
Proxy proxy = getProxy(innerSource);
String proxyUserInfo = null;
if (proxy != null) {
try {
proxyUserInfo = new URI(innerSource).getUserInfo();
} catch (URISyntaxException ex) {
}
}
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
innerStream = proxy == null ? getInputStream(contextURL, innerSource)
: getAuthorizedConnection(getFileURL(contextURL, input), proxy, proxyUserInfo).getInputStream();
}
// get archive type
StringBuilder sbAnchor = new StringBuilder();
StringBuilder sbInnerInput = new StringBuilder();
ArchiveType archiveType = getArchiveType(input, sbInnerInput, sbAnchor);
input = sbInnerInput.toString();
//open channel
URL url = null;
if (innerStream == null) {
url = FileUtils.getFileURL(contextURL, input);
// creates file input stream for incremental reading (random access file)
if (archiveType == null && url.getProtocol().equals(FILE_PROTOCOL)) {
return new FileInputStream(url.getRef() != null ? getUrlFile(url) + "#" + url.getRef() : getUrlFile(url));
} else if (archiveType == null && SandboxUrlUtils.isSandboxUrl(url)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
return graph.getAuthorityProxy().getSandboxResourceInput(ContextProvider.getComponentId(), url.getHost(), getUrlFile(url));
}
try {
if (S3InputStream.isS3File(url)) {
return new S3InputStream(url);
}
try {
innerStream = getAuthorizedConnection(url).getInputStream();
}
catch (Exception e) {
throw new IOException("Cannot obtain connection input stream for URL '" + url + "'. Make sure the URL is valid.", e);
}
} catch (IOException e) {
log.debug("IOException occured for URL - host: '" + url.getHost() + "', path: '" + url.getPath() + "' (user info not shown)",
"IOException occured for URL - host: '" + url.getHost() + "', userinfo: '" + url.getUserInfo() + "', path: '" + url.getPath() + "'");
throw e;
}
}
// create archive streams
String anchor = URLDecoder.decode(sbAnchor.toString(), UTF8);
if (archiveType == ArchiveType.ZIP) {
return getZipInputStream(innerStream, anchor); // CL-2579
} else if (archiveType == ArchiveType.GZIP) {
return new GZIPInputStream(innerStream, Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE);
} else if (archiveType == ArchiveType.TAR) {
return getTarInputStream(innerStream, anchor);
} else if (archiveType == ArchiveType.TGZ) {
return getTarInputStream(new GZIPInputStream(innerStream, Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE), anchor);
}
return innerStream;
}
/**
* Gets archive type.
* @param input - input file
* @param innerInput - output parameter
* @param anchor - output parameter
* @return
*/
public static ArchiveType getArchiveType(String input, StringBuilder innerInput, StringBuilder anchor) {
// result value
ArchiveType archiveType = null;
//resolve url format for zip files
if (input.startsWith("zip:")) archiveType = ArchiveType.ZIP;
else if (input.startsWith("tar:")) archiveType = ArchiveType.TAR;
else if (input.startsWith("gzip:")) archiveType = ArchiveType.GZIP;
else if (input.startsWith("tgz:")) archiveType = ArchiveType.TGZ;
// parse the archive
if((archiveType == ArchiveType.ZIP) || (archiveType == ArchiveType.TAR) || (archiveType == ArchiveType.TGZ)) {
if (input.contains(")
anchor.append(input.substring(input.lastIndexOf(")
innerInput.append(input.substring(input.indexOf(":(") + 2, input.lastIndexOf(")
}
else if (input.contains("
anchor.append(input.substring(input.lastIndexOf('
innerInput.append(input.substring(input.indexOf(':') + 1, input.lastIndexOf('
}
else {
anchor = null;
innerInput.append(input.substring(input.indexOf(':') + 1));
}
}
else if (archiveType == ArchiveType.GZIP) {
innerInput.append(input.substring(input.indexOf(':') + 1));
}
// if doesn't exist inner input, inner input is input
if (innerInput.length() == 0) innerInput.append(input);
// remove parentheses - fixes incorrect URL resolution
if (innerInput.length() >= 2 && innerInput.charAt(0) == '(' && innerInput.charAt(innerInput.length()-1) == ')') {
innerInput.deleteCharAt(innerInput.length()-1);
innerInput.deleteCharAt(0);
}
return archiveType;
}
/**
* Creates a zip input stream.
* @param innerStream
* @param anchor
* @param resolvedAnchors - output parameter
* @return
* @throws IOException
*
* @deprecated
* This method does not really work,
* it is not possible to open multiple ZipInputStreams
* from one parent input stream without extensive buffering.
*
* Use {@link #getMatchingZipEntries(InputStream, String)} to resolve wildcards
* or {@link #getZipInputStream(InputStream, String)} to open a TarInputStream.
*/
@Deprecated
public static List<InputStream> getZipInputStreams(InputStream innerStream, String anchor, List<String> resolvedAnchors) throws IOException {
anchor = URLDecoder.decode(anchor, UTF8); // CL-2579
return getZipInputStreamsInner(innerStream, anchor, 0, resolvedAnchors, true);
}
/**
* Creates a list of names of matching entries.
* @param parentStream
* @param pattern
*
* @return resolved anchors
* @throws IOException
*/
public static List<String> getMatchingZipEntries(InputStream parentStream, String pattern) throws IOException {
if (pattern == null) {
pattern = "";
}
pattern = URLDecoder.decode(pattern, UTF8); // CL-2579
List<String> resolvedAnchors = new ArrayList<String>();
Matcher matcher;
Pattern WILDCARD_PATTERN = null;
boolean containsWildcard = pattern.contains("?") || pattern.contains("*");
if (containsWildcard) {
WILDCARD_PATTERN = Pattern.compile(pattern.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
}
//resolve url format for zip files
ZipInputStream zis = new ZipInputStream(parentStream) ;
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// wild cards
if (containsWildcard) {
matcher = WILDCARD_PATTERN.matcher(entry.getName());
if (matcher.matches()) {
resolvedAnchors.add(entry.getName());
}
// without wild cards
} else if (pattern.isEmpty() || entry.getName().equals(pattern)) { //url is given without anchor; first entry in zip file is used
resolvedAnchors.add(pattern);
}
}
// if no wild carded entry found, it is ok
if (!pattern.isEmpty() && !containsWildcard && resolvedAnchors.isEmpty()) {
throw new IOException("Wrong anchor (" + pattern + ") to zip file.");
}
return resolvedAnchors;
}
/**
* Creates a list of names of matching entries.
* @param parentStream
* @param pattern
*
* @return resolved anchors
* @throws IOException
*/
public static List<String> getMatchingTarEntries(InputStream parentStream, String pattern) throws IOException {
if (pattern == null) {
pattern = "";
}
pattern = URLDecoder.decode(pattern, UTF8); // CL-2579
List<String> resolvedAnchors = new ArrayList<String>();
Matcher matcher;
Pattern WILDCARD_PATTERN = null;
boolean containsWildcard = pattern.contains("?") || pattern.contains("*");
if (containsWildcard) {
WILDCARD_PATTERN = Pattern.compile(pattern.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
}
//resolve url format for zip files
TarInputStream tis = new TarInputStream(parentStream) ;
TarEntry entry;
while ((entry = tis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// wild cards
if (containsWildcard) {
matcher = WILDCARD_PATTERN.matcher(entry.getName());
if (matcher.matches()) {
resolvedAnchors.add(entry.getName());
}
// without wild cards
} else if (pattern.isEmpty() || entry.getName().equals(pattern)) { //url is given without anchor; first entry in zip file is used
resolvedAnchors.add(pattern);
}
}
// if no wild carded entry found, it is ok
if (!pattern.isEmpty() && !containsWildcard && resolvedAnchors.isEmpty()) {
throw new IOException("Wrong anchor (" + pattern + ") to zip file.");
}
return resolvedAnchors;
}
/**
* Wraps the parent stream into ZipInputStream
* and positions it to read the given entry (no wildcards are applicable).
*
* If no entry is given, the stream is positioned to read the first file entry.
*
* @param parentStream
* @param entryName
* @return
* @throws IOException
*/
public static ZipInputStream getZipInputStream(InputStream parentStream, String entryName) throws IOException {
ZipInputStream zis = new ZipInputStream(parentStream) ;
ZipEntry entry;
// find a matching entry
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// when url is given without anchor; first entry in zip file is used
if (StringUtils.isEmpty(entryName) || entry.getName().equals(entryName)) {
return zis;
}
}
//no entry found report
throw new IOException("Wrong anchor (" + entryName + ") to zip file.");
}
/**
* Wraps the parent stream into TarInputStream
* and positions it to read the given entry (no wildcards are applicable).
*
* If no entry is given, the stream is positioned to read the first file entry.
*
* @param parentStream
* @param entryName
* @return
* @throws IOException
*/
public static TarInputStream getTarInputStream(InputStream parentStream, String entryName) throws IOException {
TarInputStream tis = new TarInputStream(parentStream) ;
TarEntry entry;
// find a matching entry
while ((entry = tis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// when url is given without anchor; first entry in tar file is used
if (StringUtils.isEmpty(entryName) || entry.getName().equals(entryName)) {
return tis;
}
}
//no entry found report
throw new IOException("Wrong anchor (" + entryName + ") to tar file.");
}
/**
* Creates list of zip input streams (only if <code>needInputStream</code> is true).
* Also stores their names in <code>resolvedAnchors</code>.
*
* @param innerStream
* @param anchor
* @param matchFilesFrom
* @param resolvedAnchors
* @param needInputStream if <code>true</code>, input streams for individual entries will be created (costly operation)
*
* @return
* @throws IOException
*/
private static List<InputStream> getZipInputStreamsInner(InputStream innerStream, String anchor,
int matchFilesFrom, List<String> resolvedAnchors, boolean needInputStream) throws IOException {
// result list of input streams
List<InputStream> streams = new ArrayList<InputStream>();
// check and prepare support for wild card matching
Matcher matcher;
Pattern WILDCARD_PATTERS = null;
boolean bWildcardedAnchor = anchor.contains("?") || anchor.contains("*");
if (bWildcardedAnchor)
WILDCARD_PATTERS = Pattern.compile(anchor.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
// the input stream must support a buffer for wild cards.
if (bWildcardedAnchor && needInputStream) {
if (!innerStream.markSupported()) {
innerStream = new BufferedInputStream(innerStream);
}
innerStream.mark(Integer.MAX_VALUE);
}
//resolve url format for zip files
ZipInputStream zin = new ZipInputStream(innerStream) ;
ZipEntry entry;
// find entries
int iMatched = 0;
while((entry = zin.getNextEntry()) != null) { // zin is changing -> recursion !!!
// wild cards
if (bWildcardedAnchor) {
matcher = WILDCARD_PATTERS.matcher(entry.getName());
if (matcher.find()) { // TODO replace find() with matches()
if (needInputStream && iMatched++ == matchFilesFrom) { // CL-2576 - only create streams when necessary, not when just resolving wildcards
streams.add(zin);
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
innerStream.reset();
streams.addAll(getZipInputStreamsInner(innerStream, anchor, ++matchFilesFrom, resolvedAnchors, needInputStream));
innerStream.reset();
return streams;
} else { // if we don't need input streams for individual entries, there is no need for recursion
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
}
}
// without wild cards
} else if (StringUtils.isEmpty(anchor) || entry.getName().equals(anchor)) { //url is given without anchor; first entry in zip file is used
while ((entry != null) && entry.isDirectory()) { // CLS-537: skip directories, we want to read the first file
entry = zin.getNextEntry();
}
if (entry != null) {
streams.add(zin);
if (resolvedAnchors != null) resolvedAnchors.add(anchor);
return streams;
}
}
//finish up with entry
zin.closeEntry();
}
if (matchFilesFrom > 0 || streams.size() > 0) {
return streams;
}
// if no wild carded entry found, it is ok, return null
if (bWildcardedAnchor || !needInputStream) {
return null;
}
//close the archive
zin.close();
//no channel found report
throw new IOException("Wrong anchor (" + anchor + ") to zip file.");
}
/**
* Creates a tar input stream.
* @param innerStream
* @param anchor
* @param resolvedAnchors - output parameter
* @return
* @throws IOException
*
* @deprecated
* This method does not really work,
* it is not possible to open multiple TarInputStreams
* from one parent input stream without extensive buffering.
*
* Use {@link #getMatchingTarEntries(InputStream, String)} to resolve wildcards
* or {@link #getTarInputStream(InputStream, String)} to open a TarInputStream.
*/
@Deprecated
public static List<InputStream> getTarInputStreams(InputStream innerStream, String anchor, List<String> resolvedAnchors) throws IOException {
return getTarInputStreamsInner(innerStream, anchor, 0, resolvedAnchors);
}
/**
* Creates list of tar input streams.
* @param innerStream
* @param anchor
* @param matchFilesFrom
* @param resolvedAnchors
* @return
* @throws IOException
*/
private static List<InputStream> getTarInputStreamsInner(InputStream innerStream, String anchor,
int matchFilesFrom, List<String> resolvedAnchors) throws IOException {
// result list of input streams
List<InputStream> streams = new ArrayList<InputStream>();
// check and prepare support for wild card matching
Matcher matcher;
Pattern WILDCARD_PATTERS = null;
boolean bWildsCardedAnchor = anchor.contains("?") || anchor.contains("*");
if (bWildsCardedAnchor)
WILDCARD_PATTERS = Pattern.compile(anchor.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
// the input stream must support a buffer for wild cards.
if (bWildsCardedAnchor) {
if (!innerStream.markSupported()) {
innerStream = new BufferedInputStream(innerStream);
}
innerStream.mark(Integer.MAX_VALUE);
}
//resolve url format for zip files
TarInputStream tin = new TarInputStream(innerStream);
TarEntry entry;
// find entries
int iMatched = 0;
while((entry = tin.getNextEntry()) != null) { // tin is changing -> recursion !!!
// wild cards
if (bWildsCardedAnchor) {
matcher = WILDCARD_PATTERS.matcher(entry.getName());
if (matcher.find() && iMatched++ == matchFilesFrom) {
streams.add(tin);
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
innerStream.reset();
streams.addAll(getTarInputStreamsInner(innerStream, anchor, ++matchFilesFrom, resolvedAnchors));
innerStream.reset();
return streams;
}
// without wild cards
} else if(anchor == null || anchor.equals("") || entry.getName().equals(anchor)) { //url is given without anchor; first entry in zip file is used
streams.add(tin);
if (resolvedAnchors != null) resolvedAnchors.add(anchor);
return streams;
}
}
if (matchFilesFrom > 0 || streams.size() > 0) return streams;
// if no wild carded entry found, it is ok, return null
if (bWildsCardedAnchor) return null;
//close the archive
tin.close();
throw new IOException("Wrong anchor (" + anchor + ") to tar file.");
}
/**
* Creates authorized url connection.
* @param url
* @return
* @throws IOException
*/
public static URLConnection getAuthorizedConnection(URL url) throws IOException {
return URLConnectionRequest.getAuthorizedConnection(
url.openConnection(),
url.getUserInfo(),
URLConnectionRequest.URL_CONNECTION_AUTHORIZATION);
}
/**
* Creates an authorized stream.
* @param url
* @param proxy
* @param proxyUserInfo username and password to access the proxy
*
* @return
* @throws IOException
*/
public static URLConnection getAuthorizedConnection(URL url, Proxy proxy, String proxyUserInfo) throws IOException {
URLConnection connection = url.openConnection(proxy);
if (connection instanceof ProxyAuthenticable) {
((ProxyAuthenticable) connection).setProxyCredentials(new UserInfo(proxyUserInfo));
}
connection = URLConnectionRequest.getAuthorizedConnection( // set authentication
connection,
url.getUserInfo(),
URLConnectionRequest.URL_CONNECTION_AUTHORIZATION);
// FIXME does not work for HTTPS via proxy
connection = URLConnectionRequest.getAuthorizedConnection( // set proxy authentication
connection,
proxyUserInfo,
URLConnectionRequest.URL_CONNECTION_PROXY_AUTHORIZATION);
return connection;
}
/**
* Creates an authorized stream.
* @param url
* @return
* @throws IOException
*
* @deprecated Use {@link #getAuthorizedConnection(URL, Proxy, String)} instead
*/
@Deprecated
public static URLConnection getAuthorizedConnection(URL url, Proxy proxy) throws IOException {
// user info is obtained from the URL, most likely different from proxy user info
return getAuthorizedConnection(url, proxy, url.getUserInfo());
}
/**
* Returns a pair whose first element is the original URL
* with the proxy specification removed
* and whose second element is the proxy specification string (or <code>null</code>).
*
* @param url with an optional proxy specification
* @return [url, proxyString]
*/
public static Pair<String, String> extractProxyString(String url) {
String proxyString = null;
Matcher matcher = FileURLParser.getURLMatcher(url);
if (matcher != null && (proxyString = matcher.group(5)) != null) {
url = matcher.group(2) + matcher.group(3) + matcher.group(7);
}
return new Pair<String, String>(url, proxyString);
}
/**
* Creates an proxy from the file url string.
* @param fileURL
* @return
*/
public static Proxy getProxy(String fileURL) {
// create an url
URL url;
try {
url = getFileURL(fileURL);
} catch (MalformedURLException e) {
return null;
}
// get proxy type
ProxyProtocolEnum proxyProtocolEnum;
if ((proxyProtocolEnum = ProxyProtocolEnum.fromString(url.getProtocol())) == null) {
return null;
}
// no proxy
if (proxyProtocolEnum == ProxyProtocolEnum.NO_PROXY) {
return Proxy.NO_PROXY;
}
// create a proxy
SocketAddress addr = new InetSocketAddress(url.getHost(), url.getPort() < 0 ? 8080 : url.getPort());
Proxy proxy = new Proxy(Proxy.Type.valueOf(proxyProtocolEnum.getProxyString()), addr);
return proxy;
}
public static WritableByteChannel getWritableChannel(URL contextURL, String input, boolean appendData, int compressLevel) throws IOException {
return Channels.newChannel(getOutputStream(contextURL, input, appendData, compressLevel));
}
public static WritableByteChannel getWritableChannel(URL contextURL, String input, boolean appendData) throws IOException {
return getWritableChannel(contextURL, input, appendData, -1);
}
public static boolean isArchive(String input) {
return input.startsWith("zip:") || input.startsWith("tar:") || input.startsWith("gzip:") || input.startsWith("tgz:");
}
private static boolean isZipArchive(String input) {
return input.startsWith("zip:");
}
public static boolean isRemoteFile(String input) {
return input.startsWith("http:")
|| input.startsWith("https:")
|| input.startsWith("ftp:") || input.startsWith("sftp:") || input.startsWith("scp:");
}
private static boolean isConsole(String input) {
return input.equals(STD_CONSOLE);
}
private static boolean isSandbox(String input) {
return SandboxUrlUtils.isSandboxUrl(input);
}
private static boolean isDictionary(String input) {
return input.startsWith(DICTIONARY_PROTOCOL);
}
private static boolean isPort(String input) {
return input.startsWith(PORT_PROTOCOL);
}
public static boolean isLocalFile(URL contextUrl, String input) {
if (input.startsWith("file:")) {
return true;
} else if (isRemoteFile(input) || isConsole(input) || isSandbox(input) || isArchive(input) || isDictionary(input) || isPort(input)) {
return false;
} else {
for (CustomPathResolver resolver: customPathResolvers) {
if (resolver.handlesURL(contextUrl, input)) {
return false;
}
}
try {
URL url = getFileURL(contextUrl, input);
return !isSandbox(url.toString());
} catch (MalformedURLException e) {}
}
return false;
}
private static boolean isHttp(String input) {
return input.startsWith("http:") || input.startsWith("https:");
}
private static boolean hasCustomPathResolver(URL contextURL, String input) {
for (CustomPathResolver customPathResolver : customPathResolvers) {
if (customPathResolver.handlesURL(contextURL, input)) {
return true;
}
}
return false;
}
public static List<CustomPathResolver> getCustompathresolvers() {
return customPathResolvers;
}
@java.lang.SuppressWarnings("unchecked")
private static String getFirstFileInZipArchive(URL context, String filePath) throws NullPointerException, FileNotFoundException, ZipException, IOException {
File file = getJavaFile(context, filePath); // CLS-537
de.schlichtherle.util.zip.ZipFile zipFile = null;
try {
zipFile = new de.schlichtherle.util.zip.ZipFile(file);
Enumeration<de.schlichtherle.util.zip.ZipEntry> zipEnmr;
de.schlichtherle.util.zip.ZipEntry entry;
for (zipEnmr = zipFile.entries(); zipEnmr.hasMoreElements() ;) {
entry = zipEnmr.nextElement();
if (!entry.isDirectory()) {
return entry.getName();
}
}
} finally {
if (zipFile != null) {
zipFile.close();
}
}
return null;
}
/**
* Descends through the URL to figure out whether this is a local archive.
*
* If the whole URL represents a local archive, standard FS path (archive.zip/dir1/another_archive.zip/dir2/file)
* will be returned inside of the path string builder, and true will be returned.
*
* @param input URL to inspect
* @param path output buffer for full file-system path
* @return true if the URL represents a file inside a local archive
* @throws IOException
*/
private static boolean getLocalArchivePath(URL contextURL, String input, boolean appendData, int compressLevel,
StringBuilder path, int nestLevel, boolean output) throws IOException {
if (hasCustomPathResolver(contextURL, input)) {
return false;
}
if (isZipArchive(input)) {
Matcher matcher = getInnerInput(input);
// URL-centered convention, zip:(inner.zip)/outer.txt
// this might be misleading, as what you will see on the filesystem first is inner.zip
// and inside of that there will be a file named outer.txt
String innerSource; // inner part of the URL (outer file on the FS)
String outer; // outer part of the URL (inner file file on the FS)
boolean ret;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
outer = matcher.group(10);
}
else {
return false;
}
ret = getLocalArchivePath(contextURL, innerSource, appendData, compressLevel, path, nestLevel + 1, output);
if (ret) {
if (outer == null && isZipArchive(input)) {
outer = output ? DEFAULT_ZIP_FILE : getFirstFileInZipArchive(contextURL, path.toString());
if (outer == null) {
throw new IOException("The archive does not contain any files");
}
}
if (path.length() != 0) {
path.append(File.separator);
}
path.append(outer);
}
return ret;
}
else if (isLocalFile(contextURL, input) && nestLevel > 0) {
assert(path.length() == 0);
path.append(input);
return true;
}
else {
return false;
}
}
private static boolean getLocalArchiveOutputPath(URL contextURL, String input, boolean appendData,
int compressLevel, StringBuilder path) throws IOException {
return getLocalArchivePath(contextURL, input, appendData, compressLevel, path, 0, true);
}
static String getLocalArchiveInputPath(URL contextURL, String input)
throws IOException {
StringBuilder path = new StringBuilder();
return getLocalArchiveInputPath(contextURL, input, path) ? path.toString() : null;
}
/**
* Returns <code>true</code> if the URL represents a file inside a local archive.
*
* @param contextURL the context URL
* @param path the path to the file
* @return <code>true</code> if the URL represents a file inside a local archive
* @throws IOException
*/
public static boolean isLocalArchiveOutputPath(URL contextURL, String path)
throws IOException {
return getLocalArchiveOutputPath(contextURL, path, false, -1, new StringBuilder());
}
static de.schlichtherle.io.File getLocalZipArchive(URL contextURL, String localArchivePath) throws IOException {
// apply the contextURL
URL url = FileUtils.getFileURL(contextURL, localArchivePath);
String absolutePath = FileUtils.getUrlFile(url);
registerTrueZipVSFEntry(new de.schlichtherle.io.File(localArchivePath));
return new de.schlichtherle.io.File(absolutePath);
}
private static boolean getLocalArchiveInputPath(URL contextURL, String input, StringBuilder path)
throws IOException {
return getLocalArchivePath(contextURL, input, false, 0, path, 0, false);
}
private static void registerTrueZipVSFEntry(de.schlichtherle.io.File entry) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph != null) {
graph.getVfsEntries().addVFSEntry(entry);
}
}
public static OutputStream getOutputStream(URL contextURL, String input, boolean appendData, int compressLevel) throws IOException {
OutputStream os = null;
StringBuilder localArchivePath = new StringBuilder();
if (getLocalArchiveOutputPath(contextURL, input, appendData, compressLevel, localArchivePath)) {
String archPath = localArchivePath.toString();
// apply the contextURL
URL url = FileUtils.getFileURL(contextURL, archPath);
String absolutePath = getUrlFile(url);
de.schlichtherle.io.File archive = new de.schlichtherle.io.File(absolutePath);
boolean mkdirsResult = archive.getParentFile().mkdirs();
log.debug("Opening local archive entry " + archive.getAbsolutePath()
+ " (mkdirs: " + mkdirsResult
+ ", exists:" + archive.exists() + ")");
registerTrueZipVSFEntry(archive);
return new de.schlichtherle.io.FileOutputStream(absolutePath, appendData);
}
//first we try the custom path resolvers
for (CustomPathResolver customPathResolver : customPathResolvers) {
os = customPathResolver.getOutputStream(contextURL, input, appendData, compressLevel);
if (os != null) {
log.debug("Output stream '" + input + "[" + contextURL + "] was opened by custom path resolver.");
return os; //we found the desired output stream using external resolver method
}
}
// std input (console)
if (isConsole(input)) {
return Channels.newOutputStream(new SystemOutByteChannel());
}
// get inner source
Matcher matcher = getInnerInput(input);
String innerSource = null;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
// get and set proxy and go to inner source
Proxy proxy = getProxy(innerSource);
String proxyUserInfo = null;
if (proxy != null) {
try {
proxyUserInfo = new URI(innerSource).getUserInfo();
} catch (URISyntaxException ex) {
}
}
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
if (proxy == null) {
os = getOutputStream(contextURL, innerSource, appendData, compressLevel);
} else {
// this could work even for WebDAV via an authorized proxy,
// but getInnerInput() above would have to be replaced with FileURLParser.getURLMatcher().
// In addition, WebdavOutputStream creates parent directories (which is wrong, but we don't have anything better yet).
URLConnection connection = getAuthorizedConnection(getFileURL(contextURL, input), proxy, proxyUserInfo);
connection.setDoOutput(true);
os = connection.getOutputStream();
}
}
// get archive type
StringBuilder sbAnchor = new StringBuilder();
StringBuilder sbInnerInput = new StringBuilder();
ArchiveType archiveType = getArchiveType(input, sbInnerInput, sbAnchor);
input = sbInnerInput.toString();
//open channel
if (os == null) {
// create output stream
if (isRemoteFile(input) && !isHttp(input)) {
// ftp output stream
URL url = FileUtils.getFileURL(contextURL, input);
Pair<String, String> parts = FileUtils.extractProxyString(url.toString());
try {
url = FileUtils.getFileURL(contextURL, parts.getFirst());
} catch (MalformedURLException ex) {
}
String proxyString = parts.getSecond();
Proxy proxy = null;
UserInfo proxyCredentials = null;
if (proxyString != null) {
proxy = FileUtils.getProxy(proxyString);
try {
String userInfo = new URI(proxyString).getUserInfo();
if (userInfo != null) {
proxyCredentials = new UserInfo(userInfo);
}
} catch (URISyntaxException use) {
}
}
URLConnection urlConnection = ((proxy != null) ? url.openConnection(proxy) : url.openConnection());
if (urlConnection instanceof ProxyAuthenticable) {
((ProxyAuthenticable) urlConnection).setProxyCredentials(proxyCredentials);
}
if (urlConnection instanceof SFTPConnection) {
((SFTPConnection)urlConnection).setMode(appendData? ChannelSftp.APPEND : ChannelSftp.OVERWRITE);
}
try {
os = urlConnection.getOutputStream();
} catch (IOException e) {
log.debug("IOException occured for URL - host: '" + url.getHost() + "', path: '" + url.getPath() + "' (user info not shown)",
"IOException occured for URL - host: '" + url.getHost() + "', userinfo: '" + url.getUserInfo() + "', path: '" + url.getPath() + "'");
throw e;
}
} else if (S3InputStream.isS3File(input)) {
// must be done before isHttp() check
return new S3OutputStream(new URL(input));
} else if (isHttp(input)) {
return new WebdavOutputStream(input);
} else if (isSandbox(input)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
URL url = FileUtils.getFileURL(contextURL, input);
return graph.getAuthorityProxy().getSandboxResourceOutput(ContextProvider.getComponentId(), url.getHost(), SandboxUrlUtils.getRelativeUrl(url.toString()), appendData);
} else {
// file path or relative URL
URL url = FileUtils.getFileURL(contextURL, input);
if (isSandbox(url.toString())) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
return graph.getAuthorityProxy().getSandboxResourceOutput(ContextProvider.getComponentId(), url.getHost(), getUrlFile(url), appendData);
}
// file input stream
String filePath = url.getRef() != null ? getUrlFile(url) + "#" + url.getRef() : getUrlFile(url);
os = new FileOutputStream(filePath, appendData);
}
}
// create writable channel
// zip channel
if(archiveType == ArchiveType.ZIP) {
// resolve url format for zip files
if (appendData) {
throw new IOException("Appending to remote archives is not supported");
}
de.schlichtherle.util.zip.ZipOutputStream zout = new de.schlichtherle.util.zip.ZipOutputStream(os);
if (compressLevel != -1) {
zout.setLevel(compressLevel);
}
String anchor = sbAnchor.toString();
de.schlichtherle.util.zip.ZipEntry entry =
new de.schlichtherle.util.zip.ZipEntry(anchor.equals("") ? DEFAULT_ZIP_FILE : anchor);
zout.putNextEntry(entry);
return zout;
}
// gzip channel
else if (archiveType == ArchiveType.GZIP) {
if (appendData) {
throw new IOException("Appending to remote archives is not supported");
}
GZIPOutputStream gzos = new GZIPOutputStream(os, Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE);
return gzos;
}
// other channel
return os;
}
/**
* This method checks whether it is possible to write to given file.
*
* @param contextURL
* @param fileURL
* @param mkDirs - tries to make directories if it is necessary
* @return true if can write, false otherwise
* @throws ComponentNotReadyException
*/
@SuppressWarnings(value = "RV_ABSOLUTE_VALUE_OF_HASHCODE")
public static boolean canWrite(URL contextURL, String fileURL, boolean mkDirs) throws ComponentNotReadyException {
// get inner source
Matcher matcher = getInnerInput(fileURL);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
return canWrite(contextURL, innerSource, mkDirs);
}
String fileName;
if (fileURL.startsWith("zip:") || fileURL.startsWith("tar:") || fileURL.startsWith("tgz:")){
int pos;
fileName = fileURL.substring(fileURL.indexOf(':') + 1,
(pos = fileURL.indexOf('#')) == -1 ? fileURL.length() : pos);
}else if (fileURL.startsWith("gzip:")){
fileName = fileURL.substring(fileURL.indexOf(':') + 1);
}else{
fileName = fileURL;
}
MultiOutFile multiOut = new MultiOutFile(fileName);
File file;
URL url;
boolean tmp = false;
//create file on given URL
try {
String filename = multiOut.next();
if(filename.startsWith("port:")) return true;
if(filename.startsWith("dict:")) return true;
url = getFileURL(contextURL, filename);
if(!url.getProtocol().equalsIgnoreCase("file")) return true;
// if the url is a path, make a fake file
String sUrl = getUrlFile(url);
boolean isFile = !sUrl.endsWith("/") && !sUrl.endsWith("\\");
if (!isFile) {
if (fileURL.indexOf("
sUrl = sUrl + "tmpfile" + Math.abs(sUrl.hashCode());
} else {
sUrl = sUrl + "tmpfile" + UUID.randomUUID();
}
}
file = new File(sUrl);
} catch (Exception e) {
throw new ComponentNotReadyException(e + ": " + fileURL, e);
}
//check if can write to this file
tmp = file.exists() ? file.canWrite() : createFile(file, mkDirs);
if (!tmp) {
throw new ComponentNotReadyException("Can't write to: " + fileURL);
}
return true;
}
/**
* Creates the parent dirs of the target file,
* if necessary. It is assumed that the target
* is a regular file, not a directory.
*
* The parent directories may not have been created,
* even if the method does not throw any exception.
*
* @param contextURL
* @param fileURL
* @throws ComponentNotReadyException
*/
public static void createParentDirs(URL contextURL, String fileURL) throws ComponentNotReadyException {
try {
URL innerMostURL = FileUtils.getFileURL(contextURL, FileURLParser.getMostInnerAddress(fileURL));
String innerMostURLString = innerMostURL.toString();
boolean isFile = !innerMostURLString.endsWith("/") && !innerMostURLString.endsWith("\\");
if (FileUtils.isLocalFile(contextURL, innerMostURLString)) {
File file = FileUtils.getJavaFile(contextURL, innerMostURLString);
String sFile = isFile ? file.getParent() : file.getPath();
FileUtils.makeDirs(contextURL, sFile);
} else if (SandboxUrlUtils.isSandboxUrl(innerMostURLString)) {
String parentDirUrl = FileURLParser.getParentDirectory(innerMostURLString);
FileUtils.makeDirs(null, parentDirUrl);
} else {
Operation operation = Operation.create(innerMostURL.getProtocol());
FileManager manager = FileManager.getInstance();
String sFile = isFile ? URIUtils.getParentURI(URI.create(innerMostURLString)).toString() : innerMostURLString;
if (manager.canPerform(operation)) {
manager.create(CloverURI.createURI(sFile), new CreateParameters().setDirectory(true).setMakeParents(true));
// ignore the result
}
}
} catch (Exception e) { // FIXME parent dir creation fails for proxies
log.debug(e);
}
}
/**
* Creates directory for fileURL if it is necessary.
* @param contextURL
* @param fileURL
* @return created parent directory
* @throws ComponentNotReadyException
*/
public static File makeDirs(URL contextURL, String fileURL) throws ComponentNotReadyException {
if (contextURL == null && fileURL == null) return null;
URL url;
try {
url = FileUtils.getFileURL(contextURL, FileURLParser.getMostInnerAddress(fileURL));
} catch (MalformedURLException e) {
return null;
}
if (SandboxUrlUtils.isSandboxUrl(url)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
try {
graph.getAuthorityProxy().makeDirectories(url.getHost(), url.getPath());
} catch (IOException exception) {
throw new ComponentNotReadyException("Making of sandbox directories failed!", exception);
}
return null;
}
if (!url.getProtocol().equals(FILE_PROTOCOL)) return null;
//find the first non-existing directory
File file = new File(url.getPath());
File fileTmp = file;
File createDir = null;
while (fileTmp != null && !fileTmp.exists()) {
createDir = fileTmp;
fileTmp = fileTmp.getParentFile();
}
if (createDir != null && !file.mkdirs()) {
if (!file.exists()) {
// dir still doesn't exist - throw ex.
throw new ComponentNotReadyException("Cannot create directory: " + file);
}
}
return createDir;
}
/**
* Gets file path from URL, properly handles special URL characters (like %20)
* @param url
* @return
* @throws UnsupportedEncodingException
*
* @see #handleSpecialCharacters(java.net.URL)
*/
private static String getUrlFile(URL url) {
try {
final String fixedFileUrl = handleSpecialCharacters(url);
return URLDecoder.decode(fixedFileUrl, UTF8);
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException("Encoding not supported!", ex);
}
}
/**
* Fix problems with special characters that occurs while running on Mac OS X enviroment and using path
* which contains '+' character, e.g. /var/folders/t6/t6VjEdukHKWHBtJyNy8wEU+++TI/-Tmp-/.
* Without special handling, method #getUrlFile will return /var/folders/t6/t6VjEdukHKWHBtJyNy8wEU TI/-Tmp-/,
* handling '+' characeter as ' ' (space).
*
* @param url
* @return
*/
private static String handleSpecialCharacters(URL url) {
return url.getFile().replace("+", PLUS_CHAR_ENCODED);
}
/**
* Tries to create file and directories.
* @param fileURL
* @return
* @throws ComponentNotReadyException
*/
private static boolean createFile(File file, boolean mkDirs) throws ComponentNotReadyException {
boolean tmp = false;
boolean fails = false;
try {
tmp = file.createNewFile();
} catch (IOException e) {
if (!mkDirs) throw new ComponentNotReadyException(e + ": " + file);
fails = true;
}
File createdDir = null;
if (fails) {
createdDir = file.getParentFile();
createdDir = makeDirs(null, createdDir.getAbsolutePath());
try {
tmp = file.createNewFile();
} catch (IOException e) {
if (createdDir != null) {
if (!deleteFile(createdDir)) {
log.error("error delete " + createdDir);
}
}
throw new ComponentNotReadyException(e + ": " + file);
}
}
if (tmp) {
if (!file.delete()) {
log.error("error delete " + file.getAbsolutePath());
}
}
if (createdDir != null) {
if (!deleteFile(createdDir)) {
log.error("error delete " + createdDir);
}
}
return tmp;
}
/**
* Deletes file.
* @param file
* @return true if the file is deleted
*/
private static boolean deleteFile(File file) {
if (!file.exists()) return true;
//list and delete all sub-directories
for (File child: file.listFiles()) {
if (!deleteFile(child)) {
return false;
}
}
return file.delete();
}
/**
* This method checks whether is is possible to write to given file
*
* @param contextURL
* @param fileURL
* @return true if can write, false otherwise
* @throws ComponentNotReadyException
*/
public static boolean canWrite(URL contextURL, String fileURL) throws ComponentNotReadyException {
return canWrite(contextURL, fileURL, false);
}
/**
* This method checks whether is is possible to write to given directory
*
* @param dest
* @return true if can write, false otherwise
*/
public static boolean canWrite(File dest){
if (dest.exists()) return dest.canWrite();
List<File> dirs = getDirs(dest);
boolean result = dest.mkdirs();
//clean up
for (File dir : dirs) {
if (dir.exists()) {
boolean deleted = dir.delete();
if( !deleted ){
log.error("error delete " + dir.getAbsolutePath());
}
}
}
return result;
}
/**
* @param file
* @return list of directories, which have to be created to create this directory (don't exist),
* empty list if requested directory exists
*/
private static List<File> getDirs(File file){
ArrayList<File> dirs = new ArrayList<File>();
File dir = file;
if (file.exists()) return dirs;
dirs.add(file);
while (!(dir = dir.getParentFile()).exists()) {
dirs.add(dir);
}
return dirs;
}
public static Matcher getInnerInput(String source) {
Matcher matcher = INNER_SOURCE.matcher(source);
return matcher.find() ? matcher : null;
}
/**
* Returns file name of input (URL).
*
* @param input - url file name
* @return file name
* @throws MalformedURLException
*
* @see java.net.URL#getFile()
*/
public static String getFile(URL contextURL, String input) throws MalformedURLException {
Matcher matcher = getInnerInput(input);
String innerSource2, innerSource3;
if (matcher != null && (innerSource2 = matcher.group(5)) != null) {
if (!(innerSource3 = matcher.group(7)).equals("")) {
return innerSource3.substring(1);
} else {
input = getFile(null, innerSource2);
}
}
URL url = getFileURL(contextURL, input);
if (SandboxUrlUtils.isSandboxUrl(url)) { // CLS-754
try {
CloverURI cloverUri = CloverURI.createURI(url.toURI());
File file = FileManager.getInstance().getFile(cloverUri);
if (file != null) {
return file.toString();
}
} catch (Exception e) {
MalformedURLException mue = new MalformedURLException("URL '" + url.toString() + "' cannot be converted to File.");
mue.initCause(e);
throw mue;
}
}
if (url.getRef() != null) return url.getRef();
else {
input = getUrlFile(url);
if (input.startsWith("zip:") || input.startsWith("tar:") || input.startsWith("tgz:")) {
input = input.contains("
input.substring(input.lastIndexOf('
input.substring(input.indexOf(':') + 1);
} else if (input.startsWith("gzip:")) {
input = input.substring(input.indexOf(':') + 1);
}
return normalizeFilePath(input);
}
}
/**
* Adds final slash to the directory path, if it is necessary.
* @param directoryPath
* @return
*/
public static String appendSlash(String directoryPath) {
if(directoryPath.length() == 0 || directoryPath.endsWith("/") || directoryPath.endsWith("\\")) {
return directoryPath;
} else {
return directoryPath + "/";
}
}
/**
* Deletes last directory delimiter.
* stolen from com.cloveretl.gui.utils.FileUtils
* @param path
* @return
*/
public static String removeTrailingSlash(String path) {
if (path != null && path.length() > 0 && path.charAt(path.length() - 1) == '/') {
return path.substring(0, path.length() - 1);
}
return path;
}
/**
* Parses address and returns true if the address contains a server.
*
* @param input
* @return
* @throws IOException
*/
public static boolean isServerURL(URL url) throws IOException {
return url != null && !url.getProtocol().equals(FILE_PROTOCOL);
}
public static boolean isArchiveURL(URL url) {
String protocol = null;
if (url != null) {
protocol = url.getProtocol();
}
return protocol.equals(TAR_PROTOCOL) || protocol.equals(GZIP_PROTOCOL) || protocol.equals(ZIP_PROTOCOL) || protocol.equals(TGZ_PROTOCOL);
}
/**
* Creates URL connection and connect the server.
*
* @param url
* @throws IOException
*/
public static void checkServer(URL url) throws IOException {
if (url == null) {
return;
}
URLConnection connection = url.openConnection();
connection.connect();
}
/**
* Gets the most inner url address.
* @param contextURL
*
* @param input
* @return
* @throws IOException
*/
public static URL getInnerAddress(URL contextURL, String input) throws IOException {
URL url = null;
// get inner source
Matcher matcher = getInnerInput(input);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
url = getInnerAddress(contextURL, innerSource);
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
}
// std input (console)
if (input.equals(STD_CONSOLE)) {
return null;
}
//resolve url format for zip files
if(input.startsWith("zip:") || input.startsWith("tar:") || input.startsWith("tgz:")) {
if(!input.contains("#")) { //url is given without anchor - later is returned channel from first zip entry
input = input.substring(input.indexOf(':') + 1);
} else {
input = input.substring(input.indexOf(':') + 1, input.lastIndexOf('
}
}
else if (input.startsWith("gzip:")) {
input = input.substring(input.indexOf(':') + 1);
}
return url == null ? FileUtils.getFileURL(contextURL, input) : url;
}
/**
* Adds new custom path resolver. Useful for third-party implementation of path resolving.
* @param customPathResolver
*/
public static void addCustomPathResolver(CustomPathResolver customPathResolver) {
customPathResolvers.add(customPathResolver);
}
public static File convertUrlToFile(URL url) throws MalformedURLException {
String protocol = url.getProtocol();
if (protocol.equals(FILE_PROTOCOL)) {
try {
return new File(url.toURI());
} catch(URISyntaxException e) {
StringBuilder path = new StringBuilder(url.getFile());
if (!StringUtils.isEmpty(url.getRef())) {
path.append('#').append(url.getRef());
}
return new File(path.toString());
} catch(IllegalArgumentException e2) {
StringBuilder path = new StringBuilder(url.getFile());
if (!StringUtils.isEmpty(url.getRef())) {
path.append('#').append(url.getRef());
}
return new File(path.toString());
}
} else if (protocol.equals(SandboxUrlUtils.SANDBOX_PROTOCOL)) {
try {
CloverURI cloverUri = CloverURI.createURI(url.toURI());
File file = FileManager.getInstance().getFile(cloverUri);
if (file != null) {
return file;
}
} catch (Exception e) {
MalformedURLException mue = new MalformedURLException("URL '" + url.toString() + "' cannot be converted to File.");
mue.initCause(e);
throw mue;
}
}
throw new MalformedURLException("URL '" + url.toString() + "' cannot be converted to File.");
}
/**
* Tries to convert the given string to {@link File}.
* @param contextUrl context URL which is used for relative path
* @param file string representing the file
* @return {@link File} representation
*/
public static File getJavaFile(URL contextUrl, String file) {
URL fileURL;
try {
fileURL = FileUtils.getFileURL(contextUrl, file);
} catch (MalformedURLException e) {
throw new JetelRuntimeException("Invalid file URL definition.", e);
}
try {
return FileUtils.convertUrlToFile(fileURL);
} catch (MalformedURLException e) {
throw new JetelRuntimeException("File URL does not have 'file' protocol.", e);
}
}
/**
* <p>This method affects only windows platform following way:
* <ul><li> backslashes are replaced by slashes
* <li>if first character is slash and device specification follows, the starting slash is removed
* </ul>
*
* <p>For example:
*
* <p><tt>c:\project\data.txt -> c:/project/data.txt<br>
* /c:/project/data.txt -> c:/project/data.txt
*
* <p>A path reached from method anUrl.getPath() (or anUrl.getFile()) should be cleaned by this method.
*
* @param path
* @return
*/
public static String normalizeFilePath(String path) {
if (path == null) {
return "";
} else {
if (PlatformUtils.isWindowsPlatform()) {
//convert backslash to forward slash
path = path.indexOf('\\') == -1 ? path : path.replace('\\', '/');
//if device is present
int i = path.indexOf(':');
if (i != -1) {
//remove leading slash from device part to handle output of URL.getFile()
path = path.charAt(0) == '/' ? path.substring(1, path.length()) : path;
}
}
return path;
}
}
/**
* Standardized way how to convert an URL to string.
* For URLs with 'file' protocol only simple path is returned (for example file:/c:/project/data.txt ->c:/project/data.txt)
* The URLs with other protocols are converted by URL.toString() method.
*
* @param url
* @return
*/
public static String convertUrlToString(URL url) {
if (url == null) {
return null;
}
String urlString = null;
if (url.getProtocol().equals(FILE_PROTOCOL)) {
urlString = normalizeFilePath(url.getPath());
} else {
urlString = url.toString();
}
try {
urlString = URLDecoder.decode(urlString, UTF8);
} catch (Exception e) {
log.error("Failed to decode URL " + urlString, e);
}
return urlString;
}
public static class ArchiveURLStreamHandler extends URLStreamHandler {
private URL context;
public ArchiveURLStreamHandler() {
}
private ArchiveURLStreamHandler(URL context) {
this.context = context;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new ArchiveURLConnection(context, u);
}
}
private static class ArchiveURLConnection extends URLConnection {
private URL context;
public ArchiveURLConnection(URL context, URL url) {
super(url);
this.context = context;
}
@Override
public void connect() throws IOException {
}
@Override
public InputStream getInputStream() throws IOException {
String urlString;
try {
// Try to decode %-encoded URL
// Fix of CLD-2872 if scheme is in a zip file and the URL contains spaces (or other URL-invalid chars)
URI uri = url.toURI();
if (uri.isOpaque()) {
// This is intended to handle archive (e.g. zip:...) URLs
// Example of expected URI format: zip:(sandbox://sanboxName/path%20with%20spaces.zip)#path%20inside%20zip.xsd
// Decode only fragmet part to get zip:(sandbox://sanboxName/path%20with%20spaces.zip)#path inside zip.xsd
urlString = decodeFragment(uri);
} else {
urlString = uri.toString();
}
} catch (URISyntaxException e) {
urlString = url.toString();
}
return FileUtils.getInputStream(context, urlString);
}
private static String decodeFragment(URI uri) {
StringBuilder sb = new StringBuilder();
if (uri.getScheme() != null) {
sb.append(uri.getScheme()).append(':');
}
sb.append(uri.getRawSchemeSpecificPart());
if (uri.getFragment() != null) {
sb.append('#').append(uri.getFragment());
}
return sb.toString();
}
}
/**
* Quietly closes the passed IO object.
* Does nothing if the argument is <code>null</code>.
* Ignores any exceptions thrown when closing the object.
*
* @param closeable an IO object to be closed
*/
public static void closeQuietly(Closeable closeable) {
try {
FileUtils.close(closeable);
} catch (IOException ex) {
// ignore
}
}
/**
* Closses the passed {@link Closeable}.
* Does nothing if the argument is <code>null</code>.
*
* For multiple objects use {@link #closeAll(Closeable...)}.
*
* @param closeable an IO object to be closed
* @throws IOException
*/
public static void close(Closeable closeable) throws IOException {
if (closeable != null) {
closeable.close();
}
}
/**
* Closes all objects passed as the argument.
* If any of them throws an exception, the first exception is thrown.
*
* @param closeables
* @throws IOException
*/
public static void closeAll(Iterable<? extends Closeable> closeables) throws IOException {
if (closeables != null) {
IOException firstException = null;
for (Closeable closeable: closeables) {
if (closeable != null) {
if ((closeable instanceof Channel) && !((Channel) closeable).isOpen()) {
continue; // channel is already closed
}
try {
closeable.close();
} catch (IOException ex) {
if (firstException == null) {
firstException = ex;
}
}
}
}
if (firstException != null) {
throw firstException;
}
}
}
/**
* Closes all objects passed as the argument.
* If any of them throws an exception, the first exception is thrown.
*
* @param closeables
* @throws IOException
*/
public static void closeAll(Closeable... closeables) throws IOException {
if (closeables != null) {
closeAll(Arrays.asList(closeables));
}
}
/**
* Efficiently copies file contents from source to target.
* Creates the target file, if it does not exist.
* The parent directories of the target file are not created.
*
* @param source source file
* @param target target file
* @return <code>true</code> if the whole content of the source file was copied.
*
* @throws IOException
*/
public static boolean copyFile(File source, File target) throws IOException {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(target);
inputChannel = inputStream.getChannel();
outputChannel = outputStream.getChannel();
StreamUtils.copy(inputChannel, outputChannel);
return true;
} finally {
closeAll(outputChannel, outputStream, inputChannel, inputStream);
}
}
/**
* Delete the supplied {@link File} - for directories,
* recursively delete any nested directories or files as well.
* @param root the root <code>File</code> to delete
* @return <code>true</code> if the <code>File</code> was deleted,
* otherwise <code>false</code>
*/
public static boolean deleteRecursively(File root) throws IOException {
if (Thread.currentThread().isInterrupted()) {
throw new IOException("Interrupted");
}
if (root != null) {
if (root.isDirectory()) {
File[] children = root.listFiles();
if (children != null) {
for (File child: children) {
deleteRecursively(child);
}
}
}
return root.delete();
}
return false;
}
/**
* Checks the given string whether represents multiple URL.
* This is only simple test, whether the given string contains
* one of these three characters <b>;*?</b>.
* @param fileURL
* @return true if and only if the given string represents multiple URL
*/
public static boolean isMultiURL(String fileURL) {
return fileURL != null && (fileURL.contains(";") || fileURL.contains("*") || fileURL.contains("?"));
}
public static class InputStreamProvider implements Runnable {
private String input;
private URL contextURL;
private InputStream is;
private IOException exception;
public InputStreamProvider(URL contextURL, String input) {
this.contextURL = contextURL;
this.input = input;
}
@Override
public void run() {
try {
is = FileUtils.getInputStream(contextURL, input);
} catch (IOException e) {
exception = e;
}
}
public InputStream getInputStream() throws IOException {
if (exception == null) {
return is;
}
throw exception;
}
}
}
/*
* End class FileUtils
*/ |
package railo.runtime.tag;
import java.io.IOException;
import org.apache.commons.lang.StringUtils;
import railo.runtime.exp.ExpressionException;
import railo.runtime.exp.PageException;
import railo.runtime.ext.tag.BodyTagTryCatchFinallyImpl;
import railo.runtime.functions.string.CJustify;
import railo.runtime.functions.string.LJustify;
import railo.runtime.functions.string.RJustify;
import railo.runtime.op.Caster;
/**
* Builds a table in a ColdFusion page. Use the cfcol tag to define table column and row
* characteristics. The cftable tag renders data either as preformatted text, or, with the HTMLTable
* attribute, as an HTML table. Use cftable to create tables if you don't want to write HTML table tag
* code, or if your data can be well presented as preformatted text.
*
*
*
**/
public final class Table extends BodyTagTryCatchFinallyImpl {
/**
* Field <code>ALIGN_LEFT</code>
*/
public static final short ALIGN_LEFT=0;
/**
* Field <code>ALIGN_CENTER</code>
*/
public static final short ALIGN_CENTER=1;
/**
* Field <code>ALIGN_RIGHT</code>
*/
public static final short ALIGN_RIGHT=2;
/** Name of the cfquery from which to draw data. */
private railo.runtime.type.Query query;
/** Maximum number of rows to display in the table. */
private int maxrows=Integer.MAX_VALUE;
/** Specifies the query row from which to start processing. */
private int startrow=1;
/** Adds a border to the table. Use only when you specify the HTMLTable attribute for the table. */
private boolean border;
/** Displays headers for each column, as specified in the cfcol tag. */
private boolean colheaders;
/** Number of spaces to insert between columns 'default is 2'. */
private int colspacing=2;
/** Renders the table as an HTML 3.0 table. */
private boolean htmltable;
/** Number of lines to use for the table header. The default is 2, which leaves one line between
** the headers and the first row of the table. */
private int headerlines=2;
StringBuffer header=new StringBuffer();
StringBuffer body=new StringBuffer();
private int initRow;
private int count=0;
private boolean startNewRow;
/**
* @see javax.servlet.jsp.tagext.Tag#release()
*/
public void release() {
super.release();
query=null;
maxrows=Integer.MAX_VALUE;
startrow=1;
border=false;
colheaders=false;
colspacing=2;
htmltable=false;
headerlines=2;
if(header.length()>0)header=new StringBuffer();
body=new StringBuffer();
count=0;
}
/** set the value query
* Name of the cfquery from which to draw data.
* @param query value to set
* @throws PageException
**/
public void setQuery(String query) throws PageException {
this.query = Caster.toQuery(pageContext.getVariable(query));
}
/** set the value maxrows
* Maximum number of rows to display in the table.
* @param maxrows value to set
**/
public void setMaxrows(double maxrows) {
this.maxrows=(int)maxrows;
}
/** set the value startrow
* Specifies the query row from which to start processing.
* @param startrow value to set
**/
public void setStartrow(double startrow) {
this.startrow=(int)startrow;
if(this.startrow<=0)this.startrow=1;
}
/** set the value border
* Adds a border to the table. Use only when you specify the HTMLTable attribute for the table.
* @param border value to set
**/
public void setBorder(boolean border) {
this.border=border;
}
/** set the value colheaders
* Displays headers for each column, as specified in the cfcol tag.
* @param colheaders value to set
**/
public void setColheaders(boolean colheaders) {
this.colheaders=colheaders;
}
/** set the value colspacing
* Number of spaces to insert between columns 'default is 2'.
* @param colspacing value to set
**/
public void setColspacing(double colspacing) {
this.colspacing=(int)colspacing;
}
/** set the value htmltable
* Renders the table as an HTML 3.0 table.
* @param htmltable value to set
**/
public void setHtmltable(boolean htmltable) {
this.htmltable=htmltable;
}
/** set the value headerlines
* Number of lines to use for the table header. The default is 2, which leaves one line between
* the headers and the first row of the table.
* @param headerlines value to set
**/
public void setHeaderlines(double headerlines) {
this.headerlines=(int)headerlines;
if(this.headerlines<2)this.headerlines=2;
}
/**
* @see javax.servlet.jsp.tagext.Tag#doStartTag()
*/
public int doStartTag() throws PageException {
startNewRow=true;
initRow=query.getRecordcount();
query.go(startrow);
pageContext.undefinedScope().addCollection(query);
return query.getRecordcount()>=startrow?EVAL_BODY_INCLUDE:SKIP_BODY;
}
/**
* @see javax.servlet.jsp.tagext.BodyTag#doInitBody()
*/
public void doInitBody() {
//if(htmltable) body.append("<tr>\n");
}
/**
* @see javax.servlet.jsp.tagext.BodyTag#doAfterBody()
*/
public int doAfterBody() throws PageException {
if(htmltable) body.append("</tr>\n");
else body.append('\n');
startNewRow=true;
//print.out(query.getCurrentrow()+"-"+query.getRecordcount());
return ++count<maxrows && query.next()?EVAL_BODY_AGAIN:SKIP_BODY;
}
/**
* @see javax.servlet.jsp.tagext.Tag#doEndTag()
*/
public int doEndTag() throws PageException {
try {
_doEndTag();
} catch (IOException e) {
throw Caster.toPageException(e);
}
return EVAL_PAGE;
}
private void _doEndTag() throws IOException {
if(htmltable) {
pageContext.write("<table colspacing=\""+colspacing+"\"");
if(border) {
pageContext.write(" border=\"1\"");
}
pageContext.write(">\n");
if(header.length()>0) {
pageContext.write("<tr>\n");
pageContext.write(header.toString());
pageContext.write("</tr>\n");
}
pageContext.write(body.toString());
pageContext.write("</table>");
}
else {
pageContext.write("<pre>");
if(header.length()>0) {
pageContext.write(header.toString());
pageContext.write(StringUtils.repeat("\n",headerlines-1));
}
pageContext.write(body.toString());
pageContext.write("</pre>");
}
}
/**
* @see javax.servlet.jsp.tagext.TryCatchFinally#doFinally()
*/
public void doFinally() {
try {
pageContext.undefinedScope().removeCollection();
if(query!=null)query.go(initRow);
}
catch (PageException e) { }
}
/**
* @param strHeader
* @param text
* @param align
* @param width
* @throws ExpressionException
*/
public void setCol(String strHeader, String text, short align, int width) throws ExpressionException {
// HTML
if(htmltable) {
if(colheaders && count==0 && strHeader.trim().length()>0) {
header.append("\t<th");
addAlign(header,align);
addWidth(header,width);
header.append(">");
header.append(strHeader);
header.append("</th>\n");
}
if(htmltable && startNewRow) {
body.append("<tr>\n");
startNewRow=false;
}
body.append("\t<td");
addAlign(body,align);
addWidth(body,width);
body.append(">");
body.append(text);
body.append("</td>\n");
}
// PRE
else {
if(width<0) width=20;
if(colheaders && count==0 && strHeader.trim().length()>0) {
addPre(header,align,strHeader,width);
}
addPre(body,align,text,width);
}
}
private void addAlign(StringBuffer data,short align) {
data.append(" align=\"");
data.append(toStringAlign(align));
data.append("\"");
}
private void addWidth(StringBuffer data,int width) {
if(width>=-1) {
data.append(" width=\"");
data.append(width);
data.append("%\"");
}
}
private void addPre(StringBuffer data,short align,String value, int length) throws ExpressionException {
if(align==ALIGN_RIGHT) data.append(RJustify.call(pageContext,value,length));
else if(align==ALIGN_CENTER) data.append(CJustify.call(pageContext,value,length));
else data.append(LJustify.call(pageContext,value,length));
}
private String toStringAlign(short align) {
if(align==ALIGN_RIGHT) return "right";
if(align==ALIGN_CENTER) return "center";
return "left";
}
} |
package chapter_6;
import java.util.ArrayList;
import java.util.List;
public class Parens {
public List<String> getParans(int n) {
List<String> result = new ArrayList<String>();
getParans(n, 0, 0, new StringBuffer(), result);
return result;
}
private void getParans(int n, int numOpeningParams, int numClosingParams, StringBuffer buffer, List<String> result) {
if (numOpeningParams == n && numClosingParams == n) {
result.add(buffer.toString());
} else {
if (numOpeningParams < n) {
buffer.append('(');
numOpeningParams++;
getParans(n, numOpeningParams, numClosingParams, buffer, result);
buffer.setLength(buffer.length() - 1);
numOpeningParams
}
if (numClosingParams < numOpeningParams) {
buffer.append(')');
numClosingParams++;
getParans(n, numOpeningParams, numClosingParams, buffer, result);
buffer.setLength(buffer.length() - 1);
numClosingParams
}
}
}
} |
package com.algo.design.man.chap4;
public class BreadthFirstSearchTest{
public static void main(String args[]) throws Exception{
//LinkedListSearchTest();
//LinkedListGetTest();
//AdjecencyListTest();
VerboseBFS();
//LinkedListQueueTest();
}
public static void LinkedListSearchTest(){
LinkedList list=new LinkedList();
for(int i=0;i<10;i++){
list.add(i);
}
boolean failure=false;
for(int i=0;i<10;i++){
Node n=list.search(i);
if(n==null || i!=n.destination){
failure=true;
}
}
if(failure){
System.out.println("LinkedList BaseCase Test Failure");
}else{
System.out.println("LinkedList BaseCase Test Success");
}
}
public static void LinkedListGetTest() throws Exception{
LinkedList list=new LinkedList();
for(int i=0;i<10;i++){
list.add(i);
}
boolean failure=false;
for(int i=0;i<list.size();i++){
Node n=list.get(i);
if(n==null || i!=n.destination){
failure=true;
}
}
if(failure){
System.out.println("LinkedList GetCase Test Failure");
}else{
System.out.println("LinkedList GetCase Test Success");
}
}
public static void AdjecencyListTest() throws Exception{
int noOfNodes=5;
int[][] data=new int[][]{
{1,2},{1,5},{1,3},{2,3},{2,5},{3,4},{4,5}
};
AdjecencyList adjecencyList=new AdjecencyList(noOfNodes);
for(int i=0;i<data.length;i++){
adjecencyList.addEdge(data[i][0],data[i][1]);
adjecencyList.addEdge(data[i][1],data[i][0]);
}
//adjecencyList.print();
boolean failure=false;
for(int i=0;i<data.length;i++){
int x=adjecencyList.search(data[i][0],data[i][1]);
// System.out.println(data[i][0]+" "+data[i][1]+" "+x);
if(x!=data[i][1]){
failure=true;
}
}
if(failure){
System.out.println("AdjecencyList base test failure");
}else{
System.out.println("AdjecencyList base test Success");
}
}
public static void VerboseBFS() throws Exception{
int noOfNodes=6;
int[][] data=new int[][]{
{1,2},{1,5},{1,3},{2,3},{2,5},{3,4},{3,6},{4,5},{4,6}
};
AdjecencyList adjecencyList=new AdjecencyList(noOfNodes);
for(int i=0;i<data.length;i++){
adjecencyList.addEdge(data[i][0],data[i][1]);
adjecencyList.addEdge(data[i][1],data[i][0]);
}
AdjecencyList.breadthFirstSearch(adjecencyList,1);
}
public static class AdjecencyList{
private LinkedList[] nodes;
private int size=0;
public AdjecencyList(int size){
this.size=size;
nodes=new LinkedList[size];
}
public int size(){
return size;
}
public void print() throws Exception{
LinkedList list=nodes[0];
int i=0;
while(i<nodes.length){
list=nodes[i];
System.out.println((i+1)+":");
Node n=list.start;
while(n!=null){
System.out.print("\t"+n.destination+"\n");
n=n.next;
}
i++;
}
}
public void addEdge(int source,int destination) throws Exception{
source
if(source>=size){
throw new Exception("ArrayIndexOutOfBound: "+source+" out of "+size);
}
if(nodes[source]==null){
LinkedList list=new LinkedList();
list.add(destination);
nodes[source]=list;
}else{
LinkedList list=nodes[source];
list.add(destination);
}
}
public int search(int node,int destination){
node
//System.out.println(node+","+nodes[node]+","+degree(node)+","+destination);
if(node>=size || nodes[node]==null){
return -1;
}
int x=nodes[node].search(destination).destination;
//System.out.println(x);
return x;
}
public int get(int node,int index) throws Exception{
node
if(node>=size || nodes[node]==null){
return -1;
}
LinkedList list=nodes[node];
return list.get(index).destination;
}
public int degree(int node){
node
if(node>=size || nodes[node]==null){
return -1;
}
return nodes[node].size();
}
public static void breadthFirstSearch(AdjecencyList list,int startNode) throws Exception{
System.out.println("Starting Breadth First Search");
boolean discovered[]=new boolean[list.size()];
boolean processed[]=new boolean[list.size()];
discovered[startNode-1]=true;
int parent[]=new int[list.size()];
LinkedList toBeProcessed=new LinkedList();
int node=startNode;
int i=0;
while(i<list.size()){
int degree=list.degree(node);
System.out.println("Started Processing "+node);
int j=0;
while(j<degree){
int dest=list.get(node,j);
System.out.println("Looking at "+dest);
if(!discovered[dest-1]){
System.out.println("Discovered "+dest);
toBeProcessed.enqueue(dest);
parent[dest-1]=node;
discovered[dest-1]=true;
}
j++;
}
processed[node-1]=true;
node=toBeProcessed.dequeue();
i++;
}
for(i=0;i<parent.length;i++){
System.out.println((i+1)+" is the child of "+(parent[i]));
}
}
}
public static void LinkedListQueueTest(){
LinkedList queue=new LinkedList();
for(int i=0;i<5;i++){
queue.enqueue(i);
}
for(int i=4;i>=0;i
int a=queue.dequeue();
if(a!=i){
System.out.println("test failure"+i+""+a);
}else{
System.out.println("test success:"+i+""+a);
}
}
}
public static class LinkedList{
private Node start;
private Node end;
private int size;
public LinkedList(){
this.size=0;
}
public Node getStart(){
return start;
}
public void add(int d){
Node n=new Node();
n.destination=d;
if(start==null){
start=n;
end=n;
}else{
end.next=n;
end=n;
}
size++;
}
public Node search(int destination){
Node temp=start;
while(temp!=null && temp.destination!=destination){
temp=temp.next;
}
return temp;
}
public Node get(int index) throws Exception{
if(index>=size){
throw new Exception("IndexOutOfBound");
}
Node node=start;
int i=0;
while(i!=index){
node=node.next;
i++;
}
return node;
}
public void print() throws Exception{
int i=size-1;
Node temp=start;
while(temp!=null && i>=0){
System.out.print("\t"+temp.destination+"\n");
temp=temp.next;
}
}
public int size(){
return size;
}
public void enqueue(int destination){
Node n=new Node();
n.destination=destination;
if(start==null){
start=n;
end=n;
}else{
end.next=n;
end=n;
}
size++;
System.out.println(destination);
}
public int dequeue(){
if(start==null){
System.out.println("queue is underflow");
return -1;
}
if(start.next==null){
int data=start.destination;
start=null;
return data;
}
int data=start.destination;
Node next=start.next;
start.next=null;
start=next;
return data;
}
public boolean hasNext(){
return end!=null;
}
}
public static class Node{
public Node next;
public int destination;
public String toString(){
return "["+next+","+destination+"]";
}
}
} |
// Using a hashtable to remember the last index of every char. And keep tracking the starting point of a valid substring.
// start = max(start, last[s[i]] + 1)
// ans = max(ans, i - start + 1)
// Time complexity: O(n)
// Space complexity: O(128)
class Solution {
public int lengthOfLongestSubstring(String s) {
int[] last = new int[128];
Arrays.fill(last, -1);
int start = 0;
int ans = 0;
for (int i = 0; i < s.length(); ++i) {
if (last[s.charAt(i)] != -1)
start = Math.max(start, last[s.charAt(i)] + 1);
last[s.charAt(i)] = i;
ans = Math.max(ans, i - start + 1);
}
return ans;
}
} |
package yuku.alkitab.base.storage;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import yuku.alkitab.base.S;
import yuku.alkitab.base.model.Ari;
import yuku.alkitab.base.model.Book;
import yuku.alkitab.base.model.PericopeBlock;
import yuku.alkitab.base.model.PericopeIndex;
import yuku.alkitab.base.model.Version;
import yuku.bintex.BintexReader;
public class InternalReader implements Reader {
public static final String TAG = InternalReader.class.getSimpleName();
// # buat cache Asset
private static InputStream cache_inputStream = null;
private static String cache_file = null;
private static int cache_posInput = -1;
private final String edisiPrefix;
private final String edisiShortName;
private final String edisiLongName;
private final ReaderDecoder readerDecoder;
public InternalReader(String edisiPrefix, String edisiShortName, String edisiLongName, ReaderDecoder readerDecoder) {
this.edisiPrefix = edisiPrefix;
this.edisiShortName = edisiShortName;
this.edisiLongName = edisiLongName;
this.readerDecoder = readerDecoder;
}
@Override public String getShortName() {
return edisiShortName;
}
@Override public String getLongName() {
return edisiLongName;
}
@Override public Book[] loadBooks() {
InputStream is = S.openRaw(edisiPrefix + "_index_bt"); //$NON-NLS-1$
BintexReader in = new BintexReader(is);
try {
ArrayList<Book> xkitab = new ArrayList<Book>();
try {
int pos = 0;
while (true) {
Book k = bacaKitab(in, pos++);
xkitab.add(k);
}
} catch (IOException e) {
Log.d(TAG, "siapinKitab selesai memuat"); //$NON-NLS-1$
}
return xkitab.toArray(new Book[xkitab.size()]);
} finally {
in.close();
}
}
private static Book bacaKitab(BintexReader in, int pos) throws IOException {
Book k = new Book();
k.bookId = pos;
// autostring bookName
// shortstring resName
// int chapter_count
// uint8[chapter_count] verse_counts
// int[chapter_count+1] chapter_offsets
k.nama = k.judul = in.readAutoString();
k.file = in.readShortString();
k.nchapter = in.readInt();
k.nverses = new int[k.nchapter];
for (int i = 0; i < k.nchapter; i++) {
k.nverses[i] = in.readUint8();
}
k.pasal_offset = new int[k.nchapter + 1];
for (int i = 0; i < k.nchapter + 1; i++) {
k.pasal_offset[i] = in.readInt();
}
return k;
}
@Override public String[] loadVerseText(Book book, int pasal_1, boolean janganPisahAyat, boolean hurufKecil) {
if (pasal_1 < 1 || pasal_1 > book.nchapter) {
return null;
}
int offset = book.pasal_offset[pasal_1 - 1];
int length = 0;
try {
InputStream in;
// Log.d("alki", "muatTeks kitab=" + kitab.nama + " pasal[1base]=" + pasal + " offset=" + offset);
// Log.d("alki", "muatTeks cache_file=" + cache_file + " cache_posInput=" + cache_posInput);
if (cache_inputStream == null) {
// kasus 1: belum buka apapun
in = S.openRaw(book.file);
cache_inputStream = in;
cache_file = book.file;
in.skip(offset);
cache_posInput = offset;
// Log.d("alki", "muatTeks masuk kasus 1");
} else {
// kasus 2: uda pernah buka. Cek apakah filenya sama
if (book.file.equals(cache_file)) {
// kasus 2.1: filenya sama.
if (offset >= cache_posInput) {
// bagus, kita bisa maju.
in = cache_inputStream;
in.skip(offset - cache_posInput);
cache_posInput = offset;
// Log.d("alki", "muatTeks masuk kasus 2.1 bagus");
} else {
// ga bisa mundur. tutup dan buka lagi.
cache_inputStream.close();
in = S.openRaw(book.file);
cache_inputStream = in;
in.skip(offset);
cache_posInput = offset;
// Log.d("alki", "muatTeks masuk kasus 2.1 jelek");
}
} else {
// kasus 2.2: filenya beda, tutup dan buka baru
cache_inputStream.close();
in = S.openRaw(book.file);
cache_inputStream = in;
cache_file = book.file;
in.skip(offset);
cache_posInput = offset;
// Log.d("alki", "muatTeks masuk kasus 2.2");
}
}
if (pasal_1 == book.nchapter) {
length = in.available();
} else {
length = book.pasal_offset[pasal_1] - offset;
}
byte[] ba = new byte[length];
in.read(ba);
cache_posInput += ba.length;
// jangan ditutup walau uda baca. Siapa tau masih sama filenya dengan sebelumnya.
if (janganPisahAyat) {
return new String[] { readerDecoder.jadikanStringTunggal(ba, hurufKecil) };
} else {
return readerDecoder.pisahJadiAyat(ba, hurufKecil);
}
} catch (IOException e) {
return new String[] { e.getMessage() };
}
}
@Override public PericopeIndex loadPericopeIndex() {
long wmulai = System.currentTimeMillis();
InputStream is = S.openRaw(edisiPrefix + "_pericope_index_bt"); //$NON-NLS-1$
if (is == null) {
return null;
}
BintexReader in = new BintexReader(is);
try {
return PericopeIndex.read(in);
} catch (IOException e) {
Log.e(TAG, "baca perikop index ngaco", e); //$NON-NLS-1$
return null;
} finally {
in.close();
Log.d(TAG, "Muat index perikop butuh ms: " + (System.currentTimeMillis() - wmulai)); //$NON-NLS-1$
}
}
@Override public int loadPericope(Version version, int kitab, int pasal, int[] xari, PericopeBlock[] xblok, int max) {
PericopeIndex pericopeIndex = version.getIndexPerikop();
if (pericopeIndex == null) {
return 0; // ga ada perikop!
}
int ariMin = Ari.encode(kitab, pasal, 0);
int ariMax = Ari.encode(kitab, pasal + 1, 0);
int res = 0;
int pertama = pericopeIndex.findFirst(ariMin, ariMax);
if (pertama == -1) {
return 0;
}
int kini = pertama;
BintexReader in = new BintexReader(S.openRaw(edisiPrefix + "_pericope_blocks_bt")); //$NON-NLS-1$
try {
while (true) {
int ari = pericopeIndex.getAri(kini);
if (ari >= ariMax) {
// habis. Uda ga relevan
break;
}
PericopeBlock pericopeBlock = pericopeIndex.getBlock(in, kini);
kini++;
if (res < max) {
xari[res] = ari;
xblok[res] = pericopeBlock;
res++;
} else {
break;
}
}
} finally {
in.close();
}
return res;
}
} |
package org.opensim.view;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import org.opensim.modeling.*;
import org.opensim.modeling.Geometry.Representation;
import org.opensim.view.pub.ModelVisualsVtk;
import org.opensim.view.pub.OpenSimDB;
import org.opensim.view.pub.ViewDB;
import vtk.vtkActor;
import vtk.vtkAssembly;
import vtk.vtkAssemblyNode;
import vtk.vtkAssemblyPath;
import vtk.vtkCylinderSource;
import vtk.vtkLinearTransform;
import vtk.vtkMatrix4x4;
import vtk.vtkPolyDataAlgorithm;
import vtk.vtkProp3D;
import vtk.vtkProp3DCollection;
import vtk.vtkSphereSource;
import vtk.vtkStripper;
import vtk.vtkTransform;
import vtk.vtkTransformPolyDataFilter;
import vtk.vtkArrowSource;
import vtk.vtkLineSource;
import vtk.vtkProp;
/**
*
* @author Ayman. A class representing the visuals of one model.
* This class does not actually display the model. Instead it builds the
* data structures (vtkAssembly) needed to display the model and also
* maintains the maps for finding an object based on selection and vice versa.
*
* Sources of slow down:
* 1. Too many assemblies (1 per muscle).
* 2. Too many actors (markers, muscle points) these should replaced with Glyph3D or TensorGlyphs
* 3. Selection is slow because hashing vtkProp3D apparently doesn't destribute objects evenly use
* some form of Id instead (e.g. vtkId).
*/
public class SingleModelVisuals implements ModelVisualsVtk {
protected vtkAssembly modelDisplayAssembly; // assembly representing the model
protected vtkLinearTransform modelDisplayTransform; // extra transform to shift, rotate model
private double opacity;
private double[] bounds = new double[]{-.1, .1, -.1, .1, -.1, .1};
private boolean visible;
private double[] inactiveMuscleColor = new double[]{0.0, 0.0, 1.0};
//private double[] forceAlongPathColor = new double[]{0.0, 1.0, 0.0};
private double[] defaultMuscleColor = new double[]{0.8, 0.1, 0.1};
private double[] defaultMusclePointColor = new double[]{1.0, 0.0, 0.0};
//private double[] defaultWrapObjectColor = new double[]{0.0, 1.0, 1.0};
private boolean useCylinderMuscles=true;
// Maps between objects and vtkProp3D for going from Actor to Object and vice versa
// Objects are mapped to vtkProp3D in general, but some are known to be assemblies
// e.g. Muscles, Models
protected Hashtable<OpenSimObject, vtkProp3D> mapObject2VtkObjects = new Hashtable<OpenSimObject, vtkProp3D>();
protected Hashtable<vtkProp3D, OpenSimObject> mapVtkObjects2Objects = new Hashtable<vtkProp3D, OpenSimObject>(50);
//private Hashtable<OpenSimObject, LineSegmentMuscleDisplayer> mapActuator2Displayer = new Hashtable<OpenSimObject, LineSegmentMuscleDisplayer>();
//private Hashtable<OpenSimObject, LineSegmentForceDisplayer> mapPathForces2Displayer = new Hashtable<OpenSimObject, LineSegmentForceDisplayer>();
private Hashtable<Force, ObjectDisplayerInterface> mapNoPathForces2Displayer = new Hashtable<Force, ObjectDisplayerInterface>();
protected Hashtable<OpenSimObject, vtkLineSource> mapMarkers2Lines = new Hashtable<OpenSimObject, vtkLineSource>(50);
// Markers and muscle points are represented as Glyphs for performance
//private MarkersDisplayer markersRep=new MarkersDisplayer();
private vtkProp3DCollection userObjects = new vtkProp3DCollection();
private vtkProp3DCollection bodiesCollection = new vtkProp3DCollection();
private ModelComDisplayer comDisplayer;
private boolean showCOM=false;
private MuscleColoringFunction defaultColoringFunction;
private MuscleColoringFunction noColoringFunction;
private MuscleColoringFunction currentColoringFunction;
// Following declarations support the new Vis
ModelDisplayHints mdh = new ModelDisplayHints();
private DecorativeGeometryImplementationGUI dgi = new DecorativeGeometryImplementationGUI();
ArrayList<ModelComponent> modelComponents = new ArrayList<ModelComponent>();
protected HashMap<Integer, BodyDisplayer> mapBodyIndicesToDisplayers = new HashMap<Integer, BodyDisplayer>();
/**
* Creates a new instance of SingleModelVisuals
*/
public SingleModelVisuals(Model aModel) {
//initDefaultShapesAndColors();
buildModelComponentList(aModel);
modelDisplayAssembly = createModelAssembly(aModel);
OpenSimContext context=OpenSimDB.getInstance().getContext(aModel);
defaultColoringFunction = new MuscleColorByActivationFunction(context);
noColoringFunction = new MuscleNoColoringFunction(context);
setVisible(true);
}
public void addGeometryForModelComponent(ModelComponent mc, Model model) {
//System.out.println("Process object:"+mc.getConcreteClassName()+":"+mc.getName()+" "+mc.isObjectUpToDateWithProperties());
ArrayDecorativeGeometry adg = new ArrayDecorativeGeometry();
mc.generateDecorations(true, mdh, model.getWorkingState(), adg);
dgi.setCurrentModelComponent(mc);
if (adg.size()>0){ // Component has some geometry
DecorativeGeometry dg;
for (int idx=0; idx <adg.size(); idx++){
dg = adg.getElt(idx);
dg.implementGeometry(dgi);
}
}
ArrayDecorativeGeometry avdg = new ArrayDecorativeGeometry();
mc.generateDecorations(false, mdh, model.getWorkingState(), avdg);
if (avdg.size()>0){ // Component has some variable geometry
dgi.startVariableGeometry();
DecorativeGeometry dg;
for (int idx=0; idx <avdg.size(); idx++){
dg = avdg.getElt(idx);
//System.out.println("Variable Visuals for "+mc.getName()+ "index:"+idx+"is");
dg.implementGeometry(dgi);
}
dgi.finishVariableGeometry();
}
dgi.finishCurrentModelComponent(mc);
}
/**
* Find the vtkProp3D for the passed in object
*/
public vtkProp3D getVtkRepForObject(OpenSimObject obj)
{
return mapObject2VtkObjects.get(obj);
}
/**
* find the Object for passed in vtkProp3D
*/
public OpenSimObject getObjectForVtkRep(vtkProp3D prop)
{
return mapVtkObjects2Objects.get(prop);
}
/**
* Create one vtkAssembly representing the model and return it.
*/
private vtkAssembly createModelAssembly(Model model)
{
//int bid0 = dg.getBodyId();
vtkAssembly modelAssembly = new vtkAssembly();
// Keep track of ground body to avoid recomputation
BodiesList bodies = model.getBodiesList();
BodyIterator body = bodies.begin();
while (!body.equals(bodies.end())) {
int id = body.getMobilizedBodyIndex();
// Body actor
BodyDisplayer bodyRep = new BodyDisplayer(modelAssembly, body.__deref__(),
mapObject2VtkObjects, mapVtkObjects2Objects);
mapBodyIndicesToDisplayers.put(id, bodyRep);
body.next();
}
dgi.setModelAssembly(modelAssembly, mapBodyIndicesToDisplayers, model, mdh);
ModelComponentList mcList = model.getModelComponentList();
ModelComponentIterator mcIter = mcList.begin();
mcIter.next(); // Skip model itself
while (!mcIter.equals(mcList.end())){
//System.out.println("In createModelAssembly Type, name:"+mcIter.__deref__().getConcreteClassName()+mcIter.__deref__().getName());
addGeometryForModelComponent(mcIter.__deref__(), model);
mcIter.next();
}
//comDisplayer = new ModelComDisplayer(model);
if (isShowCOM())
modelAssembly.AddPart(comDisplayer.getVtkActor());
// Now the muscles and other actuators
//addGeometryForForces(model, modelAssembly);
// Add whole model assembly to object map
mapObject2VtkObjects.put(model, modelAssembly);
mapVtkObjects2Objects.put(modelAssembly, model);
// Now call update to actually set all the positions/transforms of the actors and glyphs
updateModelDisplay(model);
return modelAssembly;
}
/**
* updateModelDisplay with new transforms cached in animationCallback.
* This method must be optimized since it's invoked during live animation
* of simulations and/or analyses (ala IK).
*/
public void updateModelDisplay(Model model) {
// Cycle thru bodies and update their transforms from the kinematics engine
BodiesList bodies = model.getBodiesList();
BodyIterator bodyIter = bodies.begin();
while (!bodyIter.equals(bodies.end())) {
Body body = bodyIter.__deref__();
// Fill the maps between objects and display to support picking, highlighting, etc..
// The reverse map takes an actor to an Object and is filled as actors are created.
BodyDisplayer bodyRep= (BodyDisplayer) mapObject2VtkObjects.get(body);
vtkMatrix4x4 bodyVtkTransform= getBodyTransform(model, body);
if (bodyRep!=null)
bodyRep.SetUserMatrix(bodyVtkTransform);
//bodyRep.applyRepresentations();
bodyIter.next();
}
ModelComponentList mcList = model.getModelComponentList();
ModelComponentIterator mcIter = mcList.begin();
mcIter.next(); // Skip model itself
while (!mcIter.equals(mcList.end())){
//System.out.println("In createModelAssembly Type, name:"+mcIter.__deref__().getConcreteClassName()+mcIter.__deref__().getName());
dgi.updateDecorations(mcIter.__deref__());
mcIter.next();
}
updateVariableGeometry(model);
//updateMarkersGeometry(model.getMarkerSet());
//updateForceGeometry(model);
//comDisplayer.updateCOMLocation();
//updateUserObjects();
}
private void updateMarkersGeometry(MarkerSet markers) {
for (int i=0; i<markers.getSize(); i++)
getMarkersRep().updateMarkerGeometry(markers.get(i));
}
/**
* Functions for dealing with actuator geometry
*/
public void updateActuatorGeometry(Actuator act, boolean callUpdateDisplayer) {
/*
LineSegmentMuscleDisplayer disp = null;//mapActuator2Displayer.get(act);
if(disp != null) {
disp.updateGeometry(callUpdateDisplayer);
}
*/
}
public void setApplyMuscleColors(boolean enabled) {
/*
Iterator<LineSegmentMuscleDisplayer> dispIter = mapActuator2Displayer.values().iterator();
while(dispIter.hasNext()) dispIter.next().setApplyColoringFunction(currentColoringFunction);
*/
}
/**
* Get the vtkTransform matrix between ground and a body frame,
*/
vtkMatrix4x4 getBodyTransform(Model model, Body body)
{
double[] flattenedXform = new double[16];
OpenSimContext dContext = OpenSimDB.getInstance().getContext(model);
dContext.getTransformAsDouble16(body.getGroundTransform(dContext.getCurrentStateRef()), flattenedXform);
return convertTransformToVtkMatrix4x4(flattenedXform);
}
/**
* return a reference to the vtkAssembly representing the model
*/
public vtkAssembly getModelDisplayAssembly() {
return modelDisplayAssembly;
}
public OpenSimObject pickObject(vtkAssemblyPath asmPath) {
if (asmPath != null) {
vtkAssemblyNode pickedAsm = asmPath.GetLastNode();
vtkProp p = pickedAsm.GetViewProp();
return dgi.pickObject((vtkActor)p);
}
return null; // No selection
}
/* Make the entire model pickable or not pickable. modelDisplayAssembly.setPickable()
* does not seem to do anything, so the pickable flag for each actor in the model
* needs to be set.
*/
public void setPickable(boolean pickable) {
if (pickable) {
modelDisplayAssembly.SetPickable(1);
Enumeration<vtkProp3D> props = mapObject2VtkObjects.elements();
while (props.hasMoreElements()) {
props.nextElement().SetPickable(1);
}
} else {
modelDisplayAssembly.SetPickable(0);
Enumeration<vtkProp3D> props = mapObject2VtkObjects.elements();
while (props.hasMoreElements()) {
props.nextElement().SetPickable(0);
}
}
//getMarkersRep().setPickable(pickable);
}
public vtkLinearTransform getModelDisplayTransform() {
return modelDisplayTransform;
}
/**
* Since there's no global model opacity, we'll take the opacity of the first object
* we find and use it as value for the Opacity of he model. This has the advantage that
* if Opacities are the same for all objects then the behavior is as expected.
*/
public double getOpacity() {
vtkProp3D prop = modelDisplayAssembly.GetParts().GetLastProp3D();
if (prop instanceof vtkAssembly){ //recur
opacity = getAssemblyOpacity((vtkAssembly)prop);
}
else if (prop instanceof vtkActor){ // Could be Actor or whatelse?
opacity = ((vtkActor)prop).GetProperty().GetOpacity();
}
return opacity;
}
public void setOpacity(double opacity) {
this.opacity = opacity;
}
/**
* Compute bounding box for model as this can be useful for initial placement
* This is supposed to be a ballpark rather than an accurate estimate so that minor changes to
* model do not cause overlap, but the bboox is not intended to be kept up-to-date
* unused and turned out to be very slow for some reason
private void computeModelBoundingbox() {
modelDisplayAssembly.GetBounds(bounds);
}*/
// NOTE: these functions are necessary in order to deal with the model offsets...
// Not the most general solution (e.g. if the hierarchy changed and there was more than one user matrix
// modifying the model then this would not work). But should work for now.
public void transformModelToWorldPoint(double[] point) {
vtkMatrix4x4 body2world = modelDisplayAssembly.GetUserMatrix();
if(body2world != null) {
double[] point4 = body2world.MultiplyPoint(new double[]{point[0],point[1],point[2],1.0});
for(int i=0; i<3; i++) point[i]=point4[i];
}
}
public void transformModelToWorldBounds(double[] bounds) {
vtkMatrix4x4 body2world = modelDisplayAssembly.GetUserMatrix();
if(body2world != null) {
double[] minCorner = body2world.MultiplyPoint(new double[]{bounds[0],bounds[2],bounds[4],1.0});
double[] width = new double[]{bounds[1]-bounds[0], bounds[3]-bounds[2], bounds[5]-bounds[4]};
for(int i=0; i<3; i++) { bounds[2*i]=bounds[2*i+1]=minCorner[i]; } // initialize as min corner
for(int i=0; i<3; i++) for(int j=0; j<3; j++) {
if(body2world.GetElement(i,j)<0) bounds[2*i]+=width[j]*body2world.GetElement(i,j);
else bounds[2*i+1]+=width[j]*body2world.GetElement(i,j);
}
}
}
@Override
public double[] getBoundsBodiesOnly() {
double[] bounds = getBounds();
/*bodiesCollection.InitTraversal();
for(;;) {
vtkProp3D prop = bodiesCollection.GetNextProp3D();
if(prop==null) break;
if(prop.GetVisibility()!=0) bounds = ViewDB.boundsUnion(bounds, prop.GetBounds());
}*/
if (bounds!=null)
transformModelToWorldBounds(bounds);
return bounds;
}
/**
* A flag indicating if the model assembly is shown or not for global visibility control
*/
public boolean isVisible() {
return visible;
}
public void setVisible(boolean onOff) {
this.visible = onOff;
}
double[] getOffset() {
return modelDisplayAssembly.GetPosition();
}
private double getAssemblyOpacity(vtkAssembly anAssembly) {
vtkProp3DCollection parts = anAssembly.GetParts();
parts.InitTraversal();
int n =parts.GetNumberOfItems();
for(int i=0; i<n; i++){
vtkProp3D prop = parts.GetNextProp3D();
if (prop instanceof vtkAssembly){
return getAssemblyOpacity((vtkAssembly)prop);
// Should continue traversal here
}
else if (prop instanceof vtkActor){
return ((vtkActor)prop).GetProperty().GetOpacity();
}
}
return 0;
}
/**
* Utility to convert Transform as defined by OpenSim to the form used by vtk
*/
static vtkMatrix4x4 convertTransformToVtkMatrix4x4(double[] xformAsVector) {
vtkMatrix4x4 m = new vtkMatrix4x4(); // This should be moved out for performance
// Transpose the rotation part of the matrix per Pete!!
for (int row = 0; row < 3; row++){
for (int col = row; col < 4; col++){
double swap = xformAsVector[row*4+col];
xformAsVector[row*4+col]=xformAsVector[col*4+row];
xformAsVector[col*4+row]=swap;
}
}
m.DeepCopy(xformAsVector);
return m;
}
/**
* Method used to update display of motion objects during animation
*/
private void updateUserObjects() {
//System.out.println("updateUserObjects");
ViewDB.getInstance().updateAnnotationAnchors();
}
public void addUserObject(vtkActor userObj){
if (getUserObjects().IsItemPresent(userObj)==0){
getUserObjects().AddItem(userObj);
modelDisplayAssembly.AddPart(userObj);
}
}
public void removeUserObject(vtkActor userObj){
getUserObjects().RemoveItem(userObj);
modelDisplayAssembly.RemovePart(userObj);
}
/**
* Functions to deal with glyphs for markers and muscle points/segments
*/
private void createMuscleSegmentRep(OpenSimvtkOrientedGlyphCloud aMuscleSegmentsRep) {
// Muscle segments
vtkPolyDataAlgorithm muscleSgt; //Either cylinder or ellipsoid for now
if (useCylinderMuscles) {
vtkCylinderSource muscleSegment=new vtkCylinderSource();
muscleSegment.SetRadius(ViewDB.getInstance().getMuscleDisplayRadius());
muscleSegment.SetHeight(1.0);
muscleSegment.SetCenter(0.0, 0.0, 0.0);
muscleSegment.CappingOff();
aMuscleSegmentsRep.setShape(muscleSegment.GetOutput());
}
else {
vtkSphereSource muscleSegment=new vtkSphereSource();
muscleSegment.SetRadius(ViewDB.getInstance().getMuscleDisplayRadius());
vtkTransformPolyDataFilter stretcher = new vtkTransformPolyDataFilter();
vtkTransform stretcherTransform = new vtkTransform();
stretcherTransform.Scale(20.0, 0.5/ViewDB.getInstance().getMuscleDisplayRadius(), 20.0);
muscleSegment.SetCenter(0.0, 0.0, 0.0);
stretcher.SetInput(muscleSegment.GetOutput());
stretcher.SetTransform(stretcherTransform);
aMuscleSegmentsRep.setShape(stretcher.GetOutput());
}
aMuscleSegmentsRep.setColorRange(inactiveMuscleColor, defaultMuscleColor);
}
private void createMusclePointRep(OpenSimvtkGlyphCloud aMusclePointsRep) {
// Muscle points
//vtkSphereSource viaPoint=new vtkSphereSource();
//viaPoint.SetRadius(ViewDB.getInstance().getMuscleDisplayRadius());
//viaPoint.SetCenter(0., 0., 0.);
//getMusclePointsRep().setColors(defaultMusclePointColor, SelectedObject.defaultSelectedColor);
aMusclePointsRep.setColorRange(inactiveMuscleColor, defaultMusclePointColor);
aMusclePointsRep.setSelectedColor(SelectedObject.defaultSelectedColor);
//vtkStripper strip2 = new vtkStripper();
//strip2.SetInput(viaPoint.GetOutput());
aMusclePointsRep.setShapeName("musclepoint");
aMusclePointsRep.setScaleFactor(ViewDB.getInstance().getMuscleDisplayRadius());
aMusclePointsRep.scaleByVectorComponents();
}
public OpenSimvtkGlyphCloud getGlyphObjectForActor(vtkActor act) {
if (getMarkersRep().getVtkActor()==act)
return getMarkersRep();
else
return null;
}
public MarkersDisplayer getMarkersRep() {
return null;
}
// Remmove dead references to help garbage collector.
public void cleanup() {
int rc = modelDisplayAssembly.GetReferenceCount();
vtkProp3DCollection parts = modelDisplayAssembly.GetParts();
for(int i=parts.GetNumberOfItems()-1; i>=0; i
modelDisplayAssembly.RemovePart(parts.GetLastProp3D());
}
getUserObjects().RemoveAllItems();
userObjects=null;
bodiesCollection.RemoveAllItems();
bodiesCollection=null;
modelDisplayAssembly=null;
mapObject2VtkObjects=null;
mapVtkObjects2Objects=null;
}
public vtkProp3DCollection getUserObjects() {
return userObjects;
}
// Springs and other joints
private void addNonPathForceGeometry(vtkAssembly modelAssembly, OpenSimObject fObject) {
Force f = Force.safeDownCast(fObject);
OpenSimContext context=OpenSimDB.getInstance().getContext(f.getModel());
if (context.isDisabled(f)) return;
}
public boolean isShowCOM() {
return showCOM;
}
public void setShowCOM(boolean showCOM) {
if (showCOM) modelDisplayAssembly.AddPart(comDisplayer.getVtkActor());
else modelDisplayAssembly.RemovePart(comDisplayer.getVtkActor());
this.showCOM = showCOM;
}
public void removeGeometry(OpenSimObject object) {
dgi.removeGeometry((Actuator) object);
}
private void removePathForceGeometry(Force f) {
/*
if (f.getDisplayer()!=null){
f.getDisplayer().setDisplayPreference(DisplayPreference.None);
mapPathForces2Displayer.get(f).updateGeometry(false);
}*/
}
private void removeNonPathForceGeometry(Force f) {
/*
if (f.getDisplayer()!=null){
f.getDisplayer().setDisplayPreference(DisplayPreference.None);
mapNoPathForces2Displayer.get(f).updateGeometry();
}*/
}
public void updateForceGeometry(Force f, boolean visible) {
if (!visible){ // turning off
removeGeometry(f);
}
else{/*
if (mapPathForces2Displayer.get(f)!=null){
mapPathForces2Displayer.get(f).updateGeometry(true);
LineSegmentForceDisplayer disp = mapPathForces2Displayer.get(f);
}
else if (mapNoPathForces2Displayer.get(f)!=null){
mapNoPathForces2Displayer.get(f).updateGeometry();
}*/
}
}
/**
* @return the bounds
*/
public double[] getBounds() {
return bounds;
}
public void updateObjectDisplay(OpenSimObject specificObject) {
vtkProp3D prop3D = mapObject2VtkObjects.get(specificObject);
if (prop3D!= null){
if (prop3D instanceof DecorativeGeometryDisplayer ){
DecorativeGeometryDisplayer dgd = (DecorativeGeometryDisplayer)prop3D;
dgd.updateDecorativeGeometryFromObject();
((DecorativeGeometryDisplayer)prop3D).updateDisplayFromDecorativeGeometry();
}
}
}
public void setMuscleColoringFunction(MuscleColoringFunction mcf) {
if (mcf == null)
currentColoringFunction = defaultColoringFunction;
else
currentColoringFunction = mcf;
//pushColoringFunctionToMuscles();
}
private void buildModelComponentList(Model model) {
ModelComponentList mcList = model.getModelComponentList();
ModelComponentIterator mcIter = mcList.begin();
mcIter.next(); // Skip model itself
while (!mcIter.equals(mcList.end())){
modelComponents.add(mcIter.__deref__());
mcIter.next();
}
}
public void selectObject(OpenSimObject openSimObject) {
dgi.selectObject(openSimObject); // Delegate call to DecorativeGeometryImplmentation for now
}
void highLightObject(OpenSimObject object, boolean highlight) {
if (highlight)
dgi.selectObject(object);
else {
// Call method on owner ModelCompoent
System.out.println("Trying to unhighlight "+object.getName());
// Assume ModelComponent
ModelComponent mc = ModelComponent.safeDownCast(object);
if (mc != null){
dgi.updateDecorations(mc);
}
}
}
public void setObjectColor(OpenSimObject object, double[] color) {
ModelComponent mc = ModelComponent.safeDownCast(object);
if (mc != null){
dgi.setObjectColor(mc, color);
}
}
public void upateDisplay(ModelComponent mc) {
dgi.updateDecorations(mc);
}
/**
* Cycle thru components and if they have VariableGeometry update it.
* @param model
*/
private void updateVariableGeometry(Model model) {
dgi.startVariableGeometry();
for (int mcIndex = 0; mcIndex < modelComponents.size(); mcIndex++){
ModelComponent mc = modelComponents.get(mcIndex);
//System.out.print("Processing model component "+mc.getConcreteClassName()+":"+mc.getName());
ArrayDecorativeGeometry avdg = new ArrayDecorativeGeometry();
mc.generateDecorations(false, mdh, model.getWorkingState(), avdg);
//System.out.println("Size var ="+avdg.size());
dgi.setCurrentModelComponent(mc);
if (avdg.size()>0){ // Component has some variable geometry
dgi.updateDecorations(mc, true);
}
//System.out.println("...Finished");
};
dgi.finishVariableGeometry();
}
public void addGeometry(Marker marker) {
throw new UnsupportedOperationException("Not yet implemented");
}
/**
* @return the dgi
*/
public DecorativeGeometryImplementationGUI getDecorativeGeometryImplmentation() {
return dgi;
}
} |
package com.parrot.arsdk.ardiscovery;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import com.parrot.arsdk.arsal.ARSALPrint;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Build;
public class ARDiscoveryService extends Service
{
private static final String TAG = ARDiscoveryService.class.getSimpleName();
/* Native Functions */
public static native int nativeGetProductID (int product);
private static native String nativeGetProductName(int product);
private static native String nativeGetProductPathName(int product);
private static native int nativeGetProductFromName(String name);
private static native int nativeGetProductFromProductID(int productID);
private static native int nativeGetProductFamily(int product);
public enum eARDISCOVERY_SERVICE_EVENT_STATUS
{
ARDISCOVERY_SERVICE_EVENT_STATUS_ADD,
ARDISCOVERY_SERVICE_EVENT_STATUS_REMOVED,
ARDISCOVERY_SERVICE_EVENT_STATUS_RESOLVED
}
public enum ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_ENUM
{
/** jmdns based implementation */
ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_JMDNS,
/** Android Network Service Discovery Manager implementation, only available on API 16 */
ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_NSD,
/** Custom MDNS-SD implementation */
ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_MDSNSDMIN;
}
/**
* Constant for devices services list updates notification
*/
public static final String kARDiscoveryServiceNotificationServicesDevicesListUpdated = "kARDiscoveryServiceNotificationServicesDevicesListUpdated";
public static String ARDISCOVERY_SERVICE_NET_DEVICE_FORMAT;
public static String ARDISCOVERY_SERVICE_NET_DEVICE_DOMAIN;
private static native String nativeGetDefineNetDeviceDomain ();
private static native String nativeGetDefineNetDeviceFormat ();
private HashMap<String, Intent> intentCache;
private ARDiscoveryBLEDiscovery bleDiscovery;
private ARDiscoveryWifiDiscovery wifiDiscovery;
private ARDiscoveryNsdPublisher wifiPublisher;
private final IBinder binder = new LocalBinder();
/**
* Selected wifi discovery implementation. Can be set using
* {@link #setWifiPreferredWifiDiscoveryType(ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_ENUM)}
*/
private static ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_ENUM wifiDiscoveryType;
private static Set<ARDISCOVERY_PRODUCT_ENUM> supportedProducts;
private static boolean usePublisher;
static
{
ARDISCOVERY_SERVICE_NET_DEVICE_FORMAT = nativeGetDefineNetDeviceFormat () + ".";
ARDISCOVERY_SERVICE_NET_DEVICE_DOMAIN = nativeGetDefineNetDeviceDomain () + ".";
}
/**
* Configuration: set the preferred wifi discovery type.
* This method must be called before starting ARDiscoveryService.
* @param discoveryType preferred wifi discovery type
*/
public static void setWifiPreferredWifiDiscoveryType(ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_ENUM discoveryType)
{
synchronized (ARDiscoveryService.class)
{
if (wifiDiscoveryType != null)
{
throw new RuntimeException("setWifiPreferredWifiDiscoveryType must be called before stating ARDiscoveryService");
}
wifiDiscoveryType = discoveryType;
}
}
public static void setSupportedProducts(Set<ARDISCOVERY_PRODUCT_ENUM> products)
{
synchronized (ARDiscoveryService.class)
{
if (supportedProducts != null)
{
throw new RuntimeException("setWifiPreferredWifiDiscoveryType must be called before stating ARDiscoveryService");
}
supportedProducts = products;
}
}
public static void setUsePublisher(boolean use)
{
usePublisher = use;
}
@Override
public IBinder onBind(Intent intent)
{
ARSALPrint.d(TAG,"onBind");
return binder;
}
@Override
public void onCreate()
{
initIntents();
synchronized (this.getClass())
{
if (wifiDiscoveryType == null)
{
wifiDiscoveryType = ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_ENUM.ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_MDSNSDMIN;
}
if (supportedProducts == null)
{
supportedProducts = EnumSet.allOf(ARDISCOVERY_PRODUCT_ENUM.class);
}
}
// create and open BLE discovery
bleDiscovery = new ARDiscoveryBLEDiscoveryImpl(supportedProducts);
bleDiscovery.open(this, this);
// create and open wifi discovery and publisher
initWifiDiscovery();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
if (intent == null)
{
ARSALPrint.w(TAG, "recreated by the system, don't need! stop it");
stopSelf();
}
return START_STICKY;
}
@Override
public void onDestroy()
{
super.onDestroy();
if(bleDiscovery != null)
{
bleDiscovery.close();
bleDiscovery = null;
}
if(wifiDiscovery != null)
{
wifiDiscovery.close();
wifiDiscovery = null;
}
if(wifiPublisher != null)
{
wifiPublisher.close();
wifiPublisher = null;
}
}
public class LocalBinder extends Binder
{
public ARDiscoveryService getService()
{
ARSALPrint.d(TAG,"getService");
return ARDiscoveryService.this;
}
}
private void initIntents()
{
ARSALPrint.d(TAG,"initIntents");
intentCache = new HashMap<String, Intent>();
intentCache.put(kARDiscoveryServiceNotificationServicesDevicesListUpdated, new Intent(kARDiscoveryServiceNotificationServicesDevicesListUpdated));
}
@Override
public boolean onUnbind(Intent intent)
{
ARSALPrint.d(TAG,"onUnbind");
return true; /* ensures onRebind is called */
}
@Override
public void onRebind(Intent intent)
{
ARSALPrint.d(TAG,"onRebind");
}
private synchronized void initWifiDiscovery()
{
switch (wifiDiscoveryType)
{
case ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_NSD:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
wifiDiscovery = new ARDiscoveryNsdDiscovery(supportedProducts);
if (usePublisher)
{
wifiPublisher = new ARDiscoveryNsdPublisher();
}
ARSALPrint.d(TAG, "Wifi discovery asked is nsd and it will be ARDiscoveryNsdDiscovery");
}
else
{
ARSALPrint.w(TAG, "NSD can't run on " + Build.VERSION.SDK_INT + " MdnsSdMin will be used");
wifiDiscovery = new ARDiscoveryMdnsSdMinDiscovery(supportedProducts);
wifiPublisher = null;
ARSALPrint.d(TAG, "Wifi discovery asked is nsd and it will be ARDiscoveryMdnsSdMinDiscovery");
}
break;
case ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_MDSNSDMIN:
wifiDiscovery = new ARDiscoveryMdnsSdMinDiscovery(supportedProducts);
ARSALPrint.d(TAG, "Wifi discovery asked is MDSNSDMIN and it will be ARDiscoveryMdnsSdMinDiscovery");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{ // uses NSD to publish as MdnsSdMin doesn't supports publishing yet
if (usePublisher)
{
wifiPublisher = new ARDiscoveryNsdPublisher();
}
}
else
{
wifiPublisher = null;
}
break;
case ARDISCOVERYSERVICE_WIFI_DISCOVERY_TYPE_JMDNS:
default:
wifiDiscovery = new ARDiscoveryJmdnsDiscovery(supportedProducts);
ARSALPrint.d(TAG, "Wifi discovery asked is " + wifiDiscoveryType + " and it will be ARDiscoveryJmdnsDiscovery");
wifiPublisher = null;
break;
}
ARSALPrint.v(TAG, "Opening wifi discovery");
wifiDiscovery.open(this, this);
if (wifiPublisher != null)
{
ARSALPrint.v(TAG, "Opening wifi publisher");
wifiPublisher.open(this, this);
}
else
{
ARSALPrint.i(TAG, "No wifi publisher available");
}
}
/**
* Starts discovering all wifi and bluetooth devices
*/
public synchronized void start()
{
ARSALPrint.d(TAG, "Start discoveries");
bleDiscovery.start();
wifiDiscovery.start();
}
public synchronized void stop()
{
ARSALPrint.d(TAG, "Stop discoveries");
bleDiscovery.stop();
wifiDiscovery.stop();
}
public synchronized void startWifiDiscovering()
{
if (wifiDiscovery != null)
{
ARSALPrint.d(TAG, "Start wifi discovery");
wifiDiscovery.start();
}
}
public synchronized void stopWifiDiscovering()
{
if (wifiDiscovery != null)
{
ARSALPrint.d(TAG, "Stop wifi discovery");
wifiDiscovery.stop();
}
}
public synchronized void startBLEDiscovering()
{
if (bleDiscovery != null)
{
ARSALPrint.d(TAG, "Start BLE discovery");
bleDiscovery.start();
}
}
public synchronized void stopBLEDiscovering()
{
if (bleDiscovery != null)
{
ARSALPrint.d(TAG, "Stop BLE discovery");
bleDiscovery.stop();
}
}
/* broadcast the deviceServicelist Updated */
public void broadcastDeviceServiceArrayUpdated ()
{
/* broadcast the service add */
Intent intent = intentCache.get(kARDiscoveryServiceNotificationServicesDevicesListUpdated);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
}
public List<ARDiscoveryDeviceService> getDeviceServicesArray()
{
List<ARDiscoveryDeviceService> deviceServicesArray = new ArrayList<ARDiscoveryDeviceService>();
if (wifiDiscovery != null)
{
deviceServicesArray.addAll(wifiDiscovery.getDeviceServicesArray());
}
if (bleDiscovery != null)
{
deviceServicesArray.addAll(bleDiscovery.getDeviceServicesArray());
}
ARSALPrint.d(TAG,"getDeviceServicesArray: " + deviceServicesArray);
return deviceServicesArray;
}
/**
* @brief Publishes a service of the given product
* This function unpublishes any previously published service
* @param product The product to publish
* @param name The name of the service
* @param port The port of the service
*/
public boolean publishService(ARDISCOVERY_PRODUCT_ENUM product, String name, int port)
{
boolean ret = false;
if (wifiPublisher != null)
{
ret = wifiPublisher.publishService(product, name, port);
}
return ret;
}
/**
* @brief Publishes a service of the given product_id
* This function unpublishes any previously published service
* @param product_id The product ID to publish
* @param name The name of the service
* @param port The port of the service
*/
public boolean publishService(final int product_id, final String name, final int port)
{
boolean ret = false;
if (wifiPublisher != null)
{
ret = wifiPublisher.publishService(product_id, name, port);
}
return ret;
}
/**
* @brief Unpublishes any published service
*/
public void unpublishServices()
{
if (wifiPublisher != null)
{
wifiPublisher.unpublishService();
}
}
/**
* @brief Converts a product enumerator in product ID
* This function is the only one knowing the correspondance
* between the enumerator and the products' IDs.
* @param product The product's enumerator
* @return The corresponding product ID
*/
public static int getProductID (ARDISCOVERY_PRODUCT_ENUM product)
{
return nativeGetProductID (product.getValue());
}
/**
* @brief Converts a product ID in product enumerator
* This function is the only one knowing the correspondance
* between the enumerator and the products' IDs.
* @param productID The product's ID
* @return The corresponding product enumerator
*/
public static ARDISCOVERY_PRODUCT_ENUM getProductFromProductID (int productID)
{
return ARDISCOVERY_PRODUCT_ENUM.getFromValue (nativeGetProductFromProductID (productID));
}
/**
* @brief Converts a product enum to a generic (network type) product enum
* @param product The product to convert
* @return The corresponding network type product enum
*/
public static ARDISCOVERY_PRODUCT_ENUM getProductNetworkFromProduct (ARDISCOVERY_PRODUCT_ENUM product)
{
int bleOrdinal = ARDISCOVERY_PRODUCT_ENUM.ARDISCOVERY_PRODUCT_BLESERVICE.getValue();
int productOrdinal = product.getValue();
ARDISCOVERY_PRODUCT_ENUM retVal = ARDISCOVERY_PRODUCT_ENUM.ARDISCOVERY_PRODUCT_NSNETSERVICE;
if (productOrdinal >= bleOrdinal)
{
retVal = ARDISCOVERY_PRODUCT_ENUM.ARDISCOVERY_PRODUCT_BLESERVICE;
}
return retVal;
}
/**
* @brief Converts a product ID in product name
* This function is the only one knowing the correspondance
* between the products' IDs and the product names.
* @param product The product ID
* @return The corresponding product name
*/
public static String getProductName (ARDISCOVERY_PRODUCT_ENUM product)
{
return nativeGetProductName (product.getValue());
}
/**
* @brief Converts a product ID in product path name
* This function is the only one knowing the correspondance
* between the products' IDs and the product path names.
* @param product The product ID
* @return The corresponding product path name
*/
public static String getProductPathName (ARDISCOVERY_PRODUCT_ENUM product)
{
return nativeGetProductPathName (product.getValue());
}
/**
* @brief Converts a product product name in product ID
* This function is the only one knowing the correspondance
* between the product names and the products' IDs.
* @param name The product's product name
* @return The corresponding product ID
*/
public static ARDISCOVERY_PRODUCT_ENUM getProductFromName(String name)
{
int product = nativeGetProductFromName(name);
return ARDISCOVERY_PRODUCT_ENUM.getFromValue(product);
}
/**
* @brief Converts a product family in product
* This function is the only one knowing the correspondance
* between the products and the products' families.
* @param product The product
* @return The corresponding product family
*/
public static ARDISCOVERY_PRODUCT_FAMILY_ENUM getProductFamily(ARDISCOVERY_PRODUCT_ENUM product)
{
int family = nativeGetProductFamily (product.getValue());
return ARDISCOVERY_PRODUCT_FAMILY_ENUM.getFromValue(family);
}
}; |
/**
* <p align="center"><img src="doc-files/PVManagerLogo150.png"/></p>
* <p id="contents"/>
*
* <h1>User documentation</h3>
*
* <b>
* <a href="#1">1. Reading a single channel</a><br/>
* </b>
*
* <h3 id="1">1. Reading a single channel</h3>
*
* <pre>
* // Let's statically import so the code looks cleaner
* import static org.epics.pvmanager.ExpressionLanguage.*;
* import static org.epics.pvmanager.util.TimeDuration.*;
*
* // Read channel "channelName" to most every 100 ms
* PVReader<Object> pvReader = PVManager.read(channel("channelName")).every(ms(100));
* pvReader.addPVReaderListener(new PVReaderListener() {
* public void pvChanged() {
* // Do something with each value
* Object newValue = pvReader.getValue();
* System.out.println(newValue);
* }
* });
* </pre>
* <p>
*
* <h1> Package description</h1>
*
* This package contains all the basic compononents of the PVManager framework
* and the basic support for the language to define the creation.
* <p>
* There are two distinct parts in the PVManager framework. The first part
* includes all the elements that deal with data directly: read from various
* sources ({@link ConnectionManager}), performing computation ({@link Function}),
* collecting data ({@link Collector}), scanning at the UI rate ({@link Scanner})
* and notify on appropriate threads ({@link PullNotificator}).
* <p>
* The second part consists of an expression language that allows to define
* how to connect the first set of objects with each other. {@link PVExpression}
* describes data as it's coming out at the network rate, {@link AggregatedPVExpression}
* defines data at the scanning rate for the UI, and {@link PVExpressionLanguage}
* defines static methods that define the operator in the expression language.
* <p>
* Users can extend both the first part (by extending support for different types,
* providing different support for different data source or creating new computation
* elements) and the second part (by extending the language to support other cases.
* All support for data types is relegated to separate packages: you can use
* the same style to extend the framework to your needs.
*/
package org.epics.pvmanager; |
package org.batfish.main;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeWalker;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.batfish.collections.EdgeSet;
import org.batfish.collections.FibMap;
import org.batfish.collections.FibRow;
import org.batfish.collections.FibSet;
import org.batfish.collections.FlowSinkInterface;
import org.batfish.collections.FlowSinkSet;
import org.batfish.collections.FunctionSet;
import org.batfish.collections.MultiSet;
import org.batfish.collections.NodeInterfacePair;
import org.batfish.collections.NodeRoleMap;
import org.batfish.collections.NodeSet;
import org.batfish.collections.PolicyRouteFibIpMap;
import org.batfish.collections.PolicyRouteFibNodeMap;
import org.batfish.collections.PredicateSemantics;
import org.batfish.collections.PredicateValueTypeMap;
import org.batfish.collections.QualifiedNameMap;
import org.batfish.collections.RoleNodeMap;
import org.batfish.collections.RoleSet;
import org.batfish.collections.TreeMultiSet;
import org.batfish.common.BfConsts;
import org.batfish.grammar.BatfishCombinedParser;
import org.batfish.grammar.ParseTreePrettyPrinter;
import org.batfish.grammar.juniper.JuniperCombinedParser;
import org.batfish.grammar.juniper.JuniperFlattener;
import org.batfish.grammar.logicblox.LogQLPredicateInfoExtractor;
import org.batfish.grammar.logicblox.LogiQLCombinedParser;
import org.batfish.grammar.logicblox.LogiQLPredicateInfoResolver;
import org.batfish.grammar.question.QuestionCombinedParser;
import org.batfish.grammar.question.QuestionExtractor;
import org.batfish.grammar.topology.BatfishTopologyCombinedParser;
import org.batfish.grammar.topology.BatfishTopologyExtractor;
import org.batfish.grammar.topology.GNS3TopologyCombinedParser;
import org.batfish.grammar.topology.GNS3TopologyExtractor;
import org.batfish.grammar.topology.RoleCombinedParser;
import org.batfish.grammar.topology.RoleExtractor;
import org.batfish.grammar.topology.TopologyExtractor;
import org.batfish.grammar.z3.ConcretizerQueryResultCombinedParser;
import org.batfish.grammar.z3.ConcretizerQueryResultExtractor;
import org.batfish.grammar.z3.DatalogQueryResultCombinedParser;
import org.batfish.grammar.z3.DatalogQueryResultExtractor;
import org.batfish.job.FlattenVendorConfigurationJob;
import org.batfish.job.FlattenVendorConfigurationResult;
import org.batfish.job.ParseVendorConfigurationJob;
import org.batfish.job.ParseVendorConfigurationResult;
import org.batfish.logic.LogicResourceLocator;
import org.batfish.logicblox.ConfigurationFactExtractor;
import org.batfish.logicblox.Facts;
import org.batfish.logicblox.LBInitializationException;
import org.batfish.logicblox.LBValueType;
import org.batfish.logicblox.LogicBloxFrontend;
import org.batfish.logicblox.PredicateInfo;
import org.batfish.logicblox.ProjectFile;
import org.batfish.logicblox.QueryException;
import org.batfish.logicblox.TopologyFactExtractor;
import org.batfish.question.Assertion;
import org.batfish.question.AssertionCtx;
import org.batfish.question.InterfaceSelector;
import org.batfish.question.MultipathQuestion;
import org.batfish.question.NodeSelector;
import org.batfish.question.Question;
import org.batfish.question.VerifyQuestion;
import org.batfish.representation.BgpNeighbor;
import org.batfish.representation.BgpProcess;
import org.batfish.representation.Configuration;
import org.batfish.representation.Edge;
import org.batfish.representation.Interface;
import org.batfish.representation.Ip;
import org.batfish.representation.IpProtocol;
import org.batfish.representation.LineAction;
import org.batfish.representation.OspfArea;
import org.batfish.representation.OspfProcess;
import org.batfish.representation.PolicyMap;
import org.batfish.representation.PolicyMapAction;
import org.batfish.representation.PolicyMapClause;
import org.batfish.representation.PolicyMapMatchRouteFilterListLine;
import org.batfish.representation.Prefix;
import org.batfish.representation.RouteFilterLine;
import org.batfish.representation.RouteFilterList;
import org.batfish.representation.Topology;
import org.batfish.representation.VendorConfiguration;
import org.batfish.representation.cisco.CiscoVendorConfiguration;
import org.batfish.util.StringFilter;
import org.batfish.util.SubRange;
import org.batfish.util.UrlZipExplorer;
import org.batfish.util.Util;
import org.batfish.z3.ConcretizerQuery;
import org.batfish.z3.FailureInconsistencyBlackHoleQuerySynthesizer;
import org.batfish.z3.MultipathInconsistencyQuerySynthesizer;
import org.batfish.z3.NodJob;
import org.batfish.z3.NodJobResult;
import org.batfish.z3.QuerySynthesizer;
import org.batfish.z3.ReachableQuerySynthesizer;
import org.batfish.z3.RoleReachabilityQuerySynthesizer;
import org.batfish.z3.RoleTransitQuerySynthesizer;
import org.batfish.z3.Synthesizer;
import com.logicblox.bloxweb.client.ServiceClientException;
import com.logicblox.connect.Workspace.Relation;
import com.microsoft.z3.Context;
import com.microsoft.z3.Z3Exception;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
* This class encapsulates the main control logic for Batfish.
*/
public class Batfish implements AutoCloseable {
/**
* Name of the LogiQL executable block containing basic facts that are true
* for any network
*/
private static final String BASIC_FACTS_BLOCKNAME = "BaseFacts";
/**
* Name of the file in which the topology of a network is serialized
*/
private static final String EDGES_FILENAME = "edges";
/**
* Name of the LogiQL data-plane predicate containing next hop information
* for policy-routing
*/
private static final String FIB_POLICY_ROUTE_NEXT_HOP_PREDICATE_NAME = "FibForwardPolicyRouteNextHopIp";
/**
* Name of the LogiQL data-plane predicate containing next hop information
* for destination-based routing
*/
private static final String FIB_PREDICATE_NAME = "FibNetwork";
/**
* Name of the file in which the destination-routing FIBs are serialized
*/
private static final String FIBS_FILENAME = "fibs";
/**
* Name of the file in which the policy-routing FIBs are serialized
*/
private static final String FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME = "fibs-policy-route";
/**
* Name of the LogiQL predicate containing flow-sink interface tags
*/
private static final String FLOW_SINK_PREDICATE_NAME = "FlowSinkInterface";
/**
* Name of the file in which derived flow-sink interface tags are serialized
*/
private static final String FLOW_SINKS_FILENAME = "flow-sinks";
private static final String GEN_OSPF_STARTING_IP = "10.0.0.0";
/**
* A byte-array containing the first 4 bytes comprising the header for a file
* that is the output of java serialization
*/
private static final byte[] JAVA_SERIALIZED_OBJECT_HEADER = { (byte) 0xac,
(byte) 0xed, (byte) 0x00, (byte) 0x05 };
private static final long JOB_POLLING_PERIOD_MS = 1000l;
/**
* The name of the LogiQL library for org.batfish
*/
private static final String LB_BATFISH_LIBRARY_NAME = "libbatfish";
/**
* The name of the file in which LogiQL predicate type-information and
* documentation is serialized
*/
private static final String PREDICATE_INFO_FILENAME = "predicateInfo.object";
/**
* A string containing the system-specific path separator character
*/
private static final String SEPARATOR = System.getProperty("file.separator");
/**
* Role name for generated stubs
*/
private static final String STUB_ROLE = "generated_stubs";
private static final String TESTRIG_CONFIGURATION_DIRECTORY = "configs";
/**
* The name of the [optional] topology file within a test-rig
*/
private static final String TOPOLOGY_FILENAME = "topology.net";
/**
* The name of the LogiQL predicate containing pairs of interfaces in the
* same LAN segment
*/
private static final String TOPOLOGY_PREDICATE_NAME = "LanAdjacent";
public static String flatten(String input, BatfishLogger logger,
Settings settings) {
JuniperCombinedParser jparser = new JuniperCombinedParser(input,
settings.getThrowOnParserError(), settings.getThrowOnLexerError());
ParserRuleContext jtree = parse(jparser, logger, settings);
JuniperFlattener flattener = new JuniperFlattener();
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(flattener, jtree);
return flattener.getFlattenedConfigurationText();
}
private static void initControlPlaneFactBins(
Map<String, StringBuilder> factBins) {
initFactBins(Facts.CONTROL_PLANE_FACT_COLUMN_HEADERS, factBins);
}
private static void initFactBins(Map<String, String> columnHeaderMap,
Map<String, StringBuilder> factBins) {
for (String factPredicate : columnHeaderMap.keySet()) {
String columnHeaders = columnHeaderMap.get(factPredicate);
String initialText = columnHeaders + "\n";
factBins.put(factPredicate, new StringBuilder(initialText));
}
}
private static void initTrafficFactBins(Map<String, StringBuilder> factBins) {
initFactBins(Facts.TRAFFIC_FACT_COLUMN_HEADERS, factBins);
}
public static ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
BatfishLogger logger, Settings settings) {
ParserRuleContext tree;
try {
tree = parser.parse();
}
catch (BatfishException e) {
throw new ParserBatfishException("Parser error", e);
}
List<String> errors = parser.getErrors();
int numErrors = errors.size();
if (numErrors > 0) {
logger.error(numErrors + " ERROR(S)\n");
for (int i = 0; i < numErrors; i++) {
String prefix = "ERROR " + (i + 1) + ": ";
String msg = errors.get(i);
String prefixedMsg = Util.applyPrefix(prefix, msg);
logger.error(prefixedMsg + "\n");
}
throw new ParserBatfishException("Parser error(s)");
}
else if (!settings.printParseTree()) {
logger.info("OK\n");
}
else {
logger.info("OK, PRINTING PARSE TREE:\n");
logger.info(ParseTreePrettyPrinter.print(tree, parser) + "\n\n");
}
return tree;
}
public static ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
String filename, BatfishLogger logger, Settings settings) {
logger.info("Parsing: \"" + filename + "\"...");
return parse(parser, logger, settings);
}
private List<LogicBloxFrontend> _lbFrontends;
private BatfishLogger _logger;
private PredicateInfo _predicateInfo;
private Settings _settings;
private long _timerCount;
private File _tmpLogicDir;
public Batfish(Settings settings) {
_settings = settings;
_logger = _settings.getLogger();
_lbFrontends = new ArrayList<LogicBloxFrontend>();
_tmpLogicDir = null;
}
private void addProject(LogicBloxFrontend lbFrontend) {
_logger.info("\n*** ADDING PROJECT ***\n");
resetTimer();
String settingsLogicDir = _settings.getLogicDir();
File logicDir;
if (settingsLogicDir != null) {
logicDir = new ProjectFile(settingsLogicDir);
}
else {
logicDir = retrieveLogicDir().getAbsoluteFile();
}
String result = lbFrontend.addProject(logicDir, "");
cleanupLogicDir();
if (result != null) {
throw new BatfishException(result + "\n");
}
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void addStaticFacts(LogicBloxFrontend lbFrontend, String blockName) {
_logger.info("\n*** ADDING STATIC FACTS ***\n");
resetTimer();
_logger.info("Adding " + blockName + "....");
String output = lbFrontend.execNamedBlock(LB_BATFISH_LIBRARY_NAME + ":"
+ blockName);
if (output == null) {
_logger.info("OK\n");
}
else {
throw new BatfishException(output + "\n");
}
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void anonymizeConfigurations() {
// TODO Auto-generated method stub
}
private void answer(String questionPath) {
Question question = parseQuestion(questionPath);
switch (question.getType()) {
case MULTIPATH:
answerMultipath((MultipathQuestion) question);
break;
case VERIFY:
answerVerify((VerifyQuestion) question);
break;
default:
throw new BatfishException("Unknown question type");
}
}
private void answerMultipath(MultipathQuestion question) {
String environmentName = question.getMasterEnvironment();
Path envPath = Paths.get(_settings.getAutoBaseDir(),
BfConsts.RELPATH_ENVIRONMENTS_DIR, environmentName);
Path queryDir = Paths.get(_settings.getAutoBaseDir(),
BfConsts.RELPATH_QUESTIONS_DIR, _settings.getQuestionName(),
BfConsts.RELPATH_QUERIES_DIR);
_settings.setMultipathInconsistencyQueryPath(queryDir.resolve(
BfConsts.RELPATH_MULTIPATH_QUERY_PREFIX).toString());
_settings.setNodeSetPath(envPath.resolve(BfConsts.RELPATH_ENV_NODE_SET)
.toString());
_settings.setDataPlaneDir(envPath
.resolve(BfConsts.RELPATH_DATA_PLANE_DIR).toString());
_settings.setDumpFactsDir(_settings.getTrafficFactDumpDir());
genMultipathQueries();
List<QuerySynthesizer> queries = new ArrayList<QuerySynthesizer>();
Map<String, Configuration> configurations = deserializeConfigurations(_settings
.getSerializeIndependentPath());
Set<String> flowLines = null;
try {
Context ctx = new Context();
Synthesizer dataPlane = synthesizeDataPlane(configurations, ctx);
Map<QuerySynthesizer, NodeSet> queryNodes = new HashMap<QuerySynthesizer, NodeSet>();
for (String node : configurations.keySet()) {
MultipathInconsistencyQuerySynthesizer query = new MultipathInconsistencyQuerySynthesizer(
node);
queries.add(query);
NodeSet nodes = new NodeSet();
nodes.add(node);
queryNodes.put(query, nodes);
}
flowLines = computeNodOutput(dataPlane, queries, queryNodes);
}
catch (Z3Exception e) {
throw new BatfishException("Error creating nod programs", e);
}
Map<String, StringBuilder> trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
StringBuilder wSetFlowOriginate = trafficFactBins.get("SetFlowOriginate");
for (String flowLine : flowLines) {
wSetFlowOriginate.append(flowLine);
}
dumpFacts(trafficFactBins);
}
private void answerVerify(VerifyQuestion question) {
Map<String, Configuration> configuration = deserializeConfigurations(_settings
.getSerializeIndependentPath());
Collection<Configuration> nodes = configuration.values();
AssertionCtx masterContext = new AssertionCtx();
NodeSelector nodeSelector = question.getNodeSelector();
if (nodeSelector != null) {
for (Configuration node : nodes) {
boolean nodeSelected = nodeSelector.select(node);
if (nodeSelected) {
AssertionCtx nodeContext = masterContext.copy();
nodeContext.setNode(node);
InterfaceSelector interfaceSelector = question
.getInterfaceSelector();
if (interfaceSelector != null) {
for (Interface iface : node.getInterfaces().values()) {
boolean interfaceSelected = interfaceSelector.select(node,
iface);
if (interfaceSelected) {
AssertionCtx interfaceContext = nodeContext.copy();
interfaceContext.setInterface(iface);
Assertion assertion = question.getAssertion();
assertion.check(interfaceContext, _logger, _settings);
}
}
}
}
}
}
}
/**
* This function extracts predicate type information from the logic files. It
* is meant only to be called during the build process, and should never be
* executed from a jar
*/
private void buildPredicateInfo() {
Path logicBinDirPath = null;
URL logicSourceURL = LogicResourceLocator.class.getProtectionDomain()
.getCodeSource().getLocation();
String logicSourceString = logicSourceURL.toString();
if (logicSourceString.startsWith("onejar:")) {
throw new BatfishException(
"buildPredicateInfo() should never be called from within a jar");
}
String logicPackageResourceName = LogicResourceLocator.class.getPackage()
.getName().replace('.', SEPARATOR.charAt(0));
try {
logicBinDirPath = Paths.get(LogicResourceLocator.class
.getClassLoader().getResource(logicPackageResourceName).toURI());
}
catch (URISyntaxException e) {
throw new BatfishException("Failed to resolve logic output directory",
e);
}
Path logicSrcDirPath = Paths.get(_settings.getLogicSrcDir());
final Set<Path> logicFiles = new TreeSet<Path>();
try {
Files.walkFileTree(logicSrcDirPath,
new java.nio.file.SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
String name = file.getFileName().toString();
if (!name.equals("BaseFacts.logic")
&& !name.endsWith("_rules.logic")
&& !name.startsWith("service_")
&& name.endsWith(".logic")) {
logicFiles.add(file);
}
return super.visitFile(file, attrs);
}
});
}
catch (IOException e) {
throw new BatfishException("Could not make list of logic files", e);
}
PredicateValueTypeMap predicateValueTypes = new PredicateValueTypeMap();
QualifiedNameMap qualifiedNameMap = new QualifiedNameMap();
FunctionSet functions = new FunctionSet();
PredicateSemantics predicateSemantics = new PredicateSemantics();
List<ParserRuleContext> trees = new ArrayList<ParserRuleContext>();
for (Path logicFilePath : logicFiles) {
String input = readFile(logicFilePath.toFile());
LogiQLCombinedParser parser = new LogiQLCombinedParser(input,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, logicFilePath.toString());
trees.add(tree);
}
ParseTreeWalker walker = new ParseTreeWalker();
for (ParserRuleContext tree : trees) {
LogQLPredicateInfoExtractor extractor = new LogQLPredicateInfoExtractor(
predicateValueTypes);
walker.walk(extractor, tree);
}
for (ParserRuleContext tree : trees) {
LogiQLPredicateInfoResolver resolver = new LogiQLPredicateInfoResolver(
predicateValueTypes, qualifiedNameMap, functions,
predicateSemantics);
walker.walk(resolver, tree);
}
PredicateInfo predicateInfo = new PredicateInfo(predicateSemantics,
predicateValueTypes, functions, qualifiedNameMap);
File predicateInfoFile = logicBinDirPath.resolve(PREDICATE_INFO_FILENAME)
.toFile();
serializeObject(predicateInfo, predicateInfoFile);
}
private void cleanupLogicDir() {
if (_tmpLogicDir != null) {
try {
FileUtils.deleteDirectory(_tmpLogicDir);
}
catch (IOException e) {
throw new BatfishException(
"Error cleaning up temporary logic directory", e);
}
_tmpLogicDir = null;
}
}
@Override
public void close() throws Exception {
for (LogicBloxFrontend lbFrontend : _lbFrontends) {
// Close backend threads
if (lbFrontend != null && lbFrontend.connected()) {
lbFrontend.close();
}
}
}
private void computeDataPlane(LogicBloxFrontend lbFrontend) {
_logger.info("\n*** COMPUTING DATA PLANE STRUCTURES ***\n");
resetTimer();
lbFrontend.initEntityTable();
_logger.info("Retrieving flow sink information from LogicBlox...");
FlowSinkSet flowSinks = getFlowSinkSet(lbFrontend);
_logger.info("OK\n");
_logger.info("Retrieving topology information from LogicBlox...");
EdgeSet topologyEdges = getTopologyEdges(lbFrontend);
_logger.info("OK\n");
String fibQualifiedName = _predicateInfo.getPredicateNames().get(
FIB_PREDICATE_NAME);
_logger
.info("Retrieving destination-routing FIB information from LogicBlox...");
Relation fibNetwork = lbFrontend.queryPredicate(fibQualifiedName);
_logger.info("OK\n");
String fibPolicyRouteNextHopQualifiedName = _predicateInfo
.getPredicateNames().get(FIB_POLICY_ROUTE_NEXT_HOP_PREDICATE_NAME);
_logger
.info("Retrieving policy-routing FIB information from LogicBlox...");
Relation fibPolicyRouteNextHops = lbFrontend
.queryPredicate(fibPolicyRouteNextHopQualifiedName);
_logger.info("OK\n");
_logger.info("Caclulating forwarding rules...");
FibMap fibs = getRouteForwardingRules(fibNetwork, lbFrontend);
PolicyRouteFibNodeMap policyRouteFibNodeMap = getPolicyRouteFibNodeMap(
fibPolicyRouteNextHops, lbFrontend);
_logger.info("OK\n");
Path flowSinksPath = Paths.get(_settings.getDataPlaneDir(),
FLOW_SINKS_FILENAME);
new File(_settings.getDataPlaneDir()).mkdirs();
Path fibsPath = Paths.get(_settings.getDataPlaneDir(), FIBS_FILENAME);
Path fibsPolicyRoutePath = Paths.get(_settings.getDataPlaneDir(),
FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME);
Path edgesPath = Paths.get(_settings.getDataPlaneDir(), EDGES_FILENAME);
_logger.info("Serializing flow sink set...");
serializeObject(flowSinks, flowSinksPath.toFile());
_logger.info("OK\n");
_logger.info("Serializing fibs...");
serializeObject(fibs, fibsPath.toFile());
_logger.info("OK\n");
_logger.info("Serializing policy route next hop interface map...");
serializeObject(policyRouteFibNodeMap, fibsPolicyRoutePath.toFile());
_logger.info("OK\n");
_logger.info("Serializing toplogy edges...");
serializeObject(topologyEdges, edgesPath.toFile());
_logger.info("OK\n");
printElapsedTime();
}
private Set<String> computeNodOutput(Synthesizer dataPlane,
List<QuerySynthesizer> queries,
Map<QuerySynthesizer, NodeSet> queryNodes) {
Set<String> facts = new TreeSet<String>();
int numConcurrentThreads = Runtime.getRuntime().availableProcessors();
ExecutorService pool = Executors.newFixedThreadPool(numConcurrentThreads);
// ExecutorService pool = Executors.newSingleThreadExecutor();
Set<NodJob> jobs = new HashSet<NodJob>();
for (final QuerySynthesizer query : queries) {
NodeSet nodes = queryNodes.get(query);
NodJob job = new NodJob(dataPlane, query, nodes);
jobs.add(job);
}
List<Future<NodJobResult>> results;
try {
results = pool.invokeAll(jobs);
}
catch (InterruptedException e) {
throw new BatfishException("Nod executor service interrupted", e);
}
for (Future<NodJobResult> future : results) {
try {
NodJobResult result = future.get();
if (result.terminatedSuccessfully()) {
facts.addAll(result.getFlowLines());
}
else {
Throwable failureCause = result.getFailureCause();
if (failureCause != null) {
throw new BatfishException("Failure running nod job",
failureCause);
}
else {
throw new BatfishException("Unknown failure running nod job");
}
}
}
catch (InterruptedException e) {
throw new BatfishException("Nod job interrupted", e);
}
catch (ExecutionException e) {
throw new BatfishException("Could not execute nod job", e);
}
}
pool.shutdown();
return facts;
}
private void concretize() {
_logger.info("\n*** GENERATING Z3 CONCRETIZER QUERIES ***\n");
resetTimer();
String[] concInPaths = _settings.getConcretizerInputFilePaths();
String[] negConcInPaths = _settings.getNegatedConcretizerInputFilePaths();
List<ConcretizerQuery> concretizerQueries = new ArrayList<ConcretizerQuery>();
String blacklistDstIpPath = _settings.getBlacklistDstIpPath();
if (blacklistDstIpPath != null) {
String blacklistDstIpFileText = readFile(new File(blacklistDstIpPath));
String[] blacklistDstpIpStrs = blacklistDstIpFileText.split("\n");
Set<Ip> blacklistDstIps = new TreeSet<Ip>();
for (String blacklistDstIpStr : blacklistDstpIpStrs) {
Ip blacklistDstIp = new Ip(blacklistDstIpStr);
blacklistDstIps.add(blacklistDstIp);
}
if (blacklistDstIps.size() == 0) {
_logger.warn("Warning: empty set of blacklisted destination ips\n");
}
ConcretizerQuery blacklistIpQuery = ConcretizerQuery
.blacklistDstIpQuery(blacklistDstIps);
concretizerQueries.add(blacklistIpQuery);
}
for (String concInPath : concInPaths) {
_logger.info("Reading z3 datalog query output file: \"" + concInPath
+ "\"...");
File queryOutputFile = new File(concInPath);
String queryOutputStr = readFile(queryOutputFile);
_logger.info("OK\n");
DatalogQueryResultCombinedParser parser = new DatalogQueryResultCombinedParser(
queryOutputStr, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, concInPath);
_logger.info("Computing concretizer queries...");
ParseTreeWalker walker = new ParseTreeWalker();
DatalogQueryResultExtractor extractor = new DatalogQueryResultExtractor(
_settings.concretizeUnique(), false);
walker.walk(extractor, tree);
_logger.info("OK\n");
List<ConcretizerQuery> currentQueries = extractor
.getConcretizerQueries();
if (concretizerQueries.size() == 0) {
concretizerQueries.addAll(currentQueries);
}
else {
concretizerQueries = ConcretizerQuery.crossProduct(
concretizerQueries, currentQueries);
}
}
if (negConcInPaths != null) {
for (String negConcInPath : negConcInPaths) {
_logger
.info("Reading z3 datalog query output file (to be negated): \""
+ negConcInPath + "\"...");
File queryOutputFile = new File(negConcInPath);
String queryOutputStr = readFile(queryOutputFile);
_logger.info("OK\n");
DatalogQueryResultCombinedParser parser = new DatalogQueryResultCombinedParser(
queryOutputStr, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, negConcInPath);
_logger.info("Computing concretizer queries...");
ParseTreeWalker walker = new ParseTreeWalker();
DatalogQueryResultExtractor extractor = new DatalogQueryResultExtractor(
_settings.concretizeUnique(), true);
walker.walk(extractor, tree);
_logger.info("OK\n");
List<ConcretizerQuery> currentQueries = extractor
.getConcretizerQueries();
if (concretizerQueries.size() == 0) {
concretizerQueries.addAll(currentQueries);
}
else {
concretizerQueries = ConcretizerQuery.crossProduct(
concretizerQueries, currentQueries);
}
}
}
for (int i = 0; i < concretizerQueries.size(); i++) {
ConcretizerQuery cq = concretizerQueries.get(i);
String concQueryPath = _settings.getConcretizerOutputFilePath() + "-"
+ i + ".smt2";
_logger.info("Writing concretizer query file: \"" + concQueryPath
+ "\"...");
writeFile(concQueryPath, cq.getText());
_logger.info("OK\n");
}
printElapsedTime();
}
private LogicBloxFrontend connect() {
boolean assumedToExist = !_settings.createWorkspace();
String workspaceMaster = _settings.getWorkspaceName();
if (assumedToExist) {
String jobLogicBloxHostnamePath = _settings
.getJobLogicBloxHostnamePath();
if (jobLogicBloxHostnamePath != null) {
String lbHostname = readFile(new File(jobLogicBloxHostnamePath));
_settings.setConnectBloxHost(lbHostname);
}
}
else {
String serviceLogicBloxHostname = _settings
.getServiceLogicBloxHostname();
if (serviceLogicBloxHostname != null) {
_settings.setConnectBloxHost(serviceLogicBloxHostname);
}
}
LogicBloxFrontend lbFrontend = null;
try {
lbFrontend = initFrontend(assumedToExist, workspaceMaster);
}
catch (LBInitializationException e) {
throw new BatfishException("Failed to connect to LogicBlox", e);
}
return lbFrontend;
}
private Map<String, Configuration> convertConfigurations(
Map<String, VendorConfiguration> vendorConfigurations) {
boolean processingError = false;
Map<String, Configuration> configurations = new TreeMap<String, Configuration>();
_logger
.info("\n*** CONVERTING VENDOR CONFIGURATIONS TO INDEPENDENT FORMAT ***\n");
resetTimer();
boolean pedanticAsError = _settings.getPedanticAsError();
boolean pedanticRecord = _settings.getPedanticRecord();
boolean redFlagAsError = _settings.getRedFlagAsError();
boolean redFlagRecord = _settings.getRedFlagRecord();
boolean unimplementedAsError = _settings.getUnimplementedAsError();
boolean unimplementedRecord = _settings.getUnimplementedRecord();
for (String name : vendorConfigurations.keySet()) {
_logger.debug("Processing: \"" + name + "\"");
VendorConfiguration vc = vendorConfigurations.get(name);
Warnings warnings = new Warnings(pedanticAsError, pedanticRecord,
redFlagAsError, redFlagRecord, unimplementedAsError,
unimplementedRecord, false);
try {
Configuration config = vc
.toVendorIndependentConfiguration(warnings);
configurations.put(name, config);
_logger.debug(" ...OK\n");
}
catch (BatfishException e) {
_logger.fatal("...CONVERSION ERROR\n");
_logger.fatal(ExceptionUtils.getStackTrace(e));
processingError = true;
if (_settings.getExitOnFirstError()) {
break;
}
else {
continue;
}
}
finally {
for (String warning : warnings.getRedFlagWarnings()) {
_logger.redflag(warning);
}
for (String warning : warnings.getUnimplementedWarnings()) {
_logger.unimplemented(warning);
}
for (String warning : warnings.getPedanticWarnings()) {
_logger.pedantic(warning);
}
}
}
if (processingError) {
throw new BatfishException("Vendor conversion error(s)");
}
else {
printElapsedTime();
return configurations;
}
}
public Map<String, Configuration> deserializeConfigurations(
String serializedConfigPath) {
_logger
.info("\n*** DESERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
Map<String, Configuration> configurations = new TreeMap<String, Configuration>();
File dir = new File(serializedConfigPath);
File[] serializedConfigs = dir.listFiles();
if (serializedConfigs == null) {
throw new BatfishException(
"Error reading vendor-independent configs directory: \""
+ dir.toString() + "\"");
}
for (File serializedConfig : serializedConfigs) {
String name = serializedConfig.getName();
_logger.debug("Reading config: \"" + serializedConfig + "\"");
Object object = deserializeObject(serializedConfig);
Configuration c = (Configuration) object;
configurations.put(name, c);
_logger.debug(" ...OK\n");
}
disableBlacklistedInterface(configurations);
disableBlacklistedNode(configurations);
printElapsedTime();
return configurations;
}
private Object deserializeObject(File inputFile) {
FileInputStream fis;
Object o = null;
ObjectInputStream ois;
try {
fis = new FileInputStream(inputFile);
if (!isJavaSerializationData(inputFile)) {
XStream xstream = new XStream(new DomDriver("UTF-8"));
ois = xstream.createObjectInputStream(fis);
}
else {
ois = new ObjectInputStream(fis);
}
o = ois.readObject();
ois.close();
}
catch (IOException | ClassNotFoundException e) {
throw new BatfishException("Failed to deserialize object from file: "
+ inputFile.toString(), e);
}
return o;
}
public Map<String, VendorConfiguration> deserializeVendorConfigurations(
String serializedVendorConfigPath) {
_logger.info("\n*** DESERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<String, VendorConfiguration>();
File dir = new File(serializedVendorConfigPath);
File[] serializedConfigs = dir.listFiles();
if (serializedConfigs == null) {
throw new BatfishException("Error reading vendor configs directory");
}
for (File serializedConfig : serializedConfigs) {
String name = serializedConfig.getName();
_logger.debug("Reading vendor config: \"" + serializedConfig + "\"");
Object object = deserializeObject(serializedConfig);
VendorConfiguration vc = (VendorConfiguration) object;
vendorConfigurations.put(name, vc);
_logger.debug("...OK\n");
}
printElapsedTime();
return vendorConfigurations;
}
private void disableBlacklistedInterface(
Map<String, Configuration> configurations) {
String blacklistInterfaceString = _settings.getBlacklistInterfaceString();
if (blacklistInterfaceString != null) {
String[] blacklistInterfaceStringParts = blacklistInterfaceString
.split(",");
String blacklistInterfaceNode = blacklistInterfaceStringParts[0];
String blacklistInterfaceName = blacklistInterfaceStringParts[1];
Configuration c = configurations.get(blacklistInterfaceNode);
Interface i = c.getInterfaces().get(blacklistInterfaceName);
i.setActive(false);
}
}
private void disableBlacklistedNode(Map<String, Configuration> configurations) {
String blacklistNode = _settings.getBlacklistNode();
if (blacklistNode != null) {
if (!configurations.containsKey(blacklistNode)) {
throw new BatfishException("Cannot blacklist non-existent node: "
+ blacklistNode);
}
Configuration configuration = configurations.get(blacklistNode);
for (Interface iface : configuration.getInterfaces().values()) {
iface.setActive(false);
}
}
}
private void dumpFacts(Map<String, StringBuilder> factBins) {
_logger.info("\n*** DUMPING FACTS ***\n");
resetTimer();
Path factsDir = Paths.get(_settings.getDumpFactsDir());
try {
Files.createDirectories(factsDir);
for (String factsFilename : factBins.keySet()) {
String facts = factBins.get(factsFilename).toString();
Path factsFilePath = factsDir.resolve(factsFilename);
_logger.info("Writing: \""
+ factsFilePath.toAbsolutePath().toString() + "\"\n");
FileUtils.write(factsFilePath.toFile(), facts);
}
}
catch (IOException e) {
throw new BatfishException("Failed to write fact dump file", e);
}
printElapsedTime();
}
private void dumpInterfaceDescriptions(String testRigPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> configs = parseVendorConfigurations(configurationData);
Map<String, VendorConfiguration> sortedConfigs = new TreeMap<String, VendorConfiguration>();
sortedConfigs.putAll(configs);
StringBuilder sb = new StringBuilder();
for (VendorConfiguration vconfig : sortedConfigs.values()) {
String node = vconfig.getHostname();
CiscoVendorConfiguration config = null;
try {
config = (CiscoVendorConfiguration) vconfig;
}
catch (ClassCastException e) {
continue;
}
Map<String, org.batfish.representation.cisco.Interface> sortedInterfaces = new TreeMap<String, org.batfish.representation.cisco.Interface>();
sortedInterfaces.putAll(config.getInterfaces());
for (org.batfish.representation.cisco.Interface iface : sortedInterfaces
.values()) {
String iname = iface.getName();
String description = iface.getDescription();
sb.append(node + " " + iname);
if (description != null) {
sb.append(" \"" + description + "\"");
}
sb.append("\n");
}
}
String output = sb.toString();
writeFile(outputPath, output);
}
private void flatten(String inputPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(inputPath);
Map<File, String> outputConfigurationData = new TreeMap<File, String>();
File inputFolder = new File(inputPath);
File[] configs = inputFolder.listFiles();
if (configs == null) {
throw new BatfishException("Error reading configs from input test rig");
}
try {
Files.createDirectories(Paths.get(outputPath));
}
catch (IOException e) {
throw new BatfishException(
"Could not create output testrig directory", e);
}
_logger.info("\n*** FLATTENING TEST RIG ***\n");
resetTimer();
ExecutorService pool;
boolean shuffle;
if (!_settings.getSequential()) {
int numConcurrentThreads = Runtime.getRuntime().availableProcessors();
pool = Executors.newFixedThreadPool(numConcurrentThreads);
shuffle = true;
}
else {
pool = Executors.newSingleThreadExecutor();
shuffle = false;
}
List<FlattenVendorConfigurationJob> jobs = new ArrayList<FlattenVendorConfigurationJob>();
boolean processingError = false;
for (File inputFile : configurationData.keySet()) {
Warnings warnings = new Warnings(_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(), _settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(inputFile);
String name = inputFile.getName();
File outputFile = Paths.get(outputPath,
TESTRIG_CONFIGURATION_DIRECTORY, name).toFile();
FlattenVendorConfigurationJob job = new FlattenVendorConfigurationJob(
_settings, fileText, inputFile, outputFile, warnings);
jobs.add(job);
}
if (shuffle) {
Collections.shuffle(jobs);
}
List<Future<FlattenVendorConfigurationResult>> futures = new ArrayList<Future<FlattenVendorConfigurationResult>>();
for (FlattenVendorConfigurationJob job : jobs) {
Future<FlattenVendorConfigurationResult> future = pool.submit(job);
futures.add(future);
}
while (!futures.isEmpty()) {
List<Future<FlattenVendorConfigurationResult>> currentFutures = new ArrayList<Future<FlattenVendorConfigurationResult>>();
currentFutures.addAll(futures);
for (Future<FlattenVendorConfigurationResult> future : currentFutures) {
if (future.isDone()) {
futures.remove(future);
FlattenVendorConfigurationResult result = null;
try {
result = future.get();
}
catch (InterruptedException | ExecutionException e) {
throw new BatfishException("Error executing parse job", e);
}
_logger.append(result.getHistory());
Throwable failureCause = result.getFailureCause();
if (failureCause != null) {
if (_settings.getExitOnFirstError()) {
throw new BatfishException("Failed parse job",
failureCause);
}
else {
processingError = true;
_logger.error(ExceptionUtils.getStackTrace(failureCause));
}
}
else {
File outputFile = result.getOutputFile();
String flattenedText = result.getFlattenedText();
outputConfigurationData.put(outputFile, flattenedText);
}
}
else {
continue;
}
}
if (!futures.isEmpty()) {
try {
Thread.sleep(JOB_POLLING_PERIOD_MS);
}
catch (InterruptedException e) {
throw new BatfishException("interrupted while sleeping", e);
}
}
}
pool.shutdown();
if (processingError) {
throw new BatfishException("Error flattening vendor configurations");
}
else {
printElapsedTime();
}
for (Entry<File, String> e : outputConfigurationData.entrySet()) {
File outputFile = e.getKey();
String flatConfigText = e.getValue();
String outputFileAsString = outputFile.toString();
_logger.debug("Writing config to \"" + outputFileAsString + "\"...");
writeFile(outputFileAsString, flatConfigText);
_logger.debug("OK\n");
}
Path inputTopologyPath = Paths.get(inputPath, TOPOLOGY_FILENAME);
Path outputTopologyPath = Paths.get(outputPath, TOPOLOGY_FILENAME);
if (Files.isRegularFile(inputTopologyPath)) {
String topologyFileText = readFile(inputTopologyPath.toFile());
writeFile(outputTopologyPath.toString(), topologyFileText);
}
}
private void genBlackHoleQueries() {
_logger.info("\n*** GENERATING BLACK-HOLE QUERIES ***\n");
resetTimer();
String fiQueryBasePath = _settings.getBlackHoleQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
QuerySynthesizer synth = new FailureInconsistencyBlackHoleQuerySynthesizer(
hostname);
String queryText = synth.getQueryText();
String fiQueryPath;
fiQueryPath = fiQueryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + fiQueryPath + "\"...");
writeFile(fiQueryPath, queryText);
_logger.info("OK\n");
}
printElapsedTime();
}
private void generateOspfConfigs(String topologyPath, String outputPath) {
File topologyFilePath = new File(topologyPath);
Topology topology = parseTopology(topologyFilePath);
Map<String, Configuration> configs = new TreeMap<String, Configuration>();
NodeSet allNodes = new NodeSet();
Map<NodeInterfacePair, Set<NodeInterfacePair>> interfaceMap = new HashMap<NodeInterfacePair, Set<NodeInterfacePair>>();
// first we collect set of all mentioned nodes, and build mapping from
// each interface to the set of interfaces that connect to each other
for (Edge edge : topology.getEdges()) {
allNodes.add(edge.getNode1());
allNodes.add(edge.getNode2());
NodeInterfacePair interface1 = new NodeInterfacePair(edge.getNode1(),
edge.getInt1());
NodeInterfacePair interface2 = new NodeInterfacePair(edge.getNode2(),
edge.getInt2());
Set<NodeInterfacePair> interfaceSet = interfaceMap.get(interface1);
if (interfaceSet == null) {
interfaceSet = new HashSet<NodeInterfacePair>();
}
interfaceMap.put(interface1, interfaceSet);
interfaceMap.put(interface2, interfaceSet);
interfaceSet.add(interface1);
interfaceSet.add(interface2);
}
// then we create configs for every mentioned node
for (String hostname : allNodes) {
Configuration config = new Configuration(hostname);
configs.put(hostname, config);
}
// Now we create interfaces for each edge and record the number of
// neighbors so we know how large to make the subnet
long currentStartingIpAsLong = new Ip(GEN_OSPF_STARTING_IP).asLong();
Set<Set<NodeInterfacePair>> interfaceSets = new HashSet<Set<NodeInterfacePair>>();
interfaceSets.addAll(interfaceMap.values());
for (Set<NodeInterfacePair> interfaceSet : interfaceSets) {
int numInterfaces = interfaceSet.size();
if (numInterfaces < 2) {
throw new BatfishException(
"The following interface set contains less than two interfaces: "
+ interfaceSet.toString());
}
int numHostBits = 0;
for (int shiftedValue = numInterfaces - 1; shiftedValue != 0; shiftedValue >>= 1, numHostBits++) {
}
int subnetBits = 32 - numHostBits;
int offset = 0;
for (NodeInterfacePair currentPair : interfaceSet) {
Ip ip = new Ip(currentStartingIpAsLong + offset);
Prefix prefix = new Prefix(ip, subnetBits);
String ifaceName = currentPair.getInterface();
Interface iface = new Interface(ifaceName);
iface.setPrefix(prefix);
// dirty hack for setting bandwidth for now
double ciscoBandwidth = org.batfish.representation.cisco.Interface
.getDefaultBandwidth(ifaceName);
double juniperBandwidth = org.batfish.representation.juniper.Interface
.getDefaultBandwidthByName(ifaceName);
double bandwidth = Math.min(ciscoBandwidth, juniperBandwidth);
iface.setBandwidth(bandwidth);
String hostname = currentPair.getHostname();
Configuration config = configs.get(hostname);
config.getInterfaces().put(ifaceName, iface);
offset++;
}
currentStartingIpAsLong += (1 << numHostBits);
}
for (Configuration config : configs.values()) {
// use cisco arbitrarily
config.setVendor(ConfigurationFormat.CISCO);
OspfProcess proc = new OspfProcess();
config.setOspfProcess(proc);
proc.setReferenceBandwidth(org.batfish.representation.cisco.OspfProcess.DEFAULT_REFERENCE_BANDWIDTH);
long backboneArea = 0;
OspfArea area = new OspfArea(backboneArea);
proc.getAreas().put(backboneArea, area);
area.getInterfaces().addAll(config.getInterfaces().values());
}
serializeIndependentConfigs(configs, outputPath);
}
private void generateStubs(String inputRole, int stubAs,
String interfaceDescriptionRegex, String configPath) {
Map<String, Configuration> configs = deserializeConfigurations(configPath);
Pattern pattern = Pattern.compile(interfaceDescriptionRegex);
Map<String, Configuration> stubConfigurations = new TreeMap<String, Configuration>();
_logger.info("\n*** GENERATING STUBS ***\n");
resetTimer();
// load old node-roles to be updated at end
RoleSet stubRoles = new RoleSet();
stubRoles.add(STUB_ROLE);
File nodeRolesPath = new File(_settings.getNodeRolesPath());
_logger.info("Deserializing old node-roles mappings: \"" + nodeRolesPath
+ "\" ...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(nodeRolesPath);
_logger.info("OK\n");
// create origination policy common to all stubs
String stubOriginationPolicyName = "~STUB_ORIGINATION_POLICY~";
PolicyMap stubOriginationPolicy = new PolicyMap(stubOriginationPolicyName);
PolicyMapClause clause = new PolicyMapClause();
stubOriginationPolicy.getClauses().add(clause);
String stubOriginationRouteFilterListName = "~STUB_ORIGINATION_ROUTE_FILTER~";
RouteFilterList rf = new RouteFilterList(
stubOriginationRouteFilterListName);
RouteFilterLine rfl = new RouteFilterLine(LineAction.ACCEPT, Prefix.ZERO,
new SubRange(0, 0));
rf.addLine(rfl);
PolicyMapMatchRouteFilterListLine matchLine = new PolicyMapMatchRouteFilterListLine(
Collections.singleton(rf));
clause.getMatchLines().add(matchLine);
clause.setAction(PolicyMapAction.PERMIT);
// create flow sink interface common to all stubs
String flowSinkName = "TenGibabitEthernet100/100";
Interface flowSink = new Interface(flowSinkName);
flowSink.setPrefix(Prefix.ZERO);
flowSink.setActive(true);
flowSink.setBandwidth(10E9d);
Set<String> skipWarningNodes = new HashSet<String>();
for (Configuration config : configs.values()) {
if (!config.getRoles().contains(inputRole)) {
continue;
}
for (BgpNeighbor neighbor : config.getBgpProcess().getNeighbors()
.values()) {
if (!neighbor.getRemoteAs().equals(stubAs)) {
continue;
}
Prefix neighborPrefix = neighbor.getPrefix();
if (neighborPrefix.getPrefixLength() != 32) {
throw new BatfishException(
"do not currently handle generating stubs based on dynamic bgp sessions");
}
Ip neighborAddress = neighborPrefix.getAddress();
int edgeAs = neighbor.getLocalAs();
/*
* Now that we have the ip address of the stub, we want to find the
* interface that connects to it. We will extract the hostname for
* the stub from the description of this interface using the
* supplied regex.
*/
boolean found = false;
for (Interface iface : config.getInterfaces().values()) {
Prefix prefix = iface.getPrefix();
if (prefix == null || !prefix.contains(neighborAddress)) {
continue;
}
// the neighbor address falls within the network assigned to this
// interface, so now we check the description
String description = iface.getDescription();
Matcher matcher = pattern.matcher(description);
if (matcher.find()) {
String hostname = matcher.group(1);
if (configs.containsKey(hostname)) {
Configuration duplicateConfig = configs.get(hostname);
if (!duplicateConfig.getRoles().contains(STUB_ROLE)
|| duplicateConfig.getRoles().size() != 1) {
throw new BatfishException(
"A non-generated node with hostname: \""
+ hostname
+ "\" already exists in network under analysis");
}
else {
if (!skipWarningNodes.contains(hostname)) {
_logger
.warn("WARNING: Overwriting previously generated node: \""
+ hostname + "\"\n");
skipWarningNodes.add(hostname);
}
}
}
found = true;
Configuration stub = stubConfigurations.get(hostname);
// create stub if it doesn't exist yet
if (stub == null) {
stub = new Configuration(hostname);
stubConfigurations.put(hostname, stub);
stub.getInterfaces().put(flowSinkName, flowSink);
stub.setBgpProcess(new BgpProcess());
stub.getPolicyMaps().put(stubOriginationPolicyName,
stubOriginationPolicy);
stub.getRouteFilterLists().put(
stubOriginationRouteFilterListName, rf);
stub.setVendor(ConfigurationFormat.CISCO);
stub.setRoles(stubRoles);
nodeRoles.put(hostname, stubRoles);
}
// create interface that will on which peering will occur
Map<String, Interface> stubInterfaces = stub.getInterfaces();
String stubInterfaceName = "TenGigabitEthernet0/"
+ (stubInterfaces.size() - 1);
Interface stubInterface = new Interface(stubInterfaceName);
stubInterfaces.put(stubInterfaceName, stubInterface);
stubInterface.setPrefix(new Prefix(neighborAddress, prefix
.getPrefixLength()));
stubInterface.setActive(true);
stubInterface.setBandwidth(10E9d);
// create neighbor within bgp process
BgpNeighbor edgeNeighbor = new BgpNeighbor(prefix);
edgeNeighbor.getOriginationPolicies().add(
stubOriginationPolicy);
edgeNeighbor.setRemoteAs(edgeAs);
edgeNeighbor.setLocalAs(stubAs);
edgeNeighbor.setSendCommunity(true);
edgeNeighbor.setDefaultMetric(0);
stub.getBgpProcess().getNeighbors()
.put(edgeNeighbor.getPrefix(), edgeNeighbor);
break;
}
else {
throw new BatfishException(
"Unable to derive stub hostname from interface description: \""
+ description + "\" using regex: \""
+ interfaceDescriptionRegex + "\"");
}
}
if (!found) {
throw new BatfishException(
"Could not determine stub hostname corresponding to ip: \""
+ neighborAddress.toString()
+ "\" listed as neighbor on router: \""
+ config.getHostname() + "\"");
}
}
}
// write updated node-roles mappings to disk
_logger.info("Serializing updated node-roles mappings: \""
+ nodeRolesPath + "\" ...");
serializeObject(nodeRoles, nodeRolesPath);
_logger.info("OK\n");
printElapsedTime();
// write stubs to disk
serializeIndependentConfigs(stubConfigurations, configPath);
}
private void genMultipathQueries() {
_logger.info("\n*** GENERATING MULTIPATH-INCONSISTENCY QUERIES ***\n");
resetTimer();
String mpiQueryBasePath = _settings.getMultipathInconsistencyQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
QuerySynthesizer synth = new MultipathInconsistencyQuerySynthesizer(
hostname);
String queryText = synth.getQueryText();
String mpiQueryPath = mpiQueryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + mpiQueryPath + "\"...");
writeFile(mpiQueryPath, queryText);
_logger.info("OK\n");
}
_logger.info("Writing node lines for next stage...");
StringBuilder sb = new StringBuilder();
for (String node : nodes) {
sb.append(node + "\n");
}
writeFile(nodeSetTextPath, sb.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genReachableQueries() {
_logger.info("\n*** GENERATING REACHABLE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getReachableQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String acceptNode = _settings.getAcceptNode();
String blacklistedNode = _settings.getBlacklistNode();
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
for (String hostname : nodes) {
if (hostname.equals(acceptNode) || hostname.equals(blacklistedNode)) {
continue;
}
QuerySynthesizer synth = new ReachableQuerySynthesizer(hostname,
acceptNode);
String queryText = synth.getQueryText();
String queryPath;
queryPath = queryBasePath + "-" + hostname + ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
printElapsedTime();
}
private void genRoleReachabilityQueries() {
_logger.info("\n*** GENERATING NODE-TO-ROLE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getRoleReachabilityQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
String roleSetTextPath = _settings.getRoleSetPath();
String nodeRolesPath = _settings.getNodeRolesPath();
String iterationsPath = nodeRolesPath + ".iterations";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
_logger.info("Reading node roles from: \"" + nodeRolesPath + "\"...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
_logger.info("OK\n");
RoleNodeMap roleNodes = nodeRoles.toRoleNodeMap();
for (String hostname : nodes) {
for (String role : roleNodes.keySet()) {
QuerySynthesizer synth = new RoleReachabilityQuerySynthesizer(
hostname, role);
String queryText = synth.getQueryText();
String queryPath = queryBasePath + "-" + hostname + "-" + role
+ ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
}
_logger.info("Writing node lines for next stage...");
StringBuilder sbNodes = new StringBuilder();
for (String node : nodes) {
sbNodes.append(node + "\n");
}
writeFile(nodeSetTextPath, sbNodes.toString());
_logger.info("OK\n");
StringBuilder sbRoles = new StringBuilder();
_logger.info("Writing role lines for next stage...");
sbRoles = new StringBuilder();
for (String role : roleNodes.keySet()) {
sbRoles.append(role + "\n");
}
writeFile(roleSetTextPath, sbRoles.toString());
_logger.info("OK\n");
_logger
.info("Writing role-node-role iteration ordering lines for concretizer stage...");
StringBuilder sbIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transmittingRole = roleNodeEntry.getKey();
NodeSet transmittingNodes = roleNodeEntry.getValue();
if (transmittingNodes.size() < 2) {
continue;
}
String[] tNodeArray = transmittingNodes.toArray(new String[] {});
String masterNode = tNodeArray[0];
for (int i = 1; i < tNodeArray.length; i++) {
String slaveNode = tNodeArray[i];
for (String receivingRole : roleNodes.keySet()) {
String iterationLine = transmittingRole + ":" + masterNode + ":"
+ slaveNode + ":" + receivingRole + "\n";
sbIterations.append(iterationLine);
}
}
}
writeFile(iterationsPath, sbIterations.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genRoleTransitQueries() {
_logger.info("\n*** GENERATING ROLE-TO-NODE QUERIES ***\n");
resetTimer();
String queryBasePath = _settings.getRoleTransitQueryPath();
String nodeSetPath = _settings.getNodeSetPath();
String nodeSetTextPath = nodeSetPath + ".txt";
String roleSetTextPath = _settings.getRoleSetPath();
String nodeRolesPath = _settings.getNodeRolesPath();
String roleNodesPath = _settings.getRoleNodesPath();
String iterationsPath = nodeRolesPath + ".rtiterations";
String constraintsIterationsPath = nodeRolesPath
+ ".rtconstraintsiterations";
_logger.info("Reading node set from: \"" + nodeSetPath + "\"...");
NodeSet nodes = (NodeSet) deserializeObject(new File(nodeSetPath));
_logger.info("OK\n");
_logger.info("Reading node roles from: \"" + nodeRolesPath + "\"...");
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
_logger.info("OK\n");
RoleNodeMap roleNodes = nodeRoles.toRoleNodeMap();
for (Entry<String, NodeSet> sourceEntry : roleNodes.entrySet()) {
String sourceRole = sourceEntry.getKey();
for (Entry<String, NodeSet> transitEntry : roleNodes.entrySet()) {
String transitRole = transitEntry.getKey();
if (transitRole.equals(sourceRole)) {
continue;
}
NodeSet transitNodes = transitEntry.getValue();
for (String transitNode : transitNodes) {
QuerySynthesizer synth = new RoleTransitQuerySynthesizer(
sourceRole, transitNode);
String queryText = synth.getQueryText();
String queryPath = queryBasePath + "-" + transitNode + "-"
+ sourceRole + ".smt2";
_logger.info("Writing query to: \"" + queryPath + "\"...");
writeFile(queryPath, queryText);
_logger.info("OK\n");
}
}
}
_logger.info("Writing node lines for next stage...");
StringBuilder sbNodes = new StringBuilder();
for (String node : nodes) {
sbNodes.append(node + "\n");
}
writeFile(nodeSetTextPath, sbNodes.toString());
_logger.info("OK\n");
StringBuilder sbRoles = new StringBuilder();
_logger.info("Writing role lines for next stage...");
sbRoles = new StringBuilder();
for (String role : roleNodes.keySet()) {
sbRoles.append(role + "\n");
}
writeFile(roleSetTextPath, sbRoles.toString());
_logger.info("OK\n");
// not actually sure if this is necessary
StringBuilder sbRoleNodes = new StringBuilder();
_logger.info("Writing role-node mappings for concretizer stage...");
sbRoleNodes = new StringBuilder();
for (Entry<String, NodeSet> e : roleNodes.entrySet()) {
String role = e.getKey();
NodeSet currentNodes = e.getValue();
sbRoleNodes.append(role + ":");
for (String node : currentNodes) {
sbRoleNodes.append(node + ",");
}
sbRoleNodes.append(role + "\n");
}
writeFile(roleNodesPath, sbRoleNodes.toString());
_logger
.info("Writing transitrole-transitnode-sourcerole iteration ordering lines for constraints stage...");
StringBuilder sbConstraintsIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transitRole = roleNodeEntry.getKey();
NodeSet transitNodes = roleNodeEntry.getValue();
if (transitNodes.size() < 2) {
continue;
}
for (String sourceRole : roleNodes.keySet()) {
if (sourceRole.equals(transitRole)) {
continue;
}
for (String transitNode : transitNodes) {
String iterationLine = transitRole + ":" + transitNode + ":"
+ sourceRole + "\n";
sbConstraintsIterations.append(iterationLine);
}
}
}
writeFile(constraintsIterationsPath, sbConstraintsIterations.toString());
_logger.info("OK\n");
_logger
.info("Writing transitrole-master-slave-sourcerole iteration ordering lines for concretizer stage...");
StringBuilder sbIterations = new StringBuilder();
for (Entry<String, NodeSet> roleNodeEntry : roleNodes.entrySet()) {
String transitRole = roleNodeEntry.getKey();
NodeSet transitNodes = roleNodeEntry.getValue();
if (transitNodes.size() < 2) {
continue;
}
String[] tNodeArray = transitNodes.toArray(new String[] {});
String masterNode = tNodeArray[0];
for (int i = 1; i < tNodeArray.length; i++) {
String slaveNode = tNodeArray[i];
for (String sourceRole : roleNodes.keySet()) {
if (sourceRole.equals(transitRole)) {
continue;
}
String iterationLine = transitRole + ":" + masterNode + ":"
+ slaveNode + ":" + sourceRole + "\n";
sbIterations.append(iterationLine);
}
}
}
writeFile(iterationsPath, sbIterations.toString());
_logger.info("OK\n");
printElapsedTime();
}
private void genZ3(Map<String, Configuration> configurations) {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
String outputPath = _settings.getZ3File();
if (outputPath == null) {
throw new BatfishException("Need to specify output path for z3 logic");
}
String nodeSetPath = _settings.getNodeSetPath();
if (nodeSetPath == null) {
throw new BatfishException(
"Need to specify output path for serialized set of nodes in environment");
}
Path flowSinkSetPath = Paths.get(_settings.getDataPlaneDir(),
FLOW_SINKS_FILENAME);
Path fibsPath = Paths.get(_settings.getDataPlaneDir(), FIBS_FILENAME);
Path prFibsPath = Paths.get(_settings.getDataPlaneDir(),
FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME);
Path edgesPath = Paths.get(_settings.getDataPlaneDir(), EDGES_FILENAME);
_logger.info("Deserializing flow sink interface set: \""
+ flowSinkSetPath.toString() + "\"...");
FlowSinkSet flowSinks = (FlowSinkSet) deserializeObject(flowSinkSetPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing destination route fibs: \""
+ fibsPath.toString() + "\"...");
FibMap fibs = (FibMap) deserializeObject(fibsPath.toFile());
_logger.info("OK\n");
_logger.info("Deserializing policy route fibs: \""
+ prFibsPath.toString() + "\"...");
PolicyRouteFibNodeMap prFibs = (PolicyRouteFibNodeMap) deserializeObject(prFibsPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing toplogy edges: \"" + edgesPath.toString()
+ "\"...");
EdgeSet topologyEdges = (EdgeSet) deserializeObject(edgesPath.toFile());
_logger.info("OK\n");
_logger.info("Synthesizing Z3 logic...");
Synthesizer s = new Synthesizer(configurations, fibs, prFibs,
topologyEdges, _settings.getSimplify(), flowSinks);
String result = s.synthesize();
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
_logger.info("Writing Z3 logic: \"" + outputPath + "\"...");
File z3Out = new File(outputPath);
z3Out.delete();
writeFile(outputPath, result);
_logger.info("OK\n");
_logger.info("Serializing node set: \"" + nodeSetPath + "\"...");
NodeSet nodeSet = s.getNodeSet();
serializeObject(nodeSet, new File(nodeSetPath));
_logger.info("OK\n");
printElapsedTime();
}
public Map<String, Configuration> getConfigurations(
String serializedVendorConfigPath) {
Map<String, VendorConfiguration> vendorConfigurations = deserializeVendorConfigurations(serializedVendorConfigPath);
Map<String, Configuration> configurations = convertConfigurations(vendorConfigurations);
return configurations;
}
private double getElapsedTime(long beforeTime) {
long difference = System.currentTimeMillis() - beforeTime;
double seconds = difference / 1000d;
return seconds;
}
// private Set<Path> getMultipathQueryPaths(Path directory) {
// Set<Path> queryPaths = new TreeSet<Path>();
// try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(
// directory, new DirectoryStream.Filter<Path>() {
// @Override
// public boolean accept(Path path) throws IOException {
// String filename = path.getFileName().toString();
// return filename
// .startsWith(BfConsts.RELPATH_MULTIPATH_QUERY_PREFIX)
// && filename.endsWith(".smt2");
// for (Path path : directoryStream) {
// queryPaths.add(path);
// catch (IOException ex) {
// throw new BatfishException(
// "Could not list files in queries directory", ex);
// return queryPaths;
private FlowSinkSet getFlowSinkSet(LogicBloxFrontend lbFrontend) {
FlowSinkSet flowSinks = new FlowSinkSet();
String qualifiedName = _predicateInfo.getPredicateNames().get(
FLOW_SINK_PREDICATE_NAME);
Relation flowSinkRelation = lbFrontend.queryPredicate(qualifiedName);
List<String> nodes = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nodes,
flowSinkRelation.getColumns().get(0));
List<String> interfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, interfaces,
flowSinkRelation.getColumns().get(1));
for (int i = 0; i < nodes.size(); i++) {
String node = nodes.get(i);
String iface = interfaces.get(i);
FlowSinkInterface f = new FlowSinkInterface(node, iface);
flowSinks.add(f);
}
return flowSinks;
}
private List<String> getHelpPredicates(Map<String, String> predicateSemantics) {
Set<String> helpPredicateSet = new LinkedHashSet<String>();
_settings.getHelpPredicates();
if (_settings.getHelpPredicates() == null) {
helpPredicateSet.addAll(predicateSemantics.keySet());
}
else {
helpPredicateSet.addAll(_settings.getHelpPredicates());
}
List<String> helpPredicates = new ArrayList<String>();
helpPredicates.addAll(helpPredicateSet);
Collections.sort(helpPredicates);
return helpPredicates;
}
private PolicyRouteFibNodeMap getPolicyRouteFibNodeMap(
Relation fibPolicyRouteNextHops, LogicBloxFrontend lbFrontend) {
PolicyRouteFibNodeMap nodeMap = new PolicyRouteFibNodeMap();
List<String> nodeList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nodeList,
fibPolicyRouteNextHops.getColumns().get(0));
List<String> ipList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_IP, ipList,
fibPolicyRouteNextHops.getColumns().get(1));
List<String> outInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, outInterfaces,
fibPolicyRouteNextHops.getColumns().get(2));
List<String> inNodes = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, inNodes,
fibPolicyRouteNextHops.getColumns().get(3));
List<String> inInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, inInterfaces,
fibPolicyRouteNextHops.getColumns().get(4));
int size = nodeList.size();
for (int i = 0; i < size; i++) {
String nodeOut = nodeList.get(i);
String nodeIn = inNodes.get(i);
Ip ip = new Ip(ipList.get(i));
String ifaceOut = outInterfaces.get(i);
String ifaceIn = inInterfaces.get(i);
PolicyRouteFibIpMap ipMap = nodeMap.get(nodeOut);
if (ipMap == null) {
ipMap = new PolicyRouteFibIpMap();
nodeMap.put(nodeOut, ipMap);
}
EdgeSet edges = ipMap.get(ip);
if (edges == null) {
edges = new EdgeSet();
ipMap.put(ip, edges);
}
Edge newEdge = new Edge(nodeOut, ifaceOut, nodeIn, ifaceIn);
edges.add(newEdge);
}
return nodeMap;
}
public PredicateInfo getPredicateInfo(Map<String, String> logicFiles) {
// Get predicate semantics from rules file
_logger.info("\n*** PARSING PREDICATE INFO ***\n");
resetTimer();
String predicateInfoPath = getPredicateInfoPath();
PredicateInfo predicateInfo = (PredicateInfo) deserializeObject(new File(
predicateInfoPath));
printElapsedTime();
return predicateInfo;
}
private String getPredicateInfoPath() {
File logicDir = retrieveLogicDir();
return Paths.get(logicDir.toString(), PREDICATE_INFO_FILENAME).toString();
}
private FibMap getRouteForwardingRules(Relation fibNetworkForward,
LogicBloxFrontend lbFrontend) {
FibMap fibs = new FibMap();
List<String> nameList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nameList,
fibNetworkForward.getColumns().get(0));
List<String> networkList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_INDEX_NETWORK, networkList,
fibNetworkForward.getColumns().get(1));
List<String> interfaceList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, interfaceList,
fibNetworkForward.getColumns().get(2));
List<String> nextHopList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nextHopList,
fibNetworkForward.getColumns().get(3));
List<String> nextHopIntList = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, nextHopIntList,
fibNetworkForward.getColumns().get(4));
String currentHostname = "";
Map<String, Integer> startIndices = new HashMap<String, Integer>();
Map<String, Integer> endIndices = new HashMap<String, Integer>();
for (int i = 0; i < nameList.size(); i++) {
String currentRowHostname = nameList.get(i);
if (!currentHostname.equals(currentRowHostname)) {
if (i > 0) {
endIndices.put(currentHostname, i - 1);
}
currentHostname = currentRowHostname;
startIndices.put(currentHostname, i);
}
}
endIndices.put(currentHostname, nameList.size() - 1);
for (String hostname : startIndices.keySet()) {
FibSet fibRows = new FibSet();
fibs.put(hostname, fibRows);
int startIndex = startIndices.get(hostname);
int endIndex = endIndices.get(hostname);
for (int i = startIndex; i <= endIndex; i++) {
String networkStr = networkList.get(i);
Prefix prefix = new Prefix(networkStr);
String iface = interfaceList.get(i);
String nextHop = nextHopList.get(i);
String nextHopInt = nextHopIntList.get(i);
fibRows.add(new FibRow(prefix, iface, nextHop, nextHopInt));
}
}
return fibs;
}
private Map<String, String> getSemanticsFiles() {
final Map<String, String> semanticsFiles = new HashMap<String, String>();
File logicDirFile = retrieveLogicDir();
FileVisitor<Path> visitor = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
String pathString = file.toString();
if (pathString.endsWith(".semantics")) {
String contents = FileUtils.readFileToString(file.toFile());
semanticsFiles.put(pathString, contents);
}
return super.visitFile(file, attrs);
}
};
try {
Files.walkFileTree(Paths.get(logicDirFile.getAbsolutePath()), visitor);
}
catch (IOException e) {
e.printStackTrace();
}
cleanupLogicDir();
return semanticsFiles;
}
public EdgeSet getTopologyEdges(LogicBloxFrontend lbFrontend) {
EdgeSet edges = new EdgeSet();
String qualifiedName = _predicateInfo.getPredicateNames().get(
TOPOLOGY_PREDICATE_NAME);
Relation topologyRelation = lbFrontend.queryPredicate(qualifiedName);
List<String> fromRouters = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, fromRouters,
topologyRelation.getColumns().get(0));
List<String> fromInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, fromInterfaces,
topologyRelation.getColumns().get(1));
List<String> toRouters = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, toRouters,
topologyRelation.getColumns().get(2));
List<String> toInterfaces = new ArrayList<String>();
lbFrontend.fillColumn(LBValueType.ENTITY_REF_STRING, toInterfaces,
topologyRelation.getColumns().get(3));
for (int i = 0; i < fromRouters.size(); i++) {
if (Util.isLoopback(fromInterfaces.get(i))
|| Util.isLoopback(toInterfaces.get(i))) {
continue;
}
Edge newEdge = new Edge(fromRouters.get(i), fromInterfaces.get(i),
toRouters.get(i), toInterfaces.get(i));
edges.add(newEdge);
}
return edges;
}
private void histogram(String testRigPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(configurationData);
_logger.info("Building feature histogram...");
MultiSet<String> histogram = new TreeMultiSet<String>();
for (VendorConfiguration vc : vendorConfigurations.values()) {
Set<String> unimplementedFeatures = vc.getUnimplementedFeatures();
histogram.add(unimplementedFeatures);
}
_logger.info("OK\n");
for (String feature : histogram.elements()) {
int count = histogram.count(feature);
_logger.output(feature + ": " + count + "\n");
}
}
public LogicBloxFrontend initFrontend(boolean assumedToExist,
String workspace) throws LBInitializationException {
_logger.info("\n*** STARTING CONNECTBLOX SESSION ***\n");
resetTimer();
LogicBloxFrontend lbFrontend = new LogicBloxFrontend(
_settings.getConnectBloxHost(), _settings.getConnectBloxPort(),
_settings.getLbWebPort(), _settings.getLbWebAdminPort(), workspace,
assumedToExist, _logger);
lbFrontend.initialize();
if (!lbFrontend.connected()) {
throw new BatfishException(
"Error connecting to ConnectBlox service. Please make sure service is running and try again.");
}
_logger.info("SUCCESS\n");
printElapsedTime();
_lbFrontends.add(lbFrontend);
return lbFrontend;
}
private boolean isJavaSerializationData(File inputFile) {
try (FileInputStream i = new FileInputStream(inputFile)) {
int headerLength = JAVA_SERIALIZED_OBJECT_HEADER.length;
byte[] headerBytes = new byte[headerLength];
int result = i.read(headerBytes, 0, headerLength);
if (result != headerLength) {
throw new BatfishException("Read wrong number of bytes");
}
return Arrays.equals(headerBytes, JAVA_SERIALIZED_OBJECT_HEADER);
}
catch (IOException e) {
throw new BatfishException("Could not read header from file: "
+ inputFile.toString(), e);
}
}
private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser) {
return parse(parser, _logger, _settings);
}
private ParserRuleContext parse(BatfishCombinedParser<?, ?> parser,
String filename) {
_logger.info("Parsing: \"" + filename + "\"...");
return parse(parser);
}
private void parseFlowsFromConstraints(StringBuilder sb,
RoleNodeMap roleNodes) {
Path flowConstraintsDir = Paths.get(_settings.getFlowPath());
File[] constraintsFiles = flowConstraintsDir.toFile().listFiles(
new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
return filename.matches(".*-concrete-.*.smt2.out");
}
});
if (constraintsFiles == null) {
throw new BatfishException("Error reading flow constraints directory");
}
for (File constraintsFile : constraintsFiles) {
String flowConstraintsText = readFile(constraintsFile);
ConcretizerQueryResultCombinedParser parser = new ConcretizerQueryResultCombinedParser(
flowConstraintsText, _settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
ParserRuleContext tree = parse(parser, constraintsFile.toString());
ParseTreeWalker walker = new ParseTreeWalker();
ConcretizerQueryResultExtractor extractor = new ConcretizerQueryResultExtractor();
walker.walk(extractor, tree);
String id = extractor.getId();
if (id == null) {
continue;
}
Map<String, Long> constraints = extractor.getConstraints();
long src_ip = 0;
long dst_ip = 0;
long src_port = 0;
long dst_port = 0;
long protocol = IpProtocol.IP.number();
for (String varName : constraints.keySet()) {
Long value = constraints.get(varName);
switch (varName) {
case Synthesizer.SRC_IP_VAR:
src_ip = value;
break;
case Synthesizer.DST_IP_VAR:
dst_ip = value;
break;
case Synthesizer.SRC_PORT_VAR:
src_port = value;
break;
case Synthesizer.DST_PORT_VAR:
dst_port = value;
break;
case Synthesizer.IP_PROTOCOL_VAR:
protocol = value;
break;
default:
throw new Error("invalid variable name");
}
}
// TODO: cleanup dirty hack
if (roleNodes != null) {
// id is role
NodeSet nodes = roleNodes.get(id);
for (String node : nodes) {
String line = node + "|" + src_ip + "|" + dst_ip + "|"
+ src_port + "|" + dst_port + "|" + protocol + "\n";
sb.append(line);
}
}
else {
String node = id;
String line = node + "|" + src_ip + "|" + dst_ip + "|" + src_port
+ "|" + dst_port + "|" + protocol + "\n";
sb.append(line);
}
}
}
private NodeRoleMap parseNodeRoles(String testRigPath) {
Path rolePath = Paths.get(testRigPath, "node_roles");
String roleFileText = readFile(rolePath.toFile());
_logger.info("Parsing: \"" + rolePath.toAbsolutePath().toString() + "\"");
BatfishCombinedParser<?, ?> parser = new RoleCombinedParser(roleFileText,
_settings.getThrowOnParserError(), _settings.getThrowOnLexerError());
RoleExtractor extractor = new RoleExtractor();
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
NodeRoleMap nodeRoles = extractor.getRoleMap();
return nodeRoles;
}
private Question parseQuestion(String questionPath) {
File questionFile = new File(questionPath);
_logger.info("Reading question file: \"" + questionPath + "\"...");
String questionText = readFile(questionFile);
_logger.info("OK\n");
QuestionCombinedParser parser = new QuestionCombinedParser(questionText,
_settings.getThrowOnParserError(), _settings.getThrowOnLexerError());
QuestionExtractor extractor = new QuestionExtractor();
try {
ParserRuleContext tree = parse(parser, questionPath);
_logger.info("\tPost-processing...");
extractor.processParseTree(tree);
_logger.info("OK\n");
}
catch (ParserBatfishException e) {
String error = "Error parsing question: \"" + questionPath + "\"";
throw new BatfishException(error, e);
}
catch (Exception e) {
String error = "Error post-processing parse tree of question file: \""
+ questionPath + "\"";
throw new BatfishException(error, e);
}
return extractor.getQuestion();
}
private Topology parseTopology(File topologyFilePath) {
_logger.info("*** PARSING TOPOLOGY ***\n");
resetTimer();
String topologyFileText = readFile(topologyFilePath);
BatfishCombinedParser<?, ?> parser = null;
TopologyExtractor extractor = null;
_logger.info("Parsing: \""
+ topologyFilePath.getAbsolutePath().toString() + "\"");
if (topologyFileText.startsWith("autostart")) {
parser = new GNS3TopologyCombinedParser(topologyFileText,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
extractor = new GNS3TopologyExtractor();
}
else if (topologyFileText.startsWith("CONFIGPARSER_TOPOLOGY")) {
parser = new BatfishTopologyCombinedParser(topologyFileText,
_settings.getThrowOnParserError(),
_settings.getThrowOnLexerError());
extractor = new BatfishTopologyExtractor();
}
else if (topologyFileText.equals("")) {
throw new BatfishException("...ERROR: empty topology\n");
}
else {
_logger.fatal("...ERROR\n");
throw new BatfishException("Topology format error");
}
ParserRuleContext tree = parse(parser);
ParseTreeWalker walker = new ParseTreeWalker();
walker.walk(extractor, tree);
Topology topology = extractor.getTopology();
printElapsedTime();
return topology;
}
private Map<String, VendorConfiguration> parseVendorConfigurations(
Map<File, String> configurationData) {
_logger.info("\n*** PARSING VENDOR CONFIGURATION FILES ***\n");
resetTimer();
ExecutorService pool;
boolean shuffle;
if (!_settings.getSequential()) {
int numConcurrentThreads = Runtime.getRuntime().availableProcessors();
pool = Executors.newFixedThreadPool(numConcurrentThreads);
shuffle = true;
}
else {
pool = Executors.newSingleThreadExecutor();
shuffle = false;
}
Map<String, VendorConfiguration> vendorConfigurations = new TreeMap<String, VendorConfiguration>();
List<ParseVendorConfigurationJob> jobs = new ArrayList<ParseVendorConfigurationJob>();
boolean processingError = false;
for (File currentFile : configurationData.keySet()) {
Warnings warnings = new Warnings(_settings.getPedanticAsError(),
_settings.getPedanticRecord()
&& _logger.isActive(BatfishLogger.LEVEL_PEDANTIC),
_settings.getRedFlagAsError(), _settings.getRedFlagRecord()
&& _logger.isActive(BatfishLogger.LEVEL_REDFLAG),
_settings.getUnimplementedAsError(),
_settings.getUnimplementedRecord()
&& _logger.isActive(BatfishLogger.LEVEL_UNIMPLEMENTED),
_settings.printParseTree());
String fileText = configurationData.get(currentFile);
ParseVendorConfigurationJob job = new ParseVendorConfigurationJob(
_settings, fileText, currentFile, warnings);
jobs.add(job);
}
if (shuffle) {
Collections.shuffle(jobs);
}
List<Future<ParseVendorConfigurationResult>> futures = new ArrayList<Future<ParseVendorConfigurationResult>>();
for (ParseVendorConfigurationJob job : jobs) {
Future<ParseVendorConfigurationResult> future = pool.submit(job);
futures.add(future);
}
// try {
// futures = pool.invokeAll(jobs);
// catch (InterruptedException e) {
// throw new BatfishException("Error invoking parse jobs", e);
while (!futures.isEmpty()) {
List<Future<ParseVendorConfigurationResult>> currentFutures = new ArrayList<Future<ParseVendorConfigurationResult>>();
currentFutures.addAll(futures);
for (Future<ParseVendorConfigurationResult> future : currentFutures) {
if (future.isDone()) {
futures.remove(future);
ParseVendorConfigurationResult result = null;
try {
result = future.get();
}
catch (InterruptedException | ExecutionException e) {
throw new BatfishException("Error executing parse job", e);
}
String terseLogLevelPrefix;
if (_logger.isActive(BatfishLogger.LEVEL_INFO)) {
terseLogLevelPrefix = "";
}
else {
terseLogLevelPrefix = result.getFile().toString() + ": ";
}
_logger.append(result.getHistory(), terseLogLevelPrefix);
Throwable failureCause = result.getFailureCause();
if (failureCause != null) {
if (_settings.getExitOnFirstError()) {
throw new BatfishException("Failed parse job",
failureCause);
}
else {
processingError = true;
_logger.error(ExceptionUtils.getStackTrace(failureCause));
}
}
else {
VendorConfiguration vc = result.getVendorConfiguration();
if (vc != null) {
String hostname = vc.getHostname();
if (vendorConfigurations.containsKey(hostname)) {
throw new BatfishException("Duplicate hostname: "
+ hostname);
}
else {
vendorConfigurations.put(hostname, vc);
}
}
}
}
else {
continue;
}
}
if (!futures.isEmpty()) {
try {
Thread.sleep(JOB_POLLING_PERIOD_MS);
}
catch (InterruptedException e) {
throw new BatfishException("interrupted while sleeping", e);
}
}
}
pool.shutdown();
if (processingError) {
return null;
}
else {
printElapsedTime();
return vendorConfigurations;
}
}
private void populateConfigurationFactBins(
Collection<Configuration> configurations,
Map<String, StringBuilder> factBins) {
_logger
.info("\n*** EXTRACTING LOGICBLOX FACTS FROM CONFIGURATIONS ***\n");
resetTimer();
Set<Long> communities = new LinkedHashSet<Long>();
for (Configuration c : configurations) {
communities.addAll(c.getCommunities());
}
boolean pedanticAsError = _settings.getPedanticAsError();
boolean pedanticRecord = _settings.getPedanticRecord();
boolean redFlagAsError = _settings.getRedFlagAsError();
boolean redFlagRecord = _settings.getRedFlagRecord();
boolean unimplementedAsError = _settings.getUnimplementedAsError();
boolean unimplementedRecord = _settings.getUnimplementedRecord();
boolean processingError = false;
for (Configuration c : configurations) {
String hostname = c.getHostname();
_logger.debug("Extracting facts from: \"" + hostname + "\"");
Warnings warnings = new Warnings(pedanticAsError, pedanticRecord,
redFlagAsError, redFlagRecord, unimplementedAsError,
unimplementedRecord, false);
try {
ConfigurationFactExtractor cfe = new ConfigurationFactExtractor(c,
communities, factBins, warnings);
cfe.writeFacts();
_logger.debug("...OK\n");
}
catch (BatfishException e) {
_logger.fatal("...EXTRACTION ERROR\n");
_logger.fatal(ExceptionUtils.getStackTrace(e));
processingError = true;
if (_settings.getExitOnFirstError()) {
break;
}
else {
continue;
}
}
finally {
for (String warning : warnings.getRedFlagWarnings()) {
_logger.redflag(warning);
}
for (String warning : warnings.getUnimplementedWarnings()) {
_logger.unimplemented(warning);
}
for (String warning : warnings.getPedanticWarnings()) {
_logger.pedantic(warning);
}
}
}
if (processingError) {
throw new BatfishException(
"Failed to extract facts from vendor-indpendent configuration structures");
}
printElapsedTime();
}
private void postFacts(LogicBloxFrontend lbFrontend,
Map<String, StringBuilder> factBins) {
Map<String, StringBuilder> enabledFacts = new HashMap<String, StringBuilder>();
enabledFacts.putAll(factBins);
enabledFacts.keySet().removeAll(_settings.getDisabledFacts());
_logger.info("\n*** POSTING FACTS TO BLOXWEB SERVICES ***\n");
resetTimer();
_logger.info("Starting bloxweb services...");
lbFrontend.startLbWebServices();
_logger.info("OK\n");
_logger.info("Posting facts...");
try {
lbFrontend.postFacts(enabledFacts);
}
catch (ServiceClientException e) {
throw new BatfishException("Failed to post facts to bloxweb services",
e);
}
_logger.info("OK\n");
_logger.info("Stopping bloxweb services...");
lbFrontend.stopLbWebServices();
_logger.info("OK\n");
_logger.info("SUCCESS\n");
printElapsedTime();
}
private void printAllPredicateSemantics(
Map<String, String> predicateSemantics) {
// Get predicate semantics from rules file
_logger.info("\n*** PRINTING PREDICATE SEMANTICS ***\n");
List<String> helpPredicates = getHelpPredicates(predicateSemantics);
for (String predicate : helpPredicates) {
printPredicateSemantics(predicate);
_logger.info("\n");
}
}
private void printElapsedTime() {
double seconds = getElapsedTime(_timerCount);
_logger.info("Time taken for this task: " + seconds + " seconds\n");
}
private void printPredicate(LogicBloxFrontend lbFrontend,
String predicateName) {
List<String> output;
printPredicateSemantics(predicateName);
String qualifiedName = _predicateInfo.getPredicateNames().get(
predicateName);
if (qualifiedName == null) { // predicate not found
_logger.error("ERROR: No information for predicate: " + predicateName
+ "\n");
return;
}
Relation relation = lbFrontend.queryPredicate(qualifiedName);
try {
output = lbFrontend.getPredicate(_predicateInfo, relation,
predicateName);
for (String match : output) {
_logger.output(match + "\n");
}
}
catch (QueryException q) {
_logger.fatal(q.getMessage() + "\n");
}
}
private void printPredicateCount(LogicBloxFrontend lbFrontend,
String predicateName) {
int numRows = lbFrontend.queryPredicate(predicateName).getColumns()
.get(0).size();
String output = "|" + predicateName + "| = " + numRows + "\n";
_logger.info(output);
}
public void printPredicateCounts(LogicBloxFrontend lbFrontend,
Set<String> predicateNames) {
// Print predicate(s) here
_logger.info("\n*** SUBMITTING QUERY(IES) ***\n");
resetTimer();
for (String predicateName : predicateNames) {
printPredicateCount(lbFrontend, predicateName);
// _logger.info("\n");
}
printElapsedTime();
}
public void printPredicates(LogicBloxFrontend lbFrontend,
Set<String> predicateNames) {
// Print predicate(s) here
_logger.info("\n*** SUBMITTING QUERY(IES) ***\n");
resetTimer();
String queryDumpDirStr = _settings.getQueryDumpDir();
if (queryDumpDirStr == null) {
for (String predicateName : predicateNames) {
printPredicate(lbFrontend, predicateName);
}
}
else {
Path queryDumpDir = Paths.get(queryDumpDirStr);
queryDumpDir.toFile().mkdirs();
for (String predicateName : predicateNames) {
String outputPath = queryDumpDir.resolve(predicateName).toString();
printPredicateToFile(lbFrontend, predicateName, outputPath);
}
}
printElapsedTime();
}
private void printPredicateSemantics(String predicateName) {
String semantics = _predicateInfo.getPredicateSemantics(predicateName);
if (semantics == null) {
semantics = "<missing>";
}
_logger.info("\n");
_logger.info("Predicate: " + predicateName + "\n");
_logger.info("Semantics: " + semantics + "\n");
}
private void printPredicateToFile(LogicBloxFrontend lbFrontend,
String predicateName, String outputPath) {
List<String> output;
printPredicateSemantics(predicateName);
StringBuilder sb = new StringBuilder();
String qualifiedName = _predicateInfo.getPredicateNames().get(
predicateName);
if (qualifiedName == null) { // predicate not found
_logger.error("ERROR: No information for predicate: " + predicateName
+ "\n");
return;
}
Relation relation = lbFrontend.queryPredicate(qualifiedName);
try {
output = lbFrontend.getPredicate(_predicateInfo, relation,
predicateName);
for (String match : output) {
sb.append(match + "\n");
}
}
catch (QueryException q) {
_logger.fatal(q.getMessage() + "\n");
}
String outputString = sb.toString();
writeFile(outputPath, outputString);
}
private void processTopology(File topologyFilePath,
Map<String, StringBuilder> factBins) {
Topology topology = null;
topology = parseTopology(topologyFilePath);
TopologyFactExtractor tfe = new TopologyFactExtractor(topology);
tfe.writeFacts(factBins);
}
private Map<File, String> readConfigurationFiles(String testRigPath) {
_logger.info("\n*** READING CONFIGURATION FILES ***\n");
resetTimer();
Map<File, String> configurationData = new TreeMap<File, String>();
File configsPath = Paths
.get(testRigPath, TESTRIG_CONFIGURATION_DIRECTORY).toFile();
File[] configFilePaths = configsPath.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return !name.startsWith(".");
}
});
if (configFilePaths == null) {
throw new BatfishException("Error reading test rig configs directory");
}
for (File file : configFilePaths) {
_logger.debug("Reading: \"" + file.toString() + "\"\n");
String fileText = readFile(file.getAbsoluteFile()) + "\n";
configurationData.put(file, fileText);
}
printElapsedTime();
return configurationData;
}
public String readFile(File file) {
String text = null;
try {
text = FileUtils.readFileToString(file);
}
catch (IOException e) {
throw new BatfishException("Failed to read file: " + file.toString(),
e);
}
return text;
}
private void resetTimer() {
_timerCount = System.currentTimeMillis();
}
private File retrieveLogicDir() {
File logicDirFile = null;
final String locatorFilename = LogicResourceLocator.class.getSimpleName()
+ ".class";
URL logicSourceURL = LogicResourceLocator.class.getProtectionDomain()
.getCodeSource().getLocation();
String logicSourceString = logicSourceURL.toString();
UrlZipExplorer zip = null;
StringFilter lbFilter = new StringFilter() {
@Override
public boolean accept(String filename) {
return filename.endsWith(".lbb") || filename.endsWith(".lbp")
|| filename.endsWith(".semantics")
|| filename.endsWith(locatorFilename)
|| filename.endsWith(PREDICATE_INFO_FILENAME);
}
};
if (logicSourceString.startsWith("onejar:")) {
FileVisitor<Path> visitor = null;
try {
zip = new UrlZipExplorer(logicSourceURL);
Path destinationDir = Files.createTempDirectory("lbtmpproject");
File destinationDirAsFile = destinationDir.toFile();
zip.extractFiles(lbFilter, destinationDirAsFile);
visitor = new SimpleFileVisitor<Path>() {
private String _projectDirectory;
@Override
public String toString() {
return _projectDirectory;
}
@Override
public FileVisitResult visitFile(Path aFile,
BasicFileAttributes aAttrs) throws IOException {
if (aFile.endsWith(locatorFilename)) {
_projectDirectory = aFile.getParent().toString();
return FileVisitResult.TERMINATE;
}
return FileVisitResult.CONTINUE;
}
};
Files.walkFileTree(destinationDir, visitor);
_tmpLogicDir = destinationDirAsFile;
}
catch (IOException e) {
throw new BatfishException(
"Failed to retrieve logic dir from onejar archive", e);
}
String fileString = visitor.toString();
return new File(fileString);
}
else {
String logicPackageResourceName = LogicResourceLocator.class
.getPackage().getName().replace('.', SEPARATOR.charAt(0));
try {
logicDirFile = new File(LogicResourceLocator.class.getClassLoader()
.getResource(logicPackageResourceName).toURI());
}
catch (URISyntaxException e) {
throw new BatfishException("Failed to resolve logic directory", e);
}
return logicDirFile;
}
}
private void revert(LogicBloxFrontend lbFrontend) {
_logger.info("\n*** REVERTING WORKSPACE ***\n");
String workspaceName = new File(_settings.getTestRigPath()).getName();
String branchName = _settings.getBranchName();
_logger.debug("Reverting workspace: \"" + workspaceName
+ "\" to branch: \"" + branchName + "\n");
String errorResult = lbFrontend.revertDatabase(branchName);
if (errorResult != null) {
throw new BatfishException("Failed to revert database: " + errorResult);
}
}
public void run() {
if (_settings.getAnswer()) {
String questionPath = _settings.getQuestionPath();
answer(questionPath);
return;
}
if (_settings.getBuildPredicateInfo()) {
buildPredicateInfo();
return;
}
if (_settings.getHistogram()) {
histogram(_settings.getTestRigPath());
return;
}
if (_settings.getGenerateOspfTopologyPath() != null) {
generateOspfConfigs(_settings.getGenerateOspfTopologyPath(),
_settings.getSerializeIndependentPath());
return;
}
if (_settings.getFlatten()) {
String flattenSource = _settings.getTestRigPath();
String flattenDestination = _settings.getFlattenDestination();
flatten(flattenSource, flattenDestination);
return;
}
if (_settings.getGenerateStubs()) {
String configPath = _settings.getSerializeIndependentPath();
String inputRole = _settings.getGenerateStubsInputRole();
String interfaceDescriptionRegex = _settings
.getGenerateStubsInterfaceDescriptionRegex();
int stubAs = _settings.getGenerateStubsRemoteAs();
generateStubs(inputRole, stubAs, interfaceDescriptionRegex, configPath);
return;
}
if (_settings.getZ3()) {
Map<String, Configuration> configurations = deserializeConfigurations(_settings
.getSerializeIndependentPath());
genZ3(configurations);
return;
}
if (_settings.getAnonymize()) {
anonymizeConfigurations();
return;
}
if (_settings.getInterfaceFailureInconsistencyReachableQuery()) {
genReachableQueries();
return;
}
if (_settings.getRoleReachabilityQuery()) {
genRoleReachabilityQueries();
return;
}
if (_settings.getRoleTransitQuery()) {
genRoleTransitQueries();
return;
}
if (_settings.getInterfaceFailureInconsistencyBlackHoleQuery()) {
genBlackHoleQueries();
return;
}
if (_settings.getGenerateMultipathInconsistencyQuery()) {
genMultipathQueries();
return;
}
if (_settings.getSerializeVendor()) {
String testRigPath = _settings.getTestRigPath();
String outputPath = _settings.getSerializeVendorPath();
serializeVendorConfigs(testRigPath, outputPath);
return;
}
if (_settings.dumpInterfaceDescriptions()) {
String testRigPath = _settings.getTestRigPath();
String outputPath = _settings.getDumpInterfaceDescriptionsPath();
dumpInterfaceDescriptions(testRigPath, outputPath);
return;
}
if (_settings.getSerializeIndependent()) {
String inputPath = _settings.getSerializeVendorPath();
String outputPath = _settings.getSerializeIndependentPath();
serializeIndependentConfigs(inputPath, outputPath);
return;
}
if (_settings.getConcretize()) {
concretize();
return;
}
if (_settings.getQuery() || _settings.getPrintSemantics()
|| _settings.getDataPlane()) {
Map<String, String> logicFiles = getSemanticsFiles();
_predicateInfo = getPredicateInfo(logicFiles);
// Print predicate semantics and quit if requested
if (_settings.getPrintSemantics()) {
printAllPredicateSemantics(_predicateInfo.getPredicateSemantics());
return;
}
}
Map<String, StringBuilder> cpFactBins = null;
if (_settings.getFacts() || _settings.getDumpControlPlaneFacts()) {
cpFactBins = new LinkedHashMap<String, StringBuilder>();
initControlPlaneFactBins(cpFactBins);
Map<String, Configuration> configurations = deserializeConfigurations(_settings
.getSerializeIndependentPath());
writeTopologyFacts(_settings.getTestRigPath(), configurations,
cpFactBins);
writeConfigurationFacts(configurations, cpFactBins);
String flowSinkPath = _settings.getFlowSinkPath();
if (flowSinkPath != null) {
FlowSinkSet flowSinks = (FlowSinkSet) deserializeObject(new File(
flowSinkPath));
writeFlowSinkFacts(flowSinks, cpFactBins);
}
if (_settings.getDumpControlPlaneFacts()) {
dumpFacts(cpFactBins);
}
if (!(_settings.getFacts() || _settings.createWorkspace())) {
return;
}
}
// Start frontend
LogicBloxFrontend lbFrontend = null;
if (_settings.createWorkspace() || _settings.getFacts()
|| _settings.getQuery() || _settings.getDataPlane()
|| _settings.revert()) {
lbFrontend = connect();
}
if (_settings.revert()) {
revert(lbFrontend);
return;
}
// Create new workspace (will overwrite existing) if requested
if (_settings.createWorkspace()) {
addProject(lbFrontend);
String lbHostnamePath = _settings.getJobLogicBloxHostnamePath();
String lbHostname = _settings.getServiceLogicBloxHostname();
if (lbHostnamePath != null && lbHostname != null) {
writeFile(lbHostnamePath, lbHostname);
}
if (!_settings.getFacts()) {
return;
}
}
// Post facts if requested
if (_settings.getFacts()) {
addStaticFacts(lbFrontend, BASIC_FACTS_BLOCKNAME);
postFacts(lbFrontend, cpFactBins);
return;
}
if (_settings.getQuery()) {
lbFrontend.initEntityTable();
Map<String, String> allPredicateNames = _predicateInfo
.getPredicateNames();
Set<String> predicateNames = new TreeSet<String>();
if (_settings.getQueryAll()) {
predicateNames.addAll(allPredicateNames.keySet());
}
else {
predicateNames.addAll(_settings.getPredicates());
}
if (_settings.getCountsOnly()) {
printPredicateCounts(lbFrontend, predicateNames);
}
else {
printPredicates(lbFrontend, predicateNames);
}
return;
}
if (_settings.getDataPlane()) {
computeDataPlane(lbFrontend);
return;
}
Map<String, StringBuilder> trafficFactBins = null;
if (_settings.getPostFlows()) {
trafficFactBins = new LinkedHashMap<String, StringBuilder>();
Path dumpDir = Paths.get(_settings.getTrafficFactDumpDir());
for (String predicate : Facts.TRAFFIC_FACT_COLUMN_HEADERS.keySet()) {
File factFile = dumpDir.resolve(predicate).toFile();
String contents = readFile(factFile);
StringBuilder sb = new StringBuilder();
trafficFactBins.put(predicate, sb);
sb.append(contents);
}
lbFrontend = connect();
postFacts(lbFrontend, trafficFactBins);
return;
}
if (_settings.getFlows() || _settings.getDumpTrafficFacts()) {
trafficFactBins = new LinkedHashMap<String, StringBuilder>();
initTrafficFactBins(trafficFactBins);
writeTrafficFacts(trafficFactBins);
if (_settings.getDumpTrafficFacts()) {
dumpFacts(trafficFactBins);
}
if (_settings.getFlows()) {
lbFrontend = connect();
postFacts(lbFrontend, trafficFactBins);
return;
}
}
throw new BatfishException(
"No task performed! Run with -help flag to see usage");
}
private void serializeIndependentConfigs(
Map<String, Configuration> configurations, String outputPath) {
_logger
.info("\n*** SERIALIZING VENDOR-INDEPENDENT CONFIGURATION STRUCTURES ***\n");
resetTimer();
new File(outputPath).mkdirs();
for (String name : configurations.keySet()) {
Configuration c = configurations.get(name);
Path currentOutputPath = Paths.get(outputPath, name);
_logger.info("Serializing: \"" + name + "\" ==> \""
+ currentOutputPath.toString() + "\"");
serializeObject(c, currentOutputPath.toFile());
_logger.debug(" ...OK\n");
}
printElapsedTime();
}
private void serializeIndependentConfigs(String vendorConfigPath,
String outputPath) {
Map<String, Configuration> configurations = getConfigurations(vendorConfigPath);
serializeIndependentConfigs(configurations, outputPath);
}
private void serializeObject(Object object, File outputFile) {
FileOutputStream fos;
ObjectOutputStream oos;
try {
fos = new FileOutputStream(outputFile);
if (_settings.getSerializeToText()) {
XStream xstream = new XStream(new DomDriver("UTF-8"));
oos = xstream.createObjectOutputStream(fos);
}
else {
oos = new ObjectOutputStream(fos);
}
oos.writeObject(object);
oos.close();
}
catch (IOException e) {
throw new BatfishException(
"Failed to serialize object to output file: "
+ outputFile.toString(), e);
}
}
private void serializeVendorConfigs(String testRigPath, String outputPath) {
Map<File, String> configurationData = readConfigurationFiles(testRigPath);
Map<String, VendorConfiguration> vendorConfigurations = parseVendorConfigurations(configurationData);
if (vendorConfigurations == null) {
throw new BatfishException("Exiting due to parser errors\n");
}
String nodeRolesPath = _settings.getNodeRolesPath();
if (nodeRolesPath != null) {
NodeRoleMap nodeRoles = parseNodeRoles(testRigPath);
for (Entry<String, RoleSet> nodeRolesEntry : nodeRoles.entrySet()) {
String hostname = nodeRolesEntry.getKey();
VendorConfiguration config = vendorConfigurations.get(hostname);
if (config == null) {
throw new BatfishException(
"role set assigned to non-existent node: \"" + hostname
+ "\"");
}
RoleSet roles = nodeRolesEntry.getValue();
config.setRoles(roles);
}
if (!_settings.getNoOutput()) {
_logger.info("Serializing node-roles mappings: \"" + nodeRolesPath
+ "\"...");
serializeObject(nodeRoles, new File(nodeRolesPath));
_logger.info("OK\n");
}
}
if (!_settings.getNoOutput()) {
_logger
.info("\n*** SERIALIZING VENDOR CONFIGURATION STRUCTURES ***\n");
resetTimer();
new File(outputPath).mkdirs();
for (String name : vendorConfigurations.keySet()) {
VendorConfiguration vc = vendorConfigurations.get(name);
Path currentOutputPath = Paths.get(outputPath, name);
_logger.debug("Serializing: \"" + name + "\" ==> \""
+ currentOutputPath.toString() + "\"...");
serializeObject(vc, currentOutputPath.toFile());
_logger.debug("OK\n");
}
printElapsedTime();
}
}
private Synthesizer synthesizeDataPlane(
Map<String, Configuration> configurations, Context ctx)
throws Z3Exception {
_logger.info("\n*** GENERATING Z3 LOGIC ***\n");
resetTimer();
String dataPlaneDir = _settings.getDataPlaneDir();
if (dataPlaneDir == null) {
throw new BatfishException("Data plane dir not set");
}
Path flowSinkSetPath = Paths.get(dataPlaneDir, FLOW_SINKS_FILENAME);
Path fibsPath = Paths.get(dataPlaneDir, FIBS_FILENAME);
Path prFibsPath = Paths.get(dataPlaneDir,
FIBS_POLICY_ROUTE_NEXT_HOP_FILENAME);
Path edgesPath = Paths.get(dataPlaneDir, EDGES_FILENAME);
_logger.info("Deserializing flow sink interface set: \""
+ flowSinkSetPath.toString() + "\"...");
FlowSinkSet flowSinks = (FlowSinkSet) deserializeObject(flowSinkSetPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing destination route fibs: \""
+ fibsPath.toString() + "\"...");
FibMap fibs = (FibMap) deserializeObject(fibsPath.toFile());
_logger.info("OK\n");
_logger.info("Deserializing policy route fibs: \""
+ prFibsPath.toString() + "\"...");
PolicyRouteFibNodeMap prFibs = (PolicyRouteFibNodeMap) deserializeObject(prFibsPath
.toFile());
_logger.info("OK\n");
_logger.info("Deserializing toplogy edges: \"" + edgesPath.toString()
+ "\"...");
EdgeSet topologyEdges = (EdgeSet) deserializeObject(edgesPath.toFile());
_logger.info("OK\n");
_logger.info("Synthesizing Z3 logic...");
Synthesizer s = new Synthesizer(configurations, fibs, prFibs,
topologyEdges, _settings.getSimplify(), flowSinks);
List<String> warnings = s.getWarnings();
int numWarnings = warnings.size();
if (numWarnings == 0) {
_logger.info("OK\n");
}
else {
for (String warning : warnings) {
_logger.warn(warning);
}
}
printElapsedTime();
return s;
}
public void writeConfigurationFacts(
Map<String, Configuration> configurations,
Map<String, StringBuilder> factBins) {
populateConfigurationFactBins(configurations.values(), factBins);
}
private void writeFile(String outputPath, String output) {
File outputFile = new File(outputPath);
try {
FileUtils.write(outputFile, output);
}
catch (IOException e) {
throw new BatfishException("Failed to write file: " + outputPath, e);
}
}
private void writeFlowSinkFacts(FlowSinkSet flowSinks,
Map<String, StringBuilder> cpFactBins) {
StringBuilder sb = cpFactBins.get("SetFlowSinkInterface");
for (FlowSinkInterface f : flowSinks) {
String node = f.getNode();
String iface = f.getInterface();
sb.append(node + "|" + iface + "\n");
}
}
public void writeTopologyFacts(String testRigPath,
Map<String, Configuration> configurations,
Map<String, StringBuilder> factBins) {
Path topologyFilePath = Paths.get(testRigPath, TOPOLOGY_FILENAME);
// Get generated facts from topology file
if (Files.exists(topologyFilePath)) {
processTopology(topologyFilePath.toFile(), factBins);
}
else {
// tell logicblox to guess adjacencies based on interface
// subnetworks
_logger
.info("*** (GUESSING TOPOLOGY IN ABSENCE OF EXPLICIT FILE) ***\n");
StringBuilder wGuessTopology = factBins.get("GuessTopology");
wGuessTopology.append("1\n");
}
}
private void writeTrafficFacts(Map<String, StringBuilder> factBins) {
StringBuilder wSetFlowOriginate = factBins.get("SetFlowOriginate");
RoleNodeMap roleNodes = null;
if (_settings.getRoleHeaders()) {
String nodeRolesPath = _settings.getNodeRolesPath();
NodeRoleMap nodeRoles = (NodeRoleMap) deserializeObject(new File(
nodeRolesPath));
roleNodes = nodeRoles.toRoleNodeMap();
}
parseFlowsFromConstraints(wSetFlowOriginate, roleNodes);
if (_settings.duplicateRoleFlows()) {
StringBuilder wDuplicateRoleFlows = factBins.get("DuplicateRoleFlows");
wDuplicateRoleFlows.append("1\n");
}
}
} |
package nl.idgis.publisher.job;
import static nl.idgis.publisher.database.QCategory.category;
import static nl.idgis.publisher.database.QJob.job;
import static nl.idgis.publisher.database.QImportJob.importJob;
import static nl.idgis.publisher.database.QImportJobColumn.importJobColumn;
import static nl.idgis.publisher.database.QSourceDataset.sourceDataset;
import static nl.idgis.publisher.database.QSourceDatasetVersionColumn.sourceDatasetVersionColumn;
import static nl.idgis.publisher.database.QSourceDatasetVersion.sourceDatasetVersion;
import static nl.idgis.publisher.database.QDataset.dataset;
import static nl.idgis.publisher.database.QDatasetColumn.datasetColumn;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import nl.idgis.publisher.AbstractServiceTest;
import nl.idgis.publisher.database.messages.DatasetStatusInfo;
import nl.idgis.publisher.database.messages.GetDatasetStatus;
import nl.idgis.publisher.database.messages.HarvestJobInfo;
import nl.idgis.publisher.database.messages.ImportJobInfo;
import nl.idgis.publisher.database.messages.ServiceJobInfo;
import nl.idgis.publisher.database.messages.UpdateJobState;
import nl.idgis.publisher.domain.job.JobState;
import nl.idgis.publisher.domain.service.Column;
import nl.idgis.publisher.domain.service.Type;
import nl.idgis.publisher.job.messages.CreateHarvestJob;
import nl.idgis.publisher.job.messages.CreateImportJob;
import nl.idgis.publisher.job.messages.CreateServiceJob;
import nl.idgis.publisher.job.messages.GetHarvestJobs;
import nl.idgis.publisher.job.messages.GetImportJobs;
import nl.idgis.publisher.job.messages.GetServiceJobs;
import nl.idgis.publisher.protocol.messages.Ack;
import nl.idgis.publisher.utils.TypedIterable;
import org.junit.Test;
import com.mysema.query.Tuple;
public class JobTest extends AbstractServiceTest {
@Test
public void testHarvestJob() throws Exception {
insertDataSource();
Object result = sync.ask(jobManager, new CreateHarvestJob("testDataSource"));
assertTrue(result instanceof Ack);
Tuple t = query().from(job).singleResult(job.all());
assertNotNull(t);
assertEquals("HARVEST", t.get(job.type));
TypedIterable<?> jobs = sync.ask(jobManager, new GetHarvestJobs(), TypedIterable.class);
assertTrue(jobs.contains(HarvestJobInfo.class));
Iterator<HarvestJobInfo> jobsItr = jobs.cast(HarvestJobInfo.class).iterator();
assertTrue(jobsItr.hasNext());
HarvestJobInfo job = jobsItr.next();
assertNotNull(job);
assertEquals("testDataSource", job.getDataSourceId());
assertFalse(jobsItr.hasNext());
}
@Test
public void testImportAndServiceJob() throws Exception {
int dataSourceId = insertDataSource();
int sourceDatasetId =
insert(sourceDataset)
.set(sourceDataset.dataSourceId, dataSourceId)
.set(sourceDataset.identification, "testSourceDataset")
.executeWithKey(sourceDataset.id);
int categoryId =
insert(category)
.set(category.identification, "testCategory")
.set(category.name, "My Test Category")
.executeWithKey(category.id);
Timestamp testRevision = new Timestamp(new Date().getTime());
int versionId =
insert(sourceDatasetVersion)
.set(sourceDatasetVersion.name, "My Test SourceDataset")
.set(sourceDatasetVersion.type, "VECTOR")
.set(sourceDatasetVersion.revision, testRevision)
.set(sourceDatasetVersion.sourceDatasetId, sourceDatasetId)
.set(sourceDatasetVersion.categoryId, categoryId)
.executeWithKey(sourceDatasetVersion.id);
for(int i = 0; i < 10; i++) {
insert(sourceDatasetVersionColumn)
.set(sourceDatasetVersionColumn.sourceDatasetVersionId, versionId)
.set(sourceDatasetVersionColumn.index, i)
.set(sourceDatasetVersionColumn.name, "test" + i)
.set(sourceDatasetVersionColumn.dataType, "GEOMETRY")
.execute();
}
int datasetId =
insert(dataset)
.set(dataset.name, "My Test Dataset")
.set(dataset.identification, "testDataset")
.set(dataset.sourceDatasetId, sourceDatasetId)
.set(dataset.uuid, UUID.randomUUID().toString())
.set(dataset.fileUuid, UUID.randomUUID().toString())
.executeWithKey(dataset.id);
for(int i = 0; i < 10; i++) {
insert(datasetColumn)
.set(datasetColumn.datasetId, datasetId)
.set(datasetColumn.index, i)
.set(datasetColumn.name, "test" + i)
.set(datasetColumn.dataType, "GEOMETRY")
.execute();
}
Object result = sync.ask(database, new GetDatasetStatus());
assertTrue(result instanceof TypedIterable);
TypedIterable<?> typedIterable = (TypedIterable<?>)result;
assertTrue(typedIterable.contains(DatasetStatusInfo.class));
Iterator<DatasetStatusInfo> i = typedIterable.cast(DatasetStatusInfo.class).iterator();
assertTrue(i.hasNext());
DatasetStatusInfo datasetStatus = i.next();
assertNotNull(datasetStatus);
assertEquals("testDataset", datasetStatus.getDatasetId());
assertFalse(datasetStatus.isImported());
assertFalse(datasetStatus.isServiceCreated());
assertFalse(i.hasNext());
result = sync.ask(jobManager, new CreateImportJob("testDataset"));
assertTrue(result instanceof Ack);
Tuple t = query().from(job).singleResult(job.all());
assertNotNull(t);
assertEquals("IMPORT", t.get(job.type));
t = query().from(importJob).singleResult(importJob.all());
assertNotNull(importJob.filterConditions);
t = query().from(importJobColumn)
.orderBy(importJobColumn.index.asc())
.singleResult(importJobColumn.all());
assertNotNull(t);
assertEquals(0, t.get(importJobColumn.index).intValue());
assertEquals("test0", t.get(importJobColumn.name));
assertEquals("GEOMETRY", t.get(importJobColumn.dataType));
TypedIterable<?> importJobsInfos = sync.ask(jobManager, new GetImportJobs(), TypedIterable.class);
assertTrue(importJobsInfos.contains(ImportJobInfo.class));
Iterator<ImportJobInfo> importJobsItr = importJobsInfos.cast(ImportJobInfo.class).iterator();
assertTrue(importJobsItr.hasNext());
ImportJobInfo importJobInfo = importJobsItr.next();
assertEquals("testDataset", importJobInfo.getDatasetId());
assertEquals("testCategory", importJobInfo.getCategoryId());
String filterCondition = importJobInfo.getFilterCondition();
assertNotNull(filterCondition);
assertColumns(importJobInfo.getColumns());
result = sync.ask(database, new GetDatasetStatus());
assertTrue(result instanceof TypedIterable);
typedIterable = (TypedIterable<?>)result;
assertTrue(typedIterable.contains(DatasetStatusInfo.class));
i = typedIterable.cast(DatasetStatusInfo.class).iterator();
assertTrue(i.hasNext());
datasetStatus = i.next();
assertNotNull(datasetStatus);
assertFalse(datasetStatus.isImported());
assertFalse(datasetStatus.isSourceDatasetColumnsChanged());
assertFalse(i.hasNext());
result = sync.ask(database, new UpdateJobState(importJobInfo, JobState.SUCCEEDED));
assertTrue(result instanceof Ack);
result = sync.ask(database, new GetDatasetStatus());
assertTrue(result instanceof TypedIterable);
typedIterable = (TypedIterable<?>) result;
assertTrue(typedIterable.contains(DatasetStatusInfo.class));
i = typedIterable.cast(DatasetStatusInfo.class).iterator();
assertNotNull(i);
assertTrue(i.hasNext());
datasetStatus = i.next();
assertFalse(datasetStatus.isServiceCreated());
result = sync.ask(jobManager, new CreateServiceJob("testDataset"));
assertTrue(result instanceof Ack);
TypedIterable<?> serviceJobsInfos = sync.ask(jobManager, new GetServiceJobs(), TypedIterable.class);
assertTrue(serviceJobsInfos.contains(ServiceJobInfo.class));
Iterator<ServiceJobInfo> serviceJobsItr = serviceJobsInfos.cast(ServiceJobInfo.class).iterator();
ServiceJobInfo serviceJobInfo = serviceJobsItr.next();
result = sync.ask(database, new UpdateJobState(serviceJobInfo, JobState.SUCCEEDED));
assertTrue(result instanceof Ack);
result = sync.ask(database, new GetDatasetStatus());
assertTrue(result instanceof TypedIterable);
typedIterable = (TypedIterable<?>) result;
assertTrue(typedIterable.contains(DatasetStatusInfo.class));
i = typedIterable.cast(DatasetStatusInfo.class).iterator();
assertNotNull(i);
assertTrue(i.hasNext());
datasetStatus = i.next();
assertTrue(datasetStatus.isServiceCreated());
}
private void assertColumns(List<Column> columns) {
assertNotNull(columns);
assertEquals(10, columns.size());
for(int i = 0; i < 10; i++) {
Column column = columns.get(i);
assertNotNull(column);
assertEquals("test" + i, column.getName());
assertEquals(Type.GEOMETRY, column.getDataType());
}
}
} |
package nl.mpi.kinnate.data;
import java.net.URI;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.ImageIcon;
import nl.mpi.arbil.data.ArbilDataNode;
import nl.mpi.arbil.data.ArbilDataNodeLoader;
import nl.mpi.arbil.data.ArbilNode;
import nl.mpi.arbil.data.ContainerNode;
import nl.mpi.arbil.util.MessageDialogHandler;
import nl.mpi.flap.model.PluginDataNodeType;
import nl.mpi.flap.model.FieldGroup;
import nl.mpi.kinnate.entityindexer.EntityCollection;
import nl.mpi.kinnate.entityindexer.IndexerParameters;
import nl.mpi.kinnate.kindata.DataTypes;
import nl.mpi.kinnate.kindata.EntityData;
import nl.mpi.kinnate.kindata.EntityRelation;
import nl.mpi.kinnate.svg.DataStoreSvg;
import nl.mpi.kinnate.svg.SymbolGraphic;
import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier;
public class KinTreeNode extends ArbilNode implements Comparable {
private UniqueIdentifier uniqueIdentifier;
protected EntityData entityData = null;
protected IndexerParameters indexerParameters;
protected ArbilNode[] childNodes = null;
static private SymbolGraphic symbolGraphic = null;
protected EntityCollection entityCollection;
protected MessageDialogHandler dialogHandler;
protected ArbilDataNodeLoader dataNodeLoader;
private String derivedLabelString = null;
final protected DataStoreSvg dataStoreSvg;
public KinTreeNode(UniqueIdentifier uniqueIdentifier, EntityData entityData, DataStoreSvg dataStoreSvg, IndexerParameters indexerParameters, MessageDialogHandler dialogHandler, EntityCollection entityCollection, ArbilDataNodeLoader dataNodeLoader) {
// todo: create new constructor that takes a unique identifer and loads from the database.
super();
this.uniqueIdentifier = uniqueIdentifier;
this.dataStoreSvg = dataStoreSvg;
this.indexerParameters = indexerParameters;
this.entityData = entityData;
this.entityCollection = entityCollection;
this.dialogHandler = dialogHandler;
this.dataNodeLoader = dataNodeLoader;
if (symbolGraphic == null) {
symbolGraphic = new SymbolGraphic(dialogHandler);
}
}
// public void setEntityData(EntityData entityData) {
// // todo: this does not cause the tree to update so it is redundent
// this.entityData = entityData;
// derivedLabelString = null;
// symbolGraphic = null;
// // todo: clear or set the child entity data
// //childNodes
public EntityData getEntityData() {
return entityData;
}
public UniqueIdentifier getUniqueIdentifier() {
return uniqueIdentifier;
}
@Override
public String toString() {
if (derivedLabelString == null) {
if (entityData == null) {
return "<entity not loaded>";
} else {
StringBuilder labelBuilder = new StringBuilder();
final String[] labelArray = entityData.getLabel();
if (labelArray != null && labelArray.length > 0) {
for (String labelString : labelArray) {
labelBuilder.append(labelString);
labelBuilder.append(" ");
}
}
derivedLabelString = labelBuilder.toString();
if (derivedLabelString.replaceAll("\\s", "").isEmpty()) {
derivedLabelString = "<unlabeled entity>";
}
}
}
return derivedLabelString;
}
@Override
public ArbilDataNode[] getAllChildren() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void getAllChildren(Vector<ArbilDataNode> allChildren) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ArbilNode[] getChildArray() {
if (childNodes == null) {
// add the related entities grouped into metanodes by relation type and within each group the subsequent nodes are filtered by the type of relation.
HashMap<DataTypes.RelationType, HashSet<KinTreeFilteredNode>> metaNodeMap = new HashMap<DataTypes.RelationType, HashSet<KinTreeFilteredNode>>();
for (EntityRelation entityRelation : entityData.getAllRelations()) {
if (!metaNodeMap.containsKey(entityRelation.getRelationType())) {
metaNodeMap.put(entityRelation.getRelationType(), new HashSet<KinTreeFilteredNode>());
}
metaNodeMap.get(entityRelation.getRelationType()).add(new KinTreeFilteredNode(entityRelation, dataStoreSvg, indexerParameters, dialogHandler, entityCollection, dataNodeLoader));
}
HashSet<ArbilNode> kinTreeMetaNodes = new HashSet<ArbilNode>();
for (Map.Entry<DataTypes.RelationType, HashSet<KinTreeFilteredNode>> filteredNodeEntry : metaNodeMap.entrySet()) {//values().toArray(new KinTreeFilteredNode[]{})
kinTreeMetaNodes.add(new FilteredNodeContainer(filteredNodeEntry.getKey().name(), null, filteredNodeEntry.getValue().toArray(new KinTreeFilteredNode[]{})));
}
getLinksMetaNode(kinTreeMetaNodes);
childNodes = kinTreeMetaNodes.toArray(new ArbilNode[]{});
}
return childNodes;
}
protected void getLinksMetaNode(HashSet<ArbilNode> kinTreeMetaNodes) {
if (entityData.archiveLinkArray != null) {
HashSet<ArbilDataNode> relationList = new HashSet<ArbilDataNode>();
for (URI archiveLink : entityData.archiveLinkArray) {
ArbilDataNode linkedArbilDataNode = dataNodeLoader.getArbilDataNode(null, archiveLink);
relationList.add(linkedArbilDataNode);
}
kinTreeMetaNodes.add(new ContainerNode(null, "External Links", null, relationList.toArray(new ArbilDataNode[]{})));
}
}
@Override
public int getChildCount() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ImageIcon getIcon() {
if (entityData != null) {
return symbolGraphic.getSymbolGraphic(entityData.getSymbolNames(dataStoreSvg.defaultSymbol), entityData.isEgo);
}
return null;
}
@Override
public String getID() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<FieldGroup> getFieldGroups() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasCatalogue() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasHistory() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasLocalResource() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean hasResource() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isArchivableFile() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isCatalogue() {
return false;
}
@Override
public boolean isChildNode() {
return false;
}
@Override
public boolean isCmdiMetaDataNode() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isCorpus() {
return false;
}
@Override
public boolean isDataLoaded() {
return true;
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public boolean isEditable() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isEmptyMetaNode() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isFavorite() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isLoading() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isDataPartiallyLoaded() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isLocal() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isMetaDataNode() {
return false;
}
@Override
public boolean isResourceSet() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setID(String id) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setLabel(String label) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLabel() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setFieldGroups(List<FieldGroup> fieldGroups) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setChildIds(List<String> idString) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public List<String> getChildIds() {
throw new UnsupportedOperationException("Not supported yet.");
}
public PluginDataNodeType getType() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isSession() {
return false;
}
public int compareTo(Object o) {
if (o instanceof KinTreeNode) {
int compResult = this.toString().compareTo(o.toString());
if (compResult == 0) {
// todo: compare by age if the labels match
// compResult = entityData
}
return compResult;
} else {
// put kin nodes in front of other nodes
return 1;
}
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final KinTreeNode other = (KinTreeNode) obj;
// we compare the entity data instance because this is the only way to update the arbil tree
// todo: this does not break the graph selection process but check for other places where equals might be used
return this.entityData == other.entityData;
//// return this.hashCode() == other.hashCode();
// if (entityData == null || other.entityData == null) {
// // todo: it would be good for this to never be null, or at least to aways have the UniqueIdentifier to compare
// return false;
// if (this.getUniqueIdentifier() != other.getUniqueIdentifier() && (this.getUniqueIdentifier() == null || !this.getUniqueIdentifier().equals(other.getUniqueIdentifier()))) {
// return false;
// return true;
}
@Override
public int hashCode() {
int hash = 0;
hash = 37 * hash + (this.uniqueIdentifier != null ? this.uniqueIdentifier.hashCode() : 0);
return hash;
}
} |
package railo.runtime.type.util;
import java.lang.reflect.Field;
import java.util.HashSet;
import railo.runtime.type.Collection.Key;
import railo.runtime.type.KeyImpl;
public class KeyConstants {
public static final Key _A=KeyImpl._const("A");
public static final Key _AAA=KeyImpl._const("AAA");
public static final Key _ABC=KeyImpl._const("ABC");
public static final Key _ACCESS=KeyImpl._const("ACCESS");
public static final Key _ACTION=KeyImpl._const("ACTION");
public static final Key _AGE=KeyImpl._const("AGE");
public static final Key _ALIAS=KeyImpl._const("ALIAS");
public static final Key _APPMANAGER=KeyImpl._const("APPMANAGER");
public static final Key _APPSERVER=KeyImpl._const("APPSERVER");
public static final Key _ARG1=KeyImpl._const("ARG1");
public static final Key _ARGS=KeyImpl._const("ARGS");
public static final Key _ARR=KeyImpl._const("ARR");
public static final Key _AS=KeyImpl._const("AS");
public static final Key _ASTERISK=KeyImpl._const("ASTERISK");
public static final Key _ATTRIBUTES=KeyImpl._const("ATTRIBUTES");
public static final Key _Accept=KeyImpl._const("Accept");
public static final Key _Assertions=KeyImpl._const("Assertions");
public static final Key _Author=KeyImpl._const("Author");
public static final Key _B=KeyImpl._const("B");
public static final Key _BBB=KeyImpl._const("BBB");
public static final Key _BUFFER=KeyImpl._const("BUFFER");
public static final Key _C=KeyImpl._const("C");
public static final Key _CACHENAME=KeyImpl._const("CACHENAME");
public static final Key _CALL=KeyImpl._const("CALL");
public static final Key _CALLER=KeyImpl._const("CALLER");
public static final Key _caller=KeyImpl._const("caller");
public static final Key _CALLSUPER=KeyImpl._const("CALLSUPER");
public static final Key _CCC=KeyImpl._const("CCC");
public static final Key _CFCATCH=KeyImpl._const("CFCATCH");
public static final Key _CFID=KeyImpl._const("CFID");
public static final Key _CFTOKEN=KeyImpl._const("CFTOKEN");
public static final Key _CF_CLIENT_=KeyImpl._const("CF_CLIENT_");
public static final Key _CHILD=KeyImpl._const("CHILD");
public static final Key _CLASS=KeyImpl._const("CLASS");
public static final Key _CLASSNAME=KeyImpl._const("CLASSNAME");
public static final Key _CODE_CACHE=KeyImpl._const("CODE_CACHE");
public static final Key _COLDFUSION=KeyImpl._const("COLDFUSION");
public static final Key _COLLECTION=KeyImpl._const("COLLECTION");
public static final Key _COLUMN=KeyImpl._const("COLUMN");
public static final Key _COLUMNS=KeyImpl._const("COLUMNS");
public static final Key _COMMENTS=KeyImpl._const("COMMENTS");
public static final Key _CONDITION=KeyImpl._const("CONDITION");
public static final Key _CONFIGURE=KeyImpl._const("CONFIGURE");
public static final Key _CONFIGXML=KeyImpl._const("CONFIGXML");
public static final Key _CONTENT=KeyImpl._const("CONTENT");
public static final Key _CONTEXT=KeyImpl._const("CONTEXT");
public static final Key _CONTROLLER=KeyImpl._const("CONTROLLER");
public static final Key _COUNT=KeyImpl._const("COUNT");
public static final Key _COUNTER=KeyImpl._const("COUNTER");
public static final Key _CS=KeyImpl._const("CS");
public static final Key _Cause=KeyImpl._const("Cause");
public static final Key _CircuitXML=KeyImpl._const("CircuitXML");
public static final Key _Commenting=KeyImpl._const("Commenting");
public static final Key _Connection=KeyImpl._const("Connection");
public static final Key _Cookie=KeyImpl._const("Cookie");
public static final Key _Created=KeyImpl._const("Created");
public static final Key _D=KeyImpl._const("D");
public static final Key _D1=KeyImpl._const("D1");
public static final Key _DATA=KeyImpl._const("DATA");
public static final Key _DATASOURCE=KeyImpl._const("DATASOURCE");
public static final Key _DATATYPE=KeyImpl._const("DATATYPE");
public static final Key _DETAIL=KeyImpl._const("DETAIL");
public static final Key _DIR=KeyImpl._const("DIR");
public static final Key _DIRECTORY=KeyImpl._const("DIRECTORY");
public static final Key _DOC=KeyImpl._const("DOC");
public static final Key _DataSource=KeyImpl._const("DataSource");
public static final Key _Datasource=KeyImpl._const("Datasource");
public static final Key _Date=KeyImpl._const("Date");
public static final Key _E=KeyImpl._const("E");
public static final Key _ENABLE21=KeyImpl._const("ENABLE21");
public static final Key _ENABLE31=KeyImpl._const("ENABLE31");
public static final Key _EVENT=KeyImpl._const("EVENT");
public static final Key _EVENTNAME=KeyImpl._const("EVENTNAME");
public static final Key _EXE=KeyImpl._const("EXE");
public static final Key _EXECUTE=KeyImpl._const("EXECUTE");
public static final Key _Elements=KeyImpl._const("Elements");
public static final Key _Encryption=KeyImpl._const("Encryption");
public static final Key _EventName=KeyImpl._const("EventName");
public static final Key _Expires=KeyImpl._const("Expires");
public static final Key _expires=KeyImpl._const("expires");
public static final Key _F=KeyImpl._const("F");
public static final Key _FATYPE=KeyImpl._const("FATYPE");
public static final Key _FB_=KeyImpl._const("FB_");
public static final Key _FIELD=KeyImpl._const("FIELD");
public static final Key _FILENAME=KeyImpl._const("FILENAME");
public static final Key _FILE=KeyImpl._const("FILE");
public static final Key _FILES=KeyImpl._const("FILES");
public static final Key _FROM=KeyImpl._const("FROM");
public static final Key _FUSEBOX=KeyImpl._const("FUSEBOX");
public static final Key _FUSEQ=KeyImpl._const("FUSEQ");
public static final Key _FilePath=KeyImpl._const("FilePath");
public static final Key _GET=KeyImpl._const("GET");
public static final Key _GETLOG=KeyImpl._const("GETLOG");
public static final Key _GETPARENT=KeyImpl._const("GETPARENT");
public static final Key _Globals=KeyImpl._const("Globals");
public static final Key _HASENDTAG=KeyImpl._const("HASENDTAG");
public static final Key _HASNULL=KeyImpl._const("HASNULL");
public static final Key _Host=KeyImpl._const("Host");
public static final Key _I=KeyImpl._const("I");
public static final Key _ID=KeyImpl._const("ID");
public static final Key _INCLUDES=KeyImpl._const("INCLUDES");
public static final Key _INIT=KeyImpl._const("INIT");
public static final Key _INSTANCE=KeyImpl._const("INSTANCE");
public static final Key _ISDONE=KeyImpl._const("ISDONE");
public static final Key _ISFALSE=KeyImpl._const("ISFALSE");
public static final Key _ITEM=KeyImpl._const("ITEM");
public static final Key _ITERATOR=KeyImpl._const("ITERATOR");
public static final Key _Invokes=KeyImpl._const("Invokes");
public static final Key _J=KeyImpl._const("J");
public static final Key _JAVALOADER=KeyImpl._const("JAVALOADER");
public static final Key _JOIN=KeyImpl._const("JOIN");
public static final Key _KEY=KeyImpl._const("KEY");
public static final Key _Keywords=KeyImpl._const("Keywords");
public static final Key _LABEL=KeyImpl._const("LABEL");
public static final Key _LEFT=KeyImpl._const("LEFT");
public static final Key _LEFT_TYPE=KeyImpl._const("LEFT_TYPE");
public static final Key _LEN=KeyImpl._const("LEN");
public static final Key _LINE=KeyImpl._const("LINE");
public static final Key _LOG=KeyImpl._const("LOG");
public static final Key _LOGFACTORY=KeyImpl._const("LOGFACTORY");
public static final Key _LOGID=KeyImpl._const("LOGID");
public static final Key _Language=KeyImpl._const("Language");
public static final Key _Layout=KeyImpl._const("Layout");
public static final Key _Legend=KeyImpl._const("Legend");
public static final Key _LogInAs=KeyImpl._const("LogInAs");
public static final Key _MANYTOMANY=KeyImpl._const("MANYTOMANY");
public static final Key _MANYTOONE=KeyImpl._const("MANYTOONE");
public static final Key _MEMENTO=KeyImpl._const("MEMENTO");
public static final Key _MESSAGE=KeyImpl._const("MESSAGE");
public static final Key _METHOD=KeyImpl._const("METHOD");
public static final Key _MODULENAME=KeyImpl._const("MODULENAME");
public static final Key _MYFUSEBOX=KeyImpl._const("MYFUSEBOX");
public static final Key _Message=KeyImpl._const("Message");
public static final Key _ModDate=KeyImpl._const("ModDate");
public static final Key _Modified=KeyImpl._const("Modified");
public static final Key _NAME=KeyImpl._const("NAME");
public static final Key _Name=KeyImpl._const("Name");
public static final Key _OBJECT=KeyImpl._const("OBJECT");
public static final Key _ONETOMANY=KeyImpl._const("ONETOMANY");
public static final Key _ORDER=KeyImpl._const("ORDER");
public static final Key _ORGLOCALE=KeyImpl._const("ORGLOCALE");
public static final Key _OUTER=KeyImpl._const("OUTER");
public static final Key _OUTPUT=KeyImpl._const("OUTPUT");
public static final Key _OVERRIDE=KeyImpl._const("OVERRIDE");
public static final Key _OfficeMap=KeyImpl._const("OfficeMap");
public static final Key _PARAMETERS=KeyImpl._const("PARAMETERS");
public static final Key _PATH=KeyImpl._const("PATH");
public static final Key _PETER=KeyImpl._const("PETER");
public static final Key _PREFIX=KeyImpl._const("PREFIX");
public static final Key _PRIMARYKEY=KeyImpl._const("PRIMARYKEY");
public static final Key _PROCESSES=KeyImpl._const("PROCESSES");
public static final Key _PROPERTY=KeyImpl._const("PROPERTY");
public static final Key _PageLayout=KeyImpl._const("PageLayout");
public static final Key _Pragma=KeyImpl._const("Pragma");
public static final Key _Printing=KeyImpl._const("Printing");
public static final Key _Producer=KeyImpl._const("Producer");
public static final Key _Properties=KeyImpl._const("Properties");
public static final Key _Q=KeyImpl._const("Q");
public static final Key _QRY=KeyImpl._const("QRY");
public static final Key _QUERY=KeyImpl._const("QUERY");
public static final Key _RAILO=KeyImpl._const("RAILO");
public static final Key _RBundles=KeyImpl._const("RBundles");
public static final Key _RES=KeyImpl._const("RES");
public static final Key _RESULT=KeyImpl._const("RESULT");
public static final Key _RETURN=KeyImpl._const("RETURN");
public static final Key _RIGHT=KeyImpl._const("RIGHT");
public static final Key _RTN=KeyImpl._const("RTN");
public static final Key _Raw_Trace=KeyImpl._const("Raw_Trace");
public static final Key _Referer=KeyImpl._const("Referer");
public static final Key _Roulette=KeyImpl._const("Roulette");
public static final Key _SCOPE=KeyImpl._const("SCOPE");
public static final Key _SCT=KeyImpl._const("SCT");
public static final Key _SELECT=KeyImpl._const("SELECT");
public static final Key _SETLOG=KeyImpl._const("SETLOG");
public static final Key _SETMEMENTO=KeyImpl._const("SETMEMENTO");
public static final Key _SETPARENT=KeyImpl._const("SETPARENT");
public static final Key _SETTINGS=KeyImpl._const("SETTINGS");
public static final Key _SIZE=KeyImpl._const("SIZE");
public static final Key _SOAPAction=KeyImpl._const("SOAPAction");
public static final Key _SQL=KeyImpl._const("SQL");
public static final Key _SQLState=KeyImpl._const("SQLState");
public static final Key _STARTWITH=KeyImpl._const("STARTWITH");
public static final Key _STR=KeyImpl._const("STR");
public static final Key _STRXML=KeyImpl._const("STRXML");
public static final Key _SUPER=KeyImpl._const("SUPER");
public static final Key _SUSI=KeyImpl._const("SUSI");
public static final Key _Secure=KeyImpl._const("Secure");
public static final Key _Server=KeyImpl._const("Server");
public static final Key _Signing=KeyImpl._const("Signing");
public static final Key _Sql=KeyImpl._const("Sql");
public static final Key _Subject=KeyImpl._const("Subject");
public static final Key _TABLE=KeyImpl._const("TABLE");
public static final Key _TEMPLATE=KeyImpl._const("TEMPLATE");
public static final Key _TEST=KeyImpl._const("TEST");
public static final Key _TEST2=KeyImpl._const("TEST2");
public static final Key _TESTEMPTY=KeyImpl._const("TESTEMPTY");
public static final Key _TEXT=KeyImpl._const("TEXT");
public static final Key _THIS=KeyImpl._const("THIS");
public static final Key _THISTAG=KeyImpl._const("THISTAG");
public static final Key _THROW=KeyImpl._const("THROW");
public static final Key _TIME=KeyImpl._const("TIME");
public static final Key _TOTAL_HEAP=KeyImpl._const("TOTAL_HEAP");
public static final Key _TRANSFER=KeyImpl._const("TRANSFER");
public static final Key _TYPE=KeyImpl._const("TYPE");
public static final Key _Title=KeyImpl._const("Title");
public static final Key _TotalPages=KeyImpl._const("TotalPages");
public static final Key _Trapped=KeyImpl._const("Trapped");
public static final Key _Type=KeyImpl._const("Type");
public static final Key _USER=KeyImpl._const("USER");
public static final Key _UTILITY=KeyImpl._const("UTILITY");
public static final Key _User_Agent=KeyImpl._const("User_Agent");
public static final Key _VALUE=KeyImpl._const("VALUE");
public static final Key _VERSION=KeyImpl._const("VERSION");
public static final Key _Version=KeyImpl._const("Version");
public static final Key _WHERE=KeyImpl._const("WHERE");
public static final Key _WS=KeyImpl._const("WS");
public static final Key _X=KeyImpl._const("X");
public static final Key _XFAS=KeyImpl._const("XFAS");
public static final Key _XML=KeyImpl._const("XML");
public static final Key _XMLNAME=KeyImpl._const("XMLNAME");
public static final Key _XMLTEXT=KeyImpl._const("XMLTEXT");
public static final Key __COUNT=KeyImpl._const("_COUNT");
public static final Key __TIME=KeyImpl._const("_TIME");
public static final Key ___filename=KeyImpl._const("__filename");
public static final Key ___isweb=KeyImpl._const("__isweb");
public static final Key ___name=KeyImpl._const("__name");
public static final Key __count=KeyImpl._const("_count");
public static final Key __time=KeyImpl._const("_time");
public static final Key _a=KeyImpl._const("a");
public static final Key _aaa=KeyImpl._const("aaa");
public static final Key _abort=KeyImpl._const("abort");
public static final Key _access=KeyImpl._const("access");
public static final Key _action=KeyImpl._const("action");
public static final Key _add=KeyImpl._const("add");
public static final Key _addAll=KeyImpl._const("addAll");
public static final Key _alias=KeyImpl._const("alias");
public static final Key _app=KeyImpl._const("app");
public static final Key _appManager=KeyImpl._const("appManager");
public static final Key _append=KeyImpl._const("append");
public static final Key _appserver=KeyImpl._const("appserver");
public static final Key _arg1=KeyImpl._const("arg1");
public static final Key _arg2=KeyImpl._const("arg2");
public static final Key _args=KeyImpl._const("args");
public static final Key _asin=KeyImpl._const("asin");
public static final Key _attributes=KeyImpl._const("attributes");
public static final Key _attrsewwe=KeyImpl._const("attrsewwe");
public static final Key _auth_type=KeyImpl._const("auth_type");
public static final Key _auth_user=KeyImpl._const("auth_user");
public static final Key _author=KeyImpl._const("author");
public static final Key _avg=KeyImpl._const("avg");
public static final Key _b=KeyImpl._const("b");
public static final Key _body=KeyImpl._const("body");
public static final Key _buffer=KeyImpl._const("buffer");
public static final Key _by=KeyImpl._const("by");
public static final Key _c=KeyImpl._const("c");
public static final Key _cache=KeyImpl._const("cache");
public static final Key _call=KeyImpl._const("call");
public static final Key _catch=KeyImpl._const("catch");
public static final Key _category=KeyImpl._const("category");
public static final Key _cert_flags=KeyImpl._const("cert_flags");
public static final Key _cfclient_=KeyImpl._const("cfclient_");
public static final Key _cfdocument=KeyImpl._const("cfdocument");
public static final Key _cfglobals=KeyImpl._const("cfglobals");
public static final Key _cfhttp=KeyImpl._const("cfhttp");
public static final Key _cfid=KeyImpl._const("cfid");
public static final Key _cflock=KeyImpl._const("cflock");
public static final Key _cfscript=KeyImpl._const("cfscript");
public static final Key _cftoken=KeyImpl._const("cftoken");
public static final Key _circuits=KeyImpl._const("circuits");
public static final Key _class=KeyImpl._const("class");
public static final Key _classname=KeyImpl._const("classname");
public static final Key _className=KeyImpl._const("className");
public static final Key _clear=KeyImpl._const("clear");
public static final Key _client=KeyImpl._const("client");
public static final Key _clone=KeyImpl._const("clone");
public static final Key _close=KeyImpl._const("close");
public static final Key _code=KeyImpl._const("code");
public static final Key _coldfusion=KeyImpl._const("coldfusion");
public static final Key _collection=KeyImpl._const("collection");
public static final Key _column=KeyImpl._const("column");
public static final Key _comment=KeyImpl._const("comment");
public static final Key _compareTo=KeyImpl._const("compareTo");
public static final Key _component=KeyImpl._const("component");
public static final Key _cond=KeyImpl._const("cond");
public static final Key _condition=KeyImpl._const("condition");
public static final Key _configXML=KeyImpl._const("configXML");
public static final Key _configure=KeyImpl._const("configure");
public static final Key _contains=KeyImpl._const("contains");
public static final Key _content=KeyImpl._const("content");
public static final Key _contentArg=KeyImpl._const("contentArg");
public static final Key _context=KeyImpl._const("context");
public static final Key _controller=KeyImpl._const("controller");
public static final Key _count=KeyImpl._const("count");
public static final Key _cs=KeyImpl._const("cs");
public static final Key _custom=KeyImpl._const("custom");
public static final Key _custom1=KeyImpl._const("custom1");
public static final Key _custom2=KeyImpl._const("custom2");
public static final Key _custom3=KeyImpl._const("custom3");
public static final Key _custom4=KeyImpl._const("custom4");
public static final Key _customx=KeyImpl._const("customx");
public static final Key _d=KeyImpl._const("d");
public static final Key _data=KeyImpl._const("data");
public static final Key _data1=KeyImpl._const("data1");
public static final Key _data2=KeyImpl._const("data2");
public static final Key _data_ID=KeyImpl._const("data_ID");
public static final Key _data_id=KeyImpl._const("data_id");
public static final Key _datasource=KeyImpl._const("datasource");
public static final Key _date=KeyImpl._const("date");
public static final Key _dc_date=KeyImpl._const("dc_date");
public static final Key _dc_subject=KeyImpl._const("dc_subject");
public static final Key _debug=KeyImpl._const("debug");
public static final Key _debugging=KeyImpl._const("debugging");
public static final Key _decorator=KeyImpl._const("decorator");
public static final Key _default=KeyImpl._const("default");
public static final Key _delete=KeyImpl._const("delete");
public static final Key _detail=KeyImpl._const("detail");
public static final Key _dir=KeyImpl._const("dir");
public static final Key _directory=KeyImpl._const("directory");
public static final Key _duplicates=KeyImpl._const("duplicates");
public static final Key _email=KeyImpl._const("email");
public static final Key _en_US=KeyImpl._const("en_US");
public static final Key _encoded=KeyImpl._const("encoded");
public static final Key _entry=KeyImpl._const("entry");
public static final Key _equals=KeyImpl._const("equals");
public static final Key _errorcode=KeyImpl._const("errorcode");
public static final Key _errortext=KeyImpl._const("errortext");
public static final Key _eval=KeyImpl._const("eval");
public static final Key _evaluation=KeyImpl._const("evaluation");
public static final Key _event=KeyImpl._const("event");
public static final Key _eventArgs=KeyImpl._const("eventArgs");
public static final Key _exe=KeyImpl._const("exe");
public static final Key _expand=KeyImpl._const("expand");
public static final Key _fb_=KeyImpl._const("fb_");
public static final Key _field=KeyImpl._const("field");
public static final Key _field1=KeyImpl._const("field1");
public static final Key _field2=KeyImpl._const("field2");
public static final Key _file=KeyImpl._const("file");
public static final Key _first=KeyImpl._const("first");
public static final Key _fontColor=KeyImpl._const("fontColor");
public static final Key _format=KeyImpl._const("format");
public static final Key _from=KeyImpl._const("from");
public static final Key _fullpath=KeyImpl._const("fullpath");
public static final Key _fusebox=KeyImpl._const("fusebox");
public static final Key _geo=KeyImpl._const("geo");
public static final Key _ger=KeyImpl._const("ger");
public static final Key _get=KeyImpl._const("get");
public static final Key _getArg=KeyImpl._const("getArg");
public static final Key _getBytes=KeyImpl._const("getBytes");
public static final Key _getClass=KeyImpl._const("getClass");
public static final Key _getColumn=KeyImpl._const("getColumn");
public static final Key _getLink=KeyImpl._const("getLink");
public static final Key _getLog=KeyImpl._const("getLog");
public static final Key _getMethod=KeyImpl._const("getMethod");
public static final Key _getName=KeyImpl._const("getName");
public static final Key _getObject=KeyImpl._const("getObject");
public static final Key _getParent=KeyImpl._const("getParent");
public static final Key _getRooms=KeyImpl._const("getRooms");
public static final Key _getSetting=KeyImpl._const("getSetting");
public static final Key _getString=KeyImpl._const("getString");
public static final Key _getTable=KeyImpl._const("getTable");
public static final Key _getTo=KeyImpl._const("getTo");
public static final Key _getType=KeyImpl._const("getType");
public static final Key _guid=KeyImpl._const("guid");
public static final Key _happy=KeyImpl._const("happy");
public static final Key _hasNext=KeyImpl._const("hasNext");
public static final Key _hashCode=KeyImpl._const("hashCode");
public static final Key _header=KeyImpl._const("header");
public static final Key _headers=KeyImpl._const("headers");
public static final Key _height=KeyImpl._const("height");
public static final Key _hide=KeyImpl._const("hide");
public static final Key _highlight=KeyImpl._const("highlight");
public static final Key _hint=KeyImpl._const("hint");
public static final Key _hit_count=KeyImpl._const("hit_count");
public static final Key _hitcount=KeyImpl._const("hitcount");
public static final Key _hits=KeyImpl._const("hits");
public static final Key _href=KeyImpl._const("href");
public static final Key _hreflang=KeyImpl._const("hreflang");
public static final Key _html=KeyImpl._const("html");
public static final Key _http_Host=KeyImpl._const("http_Host");
public static final Key _http_host=KeyImpl._const("http_host");
public static final Key _https=KeyImpl._const("https");
public static final Key _i=KeyImpl._const("i");
public static final Key _id=KeyImpl._const("id");
public static final Key _idx=KeyImpl._const("idx");
public static final Key _indexOf=KeyImpl._const("indexOf");
public static final Key _init=KeyImpl._const("init");
public static final Key _innerJoin=KeyImpl._const("innerJoin");
public static final Key _insert=KeyImpl._const("insert");
public static final Key _instance=KeyImpl._const("instance");
public static final Key _is31=KeyImpl._const("is31");
public static final Key _is7=KeyImpl._const("is7");
public static final Key _is8=KeyImpl._const("is8");
public static final Key _isDSTon=KeyImpl._const("isDSTon");
public static final Key _isEmpty=KeyImpl._const("isEmpty");
public static final Key _israilo11=KeyImpl._const("israilo11");
public static final Key _item=KeyImpl._const("item");
public static final Key _iterator=KeyImpl._const("iterator");
public static final Key _j=KeyImpl._const("j");
public static final Key _java=KeyImpl._const("java");
public static final Key _javaLoader=KeyImpl._const("javaLoader");
public static final Key _jsessionid=KeyImpl._const("jsessionid");
public static final Key _key=KeyImpl._const("key");
public static final Key _keys=KeyImpl._const("keys");
public static final Key _label=KeyImpl._const("label");
public static final Key _lang=KeyImpl._const("lang");
public static final Key _lastvisit=KeyImpl._const("lastvisit");
public static final Key _layouts=KeyImpl._const("layouts");
public static final Key _left=KeyImpl._const("left");
public static final Key _len=KeyImpl._const("len");
public static final Key _length=KeyImpl._const("length");
public static final Key _letters=KeyImpl._const("letters");
public static final Key _level=KeyImpl._const("level");
public static final Key _lft=KeyImpl._const("lft");
public static final Key _line=KeyImpl._const("line");
public static final Key _link=KeyImpl._const("link");
public static final Key _list=KeyImpl._const("list");
public static final Key _listUsers=KeyImpl._const("listUsers");
public static final Key _listener=KeyImpl._const("listener");
public static final Key _load=KeyImpl._const("load");
public static final Key _local_addr=KeyImpl._const("local_addr");
public static final Key _local_host=KeyImpl._const("local_host");
public static final Key _logFactory=KeyImpl._const("logFactory");
public static final Key _logid=KeyImpl._const("logid");
public static final Key _login=KeyImpl._const("login");
public static final Key _logout=KeyImpl._const("logout");
public static final Key _m=KeyImpl._const("m");
public static final Key _main=KeyImpl._const("main");
public static final Key _max=KeyImpl._const("max");
public static final Key _maxEvents=KeyImpl._const("maxEvents");
public static final Key _memento=KeyImpl._const("memento");
public static final Key _message=KeyImpl._const("message");
public static final Key _messageid=KeyImpl._const("messageid");
public static final Key _meta=KeyImpl._const("meta");
public static final Key _metadata=KeyImpl._const("metadata");
public static final Key _metainfo=KeyImpl._const("metainfo");
public static final Key _method=KeyImpl._const("method");
public static final Key _methodcall=KeyImpl._const("methodcall");
public static final Key _min=KeyImpl._const("min");
public static final Key _minus=KeyImpl._const("minus");
public static final Key _mode=KeyImpl._const("mode");
public static final Key _moduleName=KeyImpl._const("moduleName");
public static final Key _myFusebox=KeyImpl._const("myFusebox");
public static final Key _name=KeyImpl._const("name");
public static final Key _needssetup=KeyImpl._const("needssetup");
public static final Key _next=KeyImpl._const("next");
public static final Key _nosetup=KeyImpl._const("nosetup");
public static final Key _notify=KeyImpl._const("notify");
public static final Key _notifyAll=KeyImpl._const("notifyAll");
public static final Key _nullable=KeyImpl._const("nullable");
public static final Key _nullvalue=KeyImpl._const("nullvalue");
public static final Key _obj=KeyImpl._const("obj");
public static final Key _object=KeyImpl._const("object");
public static final Key _officeMap=KeyImpl._const("officeMap");
public static final Key _onChange=KeyImpl._const("onChange");
public static final Key _opensample=KeyImpl._const("opensample");
public static final Key _os=KeyImpl._const("os");
public static final Key _out=KeyImpl._const("out");
public static final Key _output=KeyImpl._const("output");
public static final Key _override=KeyImpl._const("override");
public static final Key _overwrite=KeyImpl._const("overwrite");
public static final Key _owner=KeyImpl._const("owner");
public static final Key _package=KeyImpl._const("package");
public static final Key _page=KeyImpl._const("page");
public static final Key _pages=KeyImpl._const("pages");
public static final Key _parameters=KeyImpl._const("parameters");
public static final Key _parent=KeyImpl._const("parent");
public static final Key _password=KeyImpl._const("password");
public static final Key _username=KeyImpl._const("username");
public static final Key _path=KeyImpl._const("path");
public static final Key _path_info=KeyImpl._const("path_info");
public static final Key _pattern=KeyImpl._const("pattern");
public static final Key _pdf=KeyImpl._const("pdf");
public static final Key _permiss=KeyImpl._const("permiss");
public static final Key _plus=KeyImpl._const("plus");
public static final Key _pointer=KeyImpl._const("pointer");
public static final Key _pos=KeyImpl._const("pos");
public static final Key _preProcess=KeyImpl._const("preProcess");
public static final Key _prefix=KeyImpl._const("prefix");
public static final Key _prepend=KeyImpl._const("prepend");
public static final Key _primarykey=KeyImpl._const("primarykey");
public static final Key _productid=KeyImpl._const("productid");
public static final Key _property=KeyImpl._const("property");
public static final Key _published=KeyImpl._const("published");
public static final Key _put=KeyImpl._const("put");
public static final Key _q=KeyImpl._const("q");
public static final Key _qDir=KeyImpl._const("qDir");
public static final Key _qry=KeyImpl._const("qry");
public static final Key _qtest=KeyImpl._const("qtest");
public static final Key _query=KeyImpl._const("query");
public static final Key _queryCache=KeyImpl._const("queryCache");
public static final Key _queryError=KeyImpl._const("queryError");
public static final Key _r99f=KeyImpl._const("r99f");
public static final Key _railo=KeyImpl._const("railo");
public static final Key _railoweb=KeyImpl._const("railoweb");
public static final Key _rank=KeyImpl._const("rank");
public static final Key _rel=KeyImpl._const("rel");
public static final Key _remove=KeyImpl._const("remove");
public static final Key _replace=KeyImpl._const("replace");
public static final Key _replyto=KeyImpl._const("replyto");
public static final Key _required=KeyImpl._const("required");
public static final Key _res=KeyImpl._const("res");
public static final Key _result=KeyImpl._const("result");
public static final Key _resultArg=KeyImpl._const("resultArg");
public static final Key _return=KeyImpl._const("return");
public static final Key _rgt=KeyImpl._const("rgt");
public static final Key _right=KeyImpl._const("right");
public static final Key _rootpath=KeyImpl._const("rootpath");
public static final Key _rst=KeyImpl._const("rst");
public static final Key _sad=KeyImpl._const("sad");
public static final Key _scope=KeyImpl._const("scope");
public static final Key _scopeKey=KeyImpl._const("scopeKey");
public static final Key _score=KeyImpl._const("score");
public static final Key _sct=KeyImpl._const("sct");
public static final Key _search=KeyImpl._const("search");
public static final Key _security=KeyImpl._const("security");
public static final Key _separator=KeyImpl._const("separator");
public static final Key _server=KeyImpl._const("server");
public static final Key _servlet=KeyImpl._const("servlet");
public static final Key _sessionid=KeyImpl._const("sessionid");
public static final Key _set=KeyImpl._const("set");
public static final Key _setEL=KeyImpl._const("setEL");
public static final Key _setFirst=KeyImpl._const("setFirst");
public static final Key _setMemento=KeyImpl._const("setMemento");
public static final Key _show=KeyImpl._const("show");
public static final Key _showudfs=KeyImpl._const("showudfs");
public static final Key _size=KeyImpl._const("size");
public static final Key _sleep=KeyImpl._const("sleep");
public static final Key _source=KeyImpl._const("source");
public static final Key _sql=KeyImpl._const("sql");
public static final Key _src=KeyImpl._const("src");
public static final Key _start=KeyImpl._const("start");
public static final Key _end=KeyImpl._const("end");
public static final Key _startwith=KeyImpl._const("startwith");
public static final Key _state=KeyImpl._const("state");
public static final Key _status=KeyImpl._const("status");
public static final Key _stop=KeyImpl._const("stop");
public static final Key _store=KeyImpl._const("store");
public static final Key _str=KeyImpl._const("str");
public static final Key _strXML=KeyImpl._const("strXML");
public static final Key _subject=KeyImpl._const("subject");
public static final Key _substring=KeyImpl._const("substring");
public static final Key _succeeded=KeyImpl._const("succeeded");
public static final Key _summary=KeyImpl._const("summary");
public static final Key _susi=KeyImpl._const("susi");
public static final Key _susi2=KeyImpl._const("susi2");
public static final Key _table=KeyImpl._const("table");
public static final Key _tagname=KeyImpl._const("tagname");
public static final Key _tc=KeyImpl._const("tc");
public static final Key _template=KeyImpl._const("template");
public static final Key _templates=KeyImpl._const("templates");
public static final Key _test=KeyImpl._const("test");
public static final Key _test1=KeyImpl._const("test1");
public static final Key _test2=KeyImpl._const("test2");
public static final Key _testcustom=KeyImpl._const("testcustom");
public static final Key _testfile=KeyImpl._const("testfile");
public static final Key _testquery=KeyImpl._const("testquery");
public static final Key _text=KeyImpl._const("text");
public static final Key _this=KeyImpl._const("this");
public static final Key _thistag=KeyImpl._const("thistag");
public static final Key _thread=KeyImpl._const("thread");
public static final Key _time=KeyImpl._const("time");
public static final Key _timers=KeyImpl._const("timers");
public static final Key _timespan=KeyImpl._const("timespan");
public static final Key _title=KeyImpl._const("title");
public static final Key _to=KeyImpl._const("to");
public static final Key _toArray=KeyImpl._const("toArray");
public static final Key _toString=KeyImpl._const("toString");
public static final Key _top=KeyImpl._const("top");
public static final Key _total=KeyImpl._const("total");
public static final Key _traces=KeyImpl._const("traces");
public static final Key _transfer=KeyImpl._const("transfer");
public static final Key _tree=KeyImpl._const("tree");
public static final Key _type=KeyImpl._const("type");
public static final Key _uid=KeyImpl._const("uid");
public static final Key _updated=KeyImpl._const("updated");
public static final Key _uri=KeyImpl._const("uri");
public static final Key _url=KeyImpl._const("url");
public static final Key _urlBase=KeyImpl._const("urlBase");
public static final Key _urltoken=KeyImpl._const("urltoken");
public static final Key _usage=KeyImpl._const("usage");
public static final Key _utility=KeyImpl._const("utility");
public static final Key _v=KeyImpl._const("v");
public static final Key _v_pages=KeyImpl._const("v_pages");
public static final Key _validate=KeyImpl._const("validate");
public static final Key _value=KeyImpl._const("value");
public static final Key _valueOf=KeyImpl._const("valueOf");
public static final Key _var=KeyImpl._const("var");
public static final Key _varname=KeyImpl._const("varname");
public static final Key _varvalue=KeyImpl._const("varvalue");
public static final Key _version=KeyImpl._const("version");
public static final Key _visitBeach=KeyImpl._const("visitBeach");
public static final Key _visitHal=KeyImpl._const("visitHal");
public static final Key _visitJohn=KeyImpl._const("visitJohn");
public static final Key _visitOcean=KeyImpl._const("visitOcean");
public static final Key _wait=KeyImpl._const("wait");
public static final Key _where=KeyImpl._const("where");
public static final Key _width=KeyImpl._const("width");
public static final Key _writeLine=KeyImpl._const("writeLine");
public static final Key _wsdl=KeyImpl._const("wsdl");
public static final Key _x=KeyImpl._const("x");
public static final Key _xfa=KeyImpl._const("xfa");
public static final Key _xml=KeyImpl._const("xml");
public static final Key _xtags=KeyImpl._const("xtags");
public static final Key _returnFormat=KeyImpl._const("returnFormat");
public static final Key _s3=KeyImpl._const("s3");
public static final Key _super=KeyImpl._const("super");
public static final Key _argumentCollection=KeyImpl._const("argumentCollection");
public static final Key _argumentcollection=KeyImpl._const("argumentcollection");
public static final Key _setArgumentCollection=KeyImpl._const("setArgumentCollection");
public static final Key _returntype=KeyImpl._const("returntype");
public static final Key _description=KeyImpl._const("description");
public static final Key _displayname=KeyImpl._const("displayname");
public static final Key _arguments=KeyImpl._const("arguments");
public static final Key _variables=KeyImpl._const("variables");
public static final Key _fieldnames=KeyImpl._const("fieldnames");
public static final Key _local=KeyImpl._const("local");
public static final Key _exceptions=KeyImpl._const("exceptions");
public static final Key _closure=KeyImpl._const("closure");
public static final Key _function=KeyImpl._const("function");
public static final Key _cgi = KeyImpl._const("cgi");
public static final Key _all = KeyImpl._const("all");
public static final Key _tag = KeyImpl._const("tag");
public static final Key _classic = KeyImpl._const("classic");
public static final Key _simple = KeyImpl._const("simple");
public static final Key _hidden = KeyImpl._const("hidden");
public static final Key _external = KeyImpl._const("external");
public static final Key _charset = KeyImpl._const("charset");
public static final Key _created = KeyImpl._const("created");
public static final Key _language = KeyImpl._const("language");
public static final Key _online = KeyImpl._const("online");
public static final Key _lastmodified = KeyImpl._const("lastmodified");
public static final Key _lastModified = KeyImpl._const("lastModified");
public static final Key _task=KeyImpl._const("task");
public static final Key _port=KeyImpl._const("port");
public static final Key _timecreated=KeyImpl._const("timecreated");
public static final Key _hash=KeyImpl._const("hash");
public static final Key _root=KeyImpl._const("root");
public static final Key _sourcename=KeyImpl._const("sourcename");
public static final Key _readonly=KeyImpl._const("readonly");
public static final Key _isvalid=KeyImpl._const("isvalid");
public static final Key _config=KeyImpl._const("config");
public static final Key _executionTime = KeyImpl._const("executionTime");
public static final Key _RECORDCOUNT = KeyImpl._const("RECORDCOUNT");
public static final Key _cached = KeyImpl._const("cached");
public static final Key _COLUMNLIST = KeyImpl._const("COLUMNLIST");
public static final Key _CURRENTROW = KeyImpl._const("CURRENTROW");
public static final Key _IDENTITYCOL = KeyImpl._const("IDENTITYCOL");
public static final Key _dateLastModified = KeyImpl._const("dateLastModified");
public static final Key _statuscode = KeyImpl._const("statuscode");
public static final Key _statustext = KeyImpl._const("statustext");
public static final Key _extends = KeyImpl._const("extends");
public static final Key _implements = KeyImpl._const("implements");
public static final Key __toDateTime = KeyImpl._const("_toDateTime");
public static final Key __toNumeric = KeyImpl._const("_toNumeric");
public static final Key __toBoolean = KeyImpl._const("_toBoolean");
public static final Key __toString = KeyImpl._const("_toString");
public static final Key _onmissingmethod = KeyImpl._const("onmissingmethod");
public static final Key _functions = KeyImpl._const("functions");
public static final Key _fullname = KeyImpl._const("fullname");
public static final Key _skeleton = KeyImpl._const("skeleton");
public static final Key _properties = KeyImpl._const("properties");
public static final Key _mappedSuperClass = KeyImpl._const("mappedSuperClass");
public static final Key _persistent = KeyImpl._const("persistent");
public static final Key _accessors = KeyImpl._const("accessors");
public static final Key _synchronized = KeyImpl._const("synchronized");
public static final Key _queryFormat = KeyImpl._const("queryFormat");
public static final Key _Hint= KeyImpl._const("Hint");
public static final Key _Entities= KeyImpl._const("Entities");
public static final Key _Pattern= KeyImpl._const("Pattern");
public static final Key _last_modified = KeyImpl._const("last_modified");
public static final Key _context_path = KeyImpl._const("context_path");
public static final Key _query_string = KeyImpl._const("query_string");
public static final Key _path_translated = KeyImpl._const("path_translated");
public static final Key _server_port_secure = KeyImpl._const("server_port_secure");
public static final Key _server_port = KeyImpl._const("server_port");
public static final Key _server_protocol = KeyImpl._const("server_protocol");
public static final Key _server_name = KeyImpl._const("server_name");
public static final Key _script_name = KeyImpl._const("script_name");
public static final Key _http_if_modified_since = KeyImpl._const("http_if_modified_since");
public static final Key _cf_template_path = KeyImpl._const("cf_template_path");
public static final Key _remote_user = KeyImpl._const("remote_user");
public static final Key _remote_addr = KeyImpl._const("remote_addr");
public static final Key _remote_host = KeyImpl._const("remote_host");
public static final Key _request_method = KeyImpl._const("request_method");
public static final Key _REDIRECT_URL = KeyImpl._const("REDIRECT_URL");
public static final Key _request_uri = KeyImpl._const("request_uri");
public static final Key _REDIRECT_QUERY_STRING = KeyImpl._const("REDIRECT_QUERY_STRING");
public static final Key _auth_password = KeyImpl._const("auth_password");
public static final Key _cert_cookie = KeyImpl._const("cert_cookie");
public static final Key _cert_keysize = KeyImpl._const("cert_keysize");
public static final Key _cert_serialnumber = KeyImpl._const("cert_serialnumber");
public static final Key _cert_issuer = KeyImpl._const("cert_issuer");
public static final Key _cert_secretkeysize = KeyImpl._const("cert_secretkeysize");
public static final Key _cert_server_subject = KeyImpl._const("cert_server_subject");
public static final Key _cert_server_issuer = KeyImpl._const("cert_server_issuer");
public static final Key _cert_subject = KeyImpl._const("cert_subject");
public static final Key _gateway_interface = KeyImpl._const("gateway_interface");
public static final Key _content_length = KeyImpl._const("content_length");
public static final Key _http_accept = KeyImpl._const("http_accept");
public static final Key _content_type = KeyImpl._const("content_type");
public static final Key _http_connection = KeyImpl._const("http_connection");
public static final Key _http_cookie = KeyImpl._const("http_cookie");
public static final Key _http_accept_encoding = KeyImpl._const("http_accept_encoding");
public static final Key _http_accept_language = KeyImpl._const("http_accept_language");
public static final Key _http_user_agent = KeyImpl._const("http_user_agent");
public static final Key _https_keysize = KeyImpl._const("https_keysize");
public static final Key _http_referer = KeyImpl._const("http_referer");
public static final Key _https_secretkeysize = KeyImpl._const("https_secretkeysize");
public static final Key _https_server_issuer = KeyImpl._const("https_server_issuer");
public static final Key _https_server_subject = KeyImpl._const("https_server_subject");
public static final Key _web_server_api = KeyImpl._const("web_server_api");
public static final Key _server_software = KeyImpl._const("server_software");
public static final Key _application = KeyImpl._const("application");
public static final Key _cookie = KeyImpl._const("cookie");
public static final Key _cluster = KeyImpl._const("cluster");
public static final Key _form = KeyImpl._const("form");
public static final Key _request = KeyImpl._const("request");
public static final Key _session = KeyImpl._const("session");
public static final Key _cferror = KeyImpl._const("cferror");
public static final Key _error = KeyImpl._const("error");
public static final Key _cfthread = KeyImpl._const("cfthread");
public static final Key _cfcatch = KeyImpl._const("cfcatch");
public static final Key _used = KeyImpl._const("used");
public static final Key _use = KeyImpl._const("use");
public static final Key _Detail = KeyImpl._const("Detail");
public static final Key _attributecollection = KeyImpl._const("attributecollection");
public static final Key _attributeCollection = KeyImpl._const("attributeCollection");
public static final Key _secure = KeyImpl._const("secure");
public static final Key _httponly = KeyImpl._const("httponly");
public static final Key _domain = KeyImpl._const("domain");
public static final Key _preservecase = KeyImpl._const("preservecase");
public static final Key _encode = KeyImpl._const("encode");
public static final Key _encodevalue = KeyImpl._const("encodevalue");
public static final Key _each = KeyImpl._const("each");
public static final Key _member = KeyImpl._const("member");
public static final Key _resource = KeyImpl._const("resource");
public static final Key _img = KeyImpl._const("img");
public static final Key _cfcLocation = KeyImpl._const("cfcLocation");
public static final Key _cfcLocations = KeyImpl._const("cfcLocations");
public static final Key _skipCFCWithError = KeyImpl._const("skipCFCWithError");
public static final Key _destination = KeyImpl._const("destination");
public static final Key _codec = KeyImpl._const("codec");
public static final Key _chaining = KeyImpl._const("chaining");
public static final Key _protocol = KeyImpl._const("protocol");
public static final Key _enabled = KeyImpl._const("enabled");
public static final Key _fieldtype = KeyImpl._const("fieldtype");
public static final Key _cfc = KeyImpl._const("cfc");
public static final Key _memory = KeyImpl._const("memory");
public static final Key _scopes = KeyImpl._const("scopes");
public static final Key _mappings = KeyImpl._const("mappings");
public static final Key _web = KeyImpl._const("web");
public static final Key _mimetype = KeyImpl._const("mimetype");
public static final Key _0 = KeyImpl._const("0");
public static final Key _1 = KeyImpl._const("1");
public static final Key _2 = KeyImpl._const("2");
public static final Key _3 = KeyImpl._const("3");
public static final Key _4 = KeyImpl._const("4");
public static final Key _5 = KeyImpl._const("5");
public static final Key _6 = KeyImpl._const("6");
public static final Key _7 = KeyImpl._const("7");
public static final Key _8 = KeyImpl._const("8");
public static final Key _9 = KeyImpl._const("9");
public static final Key _PRODUCTNAME = KeyImpl._const("PRODUCTNAME");
public static final Key _BODY = KeyImpl._const("BODY");
public static final Key _XMLVALUE = KeyImpl._const("XMLVALUE");
public static final Key _EL = KeyImpl._const("EL");
public static final Key _M = KeyImpl._const("M");
public static final Key _N = KeyImpl._const("N");
public static final Key _TEST1 = KeyImpl._const("TEST1");
public static final Key _TEST3 = KeyImpl._const("TEST3");
public static final Key _XMLDATA = KeyImpl._const("XMLDATA");
public static final Key _XMLDOC = KeyImpl._const("XMLDOC");
public static final Key _XMLROOT = KeyImpl._const("XMLROOT");
public static final Key _XMLATTRIBUTES = KeyImpl._const("XMLATTRIBUTES");
public static final Key _XMLCHILDREN = KeyImpl._const("XMLCHILDREN");
public static final Key _XMLCOMMENT = KeyImpl._const("XMLCOMMENT");
public static final Key _CHILDREN = KeyImpl._const("CHILDREN");
public static final Key _ELEMENT = KeyImpl._const("ELEMENT");
public static final Key _WARNINGS = KeyImpl._const("WARNINGS");
public static final Key _VALIDATE = KeyImpl._const("VALIDATE");
public static final Key _ERRORS = KeyImpl._const("ERRORS");
public static final Key _STATUS = KeyImpl._const("STATUS");
public static final Key _FATALERRORS = KeyImpl._const("FATALERRORS");
public static final Key _timeout = KeyImpl._const("timeout");
public static final Key _host = KeyImpl._const("host");
public static final Key _urlpath = KeyImpl._const("urlpath");
public static final Key _extensions = KeyImpl._const("extensions");
public static final Key _STATE = KeyImpl._const("STATE");
public static final Key _START = KeyImpl._const("START");
public static final Key _STOP = KeyImpl._const("STOP");
public static final Key _LAST = KeyImpl._const("LAST");
public static final Key _CONFIG = KeyImpl._const("CONFIG");
public static final Key _DIFF = KeyImpl._const("DIFF");
public static final Key _COLL = KeyImpl._const("COLL");
public static final Key _FILTER = KeyImpl._const("FILTER");
public static final Key _recurse = KeyImpl._const("recurse");
public static final Key _rest = KeyImpl._const("rest");
public static final Key _httpmethod = KeyImpl._const("httpmethod");
public static final Key _restPath = KeyImpl._const("restPath");
public static final Key _restArgName = KeyImpl._const("restArgName");
public static final Key _restArgSource = KeyImpl._const("restArgSource");
public static final Key _consumes = KeyImpl._const("consumes");
public static final Key _produces = KeyImpl._const("produces");
public static final Key _ref = KeyImpl._const("ref");
public static final Key _script = KeyImpl._const("script");
private static HashSet<String> _____keys;
public static String getFieldName(String key) {
if(_____keys==null) {
Field[] fields = KeyConstants.class.getFields();
_____keys=new HashSet<String>();
for(int i=0;i<fields.length;i++){
if(fields[i].getType()!=Key.class) continue;
_____keys.add(fields[i].getName());
}
}
key="_"+key;
return _____keys.contains(key)?key:null;
}
} |
package org.redisson;
import java.util.Locale;
public class RedissonRuntimeEnvironment {
public static final boolean isTravis = "true".equalsIgnoreCase(System.getProperty("travisEnv"));
public static final String redisBinaryPath = System.getProperty("redisBinary", "C:\\Devel\\projects\\redis\\redis-x64-4.0.2.2\\redis-server.exe");
public static final String tempDir = System.getProperty("java.io.tmpdir");
public static final String OS;
public static final boolean isWindows;
static {
OS = System.getProperty("os.name", "generic");
isWindows = OS.toLowerCase(Locale.ENGLISH).contains("win");
}
} |
package com.neverwinterdp.vm.client;
import static com.neverwinterdp.vm.tool.VMClusterBuilder.h1;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeoutException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import com.mycila.jmx.annotation.JmxBean;
import com.neverwinterdp.registry.ErrorCode;
import com.neverwinterdp.registry.Node;
import com.neverwinterdp.registry.NodeCreateMode;
import com.neverwinterdp.registry.Registry;
import com.neverwinterdp.registry.RegistryException;
import com.neverwinterdp.registry.event.NodeEvent;
import com.neverwinterdp.registry.event.NodeWatcher;
import com.neverwinterdp.vm.VMConfig;
import com.neverwinterdp.vm.VMDescriptor;
import com.neverwinterdp.vm.command.Command;
import com.neverwinterdp.vm.command.CommandPayload;
import com.neverwinterdp.vm.command.CommandResult;
import com.neverwinterdp.vm.command.VMCommand;
import com.neverwinterdp.vm.service.VMService;
import com.neverwinterdp.vm.service.VMServiceCommand;
@JmxBean("role=vm-client, type=VMClient, name=VMClient")
public class VMClient {
final static public String APPLICATIONS = "/applications";
private Registry registry;
private long waitForResultTimeout = 60000;
public VMClient(Registry registry) {
this.registry = registry;
}
public Registry getRegistry() { return this.registry ; }
public long getWaitForResultTimeout() { return waitForResultTimeout; }
public void setWaitForResultTimeout(long waitForResultTimeout) {
this.waitForResultTimeout = waitForResultTimeout;
}
public List<VMDescriptor> getActiveVMDescriptors() throws RegistryException {
return VMService.getActiveVMDescriptors(registry) ;
}
public List<VMDescriptor> getHistoryVMDescriptors() throws RegistryException {
return VMService.getHistoryVMDescriptors(registry) ;
}
public List<VMDescriptor> getAllVMDescriptors() throws RegistryException {
return VMService.getAllVMDescriptors(registry) ;
}
public VMDescriptor getMasterVMDescriptor() throws RegistryException {
Node vmNode = registry.getRef(VMService.LEADER_PATH);
return vmNode.getDataAs(VMDescriptor.class);
}
public void shutdown() throws Exception {
h1("Shutdow the vm masters");
registry.create(VMService.SHUTDOWN_EVENT_PATH, true, NodeCreateMode.PERSISTENT);
}
public CommandResult<?> execute(VMDescriptor vmDescriptor, Command command) throws RegistryException, Exception {
return execute(vmDescriptor, command, waitForResultTimeout);
}
public CommandResult<?> execute(VMDescriptor vmDescriptor, Command command, long timeout) throws Exception {
CommandPayload payload = new CommandPayload(command, null) ;
Node node = registry.create(vmDescriptor.getRegistryPath() + "/commands/command-", payload, NodeCreateMode.PERSISTENT_SEQUENTIAL);
CommandReponseWatcher responseWatcher = new CommandReponseWatcher(registry, node.getPath(), command);
node.watchModify(responseWatcher);
return responseWatcher.waitForResult(timeout);
}
public void execute(VMDescriptor vmDescriptor, Command command, CommandCallback callback) {
}
public VMDescriptor allocate(VMConfig vmConfig) throws Exception {
VMDescriptor masterVMDescriptor = getMasterVMDescriptor();
CommandResult<VMDescriptor> result =
(CommandResult<VMDescriptor>) execute(masterVMDescriptor, new VMServiceCommand.Allocate(vmConfig));
if(result.getErrorStacktrace() != null) {
registry.get("/").dump(System.err);
throw new Exception(result.getErrorStacktrace());
}
return result.getResult();
}
public boolean shutdown(VMDescriptor vmDescriptor) throws Exception {
CommandResult<?> result = execute(vmDescriptor, new VMCommand.Shutdown());
if(result.isDiscardResult()) return true;
return result.getResultAs(Boolean.class);
}
public boolean simulateKill(VMDescriptor vmDescriptor) throws Exception {
CommandResult<?> result = execute(vmDescriptor, new VMCommand.SimulateKill());
if(result.isDiscardResult()) return true;
return result.getResultAs(Boolean.class);
}
public boolean kill(VMDescriptor vmDescriptor) throws Exception {
//CommandResult<?> result = execute(vmDescriptor, new VMCommand.Kill());
Command command = new VMCommand.Kill();
CommandPayload payload = new CommandPayload(command, null) ;
Node node = registry.create(vmDescriptor.getRegistryPath() + "/commands/command-", payload, NodeCreateMode.PERSISTENT_SEQUENTIAL);
CommandReponseWatcher responseWatcher = new CommandReponseWatcher(registry, node.getPath(), command);
node.watchModify(responseWatcher);
try {
CommandResult<?> result = responseWatcher.waitForResult(60000);
if(result.isDiscardResult()) return true;
return result.getResultAs(Boolean.class);
} catch(Exception ex) {
throw ex ;
}
}
public boolean kill(VMDescriptor vmDescriptor, long timeout) throws Exception {
CommandResult<?> result = execute(vmDescriptor, new VMCommand.Kill(), timeout);
if(result.isDiscardResult()) return true;
return result.getResultAs(Boolean.class);
}
public FileSystem getFileSystem() throws IOException {
return FileSystem.get(new Configuration());
}
public void uploadApp(String localAppHome, String appHome) throws Exception {
}
public void createVMMaster(String localAppHome, String name) throws Exception {
throw new RuntimeException("This method need to override") ;
}
public void configureEnvironment(VMConfig vmConfig) {
throw new RuntimeException("This method need to override") ;
}
static public class CommandReponseWatcher extends NodeWatcher {
private Registry registry;
private String path;
private Command command ;
private CommandResult<?> result;
private Exception error;
private boolean discardResult = false;
public CommandReponseWatcher(Registry registry, String path, Command command) {
this.registry = registry;
this.path = path;
this.command = command ;
}
@Override
public void onEvent(NodeEvent event) {
String path = event.getPath();
try {
if(event.getType() == NodeEvent.Type.DELETE) {
discardResult = true ;
return ;
} else {
CommandPayload payload = registry.getDataAs(path, CommandPayload.class) ;
result = payload.getResult() ;
registry.delete(path);
}
} catch(RegistryException e) {
error = e ;
if(e.getErrorCode() == ErrorCode.NoNode) {
discardResult = true ;
}
} finally {
notifyForResult() ;
}
}
synchronized void notifyForResult() {
notifyAll() ;
}
synchronized public CommandResult<?> waitForResult(long timeout) throws Exception {
if(result == null) {
wait(timeout);
}
if(discardResult) {
result = new CommandResult<Object>() ;
result.setDiscardResult(true);
}
if(error != null) throw error;
if(result == null) {
String errorMsg = "Cannot get the result after " + timeout + "ms, command = " + command.getClass() +", path = " + path ;
throw new TimeoutException(errorMsg) ;
}
return result ;
}
}
} |
package io.flutter.view;
import android.annotation.TargetApi;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Insets;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.os.Build;
import android.os.Handler;
import android.os.LocaleList;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.annotation.UiThread;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowInsets;
import android.view.accessibility.AccessibilityManager;
import android.view.accessibility.AccessibilityNodeProvider;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.view.inputmethod.InputMethodManager;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicLong;
import io.flutter.app.FlutterPluginRegistry;
import io.flutter.embedding.android.AndroidKeyProcessor;
import io.flutter.embedding.android.AndroidTouchProcessor;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.renderer.FlutterRenderer;
import io.flutter.embedding.engine.systemchannels.AccessibilityChannel;
import io.flutter.embedding.engine.systemchannels.KeyEventChannel;
import io.flutter.embedding.engine.systemchannels.LifecycleChannel;
import io.flutter.embedding.engine.systemchannels.LocalizationChannel;
import io.flutter.embedding.engine.systemchannels.NavigationChannel;
import io.flutter.embedding.engine.systemchannels.PlatformChannel;
import io.flutter.embedding.engine.systemchannels.SettingsChannel;
import io.flutter.embedding.engine.systemchannels.SystemChannel;
import io.flutter.plugin.common.ActivityLifecycleListener;
import io.flutter.plugin.common.BinaryMessenger;
import io.flutter.plugin.editing.TextInputPlugin;
import io.flutter.plugin.platform.PlatformPlugin;
import io.flutter.plugin.platform.PlatformViewsController;
/**
* An Android view containing a Flutter app.
*/
public class FlutterView extends SurfaceView implements BinaryMessenger, TextureRegistry {
/**
* Interface for those objects that maintain and expose a reference to a
* {@code FlutterView} (such as a full-screen Flutter activity).
*
* <p>
* This indirection is provided to support applications that use an activity
* other than {@link io.flutter.app.FlutterActivity} (e.g. Android v4 support
* library's {@code FragmentActivity}). It allows Flutter plugins to deal in
* this interface and not require that the activity be a subclass of
* {@code FlutterActivity}.
* </p>
*/
public interface Provider {
/**
* Returns a reference to the Flutter view maintained by this object. This may
* be {@code null}.
*/
FlutterView getFlutterView();
}
private static final String TAG = "FlutterView";
static final class ViewportMetrics {
float devicePixelRatio = 1.0f;
int physicalWidth = 0;
int physicalHeight = 0;
int physicalPaddingTop = 0;
int physicalPaddingRight = 0;
int physicalPaddingBottom = 0;
int physicalPaddingLeft = 0;
int physicalViewInsetTop = 0;
int physicalViewInsetRight = 0;
int physicalViewInsetBottom = 0;
int physicalViewInsetLeft = 0;
int systemGestureInsetTop = 0;
int systemGestureInsetRight = 0;
int systemGestureInsetBottom = 0;
int systemGestureInsetLeft = 0;
}
private final DartExecutor dartExecutor;
private final FlutterRenderer flutterRenderer;
private final NavigationChannel navigationChannel;
private final KeyEventChannel keyEventChannel;
private final LifecycleChannel lifecycleChannel;
private final LocalizationChannel localizationChannel;
private final PlatformChannel platformChannel;
private final SettingsChannel settingsChannel;
private final SystemChannel systemChannel;
private final InputMethodManager mImm;
private final TextInputPlugin mTextInputPlugin;
private final AndroidKeyProcessor androidKeyProcessor;
private final AndroidTouchProcessor androidTouchProcessor;
private AccessibilityBridge mAccessibilityNodeProvider;
private final SurfaceHolder.Callback mSurfaceCallback;
private final ViewportMetrics mMetrics;
private final List<ActivityLifecycleListener> mActivityLifecycleListeners;
private final List<FirstFrameListener> mFirstFrameListeners;
private final AtomicLong nextTextureId = new AtomicLong(0L);
private FlutterNativeView mNativeView;
private boolean mIsSoftwareRenderingEnabled = false; // using the software renderer or not
private boolean didRenderFirstFrame = false;
private final AccessibilityBridge.OnAccessibilityChangeListener onAccessibilityChangeListener = new AccessibilityBridge.OnAccessibilityChangeListener() {
@Override
public void onAccessibilityChanged(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) {
resetWillNotDraw(isAccessibilityEnabled, isTouchExplorationEnabled);
}
};
public FlutterView(Context context) {
this(context, null);
}
public FlutterView(Context context, AttributeSet attrs) {
this(context, attrs, null);
}
public FlutterView(Context context, AttributeSet attrs, FlutterNativeView nativeView) {
super(context, attrs);
Activity activity = getActivity(getContext());
if (activity == null) {
throw new IllegalArgumentException("Bad context");
}
if (nativeView == null) {
mNativeView = new FlutterNativeView(activity.getApplicationContext());
} else {
mNativeView = nativeView;
}
dartExecutor = mNativeView.getDartExecutor();
flutterRenderer = new FlutterRenderer(mNativeView.getFlutterJNI());
mIsSoftwareRenderingEnabled = mNativeView.getFlutterJNI().nativeGetIsSoftwareRenderingEnabled();
mMetrics = new ViewportMetrics();
mMetrics.devicePixelRatio = context.getResources().getDisplayMetrics().density;
setFocusable(true);
setFocusableInTouchMode(true);
mNativeView.attachViewAndActivity(this, activity);
mSurfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
assertAttached();
mNativeView.getFlutterJNI().onSurfaceCreated(holder.getSurface());
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
assertAttached();
mNativeView.getFlutterJNI().onSurfaceChanged(width, height);
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
assertAttached();
mNativeView.getFlutterJNI().onSurfaceDestroyed();
}
};
getHolder().addCallback(mSurfaceCallback);
mActivityLifecycleListeners = new ArrayList<>();
mFirstFrameListeners = new ArrayList<>();
// Create all platform channels
navigationChannel = new NavigationChannel(dartExecutor);
keyEventChannel = new KeyEventChannel(dartExecutor);
lifecycleChannel = new LifecycleChannel(dartExecutor);
localizationChannel = new LocalizationChannel(dartExecutor);
platformChannel = new PlatformChannel(dartExecutor);
systemChannel = new SystemChannel(dartExecutor);
settingsChannel = new SettingsChannel(dartExecutor);
// Create and setup plugins
PlatformPlugin platformPlugin = new PlatformPlugin(activity, platformChannel);
addActivityLifecycleListener(new ActivityLifecycleListener() {
@Override
public void onPostResume() {
platformPlugin.updateSystemUiOverlays();
}
});
mImm = (InputMethodManager) getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
PlatformViewsController platformViewsController = mNativeView.getPluginRegistry().getPlatformViewsController();
mTextInputPlugin = new TextInputPlugin(this, dartExecutor, platformViewsController);
androidKeyProcessor = new AndroidKeyProcessor(keyEventChannel, mTextInputPlugin);
androidTouchProcessor = new AndroidTouchProcessor(flutterRenderer);
mNativeView.getPluginRegistry().getPlatformViewsController().attachTextInputPlugin(mTextInputPlugin);
// Send initial platform information to Dart
sendLocalesToDart(getResources().getConfiguration());
sendUserPlatformSettingsToDart();
}
private static Activity getActivity(Context context) {
if (context == null) {
return null;
}
if (context instanceof Activity) {
return (Activity) context;
}
if (context instanceof ContextWrapper) {
// Recurse up chain of base contexts until we find an Activity.
return getActivity(((ContextWrapper) context).getBaseContext());
}
return null;
}
@NonNull
public DartExecutor getDartExecutor() {
return dartExecutor;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (!isAttached()) {
return super.onKeyUp(keyCode, event);
}
androidKeyProcessor.onKeyUp(event);
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (!isAttached()) {
return super.onKeyDown(keyCode, event);
}
androidKeyProcessor.onKeyDown(event);
return super.onKeyDown(keyCode, event);
}
public FlutterNativeView getFlutterNativeView() {
return mNativeView;
}
public FlutterPluginRegistry getPluginRegistry() {
return mNativeView.getPluginRegistry();
}
public String getLookupKeyForAsset(String asset) {
return FlutterMain.getLookupKeyForAsset(asset);
}
public String getLookupKeyForAsset(String asset, String packageName) {
return FlutterMain.getLookupKeyForAsset(asset, packageName);
}
public void addActivityLifecycleListener(ActivityLifecycleListener listener) {
mActivityLifecycleListeners.add(listener);
}
public void onStart() {
lifecycleChannel.appIsInactive();
}
public void onPause() {
lifecycleChannel.appIsInactive();
}
public void onPostResume() {
for (ActivityLifecycleListener listener : mActivityLifecycleListeners) {
listener.onPostResume();
}
lifecycleChannel.appIsResumed();
}
public void onStop() {
lifecycleChannel.appIsPaused();
}
public void onMemoryPressure() {
systemChannel.sendMemoryPressureWarning();
}
/**
* Returns true if the Flutter experience associated with this {@code FlutterView} has
* rendered its first frame, or false otherwise.
*/
public boolean hasRenderedFirstFrame() {
return didRenderFirstFrame;
}
/**
* Provide a listener that will be called once when the FlutterView renders its
* first frame to the underlaying SurfaceView.
*/
public void addFirstFrameListener(FirstFrameListener listener) {
mFirstFrameListeners.add(listener);
}
/**
* Remove an existing first frame listener.
*/
public void removeFirstFrameListener(FirstFrameListener listener) {
mFirstFrameListeners.remove(listener);
}
@Deprecated
public void enableTransparentBackground() {
Log.w(TAG, "FlutterView in the v1 embedding is always a SurfaceView and will cover accessibility highlights when transparent. Consider migrating to the v2 Android embedding. https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects");
setZOrderOnTop(true);
getHolder().setFormat(PixelFormat.TRANSPARENT);
}
/**
* Reverts this back to the {@link SurfaceView} defaults, at the back of its
* window and opaque.
*/
public void disableTransparentBackground() {
setZOrderOnTop(false);
getHolder().setFormat(PixelFormat.OPAQUE);
}
public void setInitialRoute(String route) {
navigationChannel.setInitialRoute(route);
}
public void pushRoute(String route) {
navigationChannel.pushRoute(route);
}
public void popRoute() {
navigationChannel.popRoute();
}
private void sendUserPlatformSettingsToDart() {
// Lookup the current brightness of the Android OS.
boolean isNightModeOn = (getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES;
SettingsChannel.PlatformBrightness brightness = isNightModeOn
? SettingsChannel.PlatformBrightness.dark
: SettingsChannel.PlatformBrightness.light;
settingsChannel
.startMessage()
.setTextScaleFactor(getResources().getConfiguration().fontScale)
.setUse24HourFormat(DateFormat.is24HourFormat(getContext()))
.setPlatformBrightness(brightness)
.send();
}
@SuppressWarnings("deprecation")
private void sendLocalesToDart(Configuration config) {
List<Locale> locales = new ArrayList<>();
if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
LocaleList localeList = config.getLocales();
int localeCount = localeList.size();
for (int index = 0; index < localeCount; ++index) {
Locale locale = localeList.get(index);
locales.add(locale);
}
} else {
locales.add(config.locale);
}
localizationChannel.sendLocales(locales);
}
@Override
protected void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
sendLocalesToDart(newConfig);
sendUserPlatformSettingsToDart();
}
float getDevicePixelRatio() {
return mMetrics.devicePixelRatio;
}
public FlutterNativeView detach() {
if (!isAttached())
return null;
getHolder().removeCallback(mSurfaceCallback);
mNativeView.detachFromFlutterView();
FlutterNativeView view = mNativeView;
mNativeView = null;
return view;
}
public void destroy() {
if (!isAttached())
return;
getHolder().removeCallback(mSurfaceCallback);
mNativeView.destroy();
mNativeView = null;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
return mTextInputPlugin.createInputConnection(this, outAttrs);
}
@Override
public boolean checkInputConnectionProxy(View view) {
return mNativeView.getPluginRegistry().getPlatformViewsController().checkInputConnectionProxy(view);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isAttached()) {
return super.onTouchEvent(event);
}
// TODO(abarth): This version check might not be effective in some
// versions of Android that statically compile code and will be upset
// at the lack of |requestUnbufferedDispatch|. Instead, we should factor
// version-dependent code into separate classes for each supported
// version and dispatch dynamically.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
requestUnbufferedDispatch(event);
}
return androidTouchProcessor.onTouchEvent(event);
}
@Override
public boolean onHoverEvent(MotionEvent event) {
if (!isAttached()) {
return super.onHoverEvent(event);
}
boolean handled = mAccessibilityNodeProvider.onAccessibilityHoverEvent(event);
if (!handled) {
// TODO(ianh): Expose hover events to the platform,
// implementing ADD, REMOVE, etc.
}
return handled;
}
/**
* Invoked by Android when a generic motion event occurs, e.g., joystick movement, mouse hover,
* track pad touches, scroll wheel movements, etc.
*
* Flutter handles all of its own gesture detection and processing, therefore this
* method forwards all {@link MotionEvent} data from Android to Flutter.
*/
@Override
public boolean onGenericMotionEvent(MotionEvent event) {
boolean handled = isAttached() && androidTouchProcessor.onGenericMotionEvent(event);
return handled ? true : super.onGenericMotionEvent(event);
}
@Override
protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) {
mMetrics.physicalWidth = width;
mMetrics.physicalHeight = height;
updateViewportMetrics();
super.onSizeChanged(width, height, oldWidth, oldHeight);
}
// TODO(garyq): Add support for notch cutout API
// Decide if we want to zero the padding of the sides. When in Landscape orientation,
// android may decide to place the software navigation bars on the side. When the nav
// bar is hidden, the reported insets should be removed to prevent extra useless space
// on the sides.
enum ZeroSides { NONE, LEFT, RIGHT, BOTH }
ZeroSides calculateShouldZeroSides() {
// We get both orientation and rotation because rotation is all 4
// rotations relative to default rotation while orientation is portrait
// or landscape. By combining both, we can obtain a more precise measure
// of the rotation.
Activity activity = (Activity)getContext();
int orientation = activity.getResources().getConfiguration().orientation;
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
if (rotation == Surface.ROTATION_90) {
return ZeroSides.RIGHT;
}
else if (rotation == Surface.ROTATION_270) {
// In android API >= 23, the nav bar always appears on the "bottom" (USB) side.
return Build.VERSION.SDK_INT >= 23 ? ZeroSides.LEFT : ZeroSides.RIGHT;
}
// Ambiguous orientation due to landscape left/right default. Zero both sides.
else if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
return ZeroSides.BOTH;
}
}
// Square orientation deprecated in API 16, we will not check for it and return false
// to be safe and not remove any unique padding for the devices that do use it.
return ZeroSides.NONE;
}
// TODO(garyq): Use clean ways to detect keyboard instead of heuristics if possible
// TODO(garyq): The keyboard detection may interact strangely with
// Uses inset heights and screen heights as a heuristic to determine if the insets should
// be padded. When the on-screen keyboard is detected, we want to include the full inset
// but when the inset is just the hidden nav bar, we want to provide a zero inset so the space
// can be used.
@TargetApi(20)
@RequiresApi(20)
int calculateBottomKeyboardInset(WindowInsets insets) {
int screenHeight = getRootView().getHeight();
// Magic number due to this being a heuristic. This should be replaced, but we have not
// found a clean way to do it yet (Sept. 2018)
final double keyboardHeightRatioHeuristic = 0.18;
if (insets.getSystemWindowInsetBottom() < screenHeight * keyboardHeightRatioHeuristic) {
// Is not a keyboard, so return zero as inset.
return 0;
}
else {
// Is a keyboard, so return the full inset.
return insets.getSystemWindowInsetBottom();
}
}
// This callback is not present in API < 20, which means lower API devices will see
// the wider than expected padding when the status and navigation bars are hidden.
// The annotations to suppress "InlinedApi" and "NewApi" lints prevent lint warnings
// caused by usage of Android Q APIs. These calls are safe because they are
// guarded.
@Override
@TargetApi(20)
@RequiresApi(20)
@SuppressLint({"InlinedApi", "NewApi"})
public final WindowInsets onApplyWindowInsets(WindowInsets insets) {
boolean statusBarHidden =
(SYSTEM_UI_FLAG_FULLSCREEN & getWindowSystemUiVisibility()) != 0;
boolean navigationBarHidden =
(SYSTEM_UI_FLAG_HIDE_NAVIGATION & getWindowSystemUiVisibility()) != 0;
// We zero the left and/or right sides to prevent the padding the
// navigation bar would have caused.
ZeroSides zeroSides = ZeroSides.NONE;
if (navigationBarHidden) {
zeroSides = calculateShouldZeroSides();
}
// The padding on top should be removed when the statusbar is hidden.
mMetrics.physicalPaddingTop = statusBarHidden ? 0 : insets.getSystemWindowInsetTop();
mMetrics.physicalPaddingRight =
zeroSides == ZeroSides.RIGHT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetRight();
mMetrics.physicalPaddingBottom = 0;
mMetrics.physicalPaddingLeft =
zeroSides == ZeroSides.LEFT || zeroSides == ZeroSides.BOTH ? 0 : insets.getSystemWindowInsetLeft();
// Bottom system inset (keyboard) should adjust scrollable bottom edge (inset).
mMetrics.physicalViewInsetTop = 0;
mMetrics.physicalViewInsetRight = 0;
// We perform hidden navbar and keyboard handling if the navbar is set to hidden. Otherwise,
// the navbar padding should always be provided.
mMetrics.physicalViewInsetBottom =
navigationBarHidden ? calculateBottomKeyboardInset(insets) : insets.getSystemWindowInsetBottom();
mMetrics.physicalViewInsetLeft = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
Insets systemGestureInsets = insets.getSystemGestureInsets();
mMetrics.systemGestureInsetTop = systemGestureInsets.top;
mMetrics.systemGestureInsetRight = systemGestureInsets.right;
mMetrics.systemGestureInsetBottom = systemGestureInsets.bottom;
mMetrics.systemGestureInsetLeft = systemGestureInsets.left;
}
updateViewportMetrics();
return super.onApplyWindowInsets(insets);
}
@Override
@SuppressWarnings("deprecation")
protected boolean fitSystemWindows(Rect insets) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
// Status bar, left/right system insets partially obscure content (padding).
mMetrics.physicalPaddingTop = insets.top;
mMetrics.physicalPaddingRight = insets.right;
mMetrics.physicalPaddingBottom = 0;
mMetrics.physicalPaddingLeft = insets.left;
// Bottom system inset (keyboard) should adjust scrollable bottom edge (inset).
mMetrics.physicalViewInsetTop = 0;
mMetrics.physicalViewInsetRight = 0;
mMetrics.physicalViewInsetBottom = insets.bottom;
mMetrics.physicalViewInsetLeft = 0;
updateViewportMetrics();
return true;
} else {
return super.fitSystemWindows(insets);
}
}
private boolean isAttached() {
return mNativeView != null && mNativeView.isAttached();
}
void assertAttached() {
if (!isAttached())
throw new AssertionError("Platform view is not attached");
}
private void preRun() {
resetAccessibilityTree();
}
void resetAccessibilityTree() {
if (mAccessibilityNodeProvider != null) {
mAccessibilityNodeProvider.reset();
}
}
private void postRun() {
}
public void runFromBundle(FlutterRunArguments args) {
assertAttached();
preRun();
mNativeView.runFromBundle(args);
postRun();
}
/**
* Return the most recent frame as a bitmap.
*
* @return A bitmap.
*/
public Bitmap getBitmap() {
assertAttached();
return mNativeView.getFlutterJNI().getBitmap();
}
private void updateViewportMetrics() {
if (!isAttached())
return;
mNativeView.getFlutterJNI().setViewportMetrics(
mMetrics.devicePixelRatio,
mMetrics.physicalWidth,
mMetrics.physicalHeight,
mMetrics.physicalPaddingTop,
mMetrics.physicalPaddingRight,
mMetrics.physicalPaddingBottom,
mMetrics.physicalPaddingLeft,
mMetrics.physicalViewInsetTop,
mMetrics.physicalViewInsetRight,
mMetrics.physicalViewInsetBottom,
mMetrics.physicalViewInsetLeft,
mMetrics.systemGestureInsetTop,
mMetrics.systemGestureInsetRight,
mMetrics.systemGestureInsetBottom,
mMetrics.systemGestureInsetLeft
);
}
// Called by FlutterNativeView to notify first Flutter frame rendered.
public void onFirstFrame() {
didRenderFirstFrame = true;
// Allow listeners to remove themselves when they are called.
List<FirstFrameListener> listeners = new ArrayList<>(mFirstFrameListeners);
for (FirstFrameListener listener : listeners) {
listener.onFirstFrame();
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
PlatformViewsController platformViewsController = getPluginRegistry().getPlatformViewsController();
mAccessibilityNodeProvider = new AccessibilityBridge(
this,
new AccessibilityChannel(dartExecutor, getFlutterNativeView().getFlutterJNI()),
(AccessibilityManager) getContext().getSystemService(Context.ACCESSIBILITY_SERVICE),
getContext().getContentResolver(),
platformViewsController
);
mAccessibilityNodeProvider.setOnAccessibilityChangeListener(onAccessibilityChangeListener);
resetWillNotDraw(
mAccessibilityNodeProvider.isAccessibilityEnabled(),
mAccessibilityNodeProvider.isTouchExplorationEnabled()
);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mAccessibilityNodeProvider.release();
mAccessibilityNodeProvider = null;
}
// TODO(mattcarroll): Confer with Ian as to why we need this method. Delete if possible, otherwise add comments.
private void resetWillNotDraw(boolean isAccessibilityEnabled, boolean isTouchExplorationEnabled) {
if (!mIsSoftwareRenderingEnabled) {
setWillNotDraw(!(isAccessibilityEnabled || isTouchExplorationEnabled));
} else {
setWillNotDraw(false);
}
}
@Override
public AccessibilityNodeProvider getAccessibilityNodeProvider() {
if (mAccessibilityNodeProvider != null && mAccessibilityNodeProvider.isAccessibilityEnabled()) {
return mAccessibilityNodeProvider;
} else {
// TODO(goderbauer): when a11y is off this should return a one-off snapshot of
// the a11y
// tree.
return null;
}
}
@Override
@UiThread
public void send(String channel, ByteBuffer message) {
send(channel, message, null);
}
@Override
@UiThread
public void send(String channel, ByteBuffer message, BinaryReply callback) {
if (!isAttached()) {
Log.d(TAG, "FlutterView.send called on a detached view, channel=" + channel);
return;
}
mNativeView.send(channel, message, callback);
}
@Override
@UiThread
public void setMessageHandler(String channel, BinaryMessageHandler handler) {
mNativeView.setMessageHandler(channel, handler);
}
/**
* Listener will be called on the Android UI thread once when Flutter renders
* the first frame.
*/
public interface FirstFrameListener {
void onFirstFrame();
}
@Override
public TextureRegistry.SurfaceTextureEntry createSurfaceTexture() {
final SurfaceTexture surfaceTexture = new SurfaceTexture(0);
surfaceTexture.detachFromGLContext();
final SurfaceTextureRegistryEntry entry = new SurfaceTextureRegistryEntry(nextTextureId.getAndIncrement(),
surfaceTexture);
mNativeView.getFlutterJNI().registerTexture(entry.id(), surfaceTexture);
return entry;
}
final class SurfaceTextureRegistryEntry implements TextureRegistry.SurfaceTextureEntry {
private final long id;
private final SurfaceTexture surfaceTexture;
private boolean released;
SurfaceTextureRegistryEntry(long id, SurfaceTexture surfaceTexture) {
this.id = id;
this.surfaceTexture = surfaceTexture;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// The callback relies on being executed on the UI thread (unsynchronised read of mNativeView
// and also the engine code check for platform thread in Shell::OnPlatformViewMarkTextureFrameAvailable),
// so we explicitly pass a Handler for the current thread.
this.surfaceTexture.setOnFrameAvailableListener(onFrameListener, new Handler());
} else {
// Android documentation states that the listener can be called on an arbitrary thread.
// But in practice, versions of Android that predate the newer API will call the listener
// on the thread where the SurfaceTexture was constructed.
this.surfaceTexture.setOnFrameAvailableListener(onFrameListener);
}
}
private SurfaceTexture.OnFrameAvailableListener onFrameListener = new SurfaceTexture.OnFrameAvailableListener() {
@Override
public void onFrameAvailable(SurfaceTexture texture) {
if (released || mNativeView == null) {
// Even though we make sure to unregister the callback before releasing, as of Android O
// SurfaceTexture has a data race when accessing the callback, so the callback may
// still be called by a stale reference after released==true and mNativeView==null.
return;
}
mNativeView.getFlutterJNI().markTextureFrameAvailable(SurfaceTextureRegistryEntry.this.id);
}
};
@Override
public SurfaceTexture surfaceTexture() {
return surfaceTexture;
}
@Override
public long id() {
return id;
}
@Override
public void release() {
if (released) {
return;
}
released = true;
// The ordering of the next 3 calls is important:
// First we remove the frame listener, then we release the SurfaceTexture, and only after we unregister
// the texture which actually deletes the GL texture.
// Otherwise onFrameAvailableListener might be called after mNativeView==null
surfaceTexture.setOnFrameAvailableListener(null);
surfaceTexture.release();
mNativeView.getFlutterJNI().unregisterTexture(id);
}
}
} |
package cf.spring;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Mike Heath <heathma@ldschurch.org>
* @deprecated Use Spring Boot.
*/
@Deprecated
public class BootstrapSpringContext {
private static final Logger LOGGER = LoggerFactory.getLogger(BootstrapSpringContext.class);
public static ApplicationContext bootstrap(String programName, String[] args) {
final JCommander commander = new JCommander();
final Options options = new Options();
options.configFile = "config/" + programName + ".yml";
commander.addObject(options);
commander.setProgramName(programName);
try {
commander.parse(args);
System.setProperty("configFile", "file:" + options.configFile);
final ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("classpath:context.xml");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
LOGGER.info("Shutting down.");
context.close();
}
});
return context;
} catch (ParameterException e) {
System.err.println(e.getMessage());
commander.usage();
return null;
}
}
static class Options {
@Parameter(names = "-c", description = "Config file")
String configFile;
}
} |
package com.mozu.test;
import static org.junit.Assert.*;
import org.apache.http.HttpStatus;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.mozu.api.ApiContext;
import com.mozu.api.MozuApiContext;
import com.mozu.api.contracts.core.User;
import com.mozu.api.contracts.customer.CustomerAccount;
import com.mozu.api.contracts.customer.CustomerAccountAndAuthInfo;
import com.mozu.api.contracts.customer.CustomerAuthTicket;
import com.mozu.test.framework.core.MozuApiTestBase;
import com.mozu.test.framework.datafactory.CustomerAccountFactory;
import com.mozu.test.framework.datafactory.CustomerContactFactory;
import com.mozu.test.framework.helper.CustomerGenerator;
import com.mozu.test.framework.helper.Generator;
public class CustomerTests extends MozuApiTestBase {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void CreateCustomerTest1() throws Exception {
ApiContext apiContext = new MozuApiContext(tenantId, siteId, masterCatalogId, catalogId);
CustomerAccountAndAuthInfo customerAccountAndAuthInfo = CustomerGenerator.generateCustomerAccountAndAuthInfo();
CustomerAuthTicket ticket = CustomerAccountFactory.addAccountAndLogin(apiContext, customerAccountAndAuthInfo, HttpStatus.SC_CREATED, HttpStatus.SC_CREATED);
CustomerAccount getAccount = CustomerAccountFactory.getAccount(apiContext, ticket.getCustomerAccount().getId(), HttpStatus.SC_OK, HttpStatus.SC_OK);
assertEquals(getAccount.getEmailAddress(), customerAccountAndAuthInfo.getAccount().getEmailAddress());
}
@Test
public void UpdateCustomerTest1() throws Exception {
ApiContext apiContext = new MozuApiContext(tenantId, siteId, masterCatalogId, catalogId);
CustomerAccountAndAuthInfo customerAccountAndAuthInfo = CustomerGenerator.generateCustomerAccountAndAuthInfo();
CustomerAuthTicket ticket = CustomerAccountFactory.addAccountAndLogin(apiContext, customerAccountAndAuthInfo, HttpStatus.SC_CREATED, HttpStatus.SC_CREATED);
CustomerAccount getAccount = CustomerAccountFactory.getAccount(apiContext, ticket.getCustomerAccount().getId(), HttpStatus.SC_OK, HttpStatus.SC_OK);
getAccount.setEmailAddress(Generator.randomEmailAddress());
CustomerAccount updateAccount = CustomerAccountFactory.updateAccount(apiContext, getAccount, ticket.getCustomerAccount().getId(), HttpStatus.SC_OK, HttpStatus.SC_OK);
assertEquals(updateAccount.getEmailAddress(), getAccount.getEmailAddress());
}
@Test
public void UpdateCustomerTest2() throws Exception {
ApiContext apiContext = new MozuApiContext(tenantId, siteId, masterCatalogId, catalogId);
//CustomerAccountFactory.getAccounts(apiContext, HttpStatus.SC_OK, HttpStatus.SC_OK);
CustomerAccount getAccount = CustomerAccountFactory.getAccount(apiContext, 1384, HttpStatus.SC_OK, HttpStatus.SC_OK);
getAccount.setAcceptsMarketing(true);
CustomerAccount updateAccount = CustomerAccountFactory.updateAccount(apiContext, getAccount, 1384, HttpStatus.SC_OK, HttpStatus.SC_OK);
assert(!updateAccount.getAcceptsMarketing());
}
} |
package org.openlca.cloud.model;
import java.util.Date;
import org.openlca.core.model.ModelType;
public class Comment {
public long id;
public String user;
public String text;
public String refId;
public ModelType type;
public String path;
public Date date;
public boolean released;
public boolean approved;
public long replyTo;
} |
package org.openlca.core.library;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.openlca.core.database.CategorizedEntityDao;
import org.openlca.core.database.FlowDao;
import org.openlca.core.database.IDatabase;
import org.openlca.core.database.LocationDao;
import org.openlca.core.database.ProcessDao;
import org.openlca.core.matrix.IndexFlow;
import org.openlca.core.matrix.ProcessProduct;
import org.openlca.core.matrix.format.IMatrix;
import org.openlca.core.matrix.io.npy.Npy;
import org.openlca.core.matrix.io.npy.Npz;
import org.openlca.core.model.Exchange;
import org.openlca.core.model.descriptors.CategorizedDescriptor;
import org.openlca.jsonld.Json;
import org.slf4j.LoggerFactory;
public class Library {
/**
* The folder where the library files are stored.
*/
public final File folder;
private LibraryInfo info;
public Library(File folder) {
this.folder = folder;
}
public LibraryInfo getInfo() {
if (info != null)
return info;
var file = new File(folder, "library.json");
var obj = Json.readObject(file);
if (obj.isEmpty())
throw new RuntimeException("failed to read " + file);
info = LibraryInfo.fromJson(obj.get());
return info;
}
/**
* Returns the products of the library in corresponding matrix order. If this
* information is not present or something went wrong while synchronizing the
* product index with the database, an empty array is returned. Of course, this
* only works when this library is mounted to that database.
*/
public ProcessProduct[] syncProducts(IDatabase db) {
var file = new File(folder, "index_A.bin");
if (!file.exists())
return new ProcessProduct[0];
var processes = descriptors(new ProcessDao(db));
var products = descriptors(new FlowDao(db));
try (var stream = new FileInputStream(file)) {
var proto = Proto.ProductIndex.parseFrom(stream);
int size = proto.getProductCount();
var index = new ProcessProduct[size];
for (int i = 0; i < size; i++) {
var entry = proto.getProduct(i);
var process = processes.get(entry.getProcess().getId());
var product = products.get(entry.getProduct().getId());
if (process == null || product == null)
return new ProcessProduct[0];
index[i] = ProcessProduct.of(process, product);
}
return index;
} catch (Exception e) {
var log = LoggerFactory.getLogger(getClass());
log.error("failed to read product index @" + file, e);
return new ProcessProduct[0];
}
}
/**
* Returns the elementary flows of the library in corresponding matrix order. If
* this information is not present or something went wrong while synchronizing
* the flow index with the database, an empty array is returned. Of course, this
* only works when this library is mounted to that database.
*/
public IndexFlow[] syncElementaryFlows(IDatabase db) {
var file = new File(folder, "index_B.bin");
if (!file.exists())
return new IndexFlow[0];
var flows = descriptors(new FlowDao(db));
var locations = descriptors(new LocationDao(db));
try (var stream = new FileInputStream(file)) {
var proto = Proto.ElemFlowIndex.parseFrom(stream);
int size = proto.getFlowCount();
var index = new IndexFlow[size];
for (int i = 0; i < size; i++) {
var entry = proto.getFlow(i);
var flow = flows.get(entry.getFlow().getId());
var location = locations.get(entry.getLocation().getId());
if (flow == null)
return new IndexFlow[0];
index[i] = entry.getIsInput()
? IndexFlow.ofInput(flow, location)
: IndexFlow.ofOutput(flow, location);
}
return index;
} catch (Exception e) {
var log = LoggerFactory.getLogger(getClass());
log.error("failed to read flow index @" + file, e);
return new IndexFlow[0];
}
}
private <T extends CategorizedDescriptor> Map<String, T> descriptors(
CategorizedEntityDao<?, T> dao) {
return dao.getDescriptors()
.stream()
.collect(Collectors.toMap(
d -> d.refId,
d -> d));
}
public boolean hasMatrix(LibraryMatrix m) {
var npy = new File(folder, m.name() + ".npy");
if (npy.exists())
return true;
var npz = new File(folder, m.name() + ".npz");
return npz.exists();
}
public Optional<IMatrix> getMatrix(LibraryMatrix m) {
try {
var npy = new File(folder, m.name() + ".npy");
if (npy.exists())
return Optional.of(Npy.load(npy));
var npz = new File(folder, m.name() + ".npz");
return npz.exists()
? Optional.of(Npz.load(npz))
: Optional.empty();
} catch (Exception e) {
var log = LoggerFactory.getLogger(getClass());
log.error("failed to read matrix from " + folder, e);
return Optional.empty();
}
}
public Optional<double[]> getColumn(LibraryMatrix m, int column) {
try {
var npy = new File(folder, m.name() + ".npy");
if (npy.exists())
return Optional.of(Npy.loadColumn(npy, column));
var npz = new File(folder, m.name() + ".npz");
return npz.exists()
? Optional.of(Npz.loadColumn(npz, column))
: Optional.empty();
} catch (Exception e) {
var log = LoggerFactory.getLogger(getClass());
log.error("failed to read matrix from " + folder, e);
return Optional.empty();
}
}
/**
* Creates a list of exchanges from the library matrices that describe the
* inputs and outputs of the given library product. The meta-data of the
* exchanges are synchronized with the given databases. Thus, this library
* needs to be mounted to the given database.
*/
public List<Exchange> getExchanges(ProcessProduct product, IDatabase db) {
if (product == null || db == null)
return Collections.emptyList();
var products = syncProducts(db);
// find the library index of the given product
int index = -1;
for (int i = 0; i < products.length; i++) {
var p = products[i];
if (p.id() == product.id() && p.flowId() == product.flowId()) {
index = i;
break;
}
}
if (index < 0)
return Collections.emptyList();
// read the product inputs and outputs
var exchanges = new ArrayList<Exchange>();
var flowDao = new FlowDao(db);
var colA = getColumn(LibraryMatrix.A, index).orElse(null);
if (colA == null)
return Collections.emptyList();
for (int i = 0; i < colA.length; i++) {
double val = colA[i];
if (val == 0)
continue;
product = products[i];
var flow = flowDao.getForId(product.flowId());
if (flow == null)
continue;
var exchange = val < 0
? Exchange.input(flow, Math.abs(val))
: Exchange.output(flow, val);
if (i != index) {
exchange.defaultProviderId = product.id();
}
exchanges.add(exchange);
}
// read the the elementary flow inputs and outputs
var colB = getColumn(LibraryMatrix.B, index).orElse(null);
if (colB == null)
return exchanges;
var iFlows = syncElementaryFlows(db);
var locDao = new LocationDao(db);
for (int i = 0; i < colB.length; i++) {
double val = colB[i];
if (val == 0)
continue;
var iFlow = iFlows[i];
var flow = flowDao.getForId(iFlow.flow.id);
if (flow == null)
continue;
var exchange = iFlow.isInput
? Exchange.input(flow, -val)
: Exchange.output(flow, val);
if (iFlow.location != null) {
exchange.location = locDao.getForId(
iFlow.location.id);
}
exchanges.add(exchange);
}
return exchanges;
}
} |
package cx2x.decompiler;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
import xcodeml.util.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
/**
* Wrapper class to call the Fortran decompiler of OMNI Compiler directly
* from Java instead of calling it as a separated program.
*
* @author clementval
*/
public class XcodeMlToFortranDecompiler {
private BufferedReader _reader;
private XmToolFactory _toolFactory;
/**
* Constructs a new XcodeMlToFortranDecompiler object.
*
* @throws XmException If instantiation of the XmToolFactory fails.
*/
public XcodeMlToFortranDecompiler()
throws XmException
{
_toolFactory = new XmToolFactory("F");
}
private boolean openXcodeMLFile(String inputFilepath)
{
if(_reader != null) {
try {
_reader.close();
} catch(IOException e) {
e.printStackTrace();
return false;
}
}
try {
_reader = new BufferedReader(new FileReader(inputFilepath));
return true;
} catch(IOException e) {
return false;
}
}
/**
* Decompile the XcodeML file into Fortran code.
*
* @param outputFilepath Fortran output file path.
* @param inputFilepath XcodeML input file path.
* @param maxColumns Maximum number of column for the output file.
* @param lineDirectives If true, preprocessor line directives are added.
* @return True if the decompilation succeeded. False otherwise.
*/
public boolean decompile(String outputFilepath, String inputFilepath,
int maxColumns, boolean lineDirectives)
{
if(!lineDirectives) {
XmOption.setIsSuppressLineDirective(true);
}
XmOption.setCoarrayNoUseStatement(true);
XmOption.setDebugOutput(false);
if(!openXcodeMLFile(inputFilepath)) {
return false;
}
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFilepath)));
} catch(IOException e) {
e.printStackTrace();
}
try {
XmDecompiler decompiler = _toolFactory.createDecompiler();
XmDecompilerContext context = _toolFactory.createDecompilerContext();
if(maxColumns > 0) {
context.setProperty(XmDecompilerContext.KEY_MAX_COLUMNS, "" + maxColumns);
}
try {
DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = docFactory.newDocumentBuilder();
Document xcodeDoc;
xcodeDoc = builder.parse(inputFilepath);
decompiler.decompile(context, xcodeDoc, writer);
} catch(ParserConfigurationException | SAXException | IOException e) {
return false;
}
if(writer != null) {
writer.flush();
} else {
return false;
}
return true;
} catch(Exception ex) {
if(_reader != null) {
try {
_reader.close();
} catch(IOException ignored) {
}
}
if(writer != null) {
writer.close();
}
}
return false;
}
} |
package org.jenetics.util;
import java.util.function.Function;
public interface Accumulator<T> {
/**
* Accumulate the given value.
*
* @param value the value to accumulate.
*/
public void accumulate(final T value);
/**
* Return a view of this adapter with a different type {@code B}.
*
* Usage example:
* [code]
* // Convert a string on the fly into a double value.
* final Converter<String, Double> converter = new Converter<String, Double>() {
* public Double convert(final String value) {
* return Double.valueOf(value);
* }
* };
*
* // The values to accumulate
* final List<String> values = Arrays.asList("0", "1", "2", "3", "4", "5");
*
* final Accumulators.Min<Double> accumulator = new Accumulators.Min<Double>();
*
* // No pain to accumulate collections of a different type.
* Accumulators.accumulate(values, accumulator.map(converter));
* [/code]
*
* @param <B> the type of the returned adapter (view).
* @param mapper the mapper needed to map between the type of this
* adapter and the adapter view type.
* @return the adapter view with the different type.
* @throws NullPointerException if the given {@code converter} is {@code null}.
*/
public default <B> Accumulator<B> map(final Function<? super B, ? extends T> mapper) {
return value -> accumulate(mapper.apply(value));
}
} |
package org.jgrapes.core.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Channel.Default;
import org.jgrapes.core.ClassChannel;
import org.jgrapes.core.Component;
import org.jgrapes.core.ComponentType;
import org.jgrapes.core.Components;
import org.jgrapes.core.Eligible;
import org.jgrapes.core.Event;
import org.jgrapes.core.HandlerScope;
import org.jgrapes.core.Manager;
import org.jgrapes.core.NamedChannel;
import org.jgrapes.core.NamedEvent;
import org.jgrapes.core.Self;
import org.jgrapes.core.annotation.HandlerDefinition.ChannelReplacements;
/**
* This is the basic, general purpose handler annotation provided as part of the
* core package.
*
* The annotated method is invoked for events that have a type (or
* name) matching the given `events` (or `namedEvents`) element
* of the annotation and that are fired on one of
* the `channels` (or `namedChannels`) specified in the annotation.
*
* If neither event classes nor named events are specified in the
* annotation, the class of the annotated method's first parameter (which
* must be of type {@link Event} or a derived type) is used as (single)
* event class (see the examples in {@link #events()} and
* {@link #namedEvents()}).
*
* Channel matching is performed by matching the event's channels
* (see {@link Event#channels()}) with the channels specified in the
* handler. The matching algorithm invokes
* {@link Eligible#isEligibleFor(Object) isEligibleFor} for each of the
* event's channels with the class (or name, see {@link #channels()} and
* {@link Handler#namedChannels()}) of each of the channels specified
* in the handler.
*
* If neither channel classes not named channels are specified in the
* handler, or `{@link Default Channel.Default}.class` is specified as one
* of the channel classes, the matching algorithm invokes
* {@link Eligible#isEligibleFor(Object) isEligibleFor} for each of
* the event's channels with the default criterion of the component's
* channel (see {@link Manager#channel()} and
* {@link Eligible#defaultCriterion()}) as argument.
*
* Finally, independent of any specified channels, the matching algorithm
* invokes {@link Eligible#isEligibleFor(Object) isEligibleFor}
* for each of the event's channels with the component's default criterion
* as argument. This results in a match if
* the component itself is used as one of the event's channels
* (see the description of {@link Eligible}).
*
* If a match is found for a given event's properties and a handler's
* specified attributes, the handler method is invoked.
* The method can have an additional optional parameter of type
* {@link Channel} (or a derived type). This parameter does not
* influence the eligibility of the method regarding a given event,
* it determines how the method is invoked. If the method does not
* have a second parameter, it is invoked once if an event
* matches. If the parameter exists, the method is invoked once for
* each of the event's channels, provided that the optional parameter's
* type is assignable from the event's channel.
*
* Because annotation elements accept only literals as values, they
* cannot be used to register handlers with properties that are only
* known at runtime. It is therefore possible to specify a
* {@link Handler} annotation with element `dynamic=true`. Such a
* handler must be added explicitly by invoking
* {@link Evaluator#add(ComponentType, String, Object)} or
* {@link Evaluator#add(ComponentType, String, Object, Object, int)},
* thus specifying some of the handler's properties dynamically (i.e.
* at runtime).
*
* A special case is the usage of a channel that is only known at
* runtime. If there are several handlers for events on such a
* channel, a lot of methods will become dynamic. To avoid this,
* {@link Component}s support a {@link ChannelReplacements}
* parameter in their constructor. Using this, it is possible
* to specify a specially defined {@link Channel} class in the
* annotation that is replaced by a channel that is only known
* at runtime.
*
* @see Component#channel()
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@HandlerDefinition(evaluator = Handler.Evaluator.class)
public @interface Handler {
/** The default value for the <code>events</code> parameter of
* the annotation. Indicates that the parameter is not used. */
final class NoEvent extends Event<Void> {
}
/** The default value for the <code>channels</code> parameter of
* the annotation. Indicates that the parameter is not used. */
final class NoChannel extends ClassChannel {
}
/**
* Specifies classes of events that the handler is to receive.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler
* public void onStart(Start event) {
* // Invoked for Start events on the component's channel,
* // event object made available
* }
*
* {@literal @}Handler(events=Start.class)
* public void onStart() {
* // Invoked for Start events on the component's channel,
* // not interested in the event object
* }
*
* {@literal @}Handler(events={Start.class, Stop.class})
* public void onStart(Event<?> event) {
* // Invoked for Start and Stop events on the component's
* // channel, event made available (may need casting to
* // access specific properties)
* }
* }
* ```
*
* @return the event classes
*/
@SuppressWarnings("rawtypes")
Class<? extends Event>[] events() default NoEvent.class;
/**
* Specifies names of {@link NamedEvent}s that the handler is to receive.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler(namedEvents="Test")
* public void onTest(Event<?> event) {
* // Invoked for (named) "Test" events (new NamedEvent("Test"))
* // on the component's channel, event object made available
* }
* }
* ```
*
* @return the event names
*/
String[] namedEvents() default "";
/**
* Specifies classes of channels that the handler listens on. If none
* are specified, the component's channel is used.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler(channels=Feedback.class)
* public void onStart(Start event) {
* // Invoked for Start events on the "Feedback" channel
* // (class Feedback implements Channel {...}),
* // event object made available
* }
* }
* ```
*
* Specifying `channels=Channel.class` make the handler listen
* for all events, independent of the channel that they are fired on.
*
* Specifying `channels=Self.class` make the handler listen
* for events that are fired on the conponent.
*
* @return the channel classes
*/
Class<? extends Channel>[] channels() default NoChannel.class;
/**
* Specifies names of {@link NamedChannel}s that the handler listens on.
*
* ```java
* class SampleComponent extends Component {
*
* {@literal @}Handler(namedChannels="Feedback")
* public void onStart(Start event) {
* // Invoked for Start events on the (named) channel "Feedback"
* // (new NamedChannel("Feedback")), event object made available
* }
* }
* ```
*
* @return the channel names
*/
String[] namedChannels() default "";
/**
* Specifies a priority. The value is used to sort handlers.
* Handlers with higher priority are invoked first.
*
* @return the priority
*/
int priority() default 0;
/**
* Returns {@code true} if the annotated method defines a
* dynamic handler. A dynamic handler must be added to the set of
* handlers of a component explicitly at run time using
* {@link Evaluator#add(ComponentType, String, Object)}
* or {@link Evaluator#add(ComponentType, String, Object, Object, int)}.
*
* ```java
* class SampleComponent extends Component {
*
* SampleComponent() {
* Handler.Evaluator.add(this, "onStartDynamic", someChannel);
* }
*
* {@literal @}Handler(dynamic=true)
* public void onStartDynamic(Start event) {
* // Only invoked if added as handler at runtime
* }
* }
* ```
*
* @return the result
*/
boolean dynamic() default false;
/**
* This class provides the {@link Evaluator} for the
* {@link Handler} annotation provided by the core package. It
* implements the behavior as described for the annotation.
*/
class Evaluator implements HandlerDefinition.Evaluator {
@Override
public HandlerScope scope(
ComponentType component, Method method,
ChannelReplacements channelReplacements) {
Handler annotation = method.getAnnotation(Handler.class);
if (annotation == null || annotation.dynamic()) {
return null;
}
return new Scope(component, method, annotation,
channelReplacements, null, null);
}
/*
* (non-Javadoc)
*
* @see
* org.jgrapes.core.annotation.HandlerDefinition.Evaluator#getPriority()
*/
@Override
public int priority(Annotation annotation) {
return ((Handler) annotation).priority();
}
/**
* Adds the given method of the given component as a dynamic handler for
* a specific event and channel. The method with the given name must be
* annotated as dynamic handler and must have a single parameter of type
* {@link Event} (or a derived type as appropriate for the event type to
* be handled). It can have an optional parameter of type
* {@link Channel}.
*
* @param component
* the component
* @param method
* the name of the method that implements the handler
* @param eventValue
* the event key that should be used for matching this
* handler with an event. This is equivalent to an
* <code>events</code>/<code>namedEvents</code> parameter
* used with a single value in the handler annotation, but
* here all kinds of Objects are allowed as key values.
* @param channelValue
* the channel value that should be used for matching
* an event's channel with this handler. This is equivalent
* to a `channels`/`namedChannels` parameter with a single
* value in the handler annotation, but
* here all kinds of Objects are allowed as values. As a
* convenience, if the actual object provided is a
* {@link Channel}, its default criterion is used for
* matching.
* @param priority
* the priority of the handler
*/
public static void add(ComponentType component, String method,
Object eventValue, Object channelValue, int priority) {
addInternal(component, method, eventValue, channelValue, priority);
}
/**
* Add a handler like
* {@link #add(ComponentType, String, Object, Object, int)}
* but take the values for event and priority from the annotation.
*
* @param component the component
* @param method the name of the method that implements the handler
* @param channelValue the channel value that should be used
* for matching an event's channel with this handler
*/
public static void add(ComponentType component, String method,
Object channelValue) {
addInternal(component, method, null, channelValue, null);
}
@SuppressWarnings({ "PMD.CyclomaticComplexity",
"PMD.AvoidBranchingStatementAsLastInLoop" })
private static void addInternal(ComponentType component, String method,
Object eventValue, Object channelValue, Integer priority) {
try {
if (channelValue instanceof Channel) {
channelValue = ((Eligible) channelValue).defaultCriterion();
}
for (Method m : component.getClass().getMethods()) {
if (!m.getName().equals(method)) {
continue;
}
for (Annotation annotation : m.getDeclaredAnnotations()) {
Class<?> annoType = annotation.annotationType();
if (!(annoType.equals(Handler.class))) {
continue;
}
HandlerDefinition hda
= annoType.getAnnotation(HandlerDefinition.class);
if (hda == null
|| !Handler.class.isAssignableFrom(annoType)
|| !((Handler) annotation).dynamic()) {
continue;
}
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
Scope scope = new Scope(component, m,
(Handler) annotation, Collections.emptyMap(),
eventValue == null ? null
: new Object[] { eventValue },
new Object[] { channelValue });
Components.manager(component).addHandler(m, scope,
priority == null
? ((Handler) annotation).priority()
: priority);
return;
}
}
throw new IllegalArgumentException(
"No method named \"" + method + "\" with DynamicHandler"
+ " annotation and correct parameter list.");
} catch (SecurityException e) {
throw (RuntimeException) (new IllegalArgumentException()
.initCause(e));
}
}
/**
* The handler scope implementation used by the evaluator.
*/
private static class Scope implements HandlerScope {
private final Set<Object> eventCriteria = new HashSet<Object>();
private final Set<Object> channelCriteria = new HashSet<Object>();
/**
* Instantiates a new scope.
*
* @param component the component
* @param method the method
* @param annotation the annotation
* @param channelReplacements the channel replacements
* @param eventValues the event values
* @param channelValues the channel values
*/
@SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NcssCount",
"PMD.NPathComplexity", "PMD.UseVarargs",
"PMD.AvoidDeeplyNestedIfStmts",
"PMD.CollapsibleIfStatements" })
public Scope(ComponentType component, Method method,
Handler annotation,
Map<Class<? extends Channel>, Object> channelReplacements,
Object[] eventValues, Object[] channelValues) {
if (!HandlerDefinition.Evaluator.checkMethodSignature(method)) {
throw new IllegalArgumentException("Method \""
+ method.toString() + "\" cannot be used as"
+ " handler (wrong signature).");
}
if (eventValues != null) { // NOPMD, != is easier to read
eventCriteria.addAll(Arrays.asList(eventValues));
} else {
// Get all event values from the handler annotation.
if (annotation.events()[0] != Handler.NoEvent.class) {
eventCriteria
.addAll(Arrays.asList(annotation.events()));
}
// Get all named events from the annotation and add to event
// keys.
if (!annotation.namedEvents()[0].equals("")) {
eventCriteria.addAll(
Arrays.asList(annotation.namedEvents()));
}
// If no event types are given, try first parameter.
if (eventCriteria.isEmpty()) {
Class<?>[] paramTypes = method.getParameterTypes();
if (paramTypes.length > 0) {
if (Event.class.isAssignableFrom(paramTypes[0])) {
eventCriteria.add(paramTypes[0]);
}
}
}
}
if (channelValues != null) { // NOPMD, != is easier to read
channelCriteria.addAll(Arrays.asList(channelValues));
} else {
// Get channel values from the annotation.
boolean addDefaultChannel = false;
if (annotation.channels()[0] != Handler.NoChannel.class) {
for (Class<?> c : annotation.channels()) {
if (c == Self.class) {
if (!(component instanceof Channel)) {
throw new IllegalArgumentException(
"Canot use channel This.class in "
+ "annotation of " + method
+ " because " + getClass().getName()
+ " does not implement Channel.");
}
// Will be added anyway, see below, but
// channelCriteria must not remain empty,
// else the default channel is added.
channelCriteria.add(
((Channel) component).defaultCriterion());
} else if (c == Channel.Default.class) {
addDefaultChannel = true;
} else {
channelCriteria.add(channelReplacements == null
? c
: channelReplacements.getOrDefault(c, c));
}
}
}
// Get named channels from annotation and add to channel
// keys.
if (!annotation.namedChannels()[0].equals("")) {
channelCriteria.addAll(
Arrays.asList(annotation.namedChannels()));
}
if (channelCriteria.isEmpty() || addDefaultChannel) {
channelCriteria.add(Components.manager(component)
.channel().defaultCriterion());
}
}
// Finally, a component always handles events
// directed at it directly.
if (component instanceof Channel) {
channelCriteria.add(
((Channel) component).defaultCriterion());
}
}
@Override
public boolean includes(Eligible event, Eligible[] channels) {
for (Object eventValue : eventCriteria) {
if (event.isEligibleFor(eventValue)) {
// Found match regarding event, now try channels
for (Eligible channel : channels) {
for (Object channelValue : channelCriteria) {
if (channel.isEligibleFor(channelValue)) {
return true;
}
}
}
return false;
}
}
return false;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Scope [");
if (eventCriteria != null) {
builder.append("handledEvents=")
.append(eventCriteria.stream().map(crit -> {
if (crit instanceof Class) {
return Components.className((Class<?>) crit);
}
return crit.toString();
}).collect(Collectors.toSet()));
builder.append(", ");
}
if (channelCriteria != null) {
builder.append("handledChannels=");
builder.append(channelCriteria);
}
builder.append(']');
return builder.toString();
}
}
}
} |
// Revision 1.1 1999-01-31 13:33:08+00 sm11td
// Initial revision
package Debrief.Wrappers;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.beans.IntrospectionException;
import java.beans.MethodDescriptor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Vector;
import Debrief.ReaderWriter.Replay.FormatTracks;
import Debrief.Tools.Properties.TrackColorModePropertyEditor;
import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeSetWrapper;
import Debrief.Wrappers.DynamicTrackShapes.DynamicTrackShapeWrapper;
import Debrief.Wrappers.Track.AbsoluteTMASegment;
import Debrief.Wrappers.Track.CoreTMASegment;
import Debrief.Wrappers.Track.DynamicInfillSegment;
import Debrief.Wrappers.Track.PlanningSegment;
import Debrief.Wrappers.Track.RelativeTMASegment;
import Debrief.Wrappers.Track.SplittableLayer;
import Debrief.Wrappers.Track.TrackColorModeHelper;
import Debrief.Wrappers.Track.TrackColorModeHelper.DeferredDatasetColorMode;
import Debrief.Wrappers.Track.TrackColorModeHelper.TrackColorMode;
import Debrief.Wrappers.Track.TrackSegment;
import Debrief.Wrappers.Track.TrackWrapper_Support;
import Debrief.Wrappers.Track.TrackWrapper_Support.FixSetter;
import Debrief.Wrappers.Track.TrackWrapper_Support.SegmentList;
import Debrief.Wrappers.Track.TrackWrapper_Test;
import Debrief.Wrappers.Track.WormInHoleOffset;
import MWC.GUI.BaseLayer;
import MWC.GUI.CanvasType;
import MWC.GUI.DynamicPlottable;
import MWC.GUI.Editable;
import MWC.GUI.FireExtended;
import MWC.GUI.FireReformatted;
import MWC.GUI.HasEditables.ProvidesContiguousElements;
import MWC.GUI.Layer;
import MWC.GUI.Layers;
import MWC.GUI.MessageProvider;
import MWC.GUI.PlainWrapper;
import MWC.GUI.Plottable;
import MWC.GUI.Plottables;
import MWC.GUI.Plottables.IteratorWrapper;
import MWC.GUI.Canvas.CanvasTypeUtilities;
import MWC.GUI.Properties.FractionPropertyEditor;
import MWC.GUI.Properties.LabelLocationPropertyEditor;
import MWC.GUI.Properties.LineStylePropertyEditor;
import MWC.GUI.Properties.LineWidthPropertyEditor;
import MWC.GUI.Properties.NullableLocationPropertyEditor;
import MWC.GUI.Properties.TimeFrequencyPropertyEditor;
import MWC.GUI.Shapes.DraggableItem;
import MWC.GUI.Shapes.HasDraggableComponents;
import MWC.GUI.Shapes.TextLabel;
import MWC.GUI.Shapes.Symbols.SymbolFactoryPropertyEditor;
import MWC.GUI.Shapes.Symbols.Vessels.WorldScaledSym;
import MWC.GenericData.Duration;
import MWC.GenericData.HiResDate;
import MWC.GenericData.TimePeriod;
import MWC.GenericData.Watchable;
import MWC.GenericData.WatchableList;
import MWC.GenericData.WorldArea;
import MWC.GenericData.WorldDistance;
import MWC.GenericData.WorldDistance.ArrayLength;
import MWC.GenericData.WorldLocation;
import MWC.GenericData.WorldSpeed;
import MWC.GenericData.WorldVector;
import MWC.TacticalData.Fix;
import MWC.Utilities.TextFormatting.FormatRNDateTime;
/**
* the TrackWrapper maintains the GUI and data attributes of the whole track iteself, but the
* responsibility for the fixes within the track are demoted to the FixWrapper
*/
public class TrackWrapper extends MWC.GUI.PlainWrapper implements
WatchableList, MWC.GUI.Layer, DraggableItem, HasDraggableComponents,
ProvidesContiguousElements, ISecondaryTrack, DynamicPlottable
{
// member variables
/**
* class containing editable details of a track
*/
public final class trackInfo extends Editable.EditorType implements
Editable.DynamicDescriptors
{
/**
* constructor for this editor, takes the actual track as a parameter
*
* @param data
* track being edited
*/
public trackInfo(final TrackWrapper data)
{
super(data, data.getName(), "");
}
@Override
public final MethodDescriptor[] getMethodDescriptors()
{
// just add the reset color field first
final Class<TrackWrapper> c = TrackWrapper.class;
final MethodDescriptor[] _methodDescriptors =
new MethodDescriptor[]
{
method(c, "exportThis", null, "Export Shape"),
method(c, "resetLabels", null, "Reset DTG Labels"),
method(c, "calcCourseSpeed", null,
"Generate calculated Course and Speed")};
return _methodDescriptors;
}
@Override
public final String getName()
{
return super.getName();
}
@Override
public final PropertyDescriptor[] getPropertyDescriptors()
{
try
{
final PropertyDescriptor[] _coreDescriptors =
new PropertyDescriptor[]
{
displayExpertLongProp("SymbolType", "Symbol type",
"the type of symbol plotted for this label", FORMAT,
SymbolFactoryPropertyEditor.class),
displayExpertLongProp("LineThickness", "Line thickness",
"the width to draw this track", FORMAT,
LineWidthPropertyEditor.class),
expertProp("Name", "the track name"),
displayExpertProp("InterpolatePoints", "Interpolate points",
"whether to interpolate points between known data points",
SPATIAL),
expertProp("Color", "the track color", FORMAT),
displayExpertProp("EndTimeLabels", "Start/End time labels",
"Whether to label track start/end with 6-figure DTG",
VISIBILITY),
displayExpertProp("SymbolColor", "Symbol color",
"the color of the symbol (when used)", FORMAT),
displayExpertProp(
"PlotArrayCentre",
"Plot array centre",
"highlight the sensor array centre when non-zero array length provided",
VISIBILITY),
displayExpertProp("TrackFont", "Track font",
"the track label font", FORMAT),
displayExpertProp("NameVisible", "Name visible",
"show the track label", VISIBILITY),
displayExpertProp("PositionsVisible", "Positions visible",
"show individual Positions", VISIBILITY),
displayExpertProp("NameAtStart", "Name at start",
"whether to show the track name at the start (or end)",
VISIBILITY),
displayExpertProp("LinkPositions", "Link positions",
"whether to join the track points", VISIBILITY),
expertProp("Visible", "whether the track is visible",
VISIBILITY),
displayExpertLongProp("NameLocation", "Name location",
"relative location of track label", FORMAT,
MWC.GUI.Properties.NullableLocationPropertyEditor.class),
displayExpertLongProp("LabelFrequency", "Label frequency",
"the label frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("SymbolFrequency", "Symbol frequency",
"the symbol frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("ResampleDataAt", "Resample data at",
"the data sample rate", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayExpertLongProp("ArrowFrequency", "Arrow frequency",
"the direction marker frequency", TEMPORAL,
MWC.GUI.Properties.TimeFrequencyPropertyEditor.class),
displayProp("CustomTrailLength", "Custom Snail Trail",
"to specify a custom snail trail length",
Editable.EditorType.TEMPORAL),
displayExpertLongProp("CustomVectorStretch",
"Custom Vector Stretch",
"to specify a custom snail vector stretch",
Editable.EditorType.TEMPORAL, FractionPropertyEditor.class),
displayExpertLongProp("LineStyle", "Line style",
"the line style used to join track points", TEMPORAL,
MWC.GUI.Properties.LineStylePropertyEditor.class)};
PropertyDescriptor[] res;
// SPECIAL CASE: if we have a world scaled symbol, provide
// editors for
// the symbol size
final TrackWrapper item = (TrackWrapper) this.getData();
if (item._theSnailShape instanceof WorldScaledSym)
{
// yes = better create height/width editors
final PropertyDescriptor[] _coreDescriptorsWithSymbols =
new PropertyDescriptor[_coreDescriptors.length + 2];
System.arraycopy(_coreDescriptors, 0, _coreDescriptorsWithSymbols, 2,
_coreDescriptors.length);
_coreDescriptorsWithSymbols[0] =
displayExpertProp("SymbolLength", "Symbol length",
"Length of symbol", FORMAT);
_coreDescriptorsWithSymbols[1] =
displayExpertProp("SymbolWidth", "Symbol width",
"Width of symbol", FORMAT);
// and now use the new value
res = _coreDescriptorsWithSymbols;
}
else
{
res = _coreDescriptors;
}
// TRACK COLORING HANDLING
final List<TrackColorMode> datasets = getTrackColorModes();
if (datasets.size() > 0)
{
// store the datasets
TrackColorModePropertyEditor.setCustomModes(datasets);
final List<PropertyDescriptor> tmpList =
new ArrayList<PropertyDescriptor>();
tmpList.addAll(Arrays.asList(res));
// insert the editor
tmpList.add(displayExpertLongProp("TrackColorMode",
"Track Coloring Mode", "the mode in which to color the track",
FORMAT, TrackColorModePropertyEditor.class));
// ok. if we're in a measuremd mode, it may have a mode selector
res = tmpList.toArray(res);
// NOTE: this info class to implement Editable.DynamicDescriptors
// to avoid these descriptors being cached
}
return res;
}
catch (final IntrospectionException e)
{
return super.getPropertyDescriptors();
}
}
}
/**
* utility class to let us iterate through all positions without having to copy/paste them into a
* new object
*
* @author Ian
*
*/
public static class WrappedIterators implements Enumeration<Editable>
{
private final List<Enumeration<Editable>> lists = new ArrayList<>();
private int currentList = 0;
private Enumeration<Editable> currentIter;
private Editable current;
private Editable previous;
public WrappedIterators()
{
currentIter = null;
}
public WrappedIterators(final SegmentList segments)
{
final Enumeration<Editable> ele = segments.elements();
while (ele.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) ele.nextElement();
lists.add(seg.elements());
}
currentIter = this.lists.get(0);
}
public void add(final Enumeration<MWC.GUI.Editable> item)
{
lists.add(item);
if (currentIter == null)
{
currentIter = lists.get(0);
}
}
public Editable currentElement()
{
return current;
}
@Override
public boolean hasMoreElements()
{
while (currentList < lists.size() - 1 && !currentIter.hasMoreElements())
{
currentList++;
currentIter = lists.get(currentList);
}
return currentIter.hasMoreElements();
}
@Override
public Editable nextElement()
{
while (currentList < lists.size() - 1 && !currentIter.hasMoreElements())
{
currentList++;
currentIter = lists.get(currentList);
}
// cache the previous value
previous = current;
// cache the current value
current = currentIter.nextElement();
return current;
}
public Editable previousElement()
{
return previous;
}
}
private static final String SOLUTIONS_LAYER_NAME = "Solutions";
public static final String SENSORS_LAYER_NAME = "Sensors";
public static final String DYNAMIC_SHAPES_LAYER_NAME = "Dynamic Shapes";
/**
* keep track of versions - version id
*/
static final long serialVersionUID = 1;
private static String checkTheyAreNotOverlapping(final Editable[] subjects)
{
// first, check they don't overlap.
// start off by collecting the periods
final TimePeriod[] _periods =
new TimePeriod.BaseTimePeriod[subjects.length];
for (int i = 0; i < subjects.length; i++)
{
final Editable editable = subjects[i];
TimePeriod thisPeriod = null;
if (editable instanceof TrackWrapper)
{
final TrackWrapper tw = (TrackWrapper) editable;
thisPeriod =
new TimePeriod.BaseTimePeriod(tw.getStartDTG(), tw.getEndDTG());
}
else if (editable instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) editable;
thisPeriod = new TimePeriod.BaseTimePeriod(ts.startDTG(), ts.endDTG());
}
_periods[i] = thisPeriod;
}
// now test them.
String failedMsg = null;
for (int i = 0; i < _periods.length; i++)
{
final TimePeriod timePeriod = _periods[i];
for (int j = 0; j < _periods.length; j++)
{
final TimePeriod timePeriod2 = _periods[j];
// check it's not us
if (timePeriod2 != timePeriod)
{
if (timePeriod.overlaps(timePeriod2))
{
failedMsg =
"'" + subjects[i].getName() + "' and '" + subjects[j].getName()
+ "'";
break;
}
}
}
}
return failedMsg;
}
/**
*
* @param newTrack
* @param reference
* Note: these parameters are tested here
* @see TrackWrapper_Test#testTrackMerge1()
*/
private static void copyStyling(final TrackWrapper newTrack,
final TrackWrapper reference)
{
// Note: see link in javadoc for where these are tested
newTrack.setSymbolType(reference.getSymbolType());
newTrack.setSymbolWidth(reference.getSymbolWidth());
newTrack.setSymbolLength(reference.getSymbolLength());
newTrack.setSymbolColor(reference.getSymbolColor());
}
private static void duplicateFixes(final SegmentList sl,
final TrackSegment target)
{
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment segment = (TrackSegment) segs.nextElement();
if (segment instanceof CoreTMASegment)
{
final CoreTMASegment ct = (CoreTMASegment) segment;
final TrackSegment newSeg = new TrackSegment(ct);
duplicateFixes(newSeg, target);
}
else
{
duplicateFixes(segment, target);
}
}
}
private static void duplicateFixes(final TrackSegment source,
final TrackSegment target)
{
// ok, retrieve the points in the track segment
final Enumeration<Editable> tsPts = source.elements();
while (tsPts.hasMoreElements())
{
final FixWrapper existingFW = (FixWrapper) tsPts.nextElement();
final Fix existingFix = existingFW.getFix();
final Fix newFix = existingFix.makeCopy();
final FixWrapper newF = new FixWrapper(newFix);
// also duplicate the label
newF.setLabel(existingFW.getLabel());
target.addFix(newF);
}
}
/**
* put the other objects into this one as children
*
* @param wrapper
* whose going to receive it
* @param theLayers
* the top level layers object
* @param parents
* the track wrapppers containing the children
* @param subjects
* the items to insert.
*/
public static void groupTracks(final TrackWrapper target,
final Layers theLayers, final Layer[] parents, final Editable[] subjects)
{
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
target.add(ts);
}
}
else
{
if (obj instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) obj;
// reset the name if we need to
if (ts.getName().startsWith("Posi"))
{
ts.setName(FormatRNDateTime.toString(ts.startDTG().getDate()
.getTime()));
}
// and remember it
target.add(ts);
}
}
}
}
else
{
// get it's data, and add it to the target
target.add(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
}
/**
* perform a merge of the supplied tracks.
*
* @param recipient
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @param _newName
* name to give to the merged object
* @return sufficient information to undo the merge
*/
public static int mergeTracks(final TrackWrapper newTrack,
final Layers theLayers, final Editable[] subjects)
{
// check that the legs don't overlap
final String failedMsg = checkTheyAreNotOverlapping(subjects);
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = (TrackWrapper) thisL;
copyStyling(newTrack, track);
}
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
duplicateFixes(sl, newT);
newTrack.add(newT);
}
else if (obj instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) obj;
// ok, duplicate the fixes in this segment
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
duplicateFixes(ts, newT);
// and add it to the new track
newTrack.append(newT);
}
}
}
else if (thisL instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) thisL;
// ok, duplicate the fixes in this segment
final TrackSegment newT = new TrackSegment(ts.getPlotRelative());
duplicateFixes(ts, newT);
// and add it to the new track
newTrack.append(newT);
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = ts.getWrapper();
copyStyling(newTrack, track);
}
}
else if (thisL instanceof SegmentList)
{
final SegmentList sl = (SegmentList) thisL;
// is this the first one? If so, we'll copy the symbol setup
if (i == 0)
{
final TrackWrapper track = sl.getWrapper();
copyStyling(newTrack, track);
}
// it's absolute, since merged tracks are always
// absolute
final TrackSegment newT = new TrackSegment(TrackSegment.ABSOLUTE);
// ok, duplicate the fixes in this segment
duplicateFixes(sl, newT);
// and add it to the new track
newTrack.append(newT);
}
}
// and store the new track
theLayers.addThisLayer(newTrack);
return MessageProvider.OK;
}
/**
* perform a merge of the supplied tracks.
*
* @param target
* the final recipient of the other items
* @param theLayers
* @param parents
* the parent tracks for the supplied items
* @param subjects
* the actual selected items
* @return sufficient information to undo the merge
*/
public static int mergeTracksInPlace(final Editable target,
final Layers theLayers, final Layer[] parents, final Editable[] subjects)
{
// where we dump the new data points
Layer receiver = (Layer) target;
// check that the legs don't overlap
final String failedMsg = checkTheyAreNotOverlapping(subjects);
// how did we get on?
if (failedMsg != null)
{
MessageProvider.Base.Provider.show("Merge tracks", "Sorry, " + failedMsg
+ " overlap in time. Please correct this and retry",
MessageProvider.ERROR);
return MessageProvider.ERROR;
}
// right, if the target is a TMA track, we have to change it into a
// proper
// track, since
// the merged tracks probably contain manoeuvres
if (target instanceof CoreTMASegment)
{
final CoreTMASegment tma = (CoreTMASegment) target;
final TrackSegment newSegment = new TrackSegment(tma);
// now do some fancy footwork to remove the target from the wrapper,
// and
// replace it with our new segment
newSegment.getWrapper().removeElement(target);
newSegment.getWrapper().add(newSegment);
// store the new segment into the receiver
receiver = newSegment;
}
// ok, loop through the subjects, adding them onto the target
for (int i = 0; i < subjects.length; i++)
{
final Layer thisL = (Layer) subjects[i];
final TrackWrapper thisP = (TrackWrapper) parents[i];
// is this the target item (note we're comparing against the item
// passed
// in, not our
// temporary receiver, since the receiver may now be a tracksegment,
// not a
// TMA segment
if (thisL != target)
{
// is it a plain segment?
if (thisL instanceof TrackWrapper)
{
// pass down through the positions/segments
final Enumeration<Editable> pts = thisL.elements();
while (pts.hasMoreElements())
{
final Editable obj = pts.nextElement();
if (obj instanceof SegmentList)
{
final SegmentList sl = (SegmentList) obj;
final Enumeration<Editable> segs = sl.elements();
while (segs.hasMoreElements())
{
final TrackSegment ts = (TrackSegment) segs.nextElement();
receiver.add(ts);
}
}
else
{
final Layer ts = (Layer) obj;
receiver.append(ts);
}
}
}
else
{
// get it's data, and add it to the target
receiver.append(thisL);
}
// and remove the layer from it's parent
if (thisL instanceof TrackSegment)
{
thisP.removeElement(thisL);
// does this just leave an empty husk?
if (thisP.numFixes() == 0)
{
// may as well ditch it anyway
theLayers.removeThisLayer(thisP);
}
}
else
{
// we'll just remove it from the top level layer
theLayers.removeThisLayer(thisL);
}
}
}
return MessageProvider.OK;
}
/**
* whether to interpolate points in this track
*/
private boolean _interpolatePoints = false;
/**
* the end of the track to plot the label
*/
private boolean _LabelAtStart = true;
private HiResDate _lastLabelFrequency = new HiResDate(0);
private HiResDate _lastSymbolFrequency = new HiResDate(0);
private HiResDate _lastArrowFrequency = new HiResDate(0);
private HiResDate _lastDataFrequency = new HiResDate(0,
TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY);
/**
* whether to show a time label at the start/end of the track
*
*/
private boolean _endTimeLabels = true;
/**
* the width of this track
*/
private int _lineWidth = 3;
/**
* the style of this line
*
*/
private int _lineStyle = CanvasType.SOLID;
/**
* whether or not to link the Positions
*/
private boolean _linkPositions;
/**
* whether to show a highlight for the array centre
*
*/
private boolean _plotArrayCentre;
/**
* our editable details
*/
protected transient Editable.EditorType _myEditor = null;
/**
* keep a list of points waiting to be plotted
*
*/
transient private int[] _myPts;
/**
* when plotting a track, we end up calling "get visible period" very frequently. So, we'll cache
* it, together with the time the cached version was generated. This will let us decide whether to
* recalculate, or to use a cached version
*
*/
transient private TimePeriod _cachedPeriod = null;
/**
* the time that we last calculated the time period
*
*/
transient private long _timeCachedPeriodCalculated = 0;
/**
* the sensor tracks for this vessel
*/
final private BaseLayer _mySensors;
/**
* the dynamic shapes for this vessel
*/
final private BaseLayer _myDynamicShapes;
/**
* the TMA solutions for this vessel
*/
final private BaseLayer _mySolutions;
/**
* keep track of how far we are through our array of points
*
*/
transient private int _ptCtr = 0;
/**
* whether or not to show the Positions
*/
private boolean _showPositions;
/**
* the label describing this track
*/
private final MWC.GUI.Shapes.TextLabel _theLabel;
/**
* the list of wrappers we hold
*/
protected SegmentList _thePositions;
/**
* the symbol to pass on to a snail plotter
*/
private MWC.GUI.Shapes.Symbols.PlainSymbol _theSnailShape;
/**
* flag for if there is a pending update to track - particularly if it's a relative one
*/
private boolean _relativeUpdatePending = false;
// member functions
transient private FixWrapper _lastFix;
/**
* working parameters
*/
transient private WorldArea _myWorldArea;
transient private final PropertyChangeListener _locationListener;
transient private PropertyChangeListener _childTrackMovedListener;
private Duration _customTrailLength = null;
private Double _customVectorStretch = null;
/**
* how to shade the track
*
*/
private TrackColorModeHelper.TrackColorMode _trackColorMode =
TrackColorModeHelper.LegacyTrackColorModes.PER_FIX;
/**
* cache the position iterator we last used. this prevents us from having to restart at the
* beginning when getNearestTo() is being called repetitively
*/
private transient WrappedIterators _lastPosIterator;
// constructors
/**
* Wrapper for a Track (a series of position fixes). It combines the data with the formatting
* details
*/
public TrackWrapper()
{
_mySensors = new SplittableLayer(true);
_mySensors.setName(SENSORS_LAYER_NAME);
_myDynamicShapes = new SplittableLayer(true);
_myDynamicShapes.setName(DYNAMIC_SHAPES_LAYER_NAME);
_mySolutions = new BaseLayer(true);
_mySolutions.setName(SOLUTIONS_LAYER_NAME);
// create a property listener for when fixes are moved
_locationListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent arg0)
{
fixMoved();
}
};
_childTrackMovedListener = new PropertyChangeListener()
{
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
// child track move. remember that we need to recalculate & redraw
setRelativePending();
// also share the good news
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, System
.currentTimeMillis());
}
};
_linkPositions = true;
// start off with positions showing (although the default setting for a
// fix
// is to not show a symbol anyway). We need to make this "true" so that
// when a fix position is set to visible it is not over-ridden by this
// setting
_showPositions = true;
_theLabel = new MWC.GUI.Shapes.TextLabel(new WorldLocation(0, 0, 0), null);
// set an initial location for the label
setNameLocation(NullableLocationPropertyEditor.AUTO);
// initialise the symbol to use for plotting this track in snail mode
_theSnailShape =
MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol("Submarine");
// declare our arrays
_thePositions = new TrackWrapper_Support.SegmentList();
_thePositions.setWrapper(this);
}
/**
* add the indicated point to the track
*
* @param point
* the point to add
*/
@Override
public void add(final MWC.GUI.Editable point)
{
// see what type of object this is
if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
fw.setTrackWrapper(this);
addFix(fw);
}
// is this a sensor?
else if (point instanceof SensorWrapper)
{
final SensorWrapper swr = (SensorWrapper) point;
// see if we already have a sensor with this name
SensorWrapper existing = null;
final Enumeration<Editable> enumer = _mySensors.elements();
while (enumer.hasMoreElements())
{
final SensorWrapper oldS = (SensorWrapper) enumer.nextElement();
// does this have the same name?
if (oldS.getName().equals(swr.getName()))
{
// yes - ok, remember it
existing = oldS;
// and append the data points
existing.append(swr);
}
}
// did we find it already?
if (existing == null)
{
// nope, so store it
_mySensors.add(swr);
}
// tell the sensor about us
swr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
swr.setTrackName(this.getName());
}
// is this a dynamic shape?
else if (point instanceof DynamicTrackShapeSetWrapper)
{
final DynamicTrackShapeSetWrapper swr =
(DynamicTrackShapeSetWrapper) point;
// just check we don't alraedy have it
if (_myDynamicShapes.contains(swr))
{
MWC.Utilities.Errors.Trace
.trace("Don't allow duplicate shape set name:" + swr.getName());
}
else
{
// add to our list
_myDynamicShapes.add(swr);
// tell the sensor about us
swr.setHost(this);
}
}
// is this a TMA solution track?
else if (point instanceof TMAWrapper)
{
final TMAWrapper twr = (TMAWrapper) point;
// add to our list
_mySolutions.add(twr);
// tell the sensor about us
twr.setHost(this);
// and the track name (if we're loading from REP it will already
// know
// the name, but if this data is being pasted in, it may start with
// a different
// parent track name - so override it here)
twr.setTrackName(this.getName());
}
else if (point instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) point;
seg.setWrapper(this);
_thePositions.addSegment((TrackSegment) point);
// hey, sort out the positions
sortOutRelativePositions();
// special case - see if it's a relative TMA segment,
// we many need some more sorting
if (point instanceof RelativeTMASegment)
{
final RelativeTMASegment newRelativeSegment =
(RelativeTMASegment) point;
// ok, try to update the layers. get the layers for an
// existing segment
final SegmentList sl = this.getSegments();
final Enumeration<Editable> sEnum = sl.elements();
while (sEnum.hasMoreElements())
{
final TrackSegment mySegment = (TrackSegment) sEnum.nextElement();
if (mySegment != newRelativeSegment)
{
// ok, it's not this one. try the layers
if (mySegment instanceof RelativeTMASegment)
{
final RelativeTMASegment myRelativeSegnent =
(RelativeTMASegment) mySegment;
final Layers myExistingLayers = myRelativeSegnent.getLayers();
if (myExistingLayers != newRelativeSegment.getLayers())
{
newRelativeSegment.setLayers(myExistingLayers);
break;
}
}
}
}
}
// we also need to listen for a child moving
seg.addPropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
}
else if (point instanceof Layer)
{
final Layer layer = (Layer) point;
final Enumeration<Editable> items = layer.elements();
while (items.hasMoreElements())
{
final Editable thisE = items.nextElement();
add(thisE);
}
}
else
{
MWC.GUI.Dialogs.DialogFactory.showMessage("Add point",
"Sorry it is not possible to add:" + point.getName() + " to "
+ this.getName());
}
}
public void addFix(final FixWrapper theFix)
{
// do we have any track segments
if (_thePositions.isEmpty())
{
// nope, add one
final TrackSegment firstSegment = new TrackSegment(TrackSegment.ABSOLUTE);
firstSegment.setName("Positions");
_thePositions.addSegment(firstSegment);
}
// add fix to last track segment
final TrackSegment last = (TrackSegment) _thePositions.last();
last.addFix(theFix);
// tell the fix about it's daddy
theFix.setTrackWrapper(this);
if (_myWorldArea == null)
{
_myWorldArea = new WorldArea(theFix.getLocation(), theFix.getLocation());
}
else
{
_myWorldArea.extend(theFix.getLocation());
}
// flush any cached values for time period & lists of positions
flushPeriodCache();
flushPositionCache();
}
/**
* append this other layer to ourselves (although we don't really bother with it)
*
* @param other
* the layer to add to ourselves
*/
@Override
public void append(final Layer other)
{
boolean modified = false;
// is it a track?
if ((other instanceof TrackWrapper) || (other instanceof TrackSegment))
{
// yes, break it down.
final java.util.Enumeration<Editable> iter = other.elements();
while (iter.hasMoreElements())
{
final Editable nextItem = iter.nextElement();
if (nextItem instanceof Layer)
{
append((Layer) nextItem);
modified = true;
}
else
{
add(nextItem);
modified = true;
}
}
}
else
{
// nope, just add it to us.
add(other);
modified = true;
}
if (modified)
{
setRelativePending();
}
}
/**
* Calculates Course & Speed for the track.
*/
public void calcCourseSpeed()
{
// step through our fixes
final Enumeration<Editable> iter = getPositionIterator();
FixWrapper prevFw = null;
while (iter.hasMoreElements())
{
final FixWrapper currFw = (FixWrapper) iter.nextElement();
if (prevFw == null)
{
prevFw = currFw;
}
else
{
// calculate the course
final WorldVector wv =
currFw.getLocation().subtract(prevFw.getLocation());
prevFw.getFix().setCourse(wv.getBearing());
// also, set the correct label alignment
currFw.resetLabelLocation();
// calculate the speed
// get distance in meters
final WorldDistance wd = new WorldDistance(wv);
final double distance = wd.getValueIn(WorldDistance.METRES);
// get time difference in seconds
final long timeDifference =
(currFw.getTime().getMicros() - prevFw.getTime().getMicros()) / 1000000;
// get speed in meters per second and convert it to knots
final WorldSpeed speed =
new WorldSpeed(distance / timeDifference, WorldSpeed.M_sec);
final double knots =
WorldSpeed.convert(WorldSpeed.M_sec, WorldSpeed.Kts, speed
.getValue());
prevFw.setSpeed(knots);
prevFw = currFw;
}
}
// if it's a DR track this will probably change things
setRelativePending();
}
private void checkPointsArray()
{
// is our points store long enough?
if ((_myPts == null) || (_myPts.length < numFixes() * 2))
{
_myPts = new int[numFixes() * 2];
}
// reset the points counter
_ptCtr = 0;
}
public void clearPositions()
{
boolean modified = false;
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.removeAllElements();
// remember that we've made a change
modified = true;
// we've also got to clear the cache
flushPeriodCache();
flushPositionCache();
}
if (modified)
{
setRelativePending();
}
}
/**
* instruct this object to clear itself out, ready for ditching
*/
@Override
public final void closeMe()
{
// and my objects
// first ask them to close themselves
final Enumeration<Editable> it = getPositionIterator();
while (it.hasMoreElements())
{
final Editable val = it.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
else if (val instanceof TrackSegment)
{
final TrackSegment ts = (TrackSegment) val;
// and clear the parent item
ts.setWrapper(null);
// we also need to stop listen for a child moving
ts.removePropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
}
}
// now ditch them
_thePositions.removeAllElements();
_thePositions = null;
// and my objects
// first ask the sensors to close themselves
if (_mySensors != null)
{
final Enumeration<Editable> it2 = _mySensors.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySensors.removeAllElements();
}
// and my objects
// first ask the sensors to close themselves
if (_myDynamicShapes != null)
{
final Enumeration<Editable> it2 = _myDynamicShapes.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_myDynamicShapes.removeAllElements();
}
// now ask the solutions to close themselves
if (_mySolutions != null)
{
final Enumeration<Editable> it2 = _mySolutions.elements();
while (it2.hasMoreElements())
{
final Object val = it2.nextElement();
if (val instanceof PlainWrapper)
{
final PlainWrapper pw = (PlainWrapper) val;
pw.closeMe();
}
}
// now ditch them
_mySolutions.removeAllElements();
}
// and our utility objects
_lastFix = null;
// and our editor
_myEditor = null;
// now get the parent to close itself
super.closeMe();
}
/**
* switch the two track sections into one track section
*
* @param res
* the previously split track sections
*/
public void combineSections(final Vector<TrackSegment> res)
{
// ok, remember the first
final TrackSegment keeper = res.firstElement();
// now remove them all, adding them to the first
final Iterator<TrackSegment> iter = res.iterator();
while (iter.hasNext())
{
final TrackSegment pl = iter.next();
if (pl != keeper)
{
keeper.append((Layer) pl);
}
removeElement(pl);
}
// and put the keepers back in
add(keeper);
// and remember we need an update
setRelativePending();
}
@Override
public int compareTo(final Plottable arg0)
{
Integer answer = null;
// SPECIAL PROCESSING: we wish to push TMA tracks to the top of any
// tracks shown in the outline view.
// is he a track?
if (arg0 instanceof TrackWrapper)
{
final TrackWrapper other = (TrackWrapper) arg0;
// yes, he's a track. See if we're a relative track
final boolean iAmTMA = isTMATrack();
// is he relative?
final boolean heIsTMA = other.isTMATrack();
if (heIsTMA)
{
// ok, he's a TMA segment. now we need to sort out if we are.
if (iAmTMA)
{
// we're both relative, compare names
answer = getName().compareTo(other.getName());
}
else
{
// only he is relative, he comes first
answer = 1;
}
}
else
{
// he's not relative. am I?
if (iAmTMA)
{
// I am , so go first
answer = -1;
}
}
}
else
{
// we're a track, they're not - put us at the end!
answer = 1;
}
// if we haven't worked anything out yet, just use the parent implementation
if (answer == null)
{
answer = super.compareTo(arg0);
}
return answer;
}
/**
* return our tiered data as a single series of elements
*
* @return
*/
@Override
public Enumeration<Editable> contiguousElements()
{
final WrappedIterators we = new WrappedIterators();
if (_mySensors != null && _mySensors.getVisible())
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// is it visible?
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_myDynamicShapes != null && _myDynamicShapes.getVisible())
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// is it visible?
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_mySolutions != null && _mySolutions.getVisible())
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
if (sw.getVisible())
{
we.add(sw.elements());
}
}
}
if (_thePositions != null && _thePositions.getVisible())
{
we.add(getPositionIterator());
}
return we;
}
/**
* this accessor is present for debug/testing purposes only. Do not use outside testing!
*
* @return the length of the list of screen points waiting to be plotted
*/
public int debug_GetPointCtr()
{
return _ptCtr;
}
/**
* this accessor is present for debug/testing purposes only. Do not use outside testing!
*
* @return the list of screen locations about to be plotted
*/
public int[] debug_GetPoints()
{
return _myPts;
}
/**
* get an enumeration of the points in this track
*
* @return the points in this track
*/
@Override
public Enumeration<Editable> elements()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
if (!_mySensors.isEmpty())
{
res.add(_mySensors);
}
if (!_myDynamicShapes.isEmpty())
{
res.add(_myDynamicShapes);
}
if (!_mySolutions.isEmpty())
{
res.add(_mySolutions);
}
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
// editing parameters
/**
* export this track to REPLAY file
*/
@Override
public final void exportShape()
{
// call the method in PlainWrapper
this.exportThis();
}
/**
* filter the list to the specified time period, then inform any listeners (such as the time
* stepper)
*
* @param start
* the start dtg of the period
* @param end
* the end dtg of the period
*/
@Override
public final void filterListTo(final HiResDate start, final HiResDate end)
{
final Enumeration<Editable> fixWrappers = getPositionIterator();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
final HiResDate dtg = fw.getTime();
if ((dtg.greaterThanOrEqualTo(start)) && (dtg.lessThanOrEqualTo(end)))
{
fw.setVisible(true);
}
else
{
fw.setVisible(false);
}
}
// now do the same for our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// now do the same for our sensor arc data
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensor arcs
} // whether we have any sensor arcs
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final WatchableList sw = (WatchableList) iter.nextElement();
sw.filterListTo(start, end);
} // through the sensors
} // whether we have any sensors
// do we have any property listeners?
if (getSupport() != null)
{
final Debrief.GUI.Tote.StepControl.somePeriod newPeriod =
new Debrief.GUI.Tote.StepControl.somePeriod(start, end);
getSupport().firePropertyChange(WatchableList.FILTERED_PROPERTY, null,
newPeriod);
}
}
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final ComponentConstruct currentNearest,
final Layer parentLayer)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositionIterator();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
// only check it if it's visible
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
final WorldLocation fixLocation =
new WorldLocation(thisF.getLocation())
{
private static final long serialVersionUID = 1L;
@Override
public void addToMe(final WorldVector delta)
{
super.addToMe(delta);
thisF.setFixLocation(this);
}
};
// try range
currentNearest.checkMe(this, thisDist, null, parentLayer, fixLocation);
}
}
}
@Override
public void findNearestHotSpotIn(final Point cursorPos,
final WorldLocation cursorLoc, final LocationConstruct currentNearest,
final Layer parentLayer, final Layers theData)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist = new WorldDistance(0, WorldDistance.DEGS);
// cycle through the fixes
final Enumeration<Editable> fixes = getPositionIterator();
while (fixes.hasMoreElements())
{
final FixWrapper thisF = (FixWrapper) fixes.nextElement();
if (thisF.getVisible())
{
// how far away is it?
thisDist = thisF.getLocation().rangeFrom(cursorLoc, thisDist);
// is it closer?
currentNearest.checkMe(this, thisDist, null, parentLayer);
}
}
}
public void findNearestSegmentHotspotFor(final WorldLocation cursorLoc,
final Point cursorPt, final LocationConstruct currentNearest)
{
// initialise thisDist, since we're going to be over-writing it
WorldDistance thisDist;
// cycle through the track segments
final Collection<Editable> segments = _thePositions.getData();
for (final Iterator<Editable> iterator = segments.iterator(); iterator
.hasNext();)
{
final TrackSegment thisSeg = (TrackSegment) iterator.next();
if (thisSeg.getVisible())
{
// how far away is it?
thisDist =
new WorldDistance(thisSeg.rangeFrom(cursorLoc), WorldDistance.DEGS);
// is it closer?
currentNearest.checkMe(thisSeg, thisDist, null, this);
}
}
}
private void fixLabelColor()
{
if (_theLabel.getColor() == null)
{
// check we have a colour
Color labelColor = getColor();
// did we ourselves have a colour?
if (labelColor == null)
{
// nope - do we have any legs?
final Enumeration<Editable> numer = this.getPositionIterator();
if (numer.hasMoreElements())
{
// ok, use the colour of the first point
final FixWrapper pos = (FixWrapper) numer.nextElement();
labelColor = pos.getColor();
}
}
_theLabel.setColor(labelColor);
}
}
/**
* one of our fixes has moved. better tell any bits that rely on the locations of our bits
*
* @param theFix
* the fix that moved
*/
public void fixMoved()
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper nextS = (SensorWrapper) iter.nextElement();
nextS.setHost(this);
}
}
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper nextS =
(DynamicTrackShapeSetWrapper) iter.nextElement();
nextS.setHost(this);
}
}
}
/**
* ensure the cached set of raw positions gets cleared
*
*/
public void flushPeriodCache()
{
_cachedPeriod = null;
}
/**
* ensure the cached set of raw positions gets cleared
*
*/
public void flushPositionCache()
{
}
/**
* return the arrow frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getArrowFrequency()
{
return _lastArrowFrequency;
}
/**
* calculate a position the specified distance back along the ownship track (note, we always
* interpolate the parent track position)
*
* @param searchTime
* the time we're looking at
* @param sensorOffset
* how far back the sensor should be
* @param wormInHole
* whether to plot a straight line back, or make sensor follow ownship
* @return the location
*/
public FixWrapper getBacktraceTo(final HiResDate searchTime,
final ArrayLength sensorOffset, final boolean wormInHole)
{
FixWrapper res = null;
// special case - for single point tracks
if (isSinglePointTrack())
{
final TrackSegment seg =
(TrackSegment) _thePositions.elements().nextElement();
return (FixWrapper) seg.first();
}
if (wormInHole && sensorOffset != null)
{
res = WormInHoleOffset.getWormOffsetFor(this, searchTime, sensorOffset);
}
else
{
final boolean parentInterpolated = getInterpolatePoints();
setInterpolatePoints(true);
final MWC.GenericData.Watchable[] list = getNearestTo(searchTime);
// and restore the interpolated value
setInterpolatePoints(parentInterpolated);
FixWrapper wa = null;
if (list.length > 0)
{
wa = (FixWrapper) list[0];
}
// did we find it?
if (wa != null)
{
// yes, store it
res = new FixWrapper(wa.getFix().makeCopy());
// ok, are we dealing with an offset?
if (sensorOffset != null)
{
// get the current heading
final double hdg = wa.getCourse();
// and calculate where it leaves us
final WorldVector vector = new WorldVector(hdg, sensorOffset, null);
// now apply this vector to the origin
res.setLocation(new WorldLocation(res.getLocation().add(vector)));
}
}
}
return res;
}
/**
* what geographic area is covered by this track?
*
* @return get the outer bounds of the area
*/
@Override
public final WorldArea getBounds()
{
// we no longer just return the bounds of the track, because a portion
// of the track may have been made invisible.
// instead, we will pass through the full dataset and find the outer
// bounds
// of the visible area
WorldArea res = null;
if (!getVisible())
{
// hey, we're invisible, return null
}
else
{
final Enumeration<Editable> it = getPositionIterator();
while (it.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) it.nextElement();
// is this point visible?
if (fw.getVisible())
{
// has our data been initialised?
if (res == null)
{
// no, initialise it
res = new WorldArea(fw.getLocation(), fw.getLocation());
}
else
{
// yes, extend to include the new area
res.extend(fw.getLocation());
}
}
}
// also extend to include our sensor data
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
// also extend to include our sensor data
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final Plottable sw = (Plottable) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
}
// and our solution data
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final PlainWrapper sw = (PlainWrapper) iter.nextElement();
final WorldArea theseBounds = sw.getBounds();
if (theseBounds != null)
{
if (res == null)
{
res = new WorldArea(theseBounds);
}
else
{
res.extend(sw.getBounds());
}
}
} // step through the sensors
} // whether we have any sensors
} // whether we're visible
// SPECIAL CASE: if we're a DR track, the positions all
// have the same value
if (res != null)
{
// have we ended up with an empty area?
if (res.getHeight() == 0)
{
// ok - force a bounds update
sortOutRelativePositions();
// and retrieve the bounds of hte first segment
res = this.getSegments().first().getBounds();
}
}
return res;
}
/**
* this accessor is only present to support testing. It should not be used externally
*
* @return the iterator we last used in getNearestTo()
*/
public WrappedIterators getCachedIterator()
{
return _lastPosIterator;
}
/**
* length of trail to plot
*/
public final Duration getCustomTrailLength()
{
return _customTrailLength;
}
/**
* length of trail to plot
*/
public final double getCustomVectorStretch()
{
final double res;
// do we have a value?
if (_customVectorStretch != null)
{
res = _customVectorStretch;
}
else
{
res = 0;
}
return res;
}
/**
* get the list of sensor arcs for this track
*/
public final BaseLayer getDynamicShapes()
{
return _myDynamicShapes;
}
/**
* the time of the last fix
*
* @return the DTG
*/
@Override
public final HiResDate getEndDTG()
{
HiResDate dtg = null;
final TimePeriod res = getTimePeriod();
if (res != null)
{
dtg = res.getEndDTG();
}
return dtg;
}
/**
* whether to show time labels at the start/end of the track
*
* @return yes/no
*/
public boolean getEndTimeLabels()
{
return _endTimeLabels;
}
/**
* the editable details for this track
*
* @return the details
*/
@Override
public Editable.EditorType getInfo()
{
if (_myEditor == null)
{
_myEditor = new trackInfo(this);
}
return _myEditor;
}
/**
* create a new, interpolated point between the two supplied
*
* @param previous
* the previous point
* @param next
* the next point
* @return and interpolated point
*/
private final FixWrapper getInterpolatedFix(final FixWrapper previous,
final FixWrapper next, final HiResDate requestedDTG)
{
FixWrapper res = null;
// do we have a start point
if (previous == null)
{
res = next;
}
// hmm, or do we have an end point?
if (next == null)
{
res = previous;
}
// did we find it?
if (res == null)
{
res = FixWrapper.interpolateFix(previous, next, requestedDTG);
}
return res;
}
@Override
public final boolean getInterpolatePoints()
{
return _interpolatePoints;
}
/**
* get the set of fixes contained within this time period (inclusive of both end values)
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
@Override
public final Collection<Editable> getItemsBetween(final HiResDate start,
final HiResDate end)
{
SortedSet<Editable> set = null;
// does our track contain any data at all
if (!_thePositions.isEmpty())
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
// don't bother with it.
}
else
{
// SPECIAL CASE! If we've been asked to show interpolated data
// points,
// then
// we should produce a series of items between the indicated
// times. How
// about 1 minute resolution?
if (getInterpolatePoints())
{
final long ourInterval = 1000 * 60; // one minute
set = new TreeSet<Editable>();
for (long newTime = start.getDate().getTime(); newTime < end
.getDate().getTime(); newTime += ourInterval)
{
final HiResDate newD = new HiResDate(newTime);
final Watchable[] nearestOnes = getNearestTo(newD);
if (nearestOnes.length > 0)
{
final FixWrapper nearest = (FixWrapper) nearestOnes[0];
set.add(nearest);
}
}
}
else
{
// bugger that - get the real data
final Enumeration<Editable> iter = getPositionIterator();
set = new TreeSet<Editable>();
final TimePeriod period = new TimePeriod.BaseTimePeriod(start, end);
while (iter.hasMoreElements())
{
final FixWrapper nextF = (FixWrapper) iter.nextElement();
final HiResDate dtg = nextF.getDateTimeGroup();
if (period.contains(dtg))
{
set.add(nextF);
}
else if (dtg.greaterThan(end))
{
// ok, we've passed the end
break;
}
}
// // have a go..
// if (starter == null)
// starter = new FixWrapper(new Fix((start), _zeroLocation, 0.0, 0.0));
// else
// starter.getFix().setTime(new HiResDate(0, start.getMicros() - 1));
// if (finisher == null)
// finisher =
// new FixWrapper(new Fix(new HiResDate(0, end.getMicros() + 1),
// _zeroLocation, 0.0, 0.0));
// else
// finisher.getFix().setTime(new HiResDate(0, end.getMicros() + 1));
// // ok, ready, go for it.
// set = getPositionsBetween(starter, finisher);
}
}
}
return set;
}
/**
* method to allow the setting of label frequencies for the track
*
* @return frequency to use
*/
public final HiResDate getLabelFrequency()
{
return this._lastLabelFrequency;
}
/**
* what is the style used for plotting this track?
*
* @return
*/
public int getLineStyle()
{
return _lineStyle;
}
/**
* the line thickness (convenience wrapper around width)
*
* @return
*/
@Override
public int getLineThickness()
{
return _lineWidth;
}
/**
* whether to link points
*
* @return
*/
public boolean getLinkPositions()
{
return _linkPositions;
}
/**
* just have the one property listener - rather than an anonymous class
*
* @return
*/
public PropertyChangeListener getLocationListener()
{
return _locationListener;
}
/**
* name of this Track (normally the vessel name)
*
* @return the name
*/
@Override
public final String getName()
{
return _theLabel.getString();
}
/**
* whether to show the track label at the start or end of the track
*
* @return yes/no to indicate <I>At Start</I>
*/
public final boolean getNameAtStart()
{
return _LabelAtStart;
}
/**
* the relative location of the label
*
* @return the relative location
*/
public final Integer getNameLocation()
{
return _theLabel.getRelativeLocation();
}
/**
* whether the track label is visible or not
*
* @return yes/no
*/
public final boolean getNameVisible()
{
return _theLabel.getVisible();
}
/**
* find the fix nearest to this time (or the first fix for an invalid time)
*
* @param DTG
* the time of interest
* @return the nearest fix
*/
@Override
public final Watchable[] getNearestTo(final HiResDate srchDTG)
{
return getNearestTo(srchDTG, true);
}
/**
* find the fix nearest to this time (or the first fix for an invalid time)
*
* @param DTG
* the time of interest
* @param onlyVisible
* only consider visible fixes
* @return the nearest fix
*/
public final Watchable[] getNearestTo(final HiResDate srchDTG,
final boolean onlyVisible)
{
/**
* we need to end up with a watchable, not a fix, so we need to work our way through the fixes
*/
FixWrapper res = null;
// check that we do actually contain some data
if (_thePositions.isEmpty())
{
return new Watchable[]
{};
}
else if (isSinglePointTrack())
{
final TrackSegment seg =
(TrackSegment) _thePositions.elements().nextElement();
final FixWrapper fix = (FixWrapper) seg.first();
return new Watchable[]
{fix};
}
// special case - if we've been asked for an invalid time value
if (srchDTG == TimePeriod.INVALID_DATE)
{
final TrackSegment seg = (TrackSegment) _thePositions.first();
final FixWrapper fix = (FixWrapper) seg.first();
// just return our first location
return new MWC.GenericData.Watchable[]
{fix};
}
else if (_lastFix != null && _lastFix.getDTG().equals(srchDTG))
{
// see if this is the DTG we have just requested
res = _lastFix;
}
else
{
final TrackSegment firstSeg = (TrackSegment) _thePositions.first();
final TrackSegment lastSeg = (TrackSegment) _thePositions.last();
if ((firstSeg != null) && (!firstSeg.isEmpty()))
{
// see if this DTG is inside our data range
// in which case we will just return null
final FixWrapper theFirst = (FixWrapper) firstSeg.first();
final FixWrapper theLast = (FixWrapper) lastSeg.last();
if ((srchDTG.greaterThan(theFirst.getTime()))
&& (srchDTG.lessThanOrEqualTo(theLast.getTime())))
{
FixWrapper previous = null;
// do we already have a position iterator?
final Enumeration<Editable> pIter;
if (_lastPosIterator != null)
{
final FixWrapper lastPos =
(FixWrapper) _lastPosIterator.currentElement();
final FixWrapper prevPos =
(FixWrapper) _lastPosIterator.previousElement();
if (lastPos.getDTG().equals(srchDTG))
{
// ok, we know this answer, use it
res = lastPos;
pIter = null;
}
else if (lastPos.getDTG().lessThan(srchDTG))
{
// the current iterator is still valid, stick with it
pIter = _lastPosIterator;
previous = lastPos;
}
else if (prevPos != null && lastPos.getDTG().greaterThan(srchDTG)
&& prevPos.getDTG().lessThan(srchDTG))
{
// we're currently either side of the required value
// we don't need to restart the iterator
res = lastPos;
previous = prevPos;
pIter = _lastPosIterator;
}
else
{
// we've gone past the required value, and
// the previous value isn't of any use
pIter = getPositionIterator();
}
}
else
{
// we don't have a cached iterator, better create one then
pIter = getPositionIterator();
}
// yes it's inside our data range, find the first fix
// after the indicated point
if (res == null)
{
while (pIter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) pIter.nextElement();
if (!onlyVisible || fw.getVisible())
{
if (fw.getDTG().greaterThanOrEqualTo(srchDTG))
{
res = fw;
break;
}
// and remember the previous one
previous = fw;
}
}
}
// can we cache our iterator?
if (pIter != null && pIter.hasMoreElements())
{
// ok, it's still of value
_lastPosIterator = (WrappedIterators) pIter;
}
else
{
// nope, drop it.
_lastPosIterator = null;
}
// right, that's the first points on or before the indicated
// DTG. Are we
// meant
// to be interpolating?
if (res != null)
{
if (getInterpolatePoints())
{
if (!res.getTime().equals(srchDTG))
{
// do we know the previous time?
if (previous != null)
{
// cool, sort out the interpolated point USING
// THE ORIGINAL
// SEARCH TIME
res = getInterpolatedFix(previous, res, srchDTG);
// and reset the label
res.resetName();
}
}
}
}
}
else if (srchDTG.equals(theFirst.getDTG()))
{
// aaah, special case. just see if we're after a data point
// that's the
// same
// as our start time
res = theFirst;
}
}
// and remember this fix
_lastFix = res;
}
if (res != null)
{
return new MWC.GenericData.Watchable[]
{res};
}
else
{
return new MWC.GenericData.Watchable[]
{};
}
}
public boolean getPlotArrayCentre()
{
return _plotArrayCentre;
}
/**
* provide iterator for all positions that doesn't require a new list to be generated
*
* @return iterator through all positions
*/
public Enumeration<Editable> getPositionIterator()
{
return new WrappedIterators(_thePositions);
}
/**
* whether positions are being shown
*
* @return
*/
public final boolean getPositionsVisible()
{
return _showPositions;
}
/**
* method to allow the setting of data sampling frequencies for the track & sensor data
*
* @return frequency to use
*/
public final HiResDate getResampleDataAt()
{
return this._lastDataFrequency;
}
/**
* get our child segments
*
* @return
*/
public SegmentList getSegments()
{
return _thePositions;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSensors()
{
return _mySensors;
}
/**
* return the symbol to be used for plotting this track in snail mode
*/
@Override
public final MWC.GUI.Shapes.Symbols.PlainSymbol getSnailShape()
{
return _theSnailShape;
}
/**
* get the list of sensors for this track
*/
public final BaseLayer getSolutions()
{
return _mySolutions;
}
// watchable (tote related) parameters
/**
* the earliest fix in the track
*
* @return the DTG
*/
@Override
public final HiResDate getStartDTG()
{
HiResDate res = null;
final TimePeriod period = getTimePeriod();
if (period != null)
{
res = period.getStartDTG();
}
return res;
}
/**
* get the color used to plot the symbol
*
* @return the color
*/
public final Color getSymbolColor()
{
return _theSnailShape.getColor();
}
/**
* return the symbol frequencies for the track
*
* @return frequency in seconds
*/
public final HiResDate getSymbolFrequency()
{
return _lastSymbolFrequency;
}
public WorldDistance getSymbolLength()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getLength();
}
return res;
}
/**
* get the type of this symbol
*/
public final String getSymbolType()
{
return _theSnailShape.getType();
}
public WorldDistance getSymbolWidth()
{
WorldDistance res = null;
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
res = sym.getWidth();
}
return res;
}
private TimePeriod getTimePeriod()
{
TimePeriod res = null;
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segs.nextElement();
// do we have a dtg?
if ((seg.startDTG() != null) && (seg.endDTG() != null))
{
// yes, get calculating
if (res == null)
{
res = new TimePeriod.BaseTimePeriod(seg.startDTG(), seg.endDTG());
}
else
{
res.extend(seg.startDTG());
res.extend(seg.endDTG());
}
}
}
return res;
}
/**
* the colour of the points on the track
*
* @return the colour
*/
public final Color getTrackColor()
{
return getColor();
}
/**
* get the mode used to color the track
*
* @return
*/
public TrackColorMode getTrackColorMode()
{
// ok, see if we're using a deferred mode. If we are, we should correct it
if (_trackColorMode instanceof DeferredDatasetColorMode)
{
_trackColorMode =
TrackColorModeHelper.sortOutDeferredMode(
(DeferredDatasetColorMode) _trackColorMode, this);
}
return _trackColorMode;
}
public List<TrackColorMode> getTrackColorModes()
{
return TrackColorModeHelper.getAdditionalTrackColorModes(this);
}
/**
* font handler
*
* @return the font to use for the label
*/
public final java.awt.Font getTrackFont()
{
return _theLabel.getFont();
}
/**
* get the set of fixes contained within this time period which haven't been filtered, and which
* have valid depths. The isVisible flag indicates whether a track has been filtered or not. We
* also have the getVisibleFixesBetween method (below) which decides if a fix is visible if it is
* set to Visible, and it's label or symbol are visible.
* <p/>
* We don't have to worry about a valid depth, since 3d doesn't show points with invalid depth
* values
*
* @param start
* start DTG
* @param end
* end DTG
* @return series of fixes
*/
public final Collection<Editable> getUnfilteredItems(final HiResDate start,
final HiResDate end)
{
// see if we have _any_ points in range
if ((getStartDTG().greaterThan(end)) || (getEndDTG().lessThan(start)))
{
return null;
}
if (this.getVisible() == false)
{
return null;
}
// get ready for the output
final Vector<Editable> res = new Vector<Editable>(0, 1);
// put the data into a period
final TimePeriod thePeriod = new TimePeriod.BaseTimePeriod(start, end);
// step through our fixes
final Enumeration<Editable> iter = getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
if (fw.getVisible())
{
// is it visible?
if (thePeriod.contains(fw.getTime()))
{
// hey, it's valid - continue
res.add(fw);
}
}
}
return res;
}
/**
* Determine the time period for which we have visible locations
*
* @return
*/
public TimePeriod getVisiblePeriod()
{
// ok, have we determined the visible period recently?
final long tNow = System.currentTimeMillis();
// how long does the cached value remain valid for?
final long ALLOWABLE_PERIOD = 500;
if (_cachedPeriod != null
&& tNow - _timeCachedPeriodCalculated < ALLOWABLE_PERIOD)
{
// still in date, use the last calculated period
}
else
{
// ok, calculate a new one
TimePeriod res = null;
final Enumeration<Editable> pos = getPositionIterator();
while (pos.hasMoreElements())
{
final FixWrapper editable = (FixWrapper) pos.nextElement();
if (editable.getVisible())
{
final HiResDate thisT = editable.getTime();
if (res == null)
{
res = new TimePeriod.BaseTimePeriod(thisT, thisT);
}
else
{
res.extend(thisT);
}
}
}
// ok, store the new time period
_cachedPeriod = res;
// remember when it was calculated
_timeCachedPeriodCalculated = tNow;
}
return _cachedPeriod;
}
/**
* whether this object has editor details
*
* @return yes/no
*/
@Override
public final boolean hasEditor()
{
return true;
}
@Override
public boolean hasOrderedChildren()
{
return false;
}
/**
* whether this is single point track. Single point tracks get special processing.
*
* @return
*/
public boolean isSinglePointTrack()
{
final boolean res;
if (_thePositions.size() == 1)
{
final TrackSegment first =
(TrackSegment) _thePositions.elements().nextElement();
// we want to avoid getting the size() of the list.
// So, do fancy trick to check the first element is non-null,
// and the second is null
final Enumeration<Editable> elems = first.elements();
if (elems != null && elems.hasMoreElements()
&& elems.nextElement() != null && !elems.hasMoreElements())
{
res = true;
}
else
{
res = false;
}
}
else
{
res = false;
}
return res;
}
/**
* accessor to determine if this is a relative track
*
* @return
*/
public boolean isTMATrack()
{
boolean res = false;
if (_thePositions != null && !_thePositions.isEmpty()
&& _thePositions.first() instanceof CoreTMASegment)
{
res = true;
}
return res;
}
public boolean isVisibleAt(final HiResDate dtg)
{
boolean res = false;
// special case - single track
if (isSinglePointTrack())
{
// we'll assume it's never ending.
res = true;
}
else
{
final TimePeriod visiblePeriod = getVisiblePeriod();
if (visiblePeriod != null)
{
res = visiblePeriod.contains(dtg);
}
}
return res;
}
/**
* quick accessor for how many fixes we have
*
* @return
*/
public int numFixes()
{
int res = 0;
// loop through segments
final Enumeration<Editable> segs = _thePositions.elements();
while (segs.hasMoreElements())
{
// get this segment
final TrackSegment seg = (TrackSegment) segs.nextElement();
res += seg.size();
}
return res;
}
/**
* draw this track (we can leave the Positions to draw themselves)
*
* @param dest
* the destination
*/
@Override
public final void paint(final CanvasType dest)
{
// check we are visible and have some track data, else we won't work
if (!getVisible() || this.getStartDTG() == null)
{
return;
}
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
if (getColor() != null)
{
dest.setColor(getColor());
}
// firstly plot the solutions
if (_mySolutions.getVisible())
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the solutions
} // whether the solutions are visible
// now plot the sensors
if (_mySensors.getVisible())
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// just check that the sensor knows we're it's parent
if (sw.getHost() == null)
{
sw.setHost(this);
}
// and do the paint
sw.paint(dest);
} // through the sensors
} // whether the sensor layer is visible
// and now the track itself
// just check if we are drawing anything at all
if ((!getLinkPositions() || getLineStyle() == LineStylePropertyEditor.UNCONNECTED)
&& (!_showPositions))
{
return;
}
// let the fixes draw themselves in
final List<FixWrapper> endPoints = paintFixes(dest);
final boolean plotted_anything = !endPoints.isEmpty();
// and draw the track label
// still, we only plot the track label if we have plotted any
// points
if (getNameVisible() && plotted_anything)
{
// just see if we have multiple segments. if we do,
// name them individually
if (this._thePositions.size() <= 1)
{
paintSingleTrackLabel(dest, endPoints);
}
else
{
// we've got multiple segments, name them
paintMultipleSegmentLabel(dest);
}
} // if the label is visible
// lastly - paint any TMA or planning segment labels
paintVectorLabels(dest);
}
@Override
public void paint(final CanvasType dest, final long time)
{
if (!getVisible())
{
return;
}
// set the thickness for this track
dest.setLineWidth(_lineWidth);
// and set the initial colour for this track
if (getColor() != null)
{
dest.setColor(getColor());
}
// we plot only the dynamic arcs because they are MovingPlottable
if (_myDynamicShapes.getVisible())
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// and do the paint
sw.paint(dest, time);
}
}
}
/**
* paint the fixes for this track
*
* @param dest
* @return a collection containing the first & last visible fix
*/
private List<FixWrapper> paintFixes(final CanvasType dest)
{
// collate a list of the start & end points
final List<FixWrapper> endPoints = new ArrayList<FixWrapper>();
// use the track color mode
final TrackColorMode tMode = getTrackColorMode();
// we need an array to store the polyline of points in. Check it's big
// enough
checkPointsArray();
// we draw tracks as polylines. But we can't do that
// if the color/style changes. So, we have to track their values
Color lastCol = null;
final int defaultlineStyle = getLineStyle();
FixWrapper lastFix = null;
// update DR positions (if necessary)
if (_relativeUpdatePending)
{
// ok, generate the points on the relative track
sortOutRelativePositions();
// and clear the flag
_relativeUpdatePending = false;
}
// cycle through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// is it a single point segment?
final boolean singlePointSegment = seg.size() == 1;
// how shall we plot this segment?
final int thisLineStyle;
// is the parent using the default style?
if (defaultlineStyle == CanvasType.SOLID)
{
// yes, let's override it, if the segment wants to
thisLineStyle = seg.getLineStyle();
}
else
{
// no, we're using a custom style - don't override it.
thisLineStyle = defaultlineStyle;
}
// is this segment visible?
if (!seg.getVisible())
{
// nope, jump to the next
continue;
}
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// have a look at the last fix. we defer painting the fix label,
// because we want to know the id of the last visible fix, since
// we may need to paint it's label in 6 DTG
if ((getPositionsVisible() && lastFix != null && lastFix.getVisible())
|| singlePointSegment)
{
// is this the first visible fix?
final boolean isFirstVisibleFix = endPoints.size() == 1;
// special handling. if we only have one point in the segment,
// we treat it as the last fix
final FixWrapper newLastFix;
if (lastFix == null)
{
newLastFix = fw;
}
else
{
newLastFix = lastFix;
}
// more special processing - for single-point segments
final boolean symWasVisible = newLastFix.getSymbolShowing();
if (singlePointSegment)
{
newLastFix.setSymbolShowing(true);
}
paintIt(dest, newLastFix, getEndTimeLabels() && isFirstVisibleFix,
false);
if (singlePointSegment)
{
newLastFix.setSymbolShowing(symWasVisible);
}
}
// now there's a chance that our fix has forgotten it's
// parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
final Color thisFixColor = tMode.colorFor(fw);
// do our job of identifying the first & last date value
if (fw.getVisible())
{
// ok, see if this is the first one
if (endPoints.size() == 0)
{
endPoints.add(fw);
}
else
{
// have we already got an end value?
if (endPoints.size() == 2)
{
// yes, drop it
endPoints.remove(1);
}
// store a new end value
endPoints.add(fw);
}
}
else
{
// nope. Don't join it to the last position.
// ok, if we've built up a polygon, we need to write it
// now
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// remember this fix, used for relative tracks
lastFix = fw;
// ok, we only do this writing to screen if the actual
// position is visible
if (!fw.getVisible())
{
continue;
}
final java.awt.Point thisP = dest.toScreen(fw.getLocation());
// just check that there's enough GUI to create the plot
// (i.e. has a point been returned)
if (thisP == null)
{
return endPoints;
}
// are we
if (getLinkPositions()
&& (getLineStyle() != LineStylePropertyEditor.UNCONNECTED))
{
// right, just check if we're a different colour to
// the previous one
final Color thisCol = thisFixColor;
// do we know the previous colour
if (lastCol == null)
{
lastCol = thisCol;
}
// is this to be joined to the previous one?
if (fw.getLineShowing())
{
// so, grow the the polyline, unless we've got a
// colour change...
if (thisCol != lastCol)
{
// double check we haven't been modified
if (_ptCtr > _myPts.length)
{
continue;
}
// add our position to the list - we'll output
// the polyline at the end
if (_ptCtr < _myPts.length - 1)
{
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
// yup, better get rid of the previous
// polygon
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
// add our position to the list - we'll output
// the polyline at the end
if (_ptCtr > _myPts.length - 1)
{
continue;
}
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
else
{
// nope, output however much line we've got so
// far - since this
// line won't be joined to future points
paintSetOfPositions(dest, thisCol, thisLineStyle);
// start off the next line
_myPts[_ptCtr++] = thisP.x;
_myPts[_ptCtr++] = thisP.y;
}
/*
* set the colour of the track from now on to this colour, so that the "link" to the next
* fix is set to this colour if left unchanged
*/
dest.setColor(thisFixColor);
// and remember the last colour
lastCol = thisCol;
}
}// while fixWrappers has more elements
// ok - paint the label for the last visible point
if (getPositionsVisible())
{
if (endPoints.size() > 1)
{
// special handling. If it's a planning segment, we hide the
// last fix, unless it's the very last segment
// do we have more legs?
final boolean hasMoreLegs = segments.hasMoreElements();
// is this a planning track?
final boolean isPlanningTrack = this instanceof CompositeTrackWrapper;
// ok, we hide the last point for planning legs, if there are
// more legs to come
final boolean forceHideLabel = isPlanningTrack && hasMoreLegs;
// ok, get painting
paintIt(dest, endPoints.get(1), getEndTimeLabels(), forceHideLabel);
}
}
// ok, just see if we have any pending polylines to paint
paintSetOfPositions(dest, lastCol, thisLineStyle);
}
return endPoints;
}
// LAYER support methods
/**
* paint this fix, overriding the label if necessary (since the user may wish to have 6-figure
* DTGs at the start & end of the track
*
* @param dest
* where we paint to
* @param thisF
* the fix we're painting
* @param isEndPoint
* whether point is one of the ends
* @param forceHideLabel
* whether we wish to hide the label
*/
private void paintIt(final CanvasType dest, final FixWrapper thisF,
final boolean isEndPoint, final boolean forceHideLabel)
{
// have a look at the last fix. we defer painting the fix label,
// because we want to know the id of the last visible fix, since
// we may need to paint it's label in 6 DTG
final boolean isVis = thisF.getLabelShowing();
final String fmt = thisF.getLabelFormat();
final String lblVal = thisF.getLabel();
// are we plotting DTG at ends?
if (isEndPoint)
{
// set the custom format for our end labels (6-fig DTG)
thisF.setLabelFormat("ddHHmm");
thisF.setLabelShowing(true);
}
if (forceHideLabel)
{
thisF.setLabelShowing(false);
}
// this next method just paints the fix. we've put the
// call into paintThisFix so we can override the painting
// in the CompositeTrackWrapper class
paintThisFix(dest, thisF.getLocation(), thisF);
// do we need to restore it?
if (isEndPoint)
{
thisF.setLabelFormat(fmt);
thisF.setLabelShowing(isVis);
thisF.setLabel(lblVal);
}
if (forceHideLabel)
{
thisF.setLabelShowing(isVis);
}
}
private void paintMultipleSegmentLabel(final CanvasType dest)
{
final Enumeration<Editable> posis = _thePositions.elements();
while (posis.hasMoreElements())
{
final TrackSegment thisE = (TrackSegment) posis.nextElement();
// is this segment visible?
if (!thisE.getVisible())
{
continue;
}
// does it have visible data points?
if (thisE.isEmpty())
{
continue;
}
// if this is a TMA segment, we plot the name 1/2 way along. If it isn't
// we plot it at the start
if (thisE instanceof CoreTMASegment)
{
// just move along - we plot the name
// a the mid-point
}
else
{
final WorldLocation theLoc = thisE.getTrackStart();
// hey, don't abuse the track label - create a fresh one each time
final TextLabel label = new TextLabel(theLoc, thisE.getName());
// copy the font from the parent
label.setFont(_theLabel.getFont());
// is the first track a DR track?
if (thisE.getPlotRelative())
{
label.setFont(label.getFont().deriveFont(Font.ITALIC));
}
else if (_theLabel.getFont().isItalic())
{
label.setFont(label.getFont().deriveFont(Font.PLAIN));
}
// just see if this is a planning segment, with its own colors
final Color color;
if (thisE instanceof PlanningSegment)
{
final PlanningSegment ps = (PlanningSegment) thisE;
color = ps.getColor();
}
else
{
color = getColor();
}
label.setColor(color);
label.setLocation(theLoc);
label.paint(dest);
}
}
}
/**
* paint any polyline that we've built up
*
* @param dest
* - where we're painting to
* @param thisCol
* @param lineStyle
*/
private void paintSetOfPositions(final CanvasType dest, final Color thisCol,
final int lineStyle)
{
if (_ptCtr > 0)
{
dest.setColor(thisCol);
dest.setLineStyle(lineStyle);
final int[] poly = new int[_ptCtr];
System.arraycopy(_myPts, 0, poly, 0, _ptCtr);
dest.drawPolyline(poly);
dest.setLineStyle(CanvasType.SOLID);
// and reset the counter
_ptCtr = 0;
}
}
private void paintSingleTrackLabel(final CanvasType dest,
final List<FixWrapper> endPoints)
{
// check that we have found a location for the label
if (_theLabel.getLocation() == null)
{
return;
}
// check that we have set the name for the label
if (_theLabel.getString() == null)
{
_theLabel.setString(getName());
}
// does the first label have a colour?
fixLabelColor();
// ok, sort out the correct location
final FixWrapper hostFix;
if (getNameAtStart() || endPoints.size() == 1)
{
// ok, we're choosing to use the start for the location. Or,
// we've only got one fix - in which case the end "is" the start
hostFix = endPoints.get(0);
}
else
{
hostFix = endPoints.get(1);
}
// sort out the location
_theLabel.setLocation(hostFix.getLocation());
// and the relative location
// hmm, if we're plotting date labels at the ends,
// shift the track name so that it's opposite
Integer oldLoc = null;
if (this.getEndTimeLabels())
{
oldLoc = getNameLocation();
// is it auto-locate?
if (oldLoc == NullableLocationPropertyEditor.AUTO)
{
// ok, automatically locate it
final int theLoc =
LabelLocationPropertyEditor.oppositeFor(hostFix.getLabelLocation());
setNameLocation(theLoc);
}
}
// and paint it
_theLabel.paint(dest);
// ok, restore the user-favourite location
if (oldLoc != null)
{
_theLabel.setRelativeLocation(oldLoc);
}
}
/**
* get the fix to paint itself
*
* @param dest
* @param lastLocation
* @param fw
*/
protected void paintThisFix(final CanvasType dest,
final WorldLocation lastLocation, final FixWrapper fw)
{
fw.paintMe(dest, lastLocation, getTrackColorMode().colorFor(fw));
}
/**
* draw vector labels for any TMA tracks
*
* @param dest
*/
private void paintVectorLabels(final CanvasType dest)
{
// cycle through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// is this segment visible?
if (!seg.getVisible())
{
// nope, jump to the next
continue;
}
// paint only visible planning segments
if (seg instanceof PlanningSegment)
{
final PlanningSegment ps = (PlanningSegment) seg;
ps.paintLabel(dest);
}
else if (seg instanceof CoreTMASegment)
{
final CoreTMASegment tma = (CoreTMASegment) seg;
// check the segment has some data
if (!seg.isEmpty())
{
final WorldLocation firstLoc = seg.first().getBounds().getCentre();
final WorldLocation lastLoc = seg.last().getBounds().getCentre();
final Font f = new Font("Sans Serif", Font.PLAIN, 11);
final Color c = _theLabel.getColor();
// tell the segment it's being stretched
final String spdTxt =
MWC.Utilities.TextFormatting.GeneralFormat
.formatOneDecimalPlace(tma.getSpeed().getValueIn(
WorldSpeed.Kts));
// copied this text from RelativeTMASegment
double courseVal = tma.getCourse();
if (courseVal < 0)
{
courseVal += 360;
}
String textLabel =
"[" + spdTxt + " kts " + (int) courseVal + "\u00B0]";
// ok, now plot it
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, true);
textLabel = tma.getName().replace(TextLabel.NEWLINE_MARKER, " ");
CanvasTypeUtilities.drawLabelOnLine(dest, textLabel, f, c, firstLoc,
lastLoc, 1.2, false);
}
}
}
}
/**
* return the range from the nearest corner of the track
*
* @param other
* the other location
* @return the range
*/
@Override
public final double rangeFrom(final WorldLocation other)
{
double nearest = -1;
// do we have a track?
if (_myWorldArea != null)
{
// find the nearest point on the track
nearest = _myWorldArea.rangeFrom(other);
}
return nearest;
}
// track-shifting operation
// support for dragging the track around
/**
* remove the requested item from the track
*
* @param point
* the point to remove
*/
@Override
public final void removeElement(final Editable point)
{
boolean modified = false;
// just see if it's a sensor which is trying to be removed
if (point instanceof SensorWrapper)
{
_mySensors.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
// remember that we've made a change
modified = true;
}
else if (point instanceof TMAWrapper)
{
_mySolutions.removeElement(point);
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) point;
sw.setHost(null);
// remember that we've made a change
modified = true;
}
else if (point instanceof SensorContactWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
// try to remove it from this one...
sw.removeElement(point);
// remember that we've made a change
modified = true;
}
}
else if (point instanceof DynamicTrackShapeWrapper)
{
// ok, cycle through our sensors, try to remove this contact...
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
// try to remove it from this one...
sw.removeElement(point);
// remember that we've made a change
modified = true;
}
}
else if (point instanceof TrackSegment)
{
_thePositions.removeElement(point);
// and clear the parent item
final TrackSegment ts = (TrackSegment) point;
ts.setWrapper(null);
// we also need to stop listen for a child moving
ts.removePropertyChangeListener(CoreTMASegment.ADJUSTED,
_childTrackMovedListener);
// remember that we've made a change
modified = true;
}
else if (point.equals(_mySensors))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySensors.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point.equals(_myDynamicShapes))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) editable;
sw.setHost(null);
}
// and empty them out
_myDynamicShapes.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point.equals(_mySolutions))
{
// ahh, the user is trying to delete all the solution, cycle through
// them
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final Editable editable = iter.nextElement();
// tell the sensor wrapper to forget about us
final TacticalDataWrapper sw = (TacticalDataWrapper) editable;
sw.setHost(null);
}
// and empty them out
_mySolutions.removeAllElements();
// remember that we've made a change
modified = true;
}
else if (point instanceof FixWrapper)
{
final FixWrapper fw = (FixWrapper) point;
// loop through the segments
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.removeElement(point);
// and stop listening to it (if it's a fix)
fw.removePropertyChangeListener(PlainWrapper.LOCATION_CHANGED,
_locationListener);
// remember that we've made a change
modified = true;
// we've also got to clear the cache
flushPeriodCache();
flushPositionCache();
}
}
if (modified)
{
setRelativePending();
}
}
/**
* pass through the track, resetting the labels back to their original DTG
*/
@FireReformatted
public void resetLabels()
{
FormatTracks.formatTrack(this);
}
@Override
public Enumeration<Editable> segments()
{
final TreeSet<Editable> res = new TreeSet<Editable>();
// ok, we want to wrap our fast-data as a set of plottables
// see how many track segments we have
if (_thePositions.size() == 1)
{
// just the one, insert it
res.add(_thePositions.first());
}
else
{
// more than one, insert them as a tree
res.add(_thePositions);
}
return new TrackWrapper_Support.IteratorWrapper(res.iterator());
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setArrowFrequency(final HiResDate theVal)
{
this._lastArrowFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setArrowShowing(val);
}
};
setFixes(setSymbols, theVal);
}
/**
* set the colour of this track label
*
* @param theCol
* the colour
*/
@Override
@FireReformatted
public final void setColor(final Color theCol)
{
// do the parent
super.setColor(theCol);
// now do our processing
_theLabel.setColor(theCol);
}
/**
* length of trail to draw
*/
public final void setCustomTrailLength(final Duration len)
{
// just check that it's a non-null length
if (len != null)
{
if (len.getMillis() != 0)
{
_customTrailLength = len;
}
else
{
_customTrailLength = null;
}
}
}
/**
* length of trail to draw
*/
public final void setCustomVectorStretch(final double stretch)
{
_customVectorStretch = stretch;
}
/**
* whether to show time labels at the start/end of the track
*
* @param endTimeLabels
* yes/no
*/
@FireReformatted
public void setEndTimeLabels(final boolean endTimeLabels)
{
this._endTimeLabels = endTimeLabels;
}
/**
* the setter function which passes through the track
*/
private void setFixes(final FixSetter setter, final HiResDate theVal)
{
if (theVal == null)
{
return;
}
if (_thePositions.size() == 0)
{
return;
}
final long freq = theVal.getMicros();
// briefly check if we are revealing/hiding all times (ie if freq is 1
// or 0)
if (freq == TimeFrequencyPropertyEditor.SHOW_ALL_FREQUENCY)
{
// show all of the labels
final Enumeration<Editable> iter = getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) iter.nextElement();
setter.execute(fw, true);
}
}
else
{
// no, we're not just blindly doing all of them. do them at the
// correct
// frequency
// hide all of the labels/symbols first
final Enumeration<Editable> enumA = getPositionIterator();
while (enumA.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) enumA.nextElement();
setter.execute(fw, false);
}
if (freq == 0)
{
// we can ignore this, since we have just hidden all of the
// points
}
else
{
if (getStartDTG() != null)
{
// pass through the track setting the values
// sort out the start and finish times
long start_time = getStartDTG().getMicros();
final long end_time = getEndDTG().getMicros();
// first check that there is a valid time period between start
// time
// and end time
if (start_time + freq < end_time)
{
long num = start_time / freq;
// we need to add one to the quotient if it has rounded down
if (start_time % freq == 0)
{
// start is at our freq, so we don't need to increment
}
else
{
num++;
}
// calculate new start time
start_time = num * freq;
}
else
{
// there is not one of our 'intervals' between the start and
// the end,
// so use the start time
}
long nextMarker = start_time / 1000L;
final long freqMillis = freq / 1000L;
final Enumeration<Editable> iter = this.getPositionIterator();
while (iter.hasMoreElements())
{
final FixWrapper nextF = (FixWrapper) iter.nextElement();
final long hisDate = nextF.getDTG().getDate().getTime();
if (hisDate >= nextMarker)
{
setter.execute(nextF, true);
// ok, move on to the next one
nextMarker += freqMillis;
}
}
}
}
}
}
@Override
public final void setInterpolatePoints(final boolean val)
{
_interpolatePoints = val;
// note: when we switch interpolation on or off, it can change
// the fix that is to be returned from getNearestTo().
// So, we should clear the lastDTG cached value
_lastFix = null;
}
/**
* set the label frequency (in seconds)
*
* @param theVal
* frequency to use
*/
public final void setLabelFrequency(final HiResDate theVal)
{
this._lastLabelFrequency = theVal;
final FixSetter setLabel = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setLabelShowing(val);
}
};
setFixes(setLabel, theVal);
}
/**
* set the style used for plotting the lines for this track
*
* @param val
*/
public void setLineStyle(final int val)
{
_lineStyle = val;
}
/**
* the line thickness (convenience wrapper around width)
*/
public void setLineThickness(final int val)
{
_lineWidth = val;
}
/**
* whether to link points
*
* @param linkPositions
*/
public void setLinkPositions(final boolean linkPositions)
{
_linkPositions = linkPositions;
}
/**
* set the name of this track (normally the name of the vessel
*
* @param theName
* the name as a String
*/
@Override
@FireReformatted
public final void setName(final String theName)
{
_theLabel.setString(theName);
}
/**
* whether to show the track name at the start or end of the track
*
* @param val
* yes no for <I>show label at start</I>
*/
public final void setNameAtStart(final boolean val)
{
_LabelAtStart = val;
}
/**
* the relative location of the label
*
* @param val
* the relative location
*/
public final void setNameLocation(final Integer val)
{
_theLabel.setRelativeLocation(val);
}
/**
* whether to show the track name
*
* @param val
* yes/no
*/
public final void setNameVisible(final boolean val)
{
_theLabel.setVisible(val);
}
public void setPlotArrayCentre(final boolean plotArrayCentre)
{
_plotArrayCentre = plotArrayCentre;
}
/**
* whether to show the position fixes
*
* @param val
* yes/no
*/
public final void setPositionsVisible(final boolean val)
{
_showPositions = val;
}
private void setRelativePending()
{
_relativeUpdatePending = true;
}
/**
* set the data frequency (in seconds) for the track & sensor data
*
* @param theVal
* frequency to use
*/
@FireExtended
public final void setResampleDataAt(final HiResDate theVal)
{
this._lastDataFrequency = theVal;
// have a go at trimming the start time to a whole number of intervals
final long interval = theVal.getMicros();
// do we have a start time (we may just be being tested...)
if (this.getStartDTG() == null)
{
return;
}
final long currentStart = this.getStartDTG().getMicros();
long startTime = (currentStart / interval) * interval;
// just check we're in the range
if (startTime < currentStart)
{
startTime += interval;
}
// move back to millis
startTime /= 1000L;
// just check it's not a barking frequency
if (theVal.getDate().getTime() <= 0)
{
// ignore, we don't need to do anything for a zero or a -1
}
else
{
final SegmentList segments = _thePositions;
final Enumeration<Editable> theEnum = segments.elements();
while (theEnum.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) theEnum.nextElement();
seg.decimate(theVal, this, startTime);
}
// start off with the sensor data
if (_mySensors != null)
{
for (final Enumeration<Editable> iterator = _mySensors.elements(); iterator
.hasMoreElements();)
{
final SensorWrapper thisS = (SensorWrapper) iterator.nextElement();
thisS.decimate(theVal, startTime);
}
}
// now the solutions
if (_mySolutions != null)
{
for (final Enumeration<Editable> iterator = _mySolutions.elements(); iterator
.hasMoreElements();)
{
final TMAWrapper thisT = (TMAWrapper) iterator.nextElement();
thisT.decimate(theVal, startTime);
}
}
// ok, also set the arrow, symbol, label frequencies
setLabelFrequency(getLabelFrequency());
setSymbolFrequency(getSymbolFrequency());
setArrowFrequency(getArrowFrequency());
}
// remember we may need to regenerate positions, if we're a TMA solution
final Editable firstLeg = getSegments().elements().nextElement();
if (firstLeg instanceof CoreTMASegment)
{
// setRelativePending();
sortOutRelativePositions();
}
}
public final void setSymbolColor(final Color col)
{
_theSnailShape.setColor(col);
}
/**
* how frequently symbols are placed on the track
*
* @param theVal
* frequency in seconds
*/
public final void setSymbolFrequency(final HiResDate theVal)
{
this._lastSymbolFrequency = theVal;
// set the "showPositions" parameter, as long as we are
// not setting the symbols off
if (theVal == null)
{
return;
}
if (theVal.getMicros() != 0.0)
{
this.setPositionsVisible(true);
}
final FixSetter setSymbols = new FixSetter()
{
@Override
public void execute(final FixWrapper fix, final boolean val)
{
fix.setSymbolShowing(val);
}
};
setFixes(setSymbols, theVal);
}
public void setSymbolLength(final WorldDistance symbolLength)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setLength(symbolLength);
}
}
public final void setSymbolType(final String val)
{
// is this the type of our symbol?
if (val.equals(_theSnailShape.getType()))
{
// don't bother we're using it already
}
else
{
// remember the size of the symbol
final double scale = _theSnailShape.getScaleVal();
// remember the color of the symbol
final Color oldCol = _theSnailShape.getColor();
// replace our symbol with this new one
_theSnailShape = MWC.GUI.Shapes.Symbols.SymbolFactory.createSymbol(val);
_theSnailShape.setColor(oldCol);
_theSnailShape.setScaleVal(scale);
}
}
public void setSymbolWidth(final WorldDistance symbolWidth)
{
if (_theSnailShape instanceof WorldScaledSym)
{
final WorldScaledSym sym = (WorldScaledSym) _theSnailShape;
sym.setHeight(symbolWidth);
}
}
// note we are putting a track-labelled wrapper around the colour
// parameter, to make the properties window less confusing
/**
* the colour of the points on the track
*
* @param theCol
* the colour to use
*/
@FireReformatted
public final void setTrackColor(final Color theCol)
{
setColor(theCol);
}
/**
* set the mode used to color the track
*
* @param trackColorMode
*/
public void setTrackColorMode(final TrackColorMode trackColorMode)
{
this._trackColorMode = trackColorMode;
}
/**
* font handler
*
* @param font
* the font to use for the label
*/
public final void setTrackFont(final Font font)
{
_theLabel.setFont(font);
}
@Override
public void shift(final WorldLocation feature, final WorldVector vector)
{
feature.addToMe(vector);
// right, one of our fixes has moved. get the sensors to update
// themselves
fixMoved();
}
@Override
public void shift(final WorldVector vector)
{
boolean handled = false;
boolean updateAlreadyFired = false;
// check it contains a range
if (vector.getRange() > 0d)
{
// ok, move any tracks
final Enumeration<Editable> enumA = elements();
while (enumA.hasMoreElements())
{
final Object thisO = enumA.nextElement();
if (thisO instanceof TrackSegment)
{
final TrackSegment seg = (TrackSegment) thisO;
seg.shift(vector);
}
else if (thisO instanceof SegmentList)
{
final SegmentList list = (SegmentList) thisO;
final Collection<Editable> items = list.getData();
for (final Iterator<Editable> iterator = items.iterator(); iterator
.hasNext();)
{
final TrackSegment segment = (TrackSegment) iterator.next();
segment.shift(vector);
}
}
}
handled = true;
// ok, get the legs to re-generate themselves
updateAlreadyFired = sortOutRelativePositions();
}
// now update the other children - some
// are sensitive to ownship track
this.updateDependents(elements(), vector);
// did we move any dependents
if (handled && !updateAlreadyFired)
{
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, this._theLabel
.getLocation());
}
}
/**
* if we've got a relative track segment, it only learns where its individual fixes are once
* they've been initialised. This is where we do it.
*/
public boolean sortOutRelativePositions()
{
boolean moved = false;
boolean updateFired = false;
FixWrapper lastFix = null;
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
// SPECIAL HANDLING, SEE IF IT'S A TMA SEGMENT TO BE PLOTTED IN
// RELATIVE MODE
final boolean isRelative = seg.getPlotRelative();
WorldLocation tmaLastLoc = null;
long tmaLastDTG = 0;
final Enumeration<Editable> fixWrappers = seg.elements();
while (fixWrappers.hasMoreElements())
{
final FixWrapper fw = (FixWrapper) fixWrappers.nextElement();
// now there's a chance that our fix has forgotten it's parent,
// particularly if it's the victim of a
// copy/paste operation. Tell it about it's children
fw.setTrackWrapper(this);
// ok, are we in relative?
if (isRelative)
{
final long thisTime = fw.getDateTimeGroup().getDate().getTime();
// ok, is this our first location?
if (tmaLastLoc == null)
{
final WorldLocation trackStart = seg.getTrackStart();
if (trackStart != null)
{
tmaLastLoc = new WorldLocation(trackStart);
}
}
else
{
// calculate a new vector
final long timeDelta = thisTime - tmaLastDTG;
if (lastFix != null)
{
final double courseRads;
final double speedKts;
if (seg instanceof CoreTMASegment)
{
final CoreTMASegment tmaSeg = (CoreTMASegment) seg;
courseRads = Math.toRadians(tmaSeg.getCourse());
speedKts = tmaSeg.getSpeed().getValueIn(WorldSpeed.Kts);
}
else
{
courseRads = lastFix.getCourse();
speedKts = lastFix.getSpeed();
}
// check it has a location.
final double depthM;
if (fw.getLocation() != null)
{
depthM = fw.getDepth();
}
else
{
// no location - we may be extending a TMA segment
depthM = tmaLastLoc.getDepth();
}
// use the value of depth as read in from the file
tmaLastLoc.setDepth(depthM);
final WorldVector thisVec =
seg.vectorFor(timeDelta, speedKts, courseRads);
tmaLastLoc.addToMe(thisVec);
}
}
lastFix = fw;
tmaLastDTG = thisTime;
if (tmaLastLoc != null)
{
// have we found any movement yet?
if (!moved && fw.getLocation() != null
&& !fw.getLocation().equals(tmaLastLoc))
{
moved = true;
}
// dump the location into the fix
fw.setFixLocationSilent(new WorldLocation(tmaLastLoc));
}
}
}
}
// did we do anything?
if (moved)
{
// get the child components to update,
// - including sending out a "moved" message
updateDependents(elements(), new WorldVector(0, 0, 0));
// also share the good news
firePropertyChange(PlainWrapper.LOCATION_CHANGED, null, System
.currentTimeMillis());
updateFired = true;
}
return updateFired;
}
/**
* split this whole track into two sub-tracks
*
* @param splitPoint
* the point at which we perform the split
* @param splitBeforePoint
* whether to put split before or after specified point
* @return a list of the new track segments (used for subsequent undo operations)
*/
public Vector<TrackSegment> splitTrack(final FixWrapper splitPoint,
final boolean splitBeforePoint)
{
FixWrapper splitPnt = splitPoint;
Vector<TrackSegment> res = null;
TrackSegment relevantSegment = null;
// are we still in one section?
if (_thePositions.size() == 1)
{
relevantSegment = (TrackSegment) _thePositions.first();
// yup, looks like we're going to be splitting it.
// better give it a proper name
relevantSegment.setName(relevantSegment.startDTG().getDate().toString());
}
else
{
// ok, find which segment contains our data
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
if (seg.getData().contains(splitPnt))
{
relevantSegment = seg;
break;
}
}
}
if (relevantSegment == null)
{
throw new RuntimeException(
"failed to provide relevant segment, alg will break");
}
// hmm, if we're splitting after the point, we need to move along the
// bus by
// one
if (!splitBeforePoint)
{
final Collection<Editable> items = relevantSegment.getData();
final Iterator<Editable> theI = items.iterator();
Editable previous = null;
while (theI.hasNext())
{
final Editable thisE = theI.next();
// have we chosen to remember the previous item?
if (previous != null)
{
// yes, this must be the one we're after
splitPnt = (FixWrapper) thisE;
break;
}
// is this the one we're looking for?
if (thisE.equals(splitPnt))
{
// yup, remember it - we want to use the next value
previous = thisE;
}
}
}
// yup, do our first split
final SortedSet<Editable> p1 = relevantSegment.headSet(splitPnt);
final SortedSet<Editable> p2 = relevantSegment.tailSet(splitPnt);
// get our results ready
final TrackSegment ts1;
final TrackSegment ts2;
// aaah, just sort out if we are splitting a TMA segment, in which case
// want to create two
// tma segments, not track segments
if (relevantSegment instanceof RelativeTMASegment)
{
final RelativeTMASegment theTMA = (RelativeTMASegment) relevantSegment;
// find the ownship location at the relevant time
WorldLocation secondLegOrigin = null;
// get the time of the split
final HiResDate splitTime = splitPnt.getDateTimeGroup();
// aah, sort out if we are splitting before or after.
final SensorWrapper sensor = theTMA.getReferenceSensor();
if (sensor != null)
{
final Watchable[] nearestF = sensor.getNearestTo(splitTime);
if ((nearestF != null) && (nearestF.length > 0))
{
final SensorContactWrapper scw = (SensorContactWrapper) nearestF[0];
secondLegOrigin = scw.getCalculatedOrigin(null);
}
}
// if we couldn't get a sensor origin, try for the track origin
if (secondLegOrigin == null)
{
final Watchable firstMatch =
theTMA.getReferenceTrack().getNearestTo(splitTime)[0];
secondLegOrigin = firstMatch.getLocation();
}
final WorldVector secondOffset =
splitPnt.getLocation().subtract(secondLegOrigin);
// put the lists back into plottable layers
final RelativeTMASegment tr1 =
new RelativeTMASegment(theTMA, p1, theTMA.getOffset());
final RelativeTMASegment tr2 =
new RelativeTMASegment(theTMA, p2, secondOffset);
// update the freq's
tr1.setBaseFrequency(theTMA.getBaseFrequency());
tr2.setBaseFrequency(theTMA.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else if (relevantSegment instanceof AbsoluteTMASegment)
{
final AbsoluteTMASegment theTMA = (AbsoluteTMASegment) relevantSegment;
// aah, sort out if we are splitting before or after.
// find out the offset at the split point, so we can initiate it for
// the
// second part of the track
final Watchable[] matches =
this.getNearestTo(splitPnt.getDateTimeGroup());
final WorldLocation origin = matches[0].getLocation();
final FixWrapper t1Start = (FixWrapper) p1.first();
// put the lists back into plottable layers
final AbsoluteTMASegment tr1 =
new AbsoluteTMASegment(theTMA, p1, t1Start.getLocation(), null, null);
final AbsoluteTMASegment tr2 =
new AbsoluteTMASegment(theTMA, p2, origin, null, null);
// update the freq's
tr1.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
tr2.setBaseFrequency(((CoreTMASegment) relevantSegment)
.getBaseFrequency());
// and store them
ts1 = tr1;
ts2 = tr2;
}
else
{
// put the lists back into plottable layers
ts1 = new TrackSegment(p1);
ts2 = new TrackSegment(p2);
}
// now clear the positions
removeElement(relevantSegment);
// and put back our new layers
add(ts1);
add(ts2);
// remember them
res = new Vector<TrackSegment>();
res.add(ts1);
res.add(ts2);
return res;
}
/**
* extra parameter, so that jvm can produce a sensible name for this
*
* @return the track name, as a string
*/
@Override
public final String toString()
{
return "Track:" + getName();
}
public void trimTo(final TimePeriod period)
{
if (_mySensors != null)
{
final Enumeration<Editable> iter = _mySensors.elements();
while (iter.hasMoreElements())
{
final SensorWrapper sw = (SensorWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_myDynamicShapes != null)
{
final Enumeration<Editable> iter = _myDynamicShapes.elements();
while (iter.hasMoreElements())
{
final DynamicTrackShapeSetWrapper sw =
(DynamicTrackShapeSetWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_mySolutions != null)
{
final Enumeration<Editable> iter = _mySolutions.elements();
while (iter.hasMoreElements())
{
final TMAWrapper sw = (TMAWrapper) iter.nextElement();
sw.trimTo(period);
}
}
if (_thePositions != null)
{
final Enumeration<Editable> segments = _thePositions.elements();
while (segments.hasMoreElements())
{
final TrackSegment seg = (TrackSegment) segments.nextElement();
seg.trimTo(period);
}
}
}
/**
* move the whole of the track be the provided offset
*/
private final boolean updateDependents(final Enumeration<Editable> theEnum,
final WorldVector offset)
{
// keep track of if the track contains something that doesn't get
// dragged
boolean handledData = false;
// work through the elements
while (theEnum.hasMoreElements())
{
final Object thisO = theEnum.nextElement();
if (thisO instanceof DynamicInfillSegment)
{
final DynamicInfillSegment dd = (DynamicInfillSegment) thisO;
dd.reconstruct();
// ok - job well done
handledData = true;
}
else if (thisO instanceof TrackSegment)
{
// special case = we handle this higher
// up the call chain, since tracks
// have to move before any dependent children
// ok - job well done
handledData = true;
}
else if (thisO instanceof SegmentList)
{
final SegmentList list = (SegmentList) thisO;
final Collection<Editable> items = list.getData();
final IteratorWrapper enumer =
new Plottables.IteratorWrapper(items.iterator());
handledData = updateDependents(enumer, offset);
}
else if (thisO instanceof SensorWrapper)
{
final SensorWrapper sw = (SensorWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final SensorContactWrapper scw =
(SensorContactWrapper) enumS.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin == null)
{
// ok - get it to recalculate it
scw.clearCalculatedOrigin();
@SuppressWarnings("unused")
final WorldLocation newO = scw.getCalculatedOrigin(this);
// we don't use the newO - we're just
// triggering an update
}
else
{
// create new object to contain the updated location
final WorldLocation newSensorLocation =
new WorldLocation(sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a sensor wrapper
else if (thisO instanceof TMAWrapper)
{
final TMAWrapper sw = (TMAWrapper) thisO;
final Enumeration<Editable> enumS = sw.elements();
while (enumS.hasMoreElements())
{
final TMAContactWrapper scw = (TMAContactWrapper) enumS.nextElement();
// does this fix have it's own origin?
final WorldLocation sensorOrigin = scw.getOrigin();
if (sensorOrigin != null)
{
// create new object to contain the updated location
final WorldLocation newSensorLocation =
new WorldLocation(sensorOrigin);
newSensorLocation.addToMe(offset);
// so the contact did have an origin, change it
scw.setOrigin(newSensorLocation);
}
} // looping through the contacts
// ok - job well done
handledData = true;
} // whether this is a TMA wrapper
else if (thisO instanceof BaseLayer)
{
// ok, loop through it
final BaseLayer bl = (BaseLayer) thisO;
handledData = updateDependents(bl.elements(), offset);
}
} // looping through this track
// ok, did we handle the data?
if (!handledData)
{
System.err.println("TrackWrapper problem; not able to shift:" + theEnum);
}
return handledData;
}
/**
* is this track visible between these time periods?
*
* @param start
* start DTG
* @param end
* end DTG
* @return yes/no
*/
public final boolean
visibleBetween(final HiResDate start, final HiResDate end)
{
boolean visible = false;
if (getStartDTG().lessThan(end) && (getEndDTG().greaterThan(start)))
{
visible = true;
}
return visible;
}
} |
package io.rover.model;
public class GeofenceRegion {
private String mId;
private double mLatitude;
private double mLongitude;
private int mRadius;
public GeofenceRegion(String id, double latitude, double longitude, int radius) {
mId = id;
mLatitude = latitude;
mLongitude = longitude;
mRadius = radius;
}
public String getId() {
return mId;
}
public double getlatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
public int getRadius() {
return mRadius;
}
public void setId(String id) {
mId = id;
}
public void setLatitude(double latitude) {
mLatitude = latitude;
}
public void setLongitude(double longitude) {
mLongitude = longitude;
}
public void setRadius(int radius) {
mRadius = radius;
}
} |
package net.runelite.api;
/**
* Represents the entire 3D scene
*/
public interface Scene
{
/**
* Gets the tiles in the scene
*
* @return the tiles in [plane][x][y]
*/
Tile[][][] getTiles();
int getDrawDistance();
void setDrawDistance(int drawDistance);
/**
* Get the minimum scene level which will be rendered
*
* @return the plane of the minimum level
*/
int getMinLevel();
/**
* Set the minimum scene level which will be rendered
*
* @param minLevel the plane of the minimum level
*/
void setMinLevel(int minLevel);
/**
* Remove a game object from the scene
* @param gameObject
*/
void removeGameObject(GameObject gameObject);
} |
package edu.cmu.sv.trailscribe.view;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import edu.cmu.sv.trailscribe.R;
import edu.cmu.sv.trailscribe.controller.MapsController;
import edu.cmu.sv.trailscribe.dao.LocationDataSource;
import edu.cmu.sv.trailscribe.dao.SampleDataSource;
import edu.cmu.sv.trailscribe.model.Sample;
@SuppressLint("NewApi")
public class MapsActivity extends BaseActivity implements OnClickListener {
public static ActivityTheme ACTIVITY_THEME = new ActivityTheme("MapActivity", "Display map and layers", R.color.green);
public static String MSG_TAG = "MapsActivity";
// Controllers
private MapsController mController;
// Views
private WebView mWebView;
private Button mSamplesButton;
private Button mCurrentLocationButton;
private Button mPositionHistoryButton;
private Button mKmlButton;
// States
private boolean mIsDisplaySamples = false;
private boolean mIsDisplayCurrentLocation = false;
private boolean mIsDisplayPositionHistory = false;
private boolean mIsDisplayKML = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setView();
}
private void setView() {
setContentView(R.layout.activity_maps);
setMap();
setActionBar(getResources().getString(ACTIVITY_THEME.getActivityColor()));
setListener();
}
@Override
protected void setActionBar(String color) {
super.setActionBar(color);
mActionBar.setIcon(R.drawable.button_settings);
mDrawerLayout = (DrawerLayout) findViewById(R.id.maps_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout,
R.drawable.icon_trailscribe, R.string.map_display_tools, R.string.map_hide_tools) {
public void onDrawerClosed(View view) {
mActionBar.setIcon(R.drawable.button_settings);
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
mActionBar.setIcon(R.drawable.button_settings_toggle);
super.onDrawerOpened(drawerView);
}
};
mActionBar.setDisplayHomeAsUpEnabled(true);
mActionBar.setHomeButtonEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void setListener() {
mSamplesButton = (Button) findViewById(R.id.maps_samples);
mCurrentLocationButton = (Button) findViewById(R.id.maps_current_location);
mPositionHistoryButton = (Button) findViewById(R.id.maps_position_history);
mKmlButton = (Button) findViewById(R.id.maps_kml);
mSamplesButton.setOnClickListener(this);
mCurrentLocationButton.setOnClickListener(this);
mPositionHistoryButton.setOnClickListener(this);
mKmlButton.setOnClickListener(this);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
@SuppressLint("SetJavaScriptEnabled")
private void setMap() {
mWebView = (WebView) findViewById(R.id.maps_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.addJavascriptInterface(this, "android");
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.getSettings().setUseWideViewPort(false);
mWebView.setWebViewClient(new WebViewClient());
// Setting to give OpenLayers access to local KML files
// Sets whether JavaScript running in the context of a file scheme URL should be allowed to
// access content from any origin.
mWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
mController = new MapsController();
mWebView.loadUrl(mController.getURL());
}
private void setLayers(MessageToWebview message) {
mWebView.loadUrl("javascript:setLayers(\"" + message.getMessage() + "\")");
}
@JavascriptInterface
public String getSamples() {
SampleDataSource dataSource = new SampleDataSource(mDBHelper);
List<Sample> samples = dataSource.getAll();
StringBuffer buffer = new StringBuffer();
buffer.append("{'points':[");
for (int i = 0; i < samples.size(); i++) {
Sample sample = samples.get(i);
buffer.append("{'x':'").append(sample.getX()).append("', ");
buffer.append("'y':'").append(sample.getY()).append("'}");
if (i != samples.size() - 1) {
buffer.append(", ");
}
}
buffer.append("]}'");
JSONObject mapPoints = null;
try {
mapPoints = new JSONObject(buffer.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return mapPoints.toString();
}
@JavascriptInterface
public String getCurrentLocation() {
JSONObject mapPoints = null;
try {
double la = mLocation.getLatitude();
double lng = mLocation.getLongitude();
mapPoints = new JSONObject("{'points':[{'x':'" + lng + "', 'y':'" + la + "'}]}'");
} catch (JSONException e) {
e.printStackTrace();
}
return mapPoints.toString();
}
@JavascriptInterface
public String getPositionHistory() {
LocationDataSource dataSource = new LocationDataSource(mDBHelper);
List<edu.cmu.sv.trailscribe.model.Location> locations = dataSource.getAll();
StringBuffer buffer = new StringBuffer();
buffer.append("{'points':[");
for (int i = 0; i < locations.size(); i++) {
edu.cmu.sv.trailscribe.model.Location locationHistory = locations.get(i);
buffer.append("{'x':'").append(locationHistory.getX()).append("',");
buffer.append("'y':'").append(locationHistory.getY()).append("'}");
if (i != locations.size() - 1) {
buffer.append(", ");
}
}
buffer.append("]}'");
JSONObject mapPoints = null;
try {
mapPoints = new JSONObject(buffer.toString());
} catch (JSONException e) {
e.printStackTrace();
}
return mapPoints.toString();
}
@Override
public void onClick(View v) {
MessageToWebview message = MessageToWebview.Default;
switch (v.getId()) {
case R.id.maps_samples:
// Hide samples if they are currently displayed
if (mIsDisplaySamples) {
message = MessageToWebview.HideSamples;
mSamplesButton.setBackgroundResource(R.drawable.button_samples);
} else {
message = MessageToWebview.DisplaySamples;
mSamplesButton.setBackgroundResource(R.drawable.button_samples_toggle);
}
mIsDisplaySamples = !mIsDisplaySamples;
break;
case R.id.maps_current_location:
// Hide current location if it is currently displayed
if (mIsDisplayCurrentLocation) {
message = MessageToWebview.HideCurrentLocation;
mCurrentLocationButton.setBackgroundResource(R.drawable.button_current_location);
} else {
message = MessageToWebview.DisplayCurrentLocation;
mCurrentLocationButton.setBackgroundResource(R.drawable.button_current_location_toggle);
}
mIsDisplayCurrentLocation = !mIsDisplayCurrentLocation;
break;
case R.id.maps_position_history:
// Hide location history if it is currently displayed
if (mIsDisplayPositionHistory) {
message = MessageToWebview.HidePositionHistory;
mPositionHistoryButton.setBackgroundResource(R.drawable.button_position_history);
} else {
message = MessageToWebview.DisplayPositionHistory;
mPositionHistoryButton.setBackgroundResource(R.drawable.button_position_history_toggle);
}
mIsDisplayPositionHistory = !mIsDisplayPositionHistory;
break;
case R.id.maps_kml:
if (mIsDisplayKML) {
message = MessageToWebview.HideKML;
mKmlButton.setBackgroundResource(R.drawable.button_kml);
} else {
message = MessageToWebview.DisplayKML;
mKmlButton.setBackgroundResource(R.drawable.button_kml_toggle);
}
mIsDisplayKML = !mIsDisplayKML;
break;
default:
Toast.makeText(getApplicationContext(),
"Sorry, the feature is not implemented yet!", Toast.LENGTH_SHORT).show();
return;
}
setLayers(message);
}
@Override
public void onLocationChanged(Location location) {
mLocation = location;
// TODO: Verify if map layer changes whenever the location has changed
Toast.makeText(getApplicationContext(),
"onLocationChanged: (" + mLocation.getLatitude() + "," + mLocation.getLongitude() + ")", Toast.LENGTH_SHORT).show();
String state = mSamplesButton.getText().toString();
boolean shouldisplay = (state.equals(getResources().getString(R.string.map_hide_current_location)));
if (shouldisplay) {
setLayers(MessageToWebview.DisplayCurrentLocation);
}
super.onLocationChanged(location);
}
private enum MessageToWebview {
Default("default"),
DisplaySamples("DisplaySamples"),
HideSamples("HideSamples"),
DisplayCurrentLocation("DisplayCurrentLocation"),
HideCurrentLocation("HideCurrentLocation"),
DisplayPositionHistory("DisplayPositionHistory"),
HidePositionHistory("HidePositionHistory"),
DisplayKML("DisplayKML"),
HideKML("HideKML");
private final String message;
MessageToWebview(String message) {
this.message = message;
}
public String getMessage() {
return this.message;
}
}
} |
package edu.wustl.catissuecore.bizlogic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.Vector;
import edu.wustl.catissuecore.domain.CancerResearchGroup;
import edu.wustl.catissuecore.domain.Department;
import edu.wustl.catissuecore.domain.Institution;
import edu.wustl.catissuecore.domain.Password;
import edu.wustl.catissuecore.domain.User;
import edu.wustl.catissuecore.util.ApiSearchUtil;
import edu.wustl.catissuecore.util.EmailHandler;
import edu.wustl.catissuecore.util.Roles;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.common.actionForm.IValueObject;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SecurityDataBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.bizlogic.DefaultBizLogic;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.dao.AbstractDAO;
import edu.wustl.common.dao.DAO;
import edu.wustl.common.dao.DAOFactory;
import edu.wustl.common.domain.AbstractDomainObject;
import edu.wustl.common.exception.BizLogicException;
import edu.wustl.common.exceptionformatter.DefaultExceptionFormatter;
import edu.wustl.common.security.SecurityManager;
import edu.wustl.common.security.exceptions.PasswordEncryptionException;
import edu.wustl.common.security.exceptions.SMException;
import edu.wustl.common.security.exceptions.UserNotAuthorizedException;
import edu.wustl.common.util.XMLPropertyHandler;
import edu.wustl.common.util.dbManager.DAOException;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.common.util.global.PasswordManager;
import edu.wustl.common.util.global.Validator;
import edu.wustl.common.util.logger.Logger;
import gov.nih.nci.security.authorization.domainobjects.Role;
/**
* UserBizLogic is used to add user information into the database using Hibernate.
* @author kapil_kaveeshwar
*/
public class UserBizLogic extends DefaultBizLogic
{
public static final int FAIL_SAME_AS_LAST_N = 8;
public static final int FAIL_FIRST_LOGIN = 9;
public static final int FAIL_EXPIRE = 10;
public static final int FAIL_CHANGED_WITHIN_SOME_DAY = 11;
public static final int FAIL_SAME_NAME_SURNAME_EMAIL = 12;
public static final int FAIL_PASSWORD_EXPIRED = 13;
public static final int SUCCESS = 0;
/**
* Saves the user object in the database.
* @param obj The user object to be saved.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void insert(Object obj, DAO dao, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
User user = (User) obj;
gov.nih.nci.security.authorization.domainobjects.User csmUser = new gov.nih.nci.security.authorization.domainobjects.User();
try
{
List list = dao.retrieve(Department.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getDepartment().getId());
Department department = null;
if (list.size() != 0)
{
department = (Department) list.get(0);
}
list = dao.retrieve(Institution.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getInstitution().getId());
Institution institution = null;
if (list.size() != 0)
{
institution = (Institution) list.get(0);
}
list = dao.retrieve(CancerResearchGroup.class.getName(), Constants.SYSTEM_IDENTIFIER, user.getCancerResearchGroup().getId());
CancerResearchGroup cancerResearchGroup = null;
if (list.size() != 0)
{
cancerResearchGroup = (CancerResearchGroup) list.get(0);
}
user.setDepartment(department);
user.setInstitution(institution);
user.setCancerResearchGroup(cancerResearchGroup);
String generatedPassword = PasswordManager.generatePassword();
// If the page is of signup user don't create the csm user.
if (user.getPageOf().equals(Constants.PAGEOF_SIGNUP) == false)
{
csmUser.setLoginName(user.getLoginName());
csmUser.setLastName(user.getLastName());
csmUser.setFirstName(user.getFirstName());
csmUser.setEmailId(user.getEmailAddress());
csmUser.setStartDate(user.getStartDate());
csmUser.setPassword(generatedPassword);
SecurityManager.getInstance(UserBizLogic.class).createUser(csmUser);
if (user.getRoleId() != null)
{
SecurityManager.getInstance(UserBizLogic.class).assignRoleToUser(csmUser.getUserId().toString(), user.getRoleId());
}
user.setCsmUserId(csmUser.getUserId());
// user.setPassword(csmUser.getPassword());
//Add password of user in password table.Updated by Supriya Dankh
Password password = new Password();
ApiSearchUtil.setPasswordDefault(password);
//End:- Change for API Search
password.setUser(user);
password.setPassword(PasswordManager.encrypt(generatedPassword));
password.setUpdateDate(new Date());
user.getPasswordCollection().add(password);
Logger.out.debug("password stored in passwore table");
// user.setPassword(csmUser.getPassword());
}
/**
* First time login is always set to true when a new user is created
*/
user.setFirstTimeLogin(new Boolean(true));
// Create address and the user in catissue tables.
dao.insert(user.getAddress(), sessionDataBean, true, false);
dao.insert(user, sessionDataBean, true, false);
Set protectionObjects = new HashSet();
protectionObjects.add(user);
EmailHandler emailHandler = new EmailHandler();
// Send the user registration email to user and the administrator.
if (Constants.PAGEOF_SIGNUP.equals(user.getPageOf()))
{
//SecurityManager.getInstance(this.getClass()).insertAuthorizationData(null, protectionObjects, null);
emailHandler.sendUserSignUpEmail(user);
}
else
// Send the user creation email to user and the administrator.
{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(getAuthorizationData(user), protectionObjects, null);
emailHandler.sendApprovalEmail(user);
}
}
catch (DAOException daoExp)
{
Logger.out.debug(daoExp.getMessage(), daoExp);
deleteCSMUser(csmUser);
throw daoExp;
}
catch (SMException e)
{
// added to format constrainviolation message
deleteCSMUser(csmUser);
throw handleSMException(e);
}
catch (PasswordEncryptionException e)
{
Logger.out.debug(e.getMessage(), e);
deleteCSMUser(csmUser);
throw new DAOException(e.getMessage(), e);
}
}
/**
* Deletes the csm user from the csm user table.
* @param csmUser The csm user to be deleted.
* @throws DAOException
*/
private void deleteCSMUser(gov.nih.nci.security.authorization.domainobjects.User csmUser) throws DAOException
{
try
{
if (csmUser.getUserId() != null)
{
SecurityManager.getInstance(ApproveUserBizLogic.class).removeUser(csmUser.getUserId().toString());
}
}
catch (SMException smExp)
{
throw handleSMException(smExp);
}
}
/**
* This method returns collection of UserGroupRoleProtectionGroup objects that speciefies the
* user group protection group linkage through a role. It also specifies the groups the protection
* elements returned by this class should be added to.
* @return
*/
private Vector getAuthorizationData(AbstractDomainObject obj) throws SMException
{
Logger.out.debug("
Vector authorizationData = new Vector();
Set group = new HashSet();
User aUser = (User) obj;
String userId = String.valueOf(aUser.getCsmUserId());
gov.nih.nci.security.authorization.domainobjects.User user = SecurityManager.getInstance(this.getClass()).getUserById(userId);
Logger.out.debug(" User: " + user.getLoginName());
group.add(user);
// Protection group of User
String protectionGroupName = Constants.getUserPGName(aUser.getId());
SecurityDataBean userGroupRoleProtectionGroupBean = new SecurityDataBean();
userGroupRoleProtectionGroupBean.setUser(userId);
userGroupRoleProtectionGroupBean.setRoleName(Roles.UPDATE_ONLY);
userGroupRoleProtectionGroupBean.setGroupName(Constants.getUserGroupName(aUser.getId()));
userGroupRoleProtectionGroupBean.setProtectionGroupName(protectionGroupName);
userGroupRoleProtectionGroupBean.setGroup(group);
authorizationData.add(userGroupRoleProtectionGroupBean);
Logger.out.debug(authorizationData.toString());
return authorizationData;
}
/**
* Updates the persistent object in the database.
* @param obj The object to be updated.
* @param session The session in which the object is saved.
* @throws DAOException
*/
protected void update(DAO dao, Object obj, Object oldObj, SessionDataBean sessionDataBean) throws DAOException, UserNotAuthorizedException
{
User user = (User) obj;
User oldUser = (User) oldObj;
boolean isLoginUserUpdate = false;
if(sessionDataBean.getUserName().equals(oldUser.getLoginName()))
{
isLoginUserUpdate = true;
}
//If the user is rejected, its record cannot be updated.
if (Constants.ACTIVITY_STATUS_REJECT.equals(oldUser.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("errors.editRejectedUser"));
}
else if (Constants.ACTIVITY_STATUS_NEW.equals(oldUser.getActivityStatus())
|| Constants.ACTIVITY_STATUS_PENDING.equals(oldUser.getActivityStatus()))
{
//If the user is not approved yet, its record cannot be updated.
throw new DAOException(ApplicationProperties.getValue("errors.editNewPendingUser"));
}
try
{
// Get the csm userId if present.
String csmUserId = null;
/**
* Santosh: Changes done for Api
* User should not edit the first time login field.
*/
if (user.getFirstTimeLogin() == null)
{
throw new DAOException(ApplicationProperties.getValue("domain.object.null.err.msg","First Time Login"));
}
if(oldUser.getFirstTimeLogin() != null && user.getFirstTimeLogin().booleanValue() != oldUser.getFirstTimeLogin().booleanValue())
{
throw new DAOException(ApplicationProperties.getValue("errors.cannotedit.firsttimelogin"));
}
if (user.getCsmUserId() != null)
{
csmUserId = user.getCsmUserId().toString();
}
gov.nih.nci.security.authorization.domainobjects.User csmUser = SecurityManager.getInstance(UserBizLogic.class).getUserById(csmUserId);
String oldPassword = user.getOldPassword();
// If the page is of change password,
// update the password of the user in csm and catissue tables.
if (user.getPageOf().equals(Constants.PAGEOF_CHANGE_PASSWORD))
{
if (!oldPassword.equals(csmUser.getPassword()))
{
throw new DAOException(ApplicationProperties.getValue("errors.oldPassword.wrong"));
}
//Added for Password validation by Supriya Dankh.
Validator validator = new Validator();
if (!validator.isEmpty(user.getNewPassword()) && !validator.isEmpty(oldPassword))
{
int result = validatePassword(oldUser, user.getNewPassword(), oldPassword);
Logger.out.debug("return from Password validate " + result);
//if validatePassword method returns value greater than zero then validation fails
if (result != SUCCESS)
{
// get error message of validation failure
String errorMessage = getPasswordErrorMsg(result);
Logger.out.debug("Error Message from method" + errorMessage);
throw new DAOException(errorMessage);
}
}
csmUser.setPassword(user.getNewPassword());
// Set values in password domain object and adds changed password in Password Collection
Password password = new Password(PasswordManager.encrypt(user.getNewPassword()), user);
user.getPasswordCollection().add(password);
}
//Bug-1516: Jitendra Administartor should be able to edit the password
else if(user.getPageOf().equals(Constants.PAGEOF_USER_ADMIN) && !user.getNewPassword().equals(csmUser.getPassword()))
{
Validator validator = new Validator();
if (!validator.isEmpty(user.getNewPassword()))
{
int result = validatePassword(oldUser, user.getNewPassword(), oldPassword);
Logger.out.debug("return from Password validate " + result);
//if validatePassword method returns value greater than zero then validation fails
if (result != SUCCESS)
{
// get error message of validation failure
String errorMessage = getPasswordErrorMsg(result);
Logger.out.debug("Error Message from method" + errorMessage);
throw new DAOException(errorMessage);
}
}
csmUser.setPassword(user.getNewPassword());
// Set values in password domain object and adds changed password in Password Collection
Password password = new Password(PasswordManager.encrypt(user.getNewPassword()), user);
user.getPasswordCollection().add(password);
user.setFirstTimeLogin(new Boolean(true));
}
else
{
csmUser.setLoginName(user.getLoginName());
csmUser.setLastName(user.getLastName());
csmUser.setFirstName(user.getFirstName());
csmUser.setEmailId(user.getEmailAddress());
// Assign Role only if the page is of Administrative user edit.
if ((Constants.PAGEOF_USER_PROFILE.equals(user.getPageOf()) == false)
&& (Constants.PAGEOF_CHANGE_PASSWORD.equals(user.getPageOf()) == false))
{
SecurityManager.getInstance(UserBizLogic.class).assignRoleToUser(csmUser.getUserId().toString(), user.getRoleId());
}
dao.update(user.getAddress(), sessionDataBean, true, false, false);
// Audit of user address.
dao.audit(user.getAddress(), oldUser.getAddress(), sessionDataBean, true);
}
if (user.getPageOf().equals(Constants.PAGEOF_CHANGE_PASSWORD))
{
user.setFirstTimeLogin(new Boolean(false));
}
dao.update(user, sessionDataBean, true, true, true);
//Modify the csm user.
SecurityManager.getInstance(UserBizLogic.class).modifyUser(csmUser);
if(isLoginUserUpdate)
{
sessionDataBean.setUserName(csmUser.getLoginName());
}
//Audit of user.
dao.audit(obj, oldObj, sessionDataBean, true);
/* pratha commented for bug# 7304
if (Constants.ACTIVITY_STATUS_ACTIVE.equals(user.getActivityStatus()))
{
Set protectionObjects = new HashSet();
protectionObjects.add(user);
try{
SecurityManager.getInstance(this.getClass()).insertAuthorizationData(getAuthorizationData(user), protectionObjects, null);
}
catch (SMException e)
{
//digest exception
}
} */
}
catch (SMException e)
{
throw handleSMException(e);
}
catch (PasswordEncryptionException e)
{
throw new DAOException(e.getMessage(), e);
}
}
/**
* Returns the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @return the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @throws DAOException
*/
public Vector getUsers(String operation) throws DAOException
{
String sourceObjectName = User.class.getName();
//Get only the fields required
String[] selectColumnName = {Constants.SYSTEM_IDENTIFIER,Constants.LASTNAME,Constants.FIRSTNAME};
String[] whereColumnName;
String[] whereColumnCondition;
Object[] whereColumnValue;
String joinCondition;
if (operation != null && operation.equalsIgnoreCase(Constants.ADD))
{
String tmpArray1[] = {Constants.ACTIVITY_STATUS};
String tmpArray2[] = {Constants.EQUALS};
String tmpArray3[] = {Constants.ACTIVITY_STATUS_ACTIVE};
whereColumnName = tmpArray1;
whereColumnCondition = tmpArray2;
whereColumnValue = tmpArray3;
joinCondition = null;
}
else
{
String tmpArray1[] = {Constants.ACTIVITY_STATUS, Constants.ACTIVITY_STATUS};
String tmpArray2[] = {Constants.EQUALS,Constants.EQUALS};
String tmpArray3[] = {Constants.ACTIVITY_STATUS_ACTIVE, Constants.ACTIVITY_STATUS_CLOSED};
whereColumnName = tmpArray1;
whereColumnCondition = tmpArray2;
whereColumnValue = tmpArray3;
joinCondition = Constants.OR_JOIN_CONDITION;
}
//Retrieve the users whose activity status is not disabled.
List users = retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
Vector nameValuePairs = new Vector();
nameValuePairs.add(new NameValueBean(Constants.SELECT_OPTION, String.valueOf(Constants.SELECT_OPTION_VALUE)));
// If the list of users retrieved is not empty.
if (users.isEmpty() == false)
{
// Creating name value beans.
for (int i = 0; i < users.size(); i++)
{
//Changes made to optimize the query to get only required fields data
Object[] userData = (Object[])users.get(i);
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(userData[1]+", "+userData[2]);
nameValueBean.setValue(userData[0]);
nameValuePairs.add(nameValueBean);
}
}
Collections.sort(nameValuePairs);
return nameValuePairs;
}
/**
* Returns the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @return the list of NameValueBeans with name as "LastName,Firstname"
* and value as systemtIdentifier, of all users who are not disabled.
* @throws DAOException
*/
public Vector getCSMUsers() throws DAOException, SMException
{
//Retrieve the users whose activity status is not disabled.
List users = SecurityManager.getInstance(UserBizLogic.class).getUsers();
Vector nameValuePairs = new Vector();
nameValuePairs.add(new NameValueBean(Constants.SELECT_OPTION, String.valueOf(Constants.SELECT_OPTION_VALUE)));
// If the list of users retrieved is not empty.
if (users.isEmpty() == false)
{
// Creating name value beans.
for (int i = 0; i < users.size(); i++)
{
gov.nih.nci.security.authorization.domainobjects.User user = (gov.nih.nci.security.authorization.domainobjects.User) users.get(i);
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(user.getLastName() + ", " + user.getFirstName());
nameValueBean.setValue(String.valueOf(user.getUserId()));
Logger.out.debug(nameValueBean.toString());
nameValuePairs.add(nameValueBean);
}
}
Collections.sort(nameValuePairs);
return nameValuePairs;
}
/**
* Returns a list of users according to the column name and value.
* @param colName column name on the basis of which the user list is to be retrieved.
* @param colValue Value for the column name.
* @throws DAOException
*/
public List retrieve(String className, String colName, Object colValue) throws DAOException
{
List userList = null;
Logger.out.debug("In user biz logic retrieve........................");
try
{
// Get the caTISSUE user.
userList = super.retrieve(className, colName, colValue);
User appUser = null;
if (userList!=null && !userList.isEmpty())
{
appUser = (User) userList.get(0);
if (appUser.getCsmUserId() != null)
{
//Get the role of the user.
Role role = SecurityManager.getInstance(UserBizLogic.class).getUserRole(appUser.getCsmUserId().longValue());
//Logger.out.debug("In USer biz logic.............role........id......." + role.getId().toString());
if (role != null)
{
appUser.setRoleId(role.getId().toString());
}
}
}
}
catch (SMException e)
{
throw handleSMException(e);
}
return userList;
}
/**
* Retrieves and sends the login details email to the user whose email address is passed
* else returns the error key in case of an error.
* @param emailAddress the email address of the user whose password is to be sent.
* @return the error key in case of an error.
* @throws DAOException
* @throws DAOException
* @throws UserNotAuthorizedException
* @throws UserNotAuthorizedException
*/
public String sendForgotPassword(String emailAddress,SessionDataBean sessionData) throws DAOException, UserNotAuthorizedException
{
String statusMessageKey = null;
List list = retrieve(User.class.getName(), "emailAddress", emailAddress);
if (list!=null && !list.isEmpty())
{
User user = (User) list.get(0);
if (user.getActivityStatus().equals(Constants.ACTIVITY_STATUS_ACTIVE))
{
EmailHandler emailHandler = new EmailHandler();
//Send the login details email to the user.
boolean emailStatus = false;
try
{
emailStatus = emailHandler.sendLoginDetailsEmail(user, null);
}
catch (DAOException e)
{
e.printStackTrace();
}
if (emailStatus)
{
// if success commit
/**
* Update the field FirstTimeLogin which will ensure user changes his password on login
* Note --> We can not use CommonAddEditAction to update as the user has not still logged in
* and user authorisation will fail. So writing saperate code for update.
*/
user.setFirstTimeLogin(new Boolean(true));
AbstractDAO dao = DAOFactory.getInstance().getDAO(Constants.HIBERNATE_DAO);
dao.openSession(sessionData);
dao.update(user, sessionData, true, true, true);
dao.commit();
dao.closeSession();
statusMessageKey = "password.send.success";
}
else
{
statusMessageKey = "password.send.failure";
}
}
else
{
//Error key if the user is not active.
statusMessageKey = "errors.forgotpassword.user.notApproved";
}
}
else
{
// Error key if the user is not present.
statusMessageKey = "errors.forgotpassword.user.unknown";
}
return statusMessageKey;
}
/**
* Overriding the parent class's method to validate the enumerated attribute values
*/
protected boolean validate(Object obj, DAO dao, String operation) throws DAOException
{
User user = (User) obj;
ApiSearchUtil.setUserDefault(user);
//End:- Change for API Search
//Added by Ashish Gupta
/*
if (user == null)
throw new DAOException("domain.object.null.err.msg", new String[]{"User"});
*/
//END
if (Constants.PAGEOF_CHANGE_PASSWORD.equals(user.getPageOf()) == false)
{
if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_STATE_LIST, null), user
.getAddress().getState()))
{
throw new DAOException(ApplicationProperties.getValue("state.errMsg"));
}
if (!Validator.isEnumeratedValue(CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_COUNTRY_LIST, null), user
.getAddress().getCountry()))
{
throw new DAOException(ApplicationProperties.getValue("country.errMsg"));
}
if (Constants.PAGEOF_USER_ADMIN.equals(user.getPageOf()))
{
try
{
if (!Validator.isEnumeratedValue(getRoles(), user.getRoleId()))
{
throw new DAOException(ApplicationProperties.getValue("user.role.errMsg"));
}
}
catch (SMException e)
{
throw handleSMException(e);
}
if (operation.equals(Constants.ADD))
{
if (!Constants.ACTIVITY_STATUS_ACTIVE.equals(user.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.active.errMsg"));
}
}
else
{
if (!Validator.isEnumeratedValue(Constants.USER_ACTIVITY_STATUS_VALUES, user.getActivityStatus()))
{
throw new DAOException(ApplicationProperties.getValue("activityStatus.errMsg"));
}
}
}
//Added by Ashish
/**
* Two more parameter 'dao' and 'operation' is added by Vijay Pande to use it in isUniqueEmailAddress method
*/
apiValidate(user, dao,operation);
//END
}
return true;
}
//Added by Ashish
/**
* @param user user
* @param dao
* @param operation
* @return
* @throws DAOException
*/
private boolean apiValidate(User user, DAO dao, String operation)
throws DAOException
{
Validator validator = new Validator();
String message = "";
boolean validate = true;
if (validator.isEmpty(user.getEmailAddress()))
{
message = ApplicationProperties.getValue("user.emailAddress");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
else
{
if (!validator.isValidEmailAddress(user.getEmailAddress()))
{
message = ApplicationProperties.getValue("user.emailAddress");
throw new DAOException(ApplicationProperties.getValue("errors.item.format",message));
}
/**
* Name : Vijay_Pande
* Reviewer : Sntosh_Chandak
* Bug ID: 4185_2
* Patch ID: 1-2
* See also: 1
* Description: Wrong error meassage was dispayed while adding user with existing email address in use.
* Following method is provided to verify whether the email address is already present in the system or not.
*/
if(operation.equals(Constants.ADD) && !(isUniqueEmailAddress(user.getEmailAddress(),dao)))
{
String arguments[] = null;
arguments = new String[]{"User", ApplicationProperties.getValue("user.emailAddress")};
String errMsg = new DefaultExceptionFormatter().getErrorMessage("Err.ConstraintViolation", arguments);
Logger.out.debug("Unique Constraint Violated: " + errMsg);
throw new DAOException(errMsg);
}
/** -- patch ends here -- */
}
if (validator.isEmpty(user.getLastName()))
{
message = ApplicationProperties.getValue("user.lastName");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (validator.isEmpty(user.getFirstName()))
{
message = ApplicationProperties.getValue("user.firstName");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (validator.isEmpty(user.getAddress().getCity()))
{
message = ApplicationProperties.getValue("user.city");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (!validator.isValidOption(user.getAddress().getState()) || validator.isEmpty(user.getAddress().getState()))
{
message = ApplicationProperties.getValue("user.state");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (validator.isEmpty(user.getAddress().getZipCode()))
{
message = ApplicationProperties.getValue("user.zipCode");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
else
{
if (!validator.isValidZipCode(user.getAddress().getZipCode()))
{
message = ApplicationProperties.getValue("user.zipCode");
throw new DAOException(ApplicationProperties.getValue("errors.item.format",message));
}
}
if (!validator.isValidOption(user.getAddress().getCountry()) || validator.isEmpty(user.getAddress().getCountry()))
{
message = ApplicationProperties.getValue("user.country");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (validator.isEmpty(user.getAddress().getPhoneNumber()))
{
message = ApplicationProperties.getValue("user.phoneNumber");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (user.getInstitution().getId()==null || user.getInstitution().getId().longValue()<=0)
{
message = ApplicationProperties.getValue("user.institution");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (user.getDepartment().getId()==null || user.getDepartment().getId().longValue()<=0)
{
message = ApplicationProperties.getValue("user.department");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (user.getCancerResearchGroup().getId()==null || user.getCancerResearchGroup().getId().longValue()<=0)
{
message = ApplicationProperties.getValue("user.cancerResearchGroup");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
if (user.getRoleId() != null)
{
if (!validator.isValidOption(user.getRoleId()) || validator.isEmpty(String.valueOf(user.getRoleId())))
{
message = ApplicationProperties.getValue("user.role");
throw new DAOException(ApplicationProperties.getValue("errors.item.required",message));
}
}
return validate;
}
//END
/**
* Returns a list of all roles that can be assigned to a user.
* @return a list of all roles that can be assigned to a user.
* @throws SMException
*/
private List getRoles() throws SMException
{
//Sets the roleList attribute to be used in the Add/Edit User Page.
Vector roleList = SecurityManager.getInstance(UserBizLogic.class).getRoles();
List roleNameValueBeanList = new ArrayList();
NameValueBean nameValueBean = new NameValueBean();
nameValueBean.setName(Constants.SELECT_OPTION);
nameValueBean.setValue("-1");
roleNameValueBeanList.add(nameValueBean);
ListIterator iterator = roleList.listIterator();
while (iterator.hasNext())
{
Role role = (Role) iterator.next();
nameValueBean = new NameValueBean();
nameValueBean.setName(role.getName());
nameValueBean.setValue(String.valueOf(role.getId()));
roleNameValueBeanList.add(nameValueBean);
}
return roleNameValueBeanList;
}
/**
* @param oldUser User object
* @param newPassword New Password value
* @param validator VAlidator object
* @param oldPassword Old Password value
* @return SUCCESS (constant int 0) if all condition passed
* else return respective error code (constant int) value
* @throws PasswordEncryptionException
*/
private int validatePassword(User oldUser, String newPassword, String oldPassword) throws PasswordEncryptionException
{
List oldPwdList = new ArrayList(oldUser.getPasswordCollection());
Collections.sort(oldPwdList);
if (oldPwdList != null && !oldPwdList.isEmpty())
{
//Check new password is equal to last n password if value
String encryptedPassword = PasswordManager.encrypt(newPassword);
if (checkPwdNotSameAsLastN(newPassword, oldPwdList))
{
Logger.out.debug("Password is not valid returning FAIL_SAME_AS_LAST_N");
return FAIL_SAME_AS_LAST_N;
}
//Get the last updated date of the password
Date lastestUpdateDate = ((Password) oldPwdList.get(0)).getUpdateDate();
boolean firstTimeLogin = false;
if(oldUser.getFirstTimeLogin() != null)
{
firstTimeLogin = oldUser.getFirstTimeLogin().booleanValue();
}
if (!firstTimeLogin)
{
if (checkPwdUpdatedOnSameDay(lastestUpdateDate))
{
Logger.out.debug("Password is not valid returning FAIL_CHANGED_WITHIN_SOME_DAY");
return FAIL_CHANGED_WITHIN_SOME_DAY;
}
}
/**
* to check password does not contain user name,surname,email address. if same return FAIL_SAME_NAME_SURNAME_EMAIL
* eg. username=XabcY@abc.com newpassword=abc is not valid
*/
String emailAddress = oldUser.getEmailAddress();
int usernameBeforeMailaddress = emailAddress.indexOf('@');
// get substring of emailAddress before '@' character
emailAddress = emailAddress.substring(0, usernameBeforeMailaddress);
String userFirstName = oldUser.getFirstName();
String userLastName = oldUser.getLastName();
StringBuffer sb = new StringBuffer(newPassword);
if (emailAddress != null && newPassword.toLowerCase().indexOf(emailAddress.toLowerCase())!=-1)
{
Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL");
return FAIL_SAME_NAME_SURNAME_EMAIL;
}
if (userFirstName != null && newPassword.toLowerCase().indexOf(userFirstName.toLowerCase())!=-1)
{
Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL");
return FAIL_SAME_NAME_SURNAME_EMAIL;
}
if (userLastName != null && newPassword.toLowerCase().indexOf(userLastName.toLowerCase())!=-1)
{
Logger.out.debug("Password is not valid returning FAIL_SAME_NAME_SURNAME_EMAIL");
return FAIL_SAME_NAME_SURNAME_EMAIL;
}
}
return SUCCESS;
}
/**
* This function checks whether user has logged in for first time or whether user's password is expired.
* In both these case user needs to change his password so Error key is returned
* @param user - user object
* @throws DAOException - throws DAOException
*/
public String checkFirstLoginAndExpiry(User user)
{
List passwordList = new ArrayList(user.getPasswordCollection());
boolean firstTimeLogin = false;
if(user.getFirstTimeLogin() != null)
{
firstTimeLogin = user.getFirstTimeLogin().booleanValue();
}
// If user has logged in for the first time, return key of Change password on first login
if (firstTimeLogin)
{
return "errors.changePassword.changeFirstLogin";
}
Collections.sort(passwordList);
Password lastPassword = (Password)passwordList.get(0);
Date lastUpdateDate = lastPassword.getUpdateDate();
Validator validator = new Validator();
//Get difference in days between last password update date and current date.
long dayDiff = validator.getDateDiff(lastUpdateDate, new Date());
int expireDaysCount = Integer.parseInt(XMLPropertyHandler.getValue("password.expire_after_n_days"));
if (dayDiff > expireDaysCount)
{
return "errors.changePassword.expire";
}
return Constants.SUCCESS;
}
private boolean checkPwdNotSameAsLastN(String newPassword, List oldPwdList)
{
int noOfPwdNotSameAsLastN = 0;
String pwdNotSameAsLastN = XMLPropertyHandler.getValue("password.not_same_as_last_n");
if (pwdNotSameAsLastN != null && !pwdNotSameAsLastN.equals(""))
{
noOfPwdNotSameAsLastN = Integer.parseInt(pwdNotSameAsLastN);
noOfPwdNotSameAsLastN = Math.max(0, noOfPwdNotSameAsLastN);
}
boolean isSameFound = false;
int loopCount = Math.min(oldPwdList.size(), noOfPwdNotSameAsLastN);
for (int i = 0; i < loopCount; i++)
{
Password pasword = (Password) oldPwdList.get(i);
if (newPassword.equals(pasword.getPassword()))
{
isSameFound = true;
break;
}
}
return isSameFound;
}
private boolean checkPwdUpdatedOnSameDay(Date lastUpdateDate)
{
Validator validator = new Validator();
//Get difference in days between last password update date and current date.
long dayDiff = validator.getDateDiff(lastUpdateDate, new Date());
int dayDiffConstant = Integer.parseInt(XMLPropertyHandler.getValue("daysCount"));
if (dayDiff <= dayDiffConstant)
{
Logger.out.debug("Password is not valid returning FAIL_CHANGED_WITHIN_SOME_DAY");
return true;
}
return false;
}
/**
* @param errorCode int value return by validatePassword() method
* @return String error message with respect to error code
*/
private String getPasswordErrorMsg(int errorCode)
{
String errMsg = "";
switch (errorCode)
{
case FAIL_SAME_AS_LAST_N :
List parameters = new ArrayList();
String dayCount = "" + Integer.parseInt(XMLPropertyHandler.getValue("password.not_same_as_last_n"));
parameters.add(dayCount);
errMsg = ApplicationProperties.getValue("errors.newPassword.sameAsLastn",parameters);
break;
case FAIL_FIRST_LOGIN :
errMsg = ApplicationProperties.getValue("errors.changePassword.changeFirstLogin");
break;
case FAIL_EXPIRE :
errMsg = ApplicationProperties.getValue("errors.changePassword.expire");
break;
case FAIL_CHANGED_WITHIN_SOME_DAY :
errMsg = ApplicationProperties.getValue("errors.changePassword.afterSomeDays");
break;
case FAIL_SAME_NAME_SURNAME_EMAIL :
errMsg = ApplicationProperties.getValue("errors.changePassword.sameAsNameSurnameEmail");
break;
case FAIL_PASSWORD_EXPIRED :
errMsg = ApplicationProperties.getValue("errors.changePassword.expire");
default :
errMsg = PasswordManager.getErrorMessage(errorCode);
break;
}
return errMsg;
}
/**
* Name : Vijay_Pande
* Reviewer : Sntosh_Chandak
* Bug ID: 4185_2
* Patch ID: 1-2
* See also: 1
* Description: Wrong error meassage was dispayed while adding user with existing email address in use.
* Following method is provided to verify whether the email address is already present in the system or not.
*/
/**
* Method to check whether email address already exist or not
* @param emailAddress email address to be check
* @param dao an object of DAO
* @return isUnique boolean value to indicate presence of similar email address
* @throws DAOException database exception
*/
private boolean isUniqueEmailAddress(String emailAddress, DAO dao) throws DAOException
{
boolean isUnique=true;
String sourceObjectName=User.class.getName();
String[] selectColumnName=new String[] {"id"};
String[] whereColumnName = new String[]{"emailAddress"};
String[] whereColumnCondition = new String[]{"="};
Object[] whereColumnValue = new String[]{emailAddress};
String joinCondition = null;
List userList = dao.retrieve(sourceObjectName, selectColumnName, whereColumnName, whereColumnCondition, whereColumnValue, joinCondition);
if (userList.size() > 0)
{
isUnique=false;
}
return isUnique;
}
/**
* Set Role to user object before populating actionForm out of it
* @param domainObj object of AbstractDomainObject
* @param uiForm object of the class which implements IValueObject
* @throws BizLogicException
*/
protected void prePopulateUIBean(AbstractDomainObject domainObj, IValueObject uiForm) throws BizLogicException
{
Logger.out.info("Inside prePopulateUIBean method of UserBizLogic...");
User user = (User)domainObj;
Role role=null;
if (user.getCsmUserId() != null)
{
try
{
//Get the role of the user.
role = SecurityManager.getInstance(UserBizLogic.class).getUserRole(user.getCsmUserId().longValue());
if (role != null)
{
user.setRoleId(role.getId().toString());
}
// Logger.out.debug("In USer biz logic.............role........id......." + role.getId().toString());
}
catch (SMException e)
{
Logger.out.error("SMException in prePopulateUIBean method of UserBizLogic..."+e);
//throw new BizLogicException(e.getMessage());
}
}
}
// //method to return a comma seperated list of emails of administrators of a particular institute
// private String getInstitutionAdmins(Long instID) throws DAOException,SMException
// String retStr="";
// String[] userEmail;
// Long[] csmAdminIDs = SecurityManager.getInstance(UserBizLogic.class).getAllAdministrators() ;
// if (csmAdminIDs != null )
// for(int cnt=0;cnt<csmAdminIDs.length ;cnt++ )
// String sourceObjectName = User.class.getName();
// String[] selectColumnName = null;
// String[] whereColumnName = {"institution","csmUserId"};
// String[] whereColumnCondition = {"=","="};
// Object[] whereColumnValue = {instID, csmAdminIDs[cnt] };
// String joinCondition = Constants.AND_JOIN_CONDITION;
// //Retrieve the users for given institution and who are administrators.
// List users = retrieve(sourceObjectName, selectColumnName, whereColumnName,
// whereColumnCondition, whereColumnValue, joinCondition);
// if(!users.isEmpty() )
// User adminUser = (User)users.get(0);
// retStr = retStr + "," + adminUser.getEmailAddress();
// Logger.out.debug(retStr);
// retStr = retStr.substring(retStr.indexOf(",")+1 );
// Logger.out.debug(retStr);
// return retStr;
} |
package edu.wustl.catissuecore.util.global;
import java.util.HashMap;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String SESSION_DATA = "sessionData";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
//Database constants.
public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y";
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
//public static final String TRUE = "true";
//public static final String FALSE = "false";
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String ACCESS_DENIED = "access_denied";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String IDENTIFIER = "IDENTIFIER";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String ERROR_DETAIL = "Error Detail";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//Constants for audit of disabled objects.
public static final String UPDATE_OPERATION = "UPDATE";
public static final String ACTIVITY_STATUS_COLUMN = "ACTIVITY_STATUS";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_NAME_LIST = "objectNameList";
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String ATTRIBUTE_NAME_LIST = "attributeNameList";
public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList";
//Constants for Storage Container.
public static final String STORAGE_CONTAINER_TYPE = "storageType";
public static final String STORAGE_CONTAINER_TO_BE_SELECTED = "storageToBeSelected";
public static final String STORAGE_CONTAINER_POSITION = "position";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROMSITELIST="fromsiteList";
public static final String TOSITELIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final boolean switchSecurity = true;
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String MOLECULAR = "Molecular";
public static final String RNA = "RNA";
// New Participant Event Parameters
public static final String PARTICIPANT_ID="participantId";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "ShowStorageGridView.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_ACTION = "/SimpleQueryInterface.do";
public static final String SEARCH_OBJECT_ACTION = "/SearchObject.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
public static final String TABLE_DATA_TABLE_NAME = "CATISSUE_QUERY_INTERFACE_TABLE_DATA";
public static final String TABLE_DISPLAY_NAME_COLUMN = "DISPLAY_NAME";
public static final String TABLE_ALIAS_NAME_COLUMN = "ALIAS_NAME";
public static final String TABLE_FOR_SQI_COLUMN = "FOR_SQI";
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//TissueSite Tree View Constants.
public static final String PROPERTY_NAME = "propertyName";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Edit View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?systemIdentifier=";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
public static final String CONFIGURED_SELECT_COLUMN_LIST = "configuredSelectColumnList";
public static final String CONFIGURED_COLUMN_DISPLAY_NAMES = "configuredColumnDisplayNames";
//Tree Data Action
public static final String TREE_DATA_ACTION = "Data.do";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//SimpleSearchAction
public static final String SIMPLE_QUERY_NO_RESULTS = "noResults";
public static final String SIMPLE_QUERY_SINGLE_RESULT = "singleResult";
//For getting the tables for Simple Query and Fcon Query.
public static final int SIMPLE_QUERY_TABLES = 1;
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int SIMPLE_QUERY_INTERFACE_ID = 40;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
public static final int QUERY_INTERFACE_ID = 43;
//Misc
public static final String SEPARATOR = " : ";
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_ACTIVE = "Active";
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
public static final String ACTIVITY_STATUS_DISABLED = "Disabled";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Tree View Constants.
public static final String ROOT = "Root";
public static final String CATISSUE_CORE = "caTISSUE Core";
public static final String TISSUE_SITE = "Tissue Site";
public static final int TISSUE_SITE_TREE_ID = 1;
public static final int STORAGE_CONTAINER_TREE_ID = 2;
public static final int QUERY_RESULTS_TREE_ID = 3;
//Edit Object Constants.
public static final String TABLE_ALIAS_NAME = "aliasName";
public static final String FIELD_TYPE_VARCHAR = "varchar";
public static final String FIELD_TYPE_BIGINT = "bigint";
public static final String FIELD_TYPE_DATE = "date";
public static final String FIELD_TYPE_TEXT = "text";
public static final String FIELD_TYPE_TINY_INT = "tinyint";
public static final String CONDITION_VALUE_YES = "yes";
public static final String TINY_INT_VALUE_ONE = "1";
public static final String TINY_INT_VALUE_ZERO = "0";
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Tree Applet
public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults";
public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation";
public static final String PAGEOF_SPECIMEN = "pageOfSpecimen";
public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite";
//For Simple Query Interface and Edit.
public static final String PAGEOF_SIMPLE_QUERY_INTERFACE = "pageOfSimpleQueryInterface";
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_ASSIGN = true;
public static final boolean PRIVILEGE_DEASSIGN = false;
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
public static final String TREE_APPLET_NAME = "treeApplet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
//public static final String SELECT_OPTION = "-- Select --";
public static final int SELECT_OPTION_VALUE = -1;
// public static final String[] TISSUE_SITE_ARRAY = {
// SELECT_OPTION,"Sex","male","female",
// "Tissue","kidney","Left kidney","Right kidney"
public static final String[] ATTRIBUTE_NAME_ARRAY = {
SELECT_OPTION
};
public static final String[] ATTRIBUTE_CONDITION_ARRAY = {
"=","<",">"
};
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
public static final String [] STATEARRAY =
{
SELECT_OPTION,
"Alabama",//Alabama
"Alaska",//Alaska
"Arizona",//Arizona
"Arkansas",//Arkansas
"California",//California
"Colorado",//Colorado
"Connecticut",//Connecticut
"Delaware",//Delaware
"D.C.",
"Florida",//Florida
"Georgia",//Georgia
"Hawaii",//Hawaii
"Idaho",//Idaho
"Illinois",//Illinois
"Indiana",//Indiana
"Iowa",//Iowa
"Kansas",//Kansas
"Kentucky",//Kentucky
"Louisiana",//Louisiana
"Maine",//Maine
"Maryland",//Maryland
"Massachusetts",//Massachusetts
"Michigan",//Michigan
"Minnesota",//Minnesota
"Mississippi",//Mississippi
"Missouri",//Missouri
"Montana",//Montana
"Nebraska",//Nebraska
"Nevada",//Nevada
"New Hampshire",//New Hampshire
"New Jersey",//New Jersey
"New Mexico",//New Mexico
"New York",//New York
"North Carolina",//North Carolina
"North Dakota",//North Dakota
"Ohio",//Ohio
"Oklahoma",//Oklahoma
"Oregon",//Oregon
"Pennsylvania",//Pennsylvania
"Rhode Island",//Rhode Island
"South Carolina",//South Carolina
"South Dakota",//South Dakota
"Tennessee",//Tennessee
"Texas",//Texas
"Utah",//Utah
"Vermont",//Vermont
"Virginia",//Virginia
"Washington",//Washington
"West Virginia",//West Virginia
"Wisconsin",//Wisconsin
"Wyoming",//Wyoming
"Other",//Other
};
public static final String [] COUNTRYARRAY =
{
SELECT_OPTION,
"United States",
"Canada",
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",//Cameroon
"Cape Verde",//Cape Verde
"Cayman Islands",//Cayman Islands
"Central African Republic",//Central African Republic
"Chad",//Chad
"Chile",//Chile
"China",//China
"Christmas Island",//Christmas Island
"Cocos Islands",//Cocos Islands
"Colombia",//Colombia
"Comoros",//Comoros
"Congo",//Congo
"Cook Islands",//Cook Islands
"Costa Rica",//Costa Rica
"Cote D ivoire",//Cote D ivoire
"Croatia",//Croatia
"Cyprus",//Cyprus
"Czech Republic",//Czech Republic
"Denmark",//Denmark
"Djibouti",//Djibouti
"Dominica",//Dominica
"Dominican Republic",//Dominican Republic
"East Timor",//East Timor
"Ecuador",//Ecuador
"Egypt",//Egypt
"El Salvador",//El Salvador
"Equatorial Guinea",//Equatorial Guinea
"Eritrea",//Eritrea
"Estonia",//Estonia
"Ethiopia",//Ethiopia
"Falkland Islands",//Falkland Islands
"Faroe Islands",//Faroe Islands
"Fiji",//Fiji
"Finland",//Finland
"France",//France
"French Guiana",//French Guiana
"French Polynesia",//French Polynesia
"French S. Territories",//French S. Territories
"Gabon",//Gabon
"Gambia",//Gambia
"Georgia",//Georgia
"Germany",//Germany
"Ghana",//Ghana
"Gibraltar",//Gibraltar
"Greece",//Greece
"Greenland",//Greenland
"Grenada",//Grenada
"Guadeloupe",//Guadeloupe
"Guam",//Guam
"Guatemala",//Guatemala
"Guinea",//Guinea
"Guinea-Bissau",//Guinea-Bissau
"Guyana",//Guyana
"Haiti",//Haiti
"Honduras",//Honduras
"Hong Kong",//Hong Kong
"Hungary",//Hungary
"Iceland",//Iceland
"India",//India
"Indonesia",//Indonesia
"Iran",//Iran
"Iraq",//Iraq
"Ireland",//Ireland
"Israel",//Israel
"Italy",//Italy
"Jamaica",//Jamaica
"Japan",//Japan
"Jordan",//Jordan
"Kazakhstan",//Kazakhstan
"Kenya",//Kenya
"Kiribati",//Kiribati
"Korea",//Korea
"Kuwait",//Kuwait
"Kyrgyzstan",//Kyrgyzstan
"Laos",//Laos
"Latvia",//Latvia
"Lebanon",//Lebanon
"Lesotho",//Lesotho
"Liberia",//Liberia
"Liechtenstein",//Liechtenstein
"Lithuania",//Lithuania
"Luxembourg",//Luxembourg
"Macau",//Macau
"Macedonia",//Macedonia
"Madagascar",//Madagascar
"Malawi",//Malawi
"Malaysia",//Malaysia
"Maldives",//Maldives
"Mali",//Mali
"Malta",//Malta
"Marshall Islands",//Marshall Islands
"Martinique",//Martinique
"Mauritania",//Mauritania
"Mauritius",//Mauritius
"Mayotte",//Mayotte
"Mexico",//Mexico
"Micronesia",//Micronesia
"Moldova",//Moldova
"Monaco",//Monaco
"Mongolia",//Mongolia
"Montserrat",//Montserrat
"Morocco",//Morocco
"Mozambique",//Mozambique
"Myanmar",//Myanmar
"Namibia",//Namibia
"Nauru",//Nauru
"Nepal",//Nepal
"Netherlands",//Netherlands
"Netherlands Antilles",//Netherlands Antilles
"New Caledonia",//New Caledonia
"New Zealand",//New Zealand
"Nicaragua",//Nicaragua
"Niger",//Niger
"Nigeria",//Nigeria
"Niue",//Niue
"Norfolk Island",//Norfolk Island
"Norway",//Norway
"Oman",//Oman
"Pakistan",//Pakistan
"Palau",//Palau
"Panama",//Panama
"Papua New Guinea",//Papua New Guinea
"Paraguay",//Paraguay
"Peru",//Peru
"Philippines",//Philippines
"Pitcairn",//Pitcairn
"Poland",//Poland
"Portugal",//Portugal
"Puerto Rico",//Puerto Rico
"Qatar",//Qatar
"Reunion",//Reunion
"Romania",//Romania
"Russian Federation",//Russian Federation
"Rwanda",//Rwanda
"Saint Helena",//Saint Helena
"Saint Kitts and Nevis",//Saint Kitts and Nevis
"Saint Lucia",//Saint Lucia
"Saint Pierre",//Saint Pierre
"Saint Vincent",//Saint Vincent
"Samoa",//Samoa
"San Marino",//San Marino
"Sao Tome and Principe",//Sao Tome and Principe
"Saudi Arabia",//Saudi Arabia
"Senegal",//Senegal
"Seychelles",//Seychelles
"Sierra Leone",//Sierra Leone
"Singapore",//Singapore
"Slovakia",//Slovakia
"Slovenia",//Slovenia
"Solomon Islands",//Solomon Islands
"Somalia",//Somalia
"South Africa",//South Africa
"Spain",//Spain
"Sri Lanka",//Sri Lanka
"Sudan",//Sudan
"Suriname",//Suriname
"Swaziland",//Swaziland
"Sweden",//Sweden
"Switzerland",//Switzerland
"Syrian Arab Republic",//Syrian Arab Republic
"Taiwan",//Taiwan
"Tajikistan",//Tajikistan
"Tanzania",//Tanzania
"Thailand",//Thailand
"Togo",//Togo
"Tokelau",//Tokelau
"Tonga",//Tonga
"Trinidad and Tobago",//Trinidad and Tobago
"Tunisia",//Tunisia
"Turkey",//Turkey
"Turkmenistan",//Turkmenistan
"Turks and Caicos Islands",//Turks and Caicos Islands
"Tuvalu",//Tuvalu
"Uganda",//Uganda
"Ukraine",//Ukraine
"United Arab Emirates",//United Arab Emirates
"United Kingdom",//United Kingdom
"Uruguay",//Uruguay
"Uzbekistan",//Uzbekistan
"Vanuatu",//Vanuatu
"Vatican City State",//Vatican City State
"Venezuela",//Venezuela
"Vietnam",//Vietnam
"Virgin Islands",//Virgin Islands
"Wallis And Futuna Islands",//Wallis And Futuna Islands
"Western Sahara",//Western Sahara
"Yemen",//Yemen
"Yugoslavia",//Yugoslavia
"Zaire",//Zaire
"Zambia",//Zambia
"Zimbabwe",//Zimbabwe
};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
"Tissue",
"Fluid",
"Cell",
"Molecular"
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final HashMap STATIC_PROTECTION_GROUPS_FOR_OBJECT_TYPES = new HashMap();
//public static final String CDE_CONF_FILE = "CDEConfig.xml";
public static final String CDE_NAME_TISSUE_SITE = "Tissue Site";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
public static final String [] CLINICALDIAGNOSISARRAY = {
SELECT_OPTION,
"CLINICALDIAGNOSIS 1",
"CLINICALDIAGNOSIS 2",
"CLINICALDIAGNOSIS 3"
};
public static final String [] HISTOLOGICAL_QUALITY_ARRAY = {
SELECT_OPTION,
"GOOD",
"OK",
"DAMAGED"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER = "systemIdentifier";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
public static final String getCollectionProtocolPGName(Long identifier)
{
if(identifier == null)
{
return "COLLECTION_PROTOCOL_";
}
return "COLLECTION_PROTOCOL_"+identifier;
}
public static final String getCollectionProtocolPIGroupName(Long identifier)
{
if(identifier == null)
{
return "PI_COLLECTION_PROTOCOL_";
}
return "PI_COLLECTION_PROTOCOL_"+identifier;
}
public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
{
if(identifier == null)
{
return "COORDINATORS_COLLECTION_PROTOCOL_";
}
return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier;
}
public static final String getDistributionProtocolPGName(Long identifier)
{
if(identifier == null)
{
return "DISTRIBUTION_PROTOCOL_";
}
return "DISTRIBUTION_PROTOCOL_"+identifier;
}
public static final String getStorageContainerPGName(Long identifier)
{
if(identifier == null)
{
return "STORAGE_CONTAINER_";
}
return "STORAGE_CONTAINER_"+identifier;
}
public static final String getSitePGName(Long identifier)
{
if(identifier == null)
{
return "SITE_";
}
return "SITE_"+identifier;
}
public static final String getDistributionProtocolPIGroupName(Long identifier)
{
if(identifier == null)
{
return "PI_DISTRIBUTION_PROTOCOL_";
}
return "PI_DISTRIBUTION_PROTOCOL_"+identifier;
}
public static final String ACCESS_DENIED_ADMIN = "access_denied_admin";
public static final String ACCESS_DENIED_BIOSPECIMEN = "access_denied_biospecimen";
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
//public static final String ANY = "Any";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param systemIdentifier
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param systemIdentifier
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
public static final String SLIDE = "Slide";
public static final String PARAFFIN_BLOCK = "Paraffin Block";
public static final String FROZEN_BLOCK = "Frozen Block";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtocolRegistration","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
//public static final String DELIMETER = ",";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Specimen Identifier",
"Specimen.TYPE.Specimen Type",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side",
"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status",
"DistributedItem.QUANTITY.Specimen Quantity"};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?operation=add&pageOf=pageOfDistribution&specimenIdKey=";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SIMPLE_QUERY_MAP = "simpleQueryMap";
public static final String SIMPLE_QUERY_ALIAS_NAME = "simpleQueryAliasName";
public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
// MD : LightYellow and Green colors
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// Aarti: Constants for security parameter required
//while retrieving data from DAOs
public static final int INSECURE_RETRIEVE = 0;
public static final int CLASS_LEVEL_SECURE_RETRIEVE = 1;
public static final int OBJECT_LEVEL_SECURE_RETRIEVE = 2;
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Derive New From This Specimen", "createNew"},
{"Add Events", "eventParameters"},
{"Add More To Same Collection Group", "sameCollectionGroup"}
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Add New Specimen", "createNewSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Specimen Collection Group", "createSpecimenCollectionGroup"}
};
public static final String [][] PARTICIPANT_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Participant Registration", "createParticipantRegistration"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String COLLECTION_PROTOCOL ="CollectionProtocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITION_NODES_MAP = "advancedConditionNodesMap";
public static final String TREE_VECTOR = "treeVector";
public static final String ADVANCED_CONDITIONS_ROOT = "advancedCondtionsRoot";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "AND";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String COLUMN_ID_MAP = "columnIdsMap";
public static final String PARENT_SPECIMEN_ID_COLUMN = "PARENT_SPECIMEN_ID";
public static final String COLUMN = "Column";
public static final String COLUMN_DISPLAY_NAMES = "columnDisplayNames";
public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit";
public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit";
public static final String PARTICIPANT_COLUMNS = "particpantColumns";
public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns";
public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns";
public static final String SPECIMEN_COLUMNS = "SpecimenColumns";
// -- menu selection related
public static final String MENU_SELECTED = "menuSelected";
public static final String CONSTRAINT_VOILATION_ERROR = "Submission failed since a {0} with the same {1} already exists";
public static final String GENERIC_DATABASE_ERROR = "An error occured during a database operation. Please report this problem to the adminstrator";
// The unique key voilation message is "Duplicate entry %s for key %d"
// This string is used for searching " for key " string in the above error message
public static final String MYSQL_DUPL_KEY_MSG = " for key ";
public static final String CATISSUE_SPECIMEN = "CATISSUE_SPECIMEN";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String DATABASE_IN_USED = "MYSQL";
public static final String PASSWORD_CHANGE_IN_SESSION = "changepassword";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain";
} |
package edu.wustl.catissuecore.util.global;
import java.util.HashMap;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String USER = "user";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
public static final String DATE_PATTERN = "yyyy-MM-dd HH:mm aa";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy";
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String ACCESS_DENIED = "access_denied";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String IDENTIFIER = "systemIdentifier";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String ERROR_DETAIL = "Error Detail";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
//Simple Query Interface Lists
public static final String OBJECT_NAME_LIST = "objectNameList";
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String ATTRIBUTE_NAME_LIST = "attributeNameList";
public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList";
//Constants for Storage Container.
public static final String STORAGE_CONTAINER_TYPE = "storageType";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
//event parameters lists
public static final String METHODLIST = "methodList";
public static final String HOURLIST = "hourList";
public static final String MINUTESLIST = "minutesList";
public static final String EMBEDDINGMEDIUMLIST = "embeddingMediumList";
public static final String PROCEDURELIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINERLIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATIONLIST = "fixationList";
public static final String FROMSITELIST="fromsiteList";
public static final String TOSITELIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "/catissuecore/ShowStorageGridView.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
// Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
// Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
// Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "ReceivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "ReceivedEventParametersEdit.do";
// Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
// Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
// Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "/catissuecore/DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//TissueSite Tree View Constants.
public static final String PROPERTY_NAME = "propertyName";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Object View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
//Tree Data Action
public static final String TREE_DATA_ACTION = "/catissuecore/Data.do";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTEDPROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
//Misc
public static final String SEPARATOR = " : ";
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_ACTIVE = "Active";
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Tree View Constants.
public static final String ROOT = "Root";
public static final String CATISSUE_CORE = "caTISSUE Core";
public static final String TISSUE_SITE = "Tissue Site";
public static final int TISSUE_SITE_TREE_ID = 1;
public static final int STORAGE_CONTAINER_TREE_ID = 2;
public static final int QUERY_RESULTS_TREE_ID = 3;
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
//For Tree Applet
public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults";
public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation";
public static final String PAGEOF_SPECIMEN = "pageOfSpecimen";
public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
public static final String TREE_APPLET_NAME = "treeApplet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final String SELECT_OPTION = "-- Select --";
public static final String[] TISSUE_SITE_ARRAY = {
SELECT_OPTION,"Sex","male","female",
"Tissue","kidney","Left kidney","Right kidney"
};
public static final String[] ATTRIBUTE_NAME_ARRAY = {
SELECT_OPTION
};
public static final String[] ATTRIBUTE_CONDITION_ARRAY = {
"=","<",">"
};
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
public static final String [] STATEARRAY =
{
SELECT_OPTION,
"Alabama",//Alabama
"Alaska",//Alaska
"Arizona",//Arizona
"Arkansas",//Arkansas
"California",//California
"Colorado",//Colorado
"Connecticut",//Connecticut
"Delaware",//Delaware
"D.C.",
"Florida",//Florida
"Georgia",//Georgia
"Hawaii",//Hawaii
"Idaho",//Idaho
"Illinois",//Illinois
"Indiana",//Indiana
"Iowa",//Iowa
"Kansas",//Kansas
"Kentucky",//Kentucky
"Louisiana",//Louisiana
"Maine",//Maine
"Maryland",//Maryland
"Massachusetts",//Massachusetts
"Michigan",//Michigan
"Minnesota",//Minnesota
"Mississippi",//Mississippi
"Missouri",//Missouri
"Montana",//Montana
"Nebraska",//Nebraska
"Nevada",//Nevada
"New Hampshire",//New Hampshire
"New Jersey",//New Jersey
"New Mexico",//New Mexico
"New York",//New York
"North Carolina",//North Carolina
"North Dakota",//North Dakota
"Ohio",//Ohio
"Oklahoma",//Oklahoma
"Oregon",//Oregon
"Pennsylvania",//Pennsylvania
"Rhode Island",//Rhode Island
"South Carolina",//South Carolina
"South Dakota",//South Dakota
"Tennessee",//Tennessee
"Texas",//Texas
"Utah",//Utah
"Vermont",//Vermont
"Virginia",//Virginia
"Washington",//Washington
"West Virginia",//West Virginia
"Wisconsin",//Wisconsin
"Wyoming",//Wyoming
"Other",//Other
};
public static final String [] COUNTRYARRAY =
{
SELECT_OPTION,
"United States",
"Canada",
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",//Cameroon
"Cape Verde",//Cape Verde
"Cayman Islands",//Cayman Islands
"Central African Republic",//Central African Republic
"Chad",//Chad
"Chile",//Chile
"China",//China
"Christmas Island",//Christmas Island
"Cocos Islands",//Cocos Islands
"Colombia",//Colombia
"Comoros",//Comoros
"Congo",//Congo
"Cook Islands",//Cook Islands
"Costa Rica",//Costa Rica
"Cote D ivoire",//Cote D ivoire
"Croatia",//Croatia
"Cyprus",//Cyprus
"Czech Republic",//Czech Republic
"Denmark",//Denmark
"Djibouti",//Djibouti
"Dominica",//Dominica
"Dominican Republic",//Dominican Republic
"East Timor",//East Timor
"Ecuador",//Ecuador
"Egypt",//Egypt
"El Salvador",//El Salvador
"Equatorial Guinea",//Equatorial Guinea
"Eritrea",//Eritrea
"Estonia",//Estonia
"Ethiopia",//Ethiopia
"Falkland Islands",//Falkland Islands
"Faroe Islands",//Faroe Islands
"Fiji",//Fiji
"Finland",//Finland
"France",//France
"French Guiana",//French Guiana
"French Polynesia",//French Polynesia
"French S. Territories",//French S. Territories
"Gabon",//Gabon
"Gambia",//Gambia
"Georgia",//Georgia
"Germany",//Germany
"Ghana",//Ghana
"Gibraltar",//Gibraltar
"Greece",//Greece
"Greenland",//Greenland
"Grenada",//Grenada
"Guadeloupe",//Guadeloupe
"Guam",//Guam
"Guatemala",//Guatemala
"Guinea",//Guinea
"Guinea-Bissau",//Guinea-Bissau
"Guyana",//Guyana
"Haiti",//Haiti
"Honduras",//Honduras
"Hong Kong",//Hong Kong
"Hungary",//Hungary
"Iceland",//Iceland
"India",//India
"Indonesia",//Indonesia
"Iran",//Iran
"Iraq",//Iraq
"Ireland",//Ireland
"Israel",//Israel
"Italy",//Italy
"Jamaica",//Jamaica
"Japan",//Japan
"Jordan",//Jordan
"Kazakhstan",//Kazakhstan
"Kenya",//Kenya
"Kiribati",//Kiribati
"Korea",//Korea
"Kuwait",//Kuwait
"Kyrgyzstan",//Kyrgyzstan
"Laos",//Laos
"Latvia",//Latvia
"Lebanon",//Lebanon
"Lesotho",//Lesotho
"Liberia",//Liberia
"Liechtenstein",//Liechtenstein
"Lithuania",//Lithuania
"Luxembourg",//Luxembourg
"Macau",//Macau
"Macedonia",//Macedonia
"Madagascar",//Madagascar
"Malawi",//Malawi
"Malaysia",//Malaysia
"Maldives",//Maldives
"Mali",//Mali
"Malta",//Malta
"Marshall Islands",//Marshall Islands
"Martinique",//Martinique
"Mauritania",//Mauritania
"Mauritius",//Mauritius
"Mayotte",//Mayotte
"Mexico",//Mexico
"Micronesia",//Micronesia
"Moldova",//Moldova
"Monaco",//Monaco
"Mongolia",//Mongolia
"Montserrat",//Montserrat
"Morocco",//Morocco
"Mozambique",//Mozambique
"Myanmar",//Myanmar
"Namibia",//Namibia
"Nauru",//Nauru
"Nepal",//Nepal
"Netherlands",//Netherlands
"Netherlands Antilles",//Netherlands Antilles
"New Caledonia",//New Caledonia
"New Zealand",//New Zealand
"Nicaragua",//Nicaragua
"Niger",//Niger
"Nigeria",//Nigeria
"Niue",//Niue
"Norfolk Island",//Norfolk Island
"Norway",//Norway
"Oman",//Oman
"Pakistan",//Pakistan
"Palau",//Palau
"Panama",//Panama
"Papua New Guinea",//Papua New Guinea
"Paraguay",//Paraguay
"Peru",//Peru
"Philippines",//Philippines
"Pitcairn",//Pitcairn
"Poland",//Poland
"Portugal",//Portugal
"Puerto Rico",//Puerto Rico
"Qatar",//Qatar
"Reunion",//Reunion
"Romania",//Romania
"Russian Federation",//Russian Federation
"Rwanda",//Rwanda
"Saint Helena",//Saint Helena
"Saint Kitts and Nevis",//Saint Kitts and Nevis
"Saint Lucia",//Saint Lucia
"Saint Pierre",//Saint Pierre
"Saint Vincent",//Saint Vincent
"Samoa",//Samoa
"San Marino",//San Marino
"Sao Tome and Principe",//Sao Tome and Principe
"Saudi Arabia",//Saudi Arabia
"Senegal",//Senegal
"Seychelles",//Seychelles
"Sierra Leone",//Sierra Leone
"Singapore",//Singapore
"Slovakia",//Slovakia
"Slovenia",//Slovenia
"Solomon Islands",//Solomon Islands
"Somalia",//Somalia
"South Africa",//South Africa
"Spain",//Spain
"Sri Lanka",//Sri Lanka
"Sudan",//Sudan
"Suriname",//Suriname
"Swaziland",//Swaziland
"Sweden",//Sweden
"Switzerland",//Switzerland
"Syrian Arab Republic",//Syrian Arab Republic
"Taiwan",//Taiwan
"Tajikistan",//Tajikistan
"Tanzania",//Tanzania
"Thailand",//Thailand
"Togo",//Togo
"Tokelau",//Tokelau
"Tonga",//Tonga
"Trinidad and Tobago",//Trinidad and Tobago
"Tunisia",//Tunisia
"Turkey",//Turkey
"Turkmenistan",//Turkmenistan
"Turks and Caicos Islands",//Turks and Caicos Islands
"Tuvalu",//Tuvalu
"Uganda",//Uganda
"Ukraine",//Ukraine
"United Arab Emirates",//United Arab Emirates
"United Kingdom",//United Kingdom
"Uruguay",//Uruguay
"Uzbekistan",//Uzbekistan
"Vanuatu",//Vanuatu
"Vatican City State",//Vatican City State
"Venezuela",//Venezuela
"Vietnam",//Vietnam
"Virgin Islands",//Virgin Islands
"Wallis And Futuna Islands",//Wallis And Futuna Islands
"Western Sahara",//Western Sahara
"Yemen",//Yemen
"Yugoslavia",//Yugoslavia
"Zaire",//Zaire
"Zambia",//Zambia
"Zimbabwe",//Zimbabwe
};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] CANCER_RESEARCH_GROUP_VALUES = {
SELECT_OPTION,
"Siteman Cancer Center",
"Washington University"
};
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Disabled",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
//Only for showing UI.
public static final String [] INSTITUTE_VALUES = {
SELECT_OPTION,
"Washington University"
};
public static final String [] DEPARTMENT_VALUES = {
SELECT_OPTION,
"Cardiology",
"Pathology"
};
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
"Tissue",
"Fluid",
"Cell",
"Molecular"
};
public static final String [] SPECIMEN_SUB_TYPE_VALUES = {
SELECT_OPTION,
"Blood",
"Serum",
"Plasma",
};
public static final String [] TISSUE_SIDE_VALUES = {
SELECT_OPTION,
"Lavage",
"Metastatic Lesion",
};
public static final String [] PATHOLOGICAL_STATUS_VALUES = {
SELECT_OPTION,
"Primary Tumor",
"Metastatic Node",
"Non-Maglignant Tissue",
};
// public static final String [] BIOHAZARD_NAME_VALUES = {
// SELECT_OPTION,
public static final String [] BIOHAZARD_TYPE_VALUES = {
SELECT_OPTION,
"Radioactive"
};
public static final String [] ETHNICITY_VALUES = {
SELECT_OPTION,
"Ethnicity1",
"Ethnicity2",
"Ethnicity3",
};
public static final String [] PARTICIPANT_MEDICAL_RECORD_SOURCE_VALUES = {
SELECT_OPTION
};
public static final String [] STUDY_CALENDAR_EVENT_POINT_ARRAY = {
SELECT_OPTION,
"30","60","90"
};
public static final String [] CLINICAL_STATUS_ARRAY = {
SELECT_OPTION,
"Pre-Opt",
"Post-Opt"
};
public static final String [] SITE_TYPE_ARRAY = {
SELECT_OPTION,
"Collection",
"Laboratory",
"Repository", "Hospital"
};
public static final String [] BIOHAZARD_TYPE_ARRAY = {
SELECT_OPTION,
"Carcinogen",
"Infectious",
"Mutagen",
"Radioactive",
"Toxic"
};
public static final String [] HOURARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTESARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "mg";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final HashMap STATIC_PROTECTION_GROUPS_FOR_OBJECT_TYPES = new HashMap();
} |
package edu.wustl.catissuecore.util.global;
import java.util.HashMap;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String SESSION_DATA = "sessionData";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
//Database constants.
public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y";
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
//public static final String TRUE = "true";
//public static final String FALSE = "false";
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String ACCESS_DENIED = "access_denied";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String IDENTIFIER = "IDENTIFIER";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String ERROR_DETAIL = "Error Detail";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//Constants for audit of disabled objects.
public static final String UPDATE_OPERATION = "UPDATE";
public static final String ACTIVITY_STATUS_COLUMN = "ACTIVITY_STATUS";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_NAME_LIST = "objectNameList";
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String ATTRIBUTE_NAME_LIST = "attributeNameList";
public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList";
//Constants for Storage Container.
public static final String STORAGE_CONTAINER_TYPE = "storageType";
public static final String STORAGE_CONTAINER_TO_BE_SELECTED = "storageToBeSelected";
public static final String STORAGE_CONTAINER_POSITION = "position";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROMSITELIST="fromsiteList";
public static final String TOSITELIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final boolean switchSecurity = true;
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String MOLECULAR = "Molecular";
public static final String RNA = "RNA";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "ShowStorageGridView.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_ACTION = "/SimpleQueryInterface.do";
public static final String SEARCH_OBJECT_ACTION = "/SearchObject.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
public static final String TABLE_DATA_TABLE_NAME = "CATISSUE_QUERY_INTERFACE_TABLE_DATA";
public static final String TABLE_DISPLAY_NAME_COLUMN = "DISPLAY_NAME";
public static final String TABLE_ALIAS_NAME_COLUMN = "ALIAS_NAME";
public static final String TABLE_FOR_SQI_COLUMN = "FOR_SQI";
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//TissueSite Tree View Constants.
public static final String PROPERTY_NAME = "propertyName";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Object View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?systemIdentifier=";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
//Tree Data Action
public static final String TREE_DATA_ACTION = "Data.do";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//SimpleSearchAction
public static final String SIMPLE_QUERY_NO_RESULTS = "noResults";
public static final String SIMPLE_QUERY_SINGLE_RESULT = "singleResult";
//For getting the tables for Simple Query and Fcon Query.
public static final int SIMPLE_QUERY_TABLES = 1;
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int SIMPLE_QUERY_INTERFACE_ID = 40;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
//Misc
public static final String SEPARATOR = " : ";
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_ACTIVE = "Active";
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
public static final String ACTIVITY_STATUS_DISABLED = "Disabled";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Tree View Constants.
public static final String ROOT = "Root";
public static final String CATISSUE_CORE = "caTISSUE Core";
public static final String TISSUE_SITE = "Tissue Site";
public static final int TISSUE_SITE_TREE_ID = 1;
public static final int STORAGE_CONTAINER_TREE_ID = 2;
public static final int QUERY_RESULTS_TREE_ID = 3;
//Edit Object Constants.
public static final String TABLE_ALIAS_NAME = "aliasName";
public static final String FIELD_TYPE_VARCHAR = "varchar";
public static final String FIELD_TYPE_BIGINT = "bigint";
public static final String FIELD_TYPE_DATE = "date";
public static final String FIELD_TYPE_TEXT = "text";
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Tree Applet
public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults";
public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation";
public static final String PAGEOF_SPECIMEN = "pageOfSpecimen";
public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite";
//For Simple Query Interface and Edit.
public static final String PAGEOF_SIMPLE_QUERY_INTERFACE = "pageOfSimpleQueryInterface";
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_ASSIGN = true;
public static final boolean PRIVILEGE_DEASSIGN = false;
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
public static final String TREE_APPLET_NAME = "treeApplet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
//public static final String SELECT_OPTION = "-- Select --";
public static final int SELECT_OPTION_VALUE = -1;
// public static final String[] TISSUE_SITE_ARRAY = {
// SELECT_OPTION,"Sex","male","female",
// "Tissue","kidney","Left kidney","Right kidney"
public static final String[] ATTRIBUTE_NAME_ARRAY = {
SELECT_OPTION
};
public static final String[] ATTRIBUTE_CONDITION_ARRAY = {
"=","<",">"
};
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
public static final String [] STATEARRAY =
{
SELECT_OPTION,
"Alabama",//Alabama
"Alaska",//Alaska
"Arizona",//Arizona
"Arkansas",//Arkansas
"California",//California
"Colorado",//Colorado
"Connecticut",//Connecticut
"Delaware",//Delaware
"D.C.",
"Florida",//Florida
"Georgia",//Georgia
"Hawaii",//Hawaii
"Idaho",//Idaho
"Illinois",//Illinois
"Indiana",//Indiana
"Iowa",//Iowa
"Kansas",//Kansas
"Kentucky",//Kentucky
"Louisiana",//Louisiana
"Maine",//Maine
"Maryland",//Maryland
"Massachusetts",//Massachusetts
"Michigan",//Michigan
"Minnesota",//Minnesota
"Mississippi",//Mississippi
"Missouri",//Missouri
"Montana",//Montana
"Nebraska",//Nebraska
"Nevada",//Nevada
"New Hampshire",//New Hampshire
"New Jersey",//New Jersey
"New Mexico",//New Mexico
"New York",//New York
"North Carolina",//North Carolina
"North Dakota",//North Dakota
"Ohio",//Ohio
"Oklahoma",//Oklahoma
"Oregon",//Oregon
"Pennsylvania",//Pennsylvania
"Rhode Island",//Rhode Island
"South Carolina",//South Carolina
"South Dakota",//South Dakota
"Tennessee",//Tennessee
"Texas",//Texas
"Utah",//Utah
"Vermont",//Vermont
"Virginia",//Virginia
"Washington",//Washington
"West Virginia",//West Virginia
"Wisconsin",//Wisconsin
"Wyoming",//Wyoming
"Other",//Other
};
public static final String [] COUNTRYARRAY =
{
SELECT_OPTION,
"United States",
"Canada",
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",//Cameroon
"Cape Verde",//Cape Verde
"Cayman Islands",//Cayman Islands
"Central African Republic",//Central African Republic
"Chad",//Chad
"Chile",//Chile
"China",//China
"Christmas Island",//Christmas Island
"Cocos Islands",//Cocos Islands
"Colombia",//Colombia
"Comoros",//Comoros
"Congo",//Congo
"Cook Islands",//Cook Islands
"Costa Rica",//Costa Rica
"Cote D ivoire",//Cote D ivoire
"Croatia",//Croatia
"Cyprus",//Cyprus
"Czech Republic",//Czech Republic
"Denmark",//Denmark
"Djibouti",//Djibouti
"Dominica",//Dominica
"Dominican Republic",//Dominican Republic
"East Timor",//East Timor
"Ecuador",//Ecuador
"Egypt",//Egypt
"El Salvador",//El Salvador
"Equatorial Guinea",//Equatorial Guinea
"Eritrea",//Eritrea
"Estonia",//Estonia
"Ethiopia",//Ethiopia
"Falkland Islands",//Falkland Islands
"Faroe Islands",//Faroe Islands
"Fiji",//Fiji
"Finland",//Finland
"France",//France
"French Guiana",//French Guiana
"French Polynesia",//French Polynesia
"French S. Territories",//French S. Territories
"Gabon",//Gabon
"Gambia",//Gambia
"Georgia",//Georgia
"Germany",//Germany
"Ghana",//Ghana
"Gibraltar",//Gibraltar
"Greece",//Greece
"Greenland",//Greenland
"Grenada",//Grenada
"Guadeloupe",//Guadeloupe
"Guam",//Guam
"Guatemala",//Guatemala
"Guinea",//Guinea
"Guinea-Bissau",//Guinea-Bissau
"Guyana",//Guyana
"Haiti",//Haiti
"Honduras",//Honduras
"Hong Kong",//Hong Kong
"Hungary",//Hungary
"Iceland",//Iceland
"India",//India
"Indonesia",//Indonesia
"Iran",//Iran
"Iraq",//Iraq
"Ireland",//Ireland
"Israel",//Israel
"Italy",//Italy
"Jamaica",//Jamaica
"Japan",//Japan
"Jordan",//Jordan
"Kazakhstan",//Kazakhstan
"Kenya",//Kenya
"Kiribati",//Kiribati
"Korea",//Korea
"Kuwait",//Kuwait
"Kyrgyzstan",//Kyrgyzstan
"Laos",//Laos
"Latvia",//Latvia
"Lebanon",//Lebanon
"Lesotho",//Lesotho
"Liberia",//Liberia
"Liechtenstein",//Liechtenstein
"Lithuania",//Lithuania
"Luxembourg",//Luxembourg
"Macau",//Macau
"Macedonia",//Macedonia
"Madagascar",//Madagascar
"Malawi",//Malawi
"Malaysia",//Malaysia
"Maldives",//Maldives
"Mali",//Mali
"Malta",//Malta
"Marshall Islands",//Marshall Islands
"Martinique",//Martinique
"Mauritania",//Mauritania
"Mauritius",//Mauritius
"Mayotte",//Mayotte
"Mexico",//Mexico
"Micronesia",//Micronesia
"Moldova",//Moldova
"Monaco",//Monaco
"Mongolia",//Mongolia
"Montserrat",//Montserrat
"Morocco",//Morocco
"Mozambique",//Mozambique
"Myanmar",//Myanmar
"Namibia",//Namibia
"Nauru",//Nauru
"Nepal",//Nepal
"Netherlands",//Netherlands
"Netherlands Antilles",//Netherlands Antilles
"New Caledonia",//New Caledonia
"New Zealand",//New Zealand
"Nicaragua",//Nicaragua
"Niger",//Niger
"Nigeria",//Nigeria
"Niue",//Niue
"Norfolk Island",//Norfolk Island
"Norway",//Norway
"Oman",//Oman
"Pakistan",//Pakistan
"Palau",//Palau
"Panama",//Panama
"Papua New Guinea",//Papua New Guinea
"Paraguay",//Paraguay
"Peru",//Peru
"Philippines",//Philippines
"Pitcairn",//Pitcairn
"Poland",//Poland
"Portugal",//Portugal
"Puerto Rico",//Puerto Rico
"Qatar",//Qatar
"Reunion",//Reunion
"Romania",//Romania
"Russian Federation",//Russian Federation
"Rwanda",//Rwanda
"Saint Helena",//Saint Helena
"Saint Kitts and Nevis",//Saint Kitts and Nevis
"Saint Lucia",//Saint Lucia
"Saint Pierre",//Saint Pierre
"Saint Vincent",//Saint Vincent
"Samoa",//Samoa
"San Marino",//San Marino
"Sao Tome and Principe",//Sao Tome and Principe
"Saudi Arabia",//Saudi Arabia
"Senegal",//Senegal
"Seychelles",//Seychelles
"Sierra Leone",//Sierra Leone
"Singapore",//Singapore
"Slovakia",//Slovakia
"Slovenia",//Slovenia
"Solomon Islands",//Solomon Islands
"Somalia",//Somalia
"South Africa",//South Africa
"Spain",//Spain
"Sri Lanka",//Sri Lanka
"Sudan",//Sudan
"Suriname",//Suriname
"Swaziland",//Swaziland
"Sweden",//Sweden
"Switzerland",//Switzerland
"Syrian Arab Republic",//Syrian Arab Republic
"Taiwan",//Taiwan
"Tajikistan",//Tajikistan
"Tanzania",//Tanzania
"Thailand",//Thailand
"Togo",//Togo
"Tokelau",//Tokelau
"Tonga",//Tonga
"Trinidad and Tobago",//Trinidad and Tobago
"Tunisia",//Tunisia
"Turkey",//Turkey
"Turkmenistan",//Turkmenistan
"Turks and Caicos Islands",//Turks and Caicos Islands
"Tuvalu",//Tuvalu
"Uganda",//Uganda
"Ukraine",//Ukraine
"United Arab Emirates",//United Arab Emirates
"United Kingdom",//United Kingdom
"Uruguay",//Uruguay
"Uzbekistan",//Uzbekistan
"Vanuatu",//Vanuatu
"Vatican City State",//Vatican City State
"Venezuela",//Venezuela
"Vietnam",//Vietnam
"Virgin Islands",//Virgin Islands
"Wallis And Futuna Islands",//Wallis And Futuna Islands
"Western Sahara",//Western Sahara
"Yemen",//Yemen
"Yugoslavia",//Yugoslavia
"Zaire",//Zaire
"Zambia",//Zambia
"Zimbabwe",//Zimbabwe
};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
"Tissue",
"Fluid",
"Cell",
"Molecular"
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final HashMap STATIC_PROTECTION_GROUPS_FOR_OBJECT_TYPES = new HashMap();
//public static final String CDE_CONF_FILE = "CDEConfig.xml";
public static final String CDE_NAME_TISSUE_SITE = "Tissue Site";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
public static final String [] CLINICALDIAGNOSISARRAY = {
SELECT_OPTION,
"CLINICALDIAGNOSIS 1",
"CLINICALDIAGNOSIS 2",
"CLINICALDIAGNOSIS 3"
};
public static final String [] HISTOLOGICAL_QUALITY_ARRAY = {
SELECT_OPTION,
"GOOD",
"OK",
"DAMAGED"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER = "systemIdentifier";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
public static final String getCollectionProtocolPGName(Long identifier)
{
if(identifier == null)
{
return "COLLECTION_PROTOCOL_";
}
return "COLLECTION_PROTOCOL_"+identifier;
}
public static final String getCollectionProtocolPIGroupName(Long identifier)
{
if(identifier == null)
{
return "PI_COLLECTION_PROTOCOL_";
}
return "PI_COLLECTION_PROTOCOL_"+identifier;
}
public static final String getCollectionProtocolCoordinatorGroupName(Long identifier)
{
if(identifier == null)
{
return "COORDINATORS_COLLECTION_PROTOCOL_";
}
return "COORDINATORS_COLLECTION_PROTOCOL_"+identifier;
}
public static final String getDistributionProtocolPGName(Long identifier)
{
if(identifier == null)
{
return "DISTRIBUTION_PROTOCOL_";
}
return "DISTRIBUTION_PROTOCOL_"+identifier;
}
public static final String getStorageContainerPGName(Long identifier)
{
if(identifier == null)
{
return "STORAGE_CONTAINER_";
}
return "STORAGE_CONTAINER_"+identifier;
}
public static final String getSitePGName(Long identifier)
{
if(identifier == null)
{
return "SITE_";
}
return "SITE_"+identifier;
}
public static final String getDistributionProtocolPIGroupName(Long identifier)
{
if(identifier == null)
{
return "PI_DISTRIBUTION_PROTOCOL_";
}
return "PI_DISTRIBUTION_PROTOCOL_"+identifier;
}
public static final String ACCESS_DENIED_ADMIN = "access_denied_admin";
public static final String ACCESS_DENIED_BIOSPECIMEN = "access_denied_biospecimen";
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
//public static final String ANY = "Any";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param systemIdentifier
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param systemIdentifier
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
public static final String SLIDE = "Slide";
public static final String PARAFFIN_BLOCK = "Paraffin Block";
public static final String FROZEN_BLOCK = "Frozen Block";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtocolRegistration","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
//public static final String DELIMETER = ",";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Specimen Identifier",
"Specimen.TYPE.Specimen Type",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side",
"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status",
"DistributedItem.QUANTITY.Specimen Quantity"};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?operation=add&pageOf=pageOfDistribution&specimenIdKey=";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SIMPLE_QUERY_MAP = "simpleQueryMap";
public static final String SIMPLE_QUERY_ALIAS_NAME = "simpleQueryAliasName";
public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
// MD : LightYellow and Green colors
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// Aarti: Constants for security parameter required
//while retrieving data from DAOs
public static final int INSECURE_RETRIEVE = 0;
public static final int CLASS_LEVEL_SECURE_RETRIEVE = 1;
public static final int OBJECT_LEVEL_SECURE_RETRIEVE = 2;
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Derive New From This Specimen", "createNew"},
{"Add Events", "eventParameters"},
{"Add More To Same Collection Group", "sameCollectionGroup"}
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Add New Specimen", "createNewSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Specimen Collection Group", "createSpecimenCollectionGroup"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String COLLECTION_PROTOCOL ="CollectionProtocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITION_NODES_MAP = "advancedConditionNodesMap";
public static final String TREE_VECTOR = "treeVector";
public static final String ADVANCED_CONDITIONS_ROOT = "advancedCondtionsRoot";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "AND";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String COLUMN_ID_MAP = "columnIdsMap";
public static final String PARENT_SPECIMEN_ID_COLUMN = "PARENT_SPECIMEN_ID";
public static final String COLUMN = "Column";
public static final String COLUMN_DISPLAY_NAMES = "columnDisplayNames";
public static final String PAGEOF_PARTICIPANT_QUERY= "pageOfParticipantQuery";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY= "pageOfCollectionProtocolQuery";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY= "pageOfSpecimenCollectionGroupQuery";
public static final String PAGEOF_SPECIMEN_QUERY= "pageOfSpecimenQuery";
// -- menu selection related
public static final String MENU_SELECTED = "menuSelected";
public static final String CONSTRAINT_VOILATION_ERROR = "Submission failed since a {0} with the same {1} already exists";
public static final String GENERIC_DATABASE_ERROR = "An error occured during a database operation. Please report this problem to the adminstrator";
// The unique key voilation message is "Duplicate entry %s for key %d"
// This string is used for searching " for key " string in the above error message
public static final String MYSQL_DUPL_KEY_MSG = " for key ";
public static final String CATISSUE_SPECIMEN = "CATISSUE_SPECIMEN";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String DATABASE_IN_USED = "MYSQL";
public static final String PASSWORD_CHANGE_IN_SESSION = "changepassword";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
} |
package edu.wustl.catissuecore.util.global;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String SESSION_DATA = "sessionData";
public static final String LOGOUT = "logout";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
//Sri: Changed the format for displaying in Specimen Event list (#463)
public static final String TIMESTAMP_PATTERN = "MM-dd-yyyy HH:mm";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy";
public static final String TIME_PATTERN_HH_MM_SS = "HH:mm:ss";
// Mandar: Used for Date Validations in Validator Class
public static final String DATE_SEPARATOR = "-";
public static final String DATE_SEPARATOR_DOT = ".";
public static final String DATE_SEPARATOR_SLASH = "/";
public static final String MIN_YEAR = "1900";
public static final String MAX_YEAR = "9999";
//Mysql Database constants.
/*public static final String MYSQL_DATE_PATTERN = "%m-%d-%Y";
public static final String MYSQL_TIME_PATTERN = "%H:%i:%s";
public static final String MYSQL_TIME_FORMAT_FUNCTION = "TIME_FORMAT";
public static final String MYSQL_DATE_FORMAT_FUNCTION = "DATE_FORMAT";
public static final String MYSQL_STR_TO_DATE_FUNCTION = "STR_TO_DATE";*/
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String ACCESS_DENIED = "access_denied";
public static final String REDIRECT_TO_SPECIMEN = "specimenRedirect";
public static final String CALLED_FROM = "calledFrom";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String IDENTIFIER = "IDENTIFIER";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String UPPER = "UPPER";
public static final String ERROR_DETAIL = "Error Detail";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String CSM_USER_ID = "csmUserId";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
// public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String PARTICIPANT_IDENTIFIER_IN_CPR = "participant";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
public static final String RECEIVED_QUALITY_LIST = "receivedQualityList";
//Constants for audit of disabled objects.
public static final String UPDATE_OPERATION = "UPDATE";
public static final String ACTIVITY_STATUS_COLUMN = "ACTIVITY_STATUS";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String SPECIMEN_COLLECTION_GROUP_ID = "specimenCollectionGroupId";
public static final String REQ_PATH = "redirectTo";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
public static final String SPECIMEN_TYPE_MAP = "specimenTypeMap";
//Simple Query Interface Lists
public static final String OBJECT_NAME_LIST = "objectNameList";
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String SIMPLE_QUERY_INTERFACE_TITLE = "simpleQueryInterfaceTitle";
public static final String ATTRIBUTE_NAME_LIST = "attributeNameList";
public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList";
//Constants for Storage Container.
public static final String STORAGE_CONTAINER_TYPE = "storageType";
public static final String STORAGE_CONTAINER_TO_BE_SELECTED = "storageToBeSelected";
public static final String STORAGE_CONTAINER_POSITION = "position";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
public static final int STORAGE_CONTAINER_FIRST_ROW = 1;
public static final int STORAGE_CONTAINER_FIRST_COLUMN = 1;
//event parameters lists
public static final String METHOD_LIST = "methodList";
public static final String HOUR_LIST = "hourList";
public static final String MINUTES_LIST = "minutesList";
public static final String EMBEDDING_MEDIUM_LIST = "embeddingMediumList";
public static final String PROCEDURE_LIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINER_LIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATION_LIST = "fixationList";
public static final String FROM_SITE_LIST="fromsiteList";
public static final String TO_SITE_LIST="tositeList";
public static final String ITEMLIST="itemList";
public static final String DISTRIBUTIONPROTOCOLLIST="distributionProtocolList";
public static final String TISSUE_SPECIMEN_ID_LIST="tissueSpecimenIdList";
public static final String MOLECULAR_SPECIMEN_ID_LIST="molecularSpecimenIdList";
public static final String CELL_SPECIMEN_ID_LIST="cellSpecimenIdList";
public static final String FLUID_SPECIMEN_ID_LIST="fluidSpecimenIdList";
public static final String STORAGE_STATUS_LIST="storageStatusList";
public static final String CLINICAL_DIAGNOSIS_LIST = "clinicalDiagnosisList";
public static final String HISTOLOGICAL_QUALITY_LIST="histologicalQualityList";
//For Specimen Event Parameters.
public static final String SPECIMEN_ID = "specimenId";
public static final String FROM_POSITION_DATA = "fromPositionData";
public static final String POS_ONE ="posOne";
public static final String POS_TWO ="posTwo";
public static final boolean switchSecurity = true;
public static final String STORAGE_CONTAINER_ID ="storContId";
public static final String IS_RNA = "isRNA";
public static final String RNA = "RNA";
// New Participant Event Parameters
public static final String PARTICIPANT_ID="participantId";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String APPROVE_USER_ADD_ACTION = "ApproveUserAdd.do";
public static final String APPROVE_USER_EDIT_ACTION = "ApproveUserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
public static final String USER_EDIT_PROFILE_ACTION = "UserEditProfile.do";
public static final String UPDATE_PASSWORD_ACTION = "UpdatePassword.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "ShowStorageGridView.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
//Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
public static final String DATA_VIEW_FRAME_ACTION = "SpreadsheetView.do";
public static final String SIMPLE_QUERY_INTERFACE_ACTION = "/SimpleQueryInterface.do";
public static final String SEARCH_OBJECT_ACTION = "/SearchObject.do";
public static final String SIMPLE_QUERY_INTERFACE_URL = "SimpleQueryInterface.do?pageOf=pageOfSimpleQueryInterface&menuSelected=17";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
public static final String SPECIMEN_EVENT_PARAMETERS_ACTION = "ListSpecimenEventParameters.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
//Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
//Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
//Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "receivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "receivedEventParametersEdit.do";
//Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
//Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
//Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Spreadsheet Export Action
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
};
public static final String TABLE_DATA_TABLE_NAME = "CATISSUE_QUERY_TABLE_DATA";
public static final String TABLE_DISPLAY_NAME_COLUMN = "DISPLAY_NAME";
public static final String TABLE_ALIAS_NAME_COLUMN = "ALIAS_NAME";
public static final String TABLE_FOR_SQI_COLUMN = "FOR_SQI";
public static final String TABLE_ID_COLUMN = "TABLE_ID";
public static final String TABLE_NAME_COLUMN = "TABLE_NAME";
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//TissueSite Tree View Constants.
public static final String PROPERTY_NAME = "propertyName";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Edit View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_PARTICIPANT_EDIT_ACTION = "QueryParticipantEdit.do";
public static final String QUERY_COLLECTION_PROTOCOL_SEARCH_ACTION = "QueryCollectionProtocolSearch.do?systemIdentifier=";
public static final String QUERY_COLLECTION_PROTOCOL_EDIT_ACTION = "QueryCollectionProtocolEdit.do";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "QuerySpecimenCollectionGroupSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "QuerySpecimenCollectionGroupEdit.do";
public static final String QUERY_SPECIMEN_SEARCH_ACTION = "QuerySpecimenSearch.do?systemIdentifier=";
public static final String QUERY_SPECIMEN_EDIT_ACTION = "QuerySpecimenEdit.do";
//public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
public static final String CONFIGURED_SELECT_COLUMN_LIST = "configuredSelectColumnList";
public static final String CONFIGURED_COLUMN_DISPLAY_NAMES = "configuredColumnDisplayNames";
public static final String CONFIGURED_COLUMN_NAMES = "configuredColumnNames";
public static final String SELECTED_NODE = "selectedNode";
//Tree Data Action
public static final String TREE_DATA_ACTION = "Data.do";
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String COLLECTION_PROTOCOL_REGISTRATION = "CollectionProtocolRegistration";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//SimpleSearchAction
public static final String SIMPLE_QUERY_NO_RESULTS = "noResults";
public static final String SIMPLE_QUERY_SINGLE_RESULT = "singleResult";
//For getting the tables for Simple Query and Fcon Query.
public static final int SIMPLE_QUERY_TABLES = 1;
public static final int ADVANCE_QUERY_TABLES = 2;
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTED_PROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 38;
public static final int SHOPPING_CART_FORM_ID = 39;
public static final int SIMPLE_QUERY_INTERFACE_ID = 40;
public static final int CONFIGURE_RESULT_VIEW_ID = 41;
public static final int ADVANCE_QUERY_INTERFACE_ID = 42;
public static final int QUERY_INTERFACE_ID = 43;
//Misc
public static final String SEPARATOR = " : ";
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
public static final String ACTIVITY_STATUS_DISABLED = "Disabled";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Tree View Constants.
public static final String ROOT = "Root";
public static final String CATISSUE_CORE = "caTISSUE Core";
public static final String TISSUE_SITE = "Tissue Site";
public static final int TISSUE_SITE_TREE_ID = 1;
public static final int STORAGE_CONTAINER_TREE_ID = 2;
public static final int QUERY_RESULTS_TREE_ID = 3;
//Edit Object Constants.
public static final String TABLE_ALIAS_NAME = "aliasName";
public static final String FIELD_TYPE_VARCHAR = "varchar";
public static final String FIELD_TYPE_BIGINT = "bigint";
public static final String FIELD_TYPE_DATE = "date";
public static final String FIELD_TYPE_TIMESTAMP_TIME = "timestamptime";
public static final String FIELD_TYPE_TIMESTAMP_DATE = "timestampdate";
public static final String FIELD_TYPE_TEXT = "text";
public static final String FIELD_TYPE_TINY_INT = "tinyint";
public static final String CONDITION_VALUE_YES = "yes";
public static final String TINY_INT_VALUE_ONE = "1";
public static final String TINY_INT_VALUE_ZERO = "0";
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
public static final String PAGEOF_USER_PROFILE = "pageOfUserProfile";
public static final String PAGEOF_CHANGE_PASSWORD = "pageOfChangePassword";
//For Tree Applet
public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults";
public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation";
public static final String PAGEOF_SPECIMEN = "pageOfSpecimen";
public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite";
public static final String CDE_NAME = "cdeName";
//For Simple Query Interface and Edit.
public static final String PAGEOF_SIMPLE_QUERY_INTERFACE = "pageOfSimpleQueryInterface";
public static final String PAGEOF_EDIT_OBJECT = "pageOfEditObject";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_ID = "COLLECTION_PROTOCOL_ID";
public static final String QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID = "COLLECTION_PROTOCOL_EVENT_ID";
public static final String QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID = "SPECIMEN_COLLECTION_GROUP_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SPECIMEN_TYPE = "SPECIMEN_TYPE";
// Assign Privilege Constants.
public static final boolean PRIVILEGE_ASSIGN = true;
public static final boolean PRIVILEGE_DEASSIGN = false;
public static final String OPERATION_DISALLOW = "Disallow";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {
// QUERY_RESULTS_PARTICIPANT_ID,QUERY_RESULTS_COLLECTION_PROTOCOL_ID,
// QUERY_RESULTS_COLLECTION_PROTOCOL_EVENT_ID,QUERY_RESULTS_SPECIMEN_COLLECTION_GROUP_ID,
// QUERY_RESULTS_SPECIMEN_ID,QUERY_RESULTS_SPECIMEN_TYPE
"IDENTIFIER","TYPE","ONE_DIMENSION_LABEL"
};
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
public static final String TREE_APPLET_NAME = "treeApplet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final int SELECT_OPTION_VALUE = -1;
// public static final String[] TISSUE_SITE_ARRAY = {
// SELECT_OPTION,"Sex","male","female",
// "Tissue","kidney","Left kidney","Right kidney"
public static final String[] ATTRIBUTE_NAME_ARRAY = {
SELECT_OPTION
};
public static final String[] ATTRIBUTE_CONDITION_ARRAY = {
"=","<",">"
};
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed",
"Disabled"
};
public static final String [] SITE_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] USER_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
public static final String TISSUE = "Tissue";
public static final String FLUID = "Fluid";
public static final String CELL = "Cell";
public static final String MOLECULAR = "Molecular";
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
TISSUE,
FLUID,
CELL,
MOLECULAR
};
public static final String [] HOUR_ARRAY = {
"00",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTES_ARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cell count";
public static final String UNIT_MG = "g";
public static final String UNIT_CN = "count";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final String CDE_NAME_TISSUE_SITE = "Tissue Site";
public static final String CDE_NAME_CLINICAL_STATUS = "Clinical Status";
public static final String CDE_NAME_GENDER = "Gender";
public static final String CDE_NAME_GENOTYPE = "Genotype";
public static final String CDE_NAME_SPECIMEN_CLASS = "Specimen";
public static final String CDE_NAME_SPECIMEN_TYPE = "Specimen Type";
public static final String CDE_NAME_TISSUE_SIDE = "Tissue Side";
public static final String CDE_NAME_PATHOLOGICAL_STATUS = "Pathological Status";
public static final String CDE_NAME_RECEIVED_QUALITY = "Received Quality";
public static final String CDE_NAME_FIXATION_TYPE = "Fixation Type";
public static final String CDE_NAME_COLLECTION_PROCEDURE = "Collection Procedure";
public static final String CDE_NAME_CONTAINER = "Container";
public static final String CDE_NAME_METHOD = "Method";
public static final String CDE_NAME_EMBEDDING_MEDIUM = "Embedding Medium";
public static final String CDE_NAME_BIOHAZARD = "Biohazard";
public static final String CDE_NAME_ETHNICITY = "Ethnicity";
public static final String CDE_NAME_RACE = "Race";
public static final String CDE_NAME_CLINICAL_DIAGNOSIS = "Clinical Diagnosis";
public static final String CDE_NAME_SITE_TYPE = "Site Type";
public static final String CDE_NAME_COUNTRY_LIST = "Countries";
public static final String CDE_NAME_STATE_LIST = "States";
public static final String CDE_NAME_HISTOLOGICAL_QUALITY = "Histological Quality";
//Constants for Advanced Search
public static final String STRING_OPERATORS = "StringOperators";
public static final String DATE_NUMERIC_OPERATORS = "DateNumericOperators";
public static final String ENUMERATED_OPERATORS = "EnumeratedOperators";
public static final String MULTI_ENUMERATED_OPERATORS = "MultiEnumeratedOperators";
public static final String [] STORAGE_STATUS_ARRAY = {
SELECT_OPTION,
"CHECK IN",
"CHECK OUT"
};
public static final String [] CLINICALDIAGNOSISARRAY = {
SELECT_OPTION,
"CLINICALDIAGNOSIS 1",
"CLINICALDIAGNOSIS 2",
"CLINICALDIAGNOSIS 3"
};
public static final String [] HISTOLOGICAL_QUALITY_ARRAY = {
SELECT_OPTION,
"GOOD",
"OK",
"DAMAGED"
};
// constants for Data required in query
public static final String ALIAS_NAME_TABLE_NAME_MAP="objectTableNames";
public static final String SYSTEM_IDENTIFIER = "systemIdentifier";
public static final String SYSTEM_IDENTIFIER_COLUMN_NAME = "IDENTIFIER";
public static final String NAME = "name";
public static final String EVENT_PARAMETERS[] = { Constants.SELECT_OPTION,
"Cell Specimen Review", "Check In Check Out", "Collection",
"Disposal", "Embedded", "Fixed", "Fluid Specimen Review",
"Frozen", "Molecular Specimen Review", "Procedure", "Received",
"Spun", "Thaw", "Tissue Specimen Review", "Transfer" };
public static final String EVENT_PARAMETERS_COLUMNS[] = { "Identifier",
"Event Parameter", "User", "Date / Time", "PageOf"};
public static final String [] SHOPPING_CART_COLUMNS = {"","Identifier",
"Type", "Subtype", "Tissue Site", "Tissue Side", "Pathological Status"};
public static final String ACCESS_DENIED_ADMIN = "access_denied_admin";
public static final String ACCESS_DENIED_BIOSPECIMEN = "access_denied_biospecimen";
//Constants required in AssignPrivileges.jsp
public static final String ASSIGN = "assignOperation";
public static final String PRIVILEGES = "privileges";
public static final String OBJECT_TYPES = "objectTypes";
public static final String OBJECT_TYPE_VALUES = "objectTypeValues";
public static final String RECORD_IDS = "recordIds";
public static final String ATTRIBUTES = "attributes";
public static final String GROUPS = "groups";
public static final String USERS_FOR_USE_PRIVILEGE = "usersForUsePrivilege";
public static final String USERS_FOR_READ_PRIVILEGE = "usersForReadPrivilege";
public static final String ASSIGN_PRIVILEGES_ACTION = "AssignPrivileges.do";
public static final int CONTAINER_IN_ANOTHER_CONTAINER = 2;
/**
* @param systemIdentifier
* @return
*/
public static String getUserPGName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
/**
* @param systemIdentifier
* @return
*/
public static String getUserGroupName(Long identifier)
{
if(identifier == null)
{
return "USER_";
}
return "USER_"+identifier;
}
public static final String SLIDE = "Slide";
public static final String PARAFFIN_BLOCK = "Paraffin Block";
public static final String FROZEN_BLOCK = "Frozen Block";
// constants required for Distribution Report
public static final String CONFIGURATION_TABLES = "configurationTables";
public static final String DISTRIBUTION_TABLE_AlIAS[] = {"CollectionProtReg","Participant","Specimen",
"SpecimenCollectionGroup","DistributedItem"};
public static final String TABLE_COLUMN_DATA_MAP = "tableColumnDataMap";
public static final String CONFIGURE_RESULT_VIEW_ACTION = "ConfigureResultView.do";
public static final String TABLE_NAMES_LIST = "tableNamesList";
public static final String COLUMN_NAMES_LIST = "columnNamesList";
public static final String DISTRIBUTION_ID = "distributionId";
public static final String CONFIGURE_DISTRIBUTION_ACTION = "ConfigureDistribution.do";
public static final String DISTRIBUTION_REPORT_ACTION = "DistributionReport.do";
public static final String DISTRIBUTION_REPORT_SAVE_ACTION="DistributionReportSave.do";
public static final String SELECTED_COLUMNS[] = {"Specimen.IDENTIFIER.Identifier : Specimen",
"Specimen.TYPE.Type : Specimen",
"SpecimenCharacteristics.TISSUE_SITE.Tissue Site : Specimen",
"SpecimenCharacteristics.TISSUE_SIDE.Tissue Side : Specimen",
"SpecimenCharacteristics.PATHOLOGICAL_STATUS.Pathological Status : Specimen",
"DistributedItem.QUANTITY.Quantity : Distribution"};
public static final String SPECIMEN_ID_LIST = "specimenIdList";
public static final String DISTRIBUTION_ACTION = "Distribution.do?pageOf=pageOfDistribution";
public static final String DISTRIBUTION_REPORT_NAME = "Distribution Report.csv";
public static final String DISTRIBUTION_REPORT_FORM="distributionReportForm";
public static final String DISTRIBUTED_ITEMS_DATA = "distributedItemsData";
public static final String DISTRIBUTED_ITEM = "DistributedItem";
//constants for Simple Query Interface Configuration
public static final String CONFIGURE_SIMPLE_QUERY_ACTION = "ConfigureSimpleQuery.do";
public static final String CONFIGURE_SIMPLE_QUERY_VALIDATE_ACTION = "ConfigureSimpleQueryValidate.do";
public static final String CONFIGURE_SIMPLE_SEARCH_ACTION = "ConfigureSimpleSearch.do";
public static final String SIMPLE_SEARCH_ACTION = "SimpleSearch.do";
public static final String SIMPLE_SEARCH_AFTER_CONFIGURE_ACTION = "SimpleSearchAfterConfigure.do";
public static final String PAGEOF_DISTRIBUTION = "pageOfDistribution";
public static final String RESULT_VIEW_VECTOR = "resultViewVector";
public static final String SIMPLE_QUERY_MAP = "simpleQueryMap";
public static final String SIMPLE_QUERY_ALIAS_NAME = "simpleQueryAliasName";
public static final String SIMPLE_QUERY_COUNTER = "simpleQueryCount";
public static final String IDENTIFIER_FIELD_INDEX = "identifierFieldIndex";
public static final String UNDEFINED = "Undefined";
public static final String UNKNOWN = "Unknown";
public static final String SEARCH_RESULT = "SearchResult.csv";
// MD : LightYellow and Green colors for CollectionProtocol SpecimenRequirements. Bug id: 587
// public static final String ODD_COLOR = "#FEFB85";
// public static final String EVEN_COLOR = "#A7FEAB";
// Light and dark shades of GREY.
public static final String ODD_COLOR = "#E5E5E5";
public static final String EVEN_COLOR = "#F7F7F7";
// TO FORWARD THE REQUEST ON SUBMIT IF STATUS IS DISABLED
public static final String BIO_SPECIMEN = "/ManageBioSpecimen.do";
public static final String ADMINISTRATIVE = "/ManageAdministrativeData.do";
public static final String PARENT_SPECIMEN_ID = "parentSpecimenId";
public static final String COLLECTION_REGISTRATION_ID = "collectionProtocolId";
public static final String FORWARDLIST = "forwardToList";
public static final String [][] SPECIMEN_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Derive New From This Specimen", "createNew"},
{"Add Events", "eventParameters"},
{"Add More To Same Collection Group", "sameCollectionGroup"}
};
public static final String [][] SPECIMEN_COLLECTION_GROUP_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"Add New Specimen", "createNewSpecimen"}
};
public static final String [][] PROTOCOL_REGISTRATION_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Specimen Collection Group", "createSpecimenCollectionGroup"}
};
public static final String [][] PARTICIPANT_FORWARD_TO_LIST = {
{"Normal Submit", "success"},
{"New Participant Registration", "createParticipantRegistration"}
};
//Constants Required for Advance Search
//Tree related
//public static final String PARTICIPANT ='Participant';
public static final String MENU_COLLECTION_PROTOCOL ="Collection Protocol";
public static final String MENU_SPECIMEN_COLLECTION_GROUP ="Specimen Collection Group";
public static final String MENU_DISTRIBUTION_PROTOCOL = "Distribution Protocol";
public static final String COLLECTION_PROTOCOL ="CollectionProtocol";
public static final String SPECIMEN_COLLECTION_GROUP ="SpecimenCollectionGroup";
public static final String DISTRIBUTION = "Distribution";
public static final String DISTRIBUTION_PROTOCOL = "DistributionProtocol";
public static final String CP = "CP";
public static final String SCG = "SCG";
public static final String D = "D";
public static final String DP = "DP";
public static final String C = "C";
public static final String S = "S";
public static final String P = "P";
public static final String ADVANCED_CONDITION_NODES_MAP = "advancedConditionNodesMap";
public static final String TREE_VECTOR = "treeVector";
public static final String ADVANCED_CONDITIONS_ROOT = "advancedCondtionsRoot";
public static final String ADVANCED_CONDITIONS_QUERY_VIEW = "advancedCondtionsQueryView";
public static final String ADVANCED_SEARCH_ACTION = "AdvanceSearch.do";
public static final String ADVANCED_SEARCH_RESULTS_ACTION = "AdvanceSearchResults.do";
public static final String CONFIGURE_ADVANCED_SEARCH_RESULTS_ACTION = "ConfigureAdvanceSearchResults.do";
public static final String PAGEOF_ADVANCE_QUERY_INTERFACE = "pageOfAdvanceQueryInterface";
public static final String ADVANCED_QUERY_ADD = "Add";
public static final String ADVANCED_QUERY_EDIT = "Edit";
public static final String ADVANCED_QUERY_DELETE = "Delete";
public static final String ADVANCED_QUERY_OPERATOR = "Operator";
public static final String ADVANCED_QUERY_OR = "OR";
public static final String ADVANCED_QUERY_AND = "pAND";
public static final String EVENT_CONDITIONS = "eventConditions";
public static final String IDENTIFIER_COLUMN_ID_MAP = "identifierColumnIdsMap";
public static final String COLUMN_ID_MAP = "columnIdsMap";
public static final String PARENT_SPECIMEN_ID_COLUMN = "PARENT_SPECIMEN_ID";
public static final String COLUMN = "Column";
public static final String COLUMN_DISPLAY_NAMES = "columnDisplayNames";
public static final String PAGEOF_PARTICIPANT_QUERY_EDIT= "pageOfParticipantQueryEdit";
public static final String PAGEOF_COLLECTION_PROTOCOL_QUERY_EDIT= "pageOfCollectionProtocolQueryEdit";
public static final String PAGEOF_SPECIMEN_COLLECTION_GROUP_QUERY_EDIT= "pageOfSpecimenCollectionGroupQueryEdit";
public static final String PAGEOF_SPECIMEN_QUERY_EDIT= "pageOfSpecimenQueryEdit";
public static final String PARTICIPANT_COLUMNS = "particpantColumns";
public static final String COLLECTION_PROTOCOL_COLUMNS = "collectionProtocolColumns";
public static final String SPECIMEN_COLLECTION_GROUP_COLUMNS = "SpecimenCollectionGroupColumns";
public static final String SPECIMEN_COLUMNS = "SpecimenColumns";
public static final String USER_ID_COLUMN = "USER_ID";
// -- menu selection related
public static final String MENU_SELECTED = "menuSelected";
public static final String CONSTRAINT_VOILATION_ERROR = "Submission failed since a {0} with the same {1} already exists";
public static final String GENERIC_DATABASE_ERROR = "An error occured during a database operation. Please report this problem to the adminstrator";
public static final String OBJECT_NOT_FOUND_ERROR = "Submission failed since a {0} with given {1}: \"{2}\" does not exists";
// The unique key voilation message is "Duplicate entry %s for key %d"
// This string is used for searching " for key " string in the above error message
public static final String MYSQL_DUPL_KEY_MSG = " for key ";
public static final String GENERIC_SECURITYMANAGER_ERROR = "The Security Violation error occured during a database operation. Please report this problem to the adminstrator";
public static final String ORACLE_DATABASE = "ORACLE";
public static final String MYSQL_DATABASE = "MYSQL";
public static final String PASSWORD_CHANGE_IN_SESSION = "changepassword";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String PACKAGE_DOMAIN = "edu.wustl.catissuecore.domain";
//Constants for isAuditable and isSecureUpdate required for Dao methods in Bozlogic
public static final boolean IS_AUDITABLE_TRUE = true;
public static final boolean IS_SECURE_UPDATE_TRUE = true;
public static final boolean HAS_OBJECT_LEVEL_PRIVILEGE_FALSE = false;
//Constants for HTTP-API
public static final String CONTENT_TYPE = "CONTENT-TYPE";
public static final String HTTP_API = "HTTPAPI";
// For StorageContainer isFull status
public static final String IS_CONTAINER_FULL_LIST = "isContainerFullList";
public static final String [] IS_CONTAINER_FULL_VALUES = {
SELECT_OPTION,
"True",
"False"
};
public static final String STORAGE_CONTAINER_DIM_ONE_LABEL = "oneDimLabel";
public static final String STORAGE_CONTAINER_DIM_TWO_LABEL = "twoDimLabel";
public static final String NULL = "NULL";
// public static final String SPECIMEN_TYPE_TISSUE = "Tissue";
// public static final String SPECIMEN_TYPE_FLUID = "Fluid";
// public static final String SPECIMEN_TYPE_CELL = "Cell";
// public static final String SPECIMEN_TYPE_MOL = "Molecular";
public static final String SPECIMEN_TYPE_COUNT = "Count";
public static final String SPECIMEN_TYPE_QUANTITY = "Quantity";
public static final String SPECIMEN_TYPE_DETAILS = "Details";
public static final String SPECIMEN_COUNT = "totalSpecimenCount";
public static final String TOTAL = "Total";
public static final String SPECIMENS = "Specimens";
//User Roles
public static final String ADMINISTRATOR = "Administrator";
public static final String TECHNICIAN = "Technician";
public static final String SUPERVISOR = "Supervisor";
public static final String SCIENTIST = "Scientist";
// for Add New
public static final String ADD_NEW_STORAGE_TYPE_ID ="addNewStorageTypeId";
public static final String ADD_NEW_COLLECTION_PROTOCOL_ID ="addNewCollectionProtocolId";
public static final String ADD_NEW_SITE_ID ="addNewSiteId";
public static final String ADD_NEW_USER_ID ="addNewUserId";
public static final String ADD_NEW_USER_TO ="addNewUserTo";
public static final String CHILD_CONTAINER_TYPE = "childContainerType";
public static final String UNUSED = "Unused";
public static final String TYPE = "Type";
} |
package edu.wustl.catissuecore.util.global;
import java.util.HashMap;
/**
* This class stores the constants used in the operations in the application.
* @author gautam_shetty
*/
public class Constants
{
//Constants used for authentication module.
public static final String LOGIN = "login";
public static final String USER = "user";
public static final String AND_JOIN_CONDITION = "AND";
public static final String OR_JOIN_CONDITION = "OR";
public static final String DATE_PATTERN = "yyyy-MM-dd HH:mm aa";
public static final String DATE_PATTERN_YYYY_MM_DD = "yyyy-MM-dd";
public static final String DATE_PATTERN_MM_DD_YYYY = "MM-dd-yyyy";
//DAO Constants.
public static final int HIBERNATE_DAO = 1;
public static final int JDBC_DAO = 2;
public static final String SUCCESS = "success";
public static final String FAILURE = "failure";
public static final String ADD = "add";
public static final String EDIT = "edit";
public static final String VIEW = "view";
public static final String SEARCH = "search";
public static final String DELETE = "delete";
public static final String EXPORT = "export";
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
public static final String SHOPPING_CART_EXPORT = "shoppingCartExport";
public static final String NEWUSERFORM = "newUserForm";
public static final String ACCESS_DENIED = "access_denied";
//Constants required for Forgot Password
public static final String FORGOT_PASSWORD = "forgotpassword";
public static final String IDENTIFIER = "systemIdentifier";
public static final String LOGINNAME = "loginName";
public static final String LASTNAME = "lastName";
public static final String FIRSTNAME = "firstName";
public static final String ERROR_DETAIL = "Error Detail";
public static final String INSTITUTION = "institution";
public static final String EMAIL = "email";
public static final String DEPARTMENT = "department";
public static final String ADDRESS = "address";
public static final String CITY = "city";
public static final String STATE = "state";
public static final String COUNTRY = "country";
public static final String OPERATION = "operation";
public static final String ACTIVITY_STATUS = "activityStatus";
public static final String NEXT_CONTAINER_NO = "startNumber";
public static final String INSTITUTIONLIST = "institutionList";
public static final String DEPARTMENTLIST = "departmentList";
public static final String STATELIST = "stateList";
public static final String COUNTRYLIST = "countryList";
public static final String ROLELIST = "roleList";
public static final String ROLEIDLIST = "roleIdList";
public static final String CANCER_RESEARCH_GROUP_LIST = "cancerResearchGroupList";
public static final String GENDER_LIST = "genderList";
public static final String GENOTYPE_LIST = "genotypeList";
public static final String ETHNICITY_LIST = "ethnicityList";
public static final String PARTICIPANT_MEDICAL_RECORD_SOURCE_LIST = "participantMedicalRecordSourceList";
public static final String RACELIST = "raceList";
public static final String PARTICIPANT_LIST = "participantList";
public static final String PARTICIPANT_ID_LIST = "participantIdList";
public static final String PROTOCOL_LIST = "protocolList";
public static final String TIMEHOURLIST = "timeHourList";
public static final String TIMEMINUTESLIST = "timeMinutesList";
public static final String TIMEAMPMLIST = "timeAMPMList";
public static final String RECEIVEDBYLIST = "receivedByList";
public static final String COLLECTEDBYLIST = "collectedByList";
public static final String COLLECTIONSITELIST = "collectionSiteList";
public static final String RECEIVEDSITELIST = "receivedSiteList";
public static final String RECEIVEDMODELIST = "receivedModeList";
public static final String ACTIVITYSTATUSLIST = "activityStatusList";
public static final String USERLIST = "userList";
public static final String SITETYPELIST = "siteTypeList";
public static final String STORAGETYPELIST="storageTypeList";
public static final String STORAGECONTAINERLIST="storageContainerList";
public static final String SITELIST="siteList";
public static final String SITEIDLIST="siteIdList";
public static final String USERIDLIST = "userIdList";
public static final String STORAGETYPEIDLIST="storageTypeIdList";
public static final String SPECIMENCOLLECTIONLIST="specimentCollectionList";
public static final String APPROVE_USER_STATUS_LIST = "statusList";
//New Specimen lists.
public static final String SPECIMEN_COLLECTION_GROUP_LIST = "specimenCollectionGroupIdList";
public static final String SPECIMEN_TYPE_LIST = "specimenTypeList";
public static final String SPECIMEN_SUB_TYPE_LIST = "specimenSubTypeList";
public static final String TISSUE_SITE_LIST = "tissueSiteList";
public static final String TISSUE_SIDE_LIST = "tissueSideList";
public static final String PATHOLOGICAL_STATUS_LIST = "pathologicalStatusList";
public static final String BIOHAZARD_TYPE_LIST = "biohazardTypeList";
public static final String BIOHAZARD_NAME_LIST = "biohazardNameList";
public static final String BIOHAZARD_ID_LIST = "biohazardIdList";
public static final String BIOHAZARD_TYPES_LIST = "biohazardTypesList";
public static final String PARENT_SPECIMEN_ID_LIST = "parentSpecimenIdList";
//SpecimenCollecionGroup lists.
public static final String PROTOCOL_TITLE_LIST = "protocolTitleList";
public static final String PARTICIPANT_NAME_LIST = "participantNameList";
public static final String PROTOCOL_PARTICIPANT_NUMBER_LIST = "protocolParticipantNumberList";
//public static final String PROTOCOL_PARTICIPANT_NUMBER_ID_LIST = "protocolParticipantNumberIdList";
public static final String STUDY_CALENDAR_EVENT_POINT_LIST = "studyCalendarEventPointList";
//public static final String STUDY_CALENDAR_EVENT_POINT_ID_LIST="studyCalendarEventPointIdList";
public static final String PARTICIPANT_MEDICAL_IDNETIFIER_LIST = "participantMedicalIdentifierArray";
//public static final String PARTICIPANT_MEDICAL_IDNETIFIER_ID_LIST = "participantMedicalIdentifierIdArray";
public static final String CLINICAL_STATUS_LIST = "cinicalStatusList";
public static final String SPECIMEN_CLASS_LIST = "specimenClassList";
public static final String SPECIMEN_CLASS_ID_LIST = "specimenClassIdList";
//Simple Query Interface Lists
public static final String OBJECT_NAME_LIST = "objectNameList";
public static final String OBJECT_COMPLETE_NAME_LIST = "objectCompleteNameList";
public static final String ATTRIBUTE_NAME_LIST = "attributeNameList";
public static final String ATTRIBUTE_CONDITION_LIST = "attributeConditionList";
//Constants for Storage Container.
public static final String STORAGE_CONTAINER_TYPE = "storageType";
public static final String STORAGE_CONTAINER_GRID_OBJECT = "storageContainerGridObject";
public static final String STORAGE_CONTAINER_CHILDREN_STATUS = "storageContainerChildrenStatus";
public static final String START_NUMBER = "startNumber";
public static final String CHILD_CONTAINER_SYSTEM_IDENTIFIERS = "childContainerSystemIdentifiers";
//event parameters lists
public static final String METHODLIST = "methodList";
public static final String HOURLIST = "hourList";
public static final String MINUTESLIST = "minutesList";
public static final String EMBEDDINGMEDIUMLIST = "embeddingMediumList";
public static final String PROCEDURELIST = "procedureList";
public static final String PROCEDUREIDLIST = "procedureIdList";
public static final String CONTAINERLIST = "containerList";
public static final String CONTAINERIDLIST = "containerIdList";
public static final String FROMCONTAINERLIST="fromContainerList";
public static final String TOCONTAINERLIST="toContainerList";
public static final String FIXATIONLIST = "fixationList";
public static final String FROMSITELIST="fromsiteList";
public static final String TOSITELIST="tositeList";
public static final String ITEMLIST="itemList";
//Constants required in User.jsp Page
public static final String USER_SEARCH_ACTION = "UserSearch.do";
public static final String USER_ADD_ACTION = "UserAdd.do";
public static final String USER_EDIT_ACTION = "UserEdit.do";
public static final String SIGNUP_USER_ADD_ACTION = "SignUpUserAdd.do";
//Constants required in Accession.jsp Page
public static final String ACCESSION_SEARCH_ACTION = "AccessionSearch.do";
public static final String ACCESSION_ADD_ACTION = "AccessionAdd.do";
public static final String ACCESSION_EDIT_ACTION = "AccessionEdit.do";
//Constants required in StorageType.jsp Page
public static final String STORAGE_TYPE_SEARCH_ACTION = "StorageTypeSearch.do";
public static final String STORAGE_TYPE_ADD_ACTION = "StorageTypeAdd.do";
public static final String STORAGE_TYPE_EDIT_ACTION = "StorageTypeEdit.do";
//Constants required in StorageContainer.jsp Page
public static final String STORAGE_CONTAINER_SEARCH_ACTION = "StorageContainerSearch.do";
public static final String STORAGE_CONTAINER_ADD_ACTION = "StorageContainerAdd.do";
public static final String STORAGE_CONTAINER_EDIT_ACTION = "StorageContainerEdit.do";
public static final String SHOW_STORAGE_CONTAINER_GRID_VIEW_ACTION = "/catissuecore/ShowStorageGridView.do";
//Constants required in Site.jsp Page
public static final String SITE_SEARCH_ACTION = "SiteSearch.do";
public static final String SITE_ADD_ACTION = "SiteAdd.do";
public static final String SITE_EDIT_ACTION = "SiteEdit.do";
// Constants required in Site.jsp Page
public static final String BIOHAZARD_SEARCH_ACTION = "BiohazardSearch.do";
public static final String BIOHAZARD_ADD_ACTION = "BiohazardAdd.do";
public static final String BIOHAZARD_EDIT_ACTION = "BiohazardEdit.do";
//Constants required in Partcipant.jsp Page
public static final String PARTICIPANT_SEARCH_ACTION = "ParticipantSearch.do";
public static final String PARTICIPANT_ADD_ACTION = "ParticipantAdd.do";
public static final String PARTICIPANT_EDIT_ACTION = "ParticipantEdit.do";
//Constants required in Institution.jsp Page
public static final String INSTITUTION_SEARCH_ACTION = "InstitutionSearch.do";
public static final String INSTITUTION_ADD_ACTION = "InstitutionAdd.do";
public static final String INSTITUTION_EDIT_ACTION = "InstitutionEdit.do";
//Constants required in Department.jsp Page
public static final String DEPARTMENT_SEARCH_ACTION = "DepartmentSearch.do";
public static final String DEPARTMENT_ADD_ACTION = "DepartmentAdd.do";
public static final String DEPARTMENT_EDIT_ACTION = "DepartmentEdit.do";
//Constants required in CollectionProtocolRegistration.jsp Page
public static final String COLLECTION_PROTOCOL_REGISTRATION_SEARCH_ACTION = "CollectionProtocolRegistrationSearch.do";
public static final String COLLECTIONP_ROTOCOL_REGISTRATION_ADD_ACTION = "CollectionProtocolRegistrationAdd.do";
public static final String COLLECTION_PROTOCOL_REGISTRATION_EDIT_ACTION = "CollectionProtocolRegistrationEdit.do";
//Constants required in CancerResearchGroup.jsp Page
public static final String CANCER_RESEARCH_GROUP_SEARCH_ACTION = "CancerResearchGroupSearch.do";
public static final String CANCER_RESEARCH_GROUP_ADD_ACTION = "CancerResearchGroupAdd.do";
public static final String CANCER_RESEARCH_GROUP_EDIT_ACTION = "CancerResearchGroupEdit.do";
//Constants required for Approve user
public static final String USER_DETAILS_SHOW_ACTION = "UserDetailsShow.do";
public static final String APPROVE_USER_SHOW_ACTION = "ApproveUserShow.do";
//Reported Problem Constants
public static final String REPORTED_PROBLEM_ADD_ACTION = "ReportedProblemAdd.do";
public static final String REPORTED_PROBLEM_EDIT_ACTION = "ReportedProblemEdit.do";
public static final String PROBLEM_DETAILS_ACTION = "ProblemDetails.do";
public static final String REPORTED_PROBLEM_SHOW_ACTION = "ReportedProblemShow.do";
//Query Results view Actions
public static final String TREE_VIEW_ACTION = "TreeView.do";
//New Specimen Data Actions.
public static final String SPECIMEN_ADD_ACTION = "NewSpecimenAdd.do";
public static final String SPECIMEN_EDIT_ACTION = "NewSpecimenEdit.do";
public static final String SPECIMEN_SEARCH_ACTION = "NewSpecimenSearch.do";
//Create Specimen Data Actions.
public static final String CREATE_SPECIMEN_ADD_ACTION = "CreateSpecimenAdd.do";
public static final String CREATE_SPECIMEN_EDIT_ACTION = "CreateSpecimenEdit.do";
public static final String CREATE_SPECIMEN_SEARCH_ACTION = "CreateSpecimenSearch.do";
//ShoppingCart Actions.
public static final String SHOPPING_CART_OPERATION = "ShoppingCartOperation.do";
public static final String SPECIMEN_COLLECTION_GROUP_SEARCH_ACTION = "SpecimenCollectionGroup.do";
public static final String SPECIMEN_COLLECTION_GROUP_ADD_ACTION = "SpecimenCollectionGroupAdd.do";
public static final String SPECIMEN_COLLECTION_GROUP_EDIT_ACTION = "SpecimenCollectionGroupEdit.do";
// Constants required in FrozenEventParameters.jsp Page
public static final String FROZEN_EVENT_PARAMETERS_SEARCH_ACTION = "FrozenEventParametersSearch.do";
public static final String FROZEN_EVENT_PARAMETERS_ADD_ACTION = "FrozenEventParametersAdd.do";
public static final String FROZEN_EVENT_PARAMETERS_EDIT_ACTION = "FrozenEventParametersEdit.do";
// Constants required in CheckInCheckOutEventParameters.jsp Page
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_SEARCH_ACTION = "CheckInCheckOutEventParametersSearch.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_ADD_ACTION = "CheckInCheckOutEventParametersAdd.do";
public static final String CHECKIN_CHECKOUT_EVENT_PARAMETERS_EDIT_ACTION = "CheckInCheckOutEventParametersEdit.do";
// Constants required in ReceivedEventParameters.jsp Page
public static final String RECEIVED_EVENT_PARAMETERS_SEARCH_ACTION = "ReceivedEventParametersSearch.do";
public static final String RECEIVED_EVENT_PARAMETERS_ADD_ACTION = "ReceivedEventParametersAdd.do";
public static final String RECEIVED_EVENT_PARAMETERS_EDIT_ACTION = "ReceivedEventParametersEdit.do";
// Constants required in FluidSpecimenReviewEventParameters.jsp Page
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "FluidSpecimenReviewEventParametersSearch.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "FluidSpecimenReviewEventParametersAdd.do";
public static final String FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "FluidSpecimenReviewEventParametersEdit.do";
// Constants required in CELLSPECIMENREVIEWParameters.jsp Page
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "CellSpecimenReviewParametersSearch.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "CellSpecimenReviewParametersAdd.do";
public static final String CELL_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "CellSpecimenReviewParametersEdit.do";
// Constants required in tissue SPECIMEN REVIEW event Parameters.jsp Page
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_SEARCH_ACTION = "TissueSpecimenReviewEventParametersSearch.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_ADD_ACTION = "TissueSpecimenReviewEventParametersAdd.do";
public static final String TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_EDIT_ACTION = "TissueSpecimenReviewEventParametersEdit.do";
// Constants required in DisposalEventParameters.jsp Page
public static final String DISPOSAL_EVENT_PARAMETERS_SEARCH_ACTION = "DisposalEventParametersSearch.do";
public static final String DISPOSAL_EVENT_PARAMETERS_ADD_ACTION = "DisposalEventParametersAdd.do";
public static final String DISPOSAL_EVENT_PARAMETERS_EDIT_ACTION = "DisposalEventParametersEdit.do";
// Constants required in ThawEventParameters.jsp Page
public static final String THAW_EVENT_PARAMETERS_SEARCH_ACTION = "ThawEventParametersSearch.do";
public static final String THAW_EVENT_PARAMETERS_ADD_ACTION = "ThawEventParametersAdd.do";
public static final String THAW_EVENT_PARAMETERS_EDIT_ACTION = "ThawEventParametersEdit.do";
// Constants required in MOLECULARSPECIMENREVIEWParameters.jsp Page
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_SEARCH_ACTION = "MolecularSpecimenReviewParametersSearch.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_ADD_ACTION = "MolecularSpecimenReviewParametersAdd.do";
public static final String MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_EDIT_ACTION = "MolecularSpecimenReviewParametersEdit.do";
// Constants required in CollectionEventParameters.jsp Page
public static final String COLLECTION_EVENT_PARAMETERS_SEARCH_ACTION = "CollectionEventParametersSearch.do";
public static final String COLLECTION_EVENT_PARAMETERS_ADD_ACTION = "CollectionEventParametersAdd.do";
public static final String COLLECTION_EVENT_PARAMETERS_EDIT_ACTION = "CollectionEventParametersEdit.do";
// Constants required in SpunEventParameters.jsp Page
public static final String SPUN_EVENT_PARAMETERS_SEARCH_ACTION = "SpunEventParametersSearch.do";
public static final String SPUN_EVENT_PARAMETERS_ADD_ACTION = "SpunEventParametersAdd.do";
public static final String SPUN_EVENT_PARAMETERS_EDIT_ACTION = "SpunEventParametersEdit.do";
// Constants required in EmbeddedEventParameters.jsp Page
public static final String EMBEDDED_EVENT_PARAMETERS_SEARCH_ACTION = "EmbeddedEventParametersSearch.do";
public static final String EMBEDDED_EVENT_PARAMETERS_ADD_ACTION = "EmbeddedEventParametersAdd.do";
public static final String EMBEDDED_EVENT_PARAMETERS_EDIT_ACTION = "EmbeddedEventParametersEdit.do";
// Constants required in TransferEventParameters.jsp Page
public static final String TRANSFER_EVENT_PARAMETERS_SEARCH_ACTION = "TransferEventParametersSearch.do";
public static final String TRANSFER_EVENT_PARAMETERS_ADD_ACTION = "TransferEventParametersAdd.do";
public static final String TRANSFER_EVENT_PARAMETERS_EDIT_ACTION = "TransferEventParametersEdit.do";
// Constants required in FixedEventParameters.jsp Page
public static final String FIXED_EVENT_PARAMETERS_SEARCH_ACTION = "FixedEventParametersSearch.do";
public static final String FIXED_EVENT_PARAMETERS_ADD_ACTION = "FixedEventParametersAdd.do";
public static final String FIXED_EVENT_PARAMETERS_EDIT_ACTION = "FixedEventParametersEdit.do";
// Constants required in ProcedureEventParameters.jsp Page
public static final String PROCEDURE_EVENT_PARAMETERS_SEARCH_ACTION = "ProcedureEventParametersSearch.do";
public static final String PROCEDURE_EVENT_PARAMETERS_ADD_ACTION = "ProcedureEventParametersAdd.do";
public static final String PROCEDURE_EVENT_PARAMETERS_EDIT_ACTION = "ProcedureEventParametersEdit.do";
// Constants required in Distribution.jsp Page
public static final String DISTRIBUTION_SEARCH_ACTION = "DistributionSearch.do";
public static final String DISTRIBUTION_ADD_ACTION = "DistributionAdd.do";
public static final String DISTRIBUTION_EDIT_ACTION = "DistributionEdit.do";
//Levels of nodes in query results tree.
public static final int MAX_LEVEL = 5;
public static final int MIN_LEVEL = 1;
public static final String[] DEFAULT_TREE_SELECT_COLUMNS = {
Constants.QUERY_RESULTS_PARTICIPANT_ID,
Constants.QUERY_RESULTS_ACCESSION_ID,
Constants.QUERY_RESULTS_SPECIMEN_ID,
Constants.QUERY_RESULTS_SEGMENT_ID,
Constants.QUERY_RESULTS_SAMPLE_ID};
//Frame names in Query Results page.
public static final String DATA_VIEW_FRAME = "myframe1";
public static final String APPLET_VIEW_FRAME = "appletViewFrame";
//NodeSelectionlistener - Query Results Tree node selection (For spreadsheet or individual view).
public static final String DATA_VIEW_ACTION = "/catissuecore/DataView.do?nodeName=";
public static final String VIEW_TYPE = "viewType";
//Constants for type of query results view.
public static final String SPREADSHEET_VIEW = "Spreadsheet View";
public static final String OBJECT_VIEW = "Object View";
//Spreadsheet view Constants in DataViewAction.
public static final String PARTICIPANT = "Participant";
public static final String ACCESSION = "Accession";
public static final String QUERY_PARTICIPANT_SEARCH_ACTION = "QueryParticipantSearch.do?systemIdentifier=";
public static final String QUERY_ACCESSION_SEARCH_ACTION = "QueryAccessionSearch.do?systemIdentifier=";
//Individual view Constants in DataViewAction.
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
public static final String SPREADSHEET_DATA_LIST = "spreadsheetDataList";
public static final String SELECT_COLUMN_LIST = "selectColumnList";
//Tree Data Action
public static final String TREE_DATA_ACTION = "/catissuecore/Data.do";
//Constants for default column names to be shown for query result.
public static final String[] DEFAULT_SPREADSHEET_COLUMNS = {"PARTICIPANT_ID","ACCESSION_ID","SPECIMEN_ID",
"TISSUE_SITE","SPECIMEN_TYPE","SEGMENT_ID",
"SAMPLE_ID","SAMPLE_TYPE"};
public static final String SPECIMEN = "Specimen";
public static final String SEGMENT = "Segment";
public static final String SAMPLE = "Sample";
public static final String PARTICIPANT_ID_COLUMN = "PARTICIPANT_ID";
public static final String ACCESSION_ID_COLUMN = "ACCESSION_ID";
public static final String SPECIMEN_ID_COLUMN = "SPECIMEN_ID";
public static final String SEGMENT_ID_COLUMN = "SEGMENT_ID";
public static final String SAMPLE_ID_COLUMN = "SAMPLE_ID";
//Identifiers for various Form beans
public static final int USER_FORM_ID = 1;
public static final int PARTICIPANT_FORM_ID = 2;
public static final int ACCESSION_FORM_ID = 3;
public static final int REPORTEDPROBLEM_FORM_ID = 4;
public static final int INSTITUTION_FORM_ID = 5;
public static final int APPROVE_USER_FORM_ID = 6;
public static final int ACTIVITY_STATUS_FORM_ID = 7;
public static final int DEPARTMENT_FORM_ID = 8;
public static final int COLLECTION_PROTOCOL_FORM_ID = 9;
public static final int DISTRIBUTIONPROTOCOL_FORM_ID = 10;
public static final int STORAGE_CONTAINER_FORM_ID = 11;
public static final int STORAGE_TYPE_FORM_ID = 12;
public static final int SITE_FORM_ID = 13;
public static final int CANCER_RESEARCH_GROUP_FORM_ID = 14;
public static final int BIOHAZARD_FORM_ID = 15;
public static final int FROZEN_EVENT_PARAMETERS_FORM_ID = 16;
public static final int CHECKIN_CHECKOUT_EVENT_PARAMETERS_FORM_ID = 17;
public static final int RECEIVED_EVENT_PARAMETERS_FORM_ID = 18;
public static final int COLLECTION_PROTOCOL_REGISTRATION_FORM_ID = 19;
public static final int SPECIMEN_COLLECTION_GROUP_FORM_ID = 20;
public static final int FLUID_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 21;
public static final int NEW_SPECIMEN_FORM_ID = 22;
public static final int CELL_SPECIMEN_REVIEW_PARAMETERS_FORM_ID =23;
public static final int TISSUE_SPECIMEN_REVIEW_EVENT_PARAMETERS_FORM_ID = 24;
public static final int DISPOSAL_EVENT_PARAMETERS_FORM_ID = 25;
public static final int THAW_EVENT_PARAMETERS_FORM_ID = 26;
public static final int MOLECULAR_SPECIMEN_REVIEW_PARAMETERS_FORM_ID = 27;
public static final int COLLECTION_EVENT_PARAMETERS_FORM_ID = 28;
public static final int TRANSFER_EVENT_PARAMETERS_FORM_ID = 29;
public static final int SPUN_EVENT_PARAMETERS_FORM_ID = 30;
public static final int EMBEDDED_EVENT_PARAMETERS_FORM_ID = 31;
public static final int FIXED_EVENT_PARAMETERS_FORM_ID = 32;
public static final int PROCEDURE_EVENT_PARAMETERS_FORM_ID = 33;
public static final int CREATE_SPECIMEN_FORM_ID = 34;
public static final int FORGOT_PASSWORD_FORM_ID = 35;
public static final int SIGNUP_FORM_ID = 36;
public static final int DISTRIBUTION_FORM_ID = 37;
public static final int SPECIMEN_EVENT_PARAMETERS_FORM_ID = 37;
public static final int SHOPPING_CART_FORM_ID = 39;
//Misc
public static final String SEPARATOR = " : ";
//Status message key Constants
public static final String STATUS_MESSAGE_KEY = "statusMessageKey";
//Identifiers for JDBC DAO.
public static final int QUERY_RESULT_TREE_JDBC_DAO = 1;
//Activity Status values
public static final String ACTIVITY_STATUS_ACTIVE = "Active";
public static final String ACTIVITY_STATUS_APPROVE = "Approve";
public static final String ACTIVITY_STATUS_REJECT = "Reject";
public static final String ACTIVITY_STATUS_NEW = "New";
public static final String ACTIVITY_STATUS_PENDING = "Pending";
public static final String ACTIVITY_STATUS_CLOSED = "Closed";
//Approve User status values.
public static final String APPROVE_USER_APPROVE_STATUS = "Approve";
public static final String APPROVE_USER_REJECT_STATUS = "Reject";
public static final String APPROVE_USER_PENDING_STATUS = "Pending";
//Approve User Constants
public static final int ZERO = 0;
public static final int START_PAGE = 1;
public static final int NUMBER_RESULTS_PER_PAGE = 5;
public static final String PAGE_NUMBER = "pageNum";
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
public static final String TOTAL_RESULTS = "totalResults";
public static final String PREVIOUS_PAGE = "prevpage";
public static final String NEXT_PAGE = "nextPage";
public static final String ORIGINAL_DOMAIN_OBJECT_LIST = "originalDomainObjectList";
public static final String SHOW_DOMAIN_OBJECT_LIST = "showDomainObjectList";
public static final String USER_DETAILS = "details";
public static final String CURRENT_RECORD = "currentRecord";
public static final String APPROVE_USER_EMAIL_SUBJECT = "Your membership status in caTISSUE Core.";
//Tree View Constants.
public static final String ROOT = "Root";
public static final String CATISSUE_CORE = "caTISSUE Core";
public static final String TISSUE_SITE = "Tissue Site";
public static final int TISSUE_SITE_TREE_ID = 1;
public static final int STORAGE_CONTAINER_TREE_ID = 2;
//Query Interface Results View Constants
public static final String PAGEOF = "pageOf";
public static final String QUERY = "query";
public static final String PAGEOF_APPROVE_USER = "pageOfApproveUser";
public static final String PAGEOF_SIGNUP = "pageOfSignUp";
public static final String PAGEOF_USERADD = "pageOfUserAdd";
public static final String PAGEOF_USER_ADMIN = "pageOfUserAdmin";
//For Tree Applet
public static final String PAGEOF_QUERY_RESULTS = "pageOfQueryResults";
public static final String PAGEOF_STORAGE_LOCATION = "pageOfStorageLocation";
public static final String PAGEOF_SPECIMEN = "pageOfSpecimen";
public static final String PAGEOF_TISSUE_SITE = "pageOfTissueSite";
//Query results view temporary table name.
public static final String QUERY_RESULTS_TABLE = "CATISSUE_QUERY_RESULTS";
//Query results view temporary table columns.
public static final String QUERY_RESULTS_PARTICIPANT_ID = "PARTICIPANT_ID";
public static final String QUERY_RESULTS_ACCESSION_ID = "ACCESSION_ID";
public static final String QUERY_RESULTS_SPECIMEN_ID = "SPECIMEN_ID";
public static final String QUERY_RESULTS_SEGMENT_ID = "SEGMENT_ID";
public static final String QUERY_RESULTS_SAMPLE_ID = "SAMPLE_ID";
//Query results edit constants - MakeEditableAction.
public static final String EDITABLE = "editable";
//URL paths for Applet in TreeView.jsp
public static final String QUERY_TREE_APPLET = "QueryTree.class";
public static final String APPLET_CODEBASE = "Applet";
//Shopping Cart
public static final String SHOPPING_CART = "shoppingCart";
public static final String SELECT_OPTION = "-- Select --";
public static final String[] OBJECT_NAME_ARRAY = {
SELECT_OPTION,
"User","Participant","Specimen"
};
public static final String[] OBJECT_FULL_NAME_ARRAY = {
SELECT_OPTION,
"edu.wustl.catissuecore.domain.User","edu.wustl.catissuecore.domain.Participant","edu.wustl.catissuecore.domain.Specimen"
};
public static final String[] ATTRIBUTE_NAME_ARRAY = {
"Name","loginName","lastName"
};
public static final String[] ATTRIBUTE_CONDITION_ARRAY = {
"=","<",">"
};
public static final String [] RECEIVEDMODEARRAY = {
SELECT_OPTION,
"by hand", "courier", "FedEX", "UPS"
};
public static final String [] GENDER_ARRAY = {
SELECT_OPTION,
"Male",
"Female"
};
public static final String [] GENOTYPE_ARRAY = {
SELECT_OPTION,
"XX",
"XY"
};
public static final String [] RACEARRAY = {
SELECT_OPTION,
"Asian",
"American"
};
public static final String [] PROTOCOLARRAY = {
SELECT_OPTION,
"aaaa",
"bbbb",
"cccc"
};
public static final String [] RECEIVEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] COLLECTEDBYARRAY = {
SELECT_OPTION,
"xxxx",
"yyyy",
"zzzz"
};
public static final String [] TIME_HOUR_ARRAY = {"1","2","3","4","5"};
public static final String [] TIME_HOUR_AMPM_ARRAY = {"AM","PM"};
public static final String [] STATEARRAY =
{
SELECT_OPTION,
"Alabama",//Alabama
"Alaska",//Alaska
"Arizona",//Arizona
"Arkansas",//Arkansas
"California",//California
"Colorado",//Colorado
"Connecticut",//Connecticut
"Delaware",//Delaware
"D.C.",
"Florida",//Florida
"Georgia",//Georgia
"Hawaii",//Hawaii
"Idaho",//Idaho
"Illinois",//Illinois
"Indiana",//Indiana
"Iowa",//Iowa
"Kansas",//Kansas
"Kentucky",//Kentucky
"Louisiana",//Louisiana
"Maine",//Maine
"Maryland",//Maryland
"Massachusetts",//Massachusetts
"Michigan",//Michigan
"Minnesota",//Minnesota
"Mississippi",//Mississippi
"Missouri",//Missouri
"Montana",//Montana
"Nebraska",//Nebraska
"Nevada",//Nevada
"New Hampshire",//New Hampshire
"New Jersey",//New Jersey
"New Mexico",//New Mexico
"New York",//New York
"North Carolina",//North Carolina
"North Dakota",//North Dakota
"Ohio",//Ohio
"Oklahoma",//Oklahoma
"Oregon",//Oregon
"Pennsylvania",//Pennsylvania
"Rhode Island",//Rhode Island
"South Carolina",//South Carolina
"South Dakota",//South Dakota
"Tennessee",//Tennessee
"Texas",//Texas
"Utah",//Utah
"Vermont",//Vermont
"Virginia",//Virginia
"Washington",//Washington
"West Virginia",//West Virginia
"Wisconsin",//Wisconsin
"Wyoming",//Wyoming
"Other",//Other
};
public static final String [] COUNTRYARRAY =
{
SELECT_OPTION,
"United States",
"Canada",
"Afghanistan",
"Albania",
"Algeria",
"American Samoa",
"Andorra",
"Angola",
"Anguilla",
"Antarctica",
"Antigua and Barbuda",
"Argentina",
"Armenia",
"Aruba",
"Australia",
"Austria",
"Azerbaijan",
"Bahamas",
"Bahrain",
"Bangladesh",
"Barbados",
"Belarus",
"Belgium",
"Belize",
"Benin",
"Bermuda",
"Bhutan",
"Bolivia",
"Bosnia and Herzegovina",
"Botswana",
"Bouvet Island",
"Brazil",
"Brunei Darussalam",
"Bulgaria",
"Burkina Faso",
"Burundi",
"Cambodia",
"Cameroon",//Cameroon
"Cape Verde",//Cape Verde
"Cayman Islands",//Cayman Islands
"Central African Republic",//Central African Republic
"Chad",//Chad
"Chile",//Chile
"China",//China
"Christmas Island",//Christmas Island
"Cocos Islands",//Cocos Islands
"Colombia",//Colombia
"Comoros",//Comoros
"Congo",//Congo
"Cook Islands",//Cook Islands
"Costa Rica",//Costa Rica
"Cote D ivoire",//Cote D ivoire
"Croatia",//Croatia
"Cyprus",//Cyprus
"Czech Republic",//Czech Republic
"Denmark",//Denmark
"Djibouti",//Djibouti
"Dominica",//Dominica
"Dominican Republic",//Dominican Republic
"East Timor",//East Timor
"Ecuador",//Ecuador
"Egypt",//Egypt
"El Salvador",//El Salvador
"Equatorial Guinea",//Equatorial Guinea
"Eritrea",//Eritrea
"Estonia",//Estonia
"Ethiopia",//Ethiopia
"Falkland Islands",//Falkland Islands
"Faroe Islands",//Faroe Islands
"Fiji",//Fiji
"Finland",//Finland
"France",//France
"French Guiana",//French Guiana
"French Polynesia",//French Polynesia
"French S. Territories",//French S. Territories
"Gabon",//Gabon
"Gambia",//Gambia
"Georgia",//Georgia
"Germany",//Germany
"Ghana",//Ghana
"Gibraltar",//Gibraltar
"Greece",//Greece
"Greenland",//Greenland
"Grenada",//Grenada
"Guadeloupe",//Guadeloupe
"Guam",//Guam
"Guatemala",//Guatemala
"Guinea",//Guinea
"Guinea-Bissau",//Guinea-Bissau
"Guyana",//Guyana
"Haiti",//Haiti
"Honduras",//Honduras
"Hong Kong",//Hong Kong
"Hungary",//Hungary
"Iceland",//Iceland
"India",//India
"Indonesia",//Indonesia
"Iran",//Iran
"Iraq",//Iraq
"Ireland",//Ireland
"Israel",//Israel
"Italy",//Italy
"Jamaica",//Jamaica
"Japan",//Japan
"Jordan",//Jordan
"Kazakhstan",//Kazakhstan
"Kenya",//Kenya
"Kiribati",//Kiribati
"Korea",//Korea
"Kuwait",//Kuwait
"Kyrgyzstan",//Kyrgyzstan
"Laos",//Laos
"Latvia",//Latvia
"Lebanon",//Lebanon
"Lesotho",//Lesotho
"Liberia",//Liberia
"Liechtenstein",//Liechtenstein
"Lithuania",//Lithuania
"Luxembourg",//Luxembourg
"Macau",//Macau
"Macedonia",//Macedonia
"Madagascar",//Madagascar
"Malawi",//Malawi
"Malaysia",//Malaysia
"Maldives",//Maldives
"Mali",//Mali
"Malta",//Malta
"Marshall Islands",//Marshall Islands
"Martinique",//Martinique
"Mauritania",//Mauritania
"Mauritius",//Mauritius
"Mayotte",//Mayotte
"Mexico",//Mexico
"Micronesia",//Micronesia
"Moldova",//Moldova
"Monaco",//Monaco
"Mongolia",//Mongolia
"Montserrat",//Montserrat
"Morocco",//Morocco
"Mozambique",//Mozambique
"Myanmar",//Myanmar
"Namibia",//Namibia
"Nauru",//Nauru
"Nepal",//Nepal
"Netherlands",//Netherlands
"Netherlands Antilles",//Netherlands Antilles
"New Caledonia",//New Caledonia
"New Zealand",//New Zealand
"Nicaragua",//Nicaragua
"Niger",//Niger
"Nigeria",//Nigeria
"Niue",//Niue
"Norfolk Island",//Norfolk Island
"Norway",//Norway
"Oman",//Oman
"Pakistan",//Pakistan
"Palau",//Palau
"Panama",//Panama
"Papua New Guinea",//Papua New Guinea
"Paraguay",//Paraguay
"Peru",//Peru
"Philippines",//Philippines
"Pitcairn",//Pitcairn
"Poland",//Poland
"Portugal",//Portugal
"Puerto Rico",//Puerto Rico
"Qatar",//Qatar
"Reunion",//Reunion
"Romania",//Romania
"Russian Federation",//Russian Federation
"Rwanda",//Rwanda
"Saint Helena",//Saint Helena
"Saint Kitts and Nevis",//Saint Kitts and Nevis
"Saint Lucia",//Saint Lucia
"Saint Pierre",//Saint Pierre
"Saint Vincent",//Saint Vincent
"Samoa",//Samoa
"San Marino",//San Marino
"Sao Tome and Principe",//Sao Tome and Principe
"Saudi Arabia",//Saudi Arabia
"Senegal",//Senegal
"Seychelles",//Seychelles
"Sierra Leone",//Sierra Leone
"Singapore",//Singapore
"Slovakia",//Slovakia
"Slovenia",//Slovenia
"Solomon Islands",//Solomon Islands
"Somalia",//Somalia
"South Africa",//South Africa
"Spain",//Spain
"Sri Lanka",//Sri Lanka
"Sudan",//Sudan
"Suriname",//Suriname
"Swaziland",//Swaziland
"Sweden",//Sweden
"Switzerland",//Switzerland
"Syrian Arab Republic",//Syrian Arab Republic
"Taiwan",//Taiwan
"Tajikistan",//Tajikistan
"Tanzania",//Tanzania
"Thailand",//Thailand
"Togo",//Togo
"Tokelau",//Tokelau
"Tonga",//Tonga
"Trinidad and Tobago",//Trinidad and Tobago
"Tunisia",//Tunisia
"Turkey",//Turkey
"Turkmenistan",//Turkmenistan
"Turks and Caicos Islands",//Turks and Caicos Islands
"Tuvalu",//Tuvalu
"Uganda",//Uganda
"Ukraine",//Ukraine
"United Arab Emirates",//United Arab Emirates
"United Kingdom",//United Kingdom
"Uruguay",//Uruguay
"Uzbekistan",//Uzbekistan
"Vanuatu",//Vanuatu
"Vatican City State",//Vatican City State
"Venezuela",//Venezuela
"Vietnam",//Vietnam
"Virgin Islands",//Virgin Islands
"Wallis And Futuna Islands",//Wallis And Futuna Islands
"Western Sahara",//Western Sahara
"Yemen",//Yemen
"Yugoslavia",//Yugoslavia
"Zaire",//Zaire
"Zambia",//Zambia
"Zimbabwe",//Zimbabwe
};
// Constants required in CollectionProtocol.jsp Page
public static final String COLLECTIONPROTOCOL_SEARCH_ACTION = "CollectionProtocolSearch.do";
public static final String COLLECTIONPROTOCOL_ADD_ACTION = "CollectionProtocolAdd.do";
public static final String COLLECTIONPROTOCOL_EDIT_ACTION = "CollectionProtocolEdit.do";
// Constants required in DistributionProtocol.jsp Page
public static final String DISTRIBUTIONPROTOCOL_SEARCH_ACTION = "DistributionProtocolSearch.do";
public static final String DISTRIBUTIONPROTOCOL_ADD_ACTION = "DistributionProtocolAdd.do";
public static final String DISTRIBUTIONPROTOCOL_EDIT_ACTION = "DistributionProtocolEdit.do";
public static final String [] CANCER_RESEARCH_GROUP_VALUES = {
SELECT_OPTION,
"Siteman Cancer Center",
"Washington University"
};
public static final String [] ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Active",
"Disabled",
"Closed"
};
public static final String [] APPROVE_USER_STATUS_VALUES = {
SELECT_OPTION,
APPROVE_USER_APPROVE_STATUS,
APPROVE_USER_REJECT_STATUS,
APPROVE_USER_PENDING_STATUS,
};
public static final String [] REPORTED_PROBLEM_ACTIVITY_STATUS_VALUES = {
SELECT_OPTION,
"Closed",
"Pending"
};
//Only for showing UI.
public static final String [] INSTITUTE_VALUES = {
SELECT_OPTION,
"Washington University"
};
public static final String [] DEPARTMENT_VALUES = {
SELECT_OPTION,
"Cardiology",
"Pathology"
};
public static final String [] SPECIMEN_TYPE_VALUES = {
SELECT_OPTION,
"Tissue",
"Fluid",
"Cell",
"Molecular"
};
public static final String [] SPECIMEN_SUB_TYPE_VALUES = {
SELECT_OPTION,
"Blood",
"Serum",
"Plasma",
};
public static final String [] TISSUE_SITE_VALUES = {
SELECT_OPTION,
"Adrenal-Cortex",
"Adrenal-Medulla",
"Adrenal-NOS"
};
public static final String [] TISSUE_SIDE_VALUES = {
SELECT_OPTION,
"Lavage",
"Metastatic Lesion",
};
public static final String [] PATHOLOGICAL_STATUS_VALUES = {
SELECT_OPTION,
"Primary Tumor",
"Metastatic Node",
"Non-Maglignant Tissue",
};
// public static final String [] BIOHAZARD_NAME_VALUES = {
// SELECT_OPTION,
public static final String [] BIOHAZARD_TYPE_VALUES = {
SELECT_OPTION,
"Radioactive"
};
public static final String [] ETHNICITY_VALUES = {
SELECT_OPTION,
"Ethnicity1",
"Ethnicity2",
"Ethnicity3",
};
public static final String [] PARTICIPANT_MEDICAL_RECORD_SOURCE_VALUES = {
SELECT_OPTION
};
public static final String [] STUDY_CALENDAR_EVENT_POINT_ARRAY = {
SELECT_OPTION,
"30","60","90"
};
public static final String [] CLINICAL_STATUS_ARRAY = {
SELECT_OPTION,
"Pre-Opt",
"Post-Opt"
};
public static final String [] SITE_TYPE_ARRAY = {
SELECT_OPTION,
"Collection",
"Laboratory",
"Repository", "Hospital"
};
public static final String [] BIOHAZARD_TYPE_ARRAY = {
SELECT_OPTION,
"Carcinogen",
"Infectious",
"Mutagen",
"Radioactive",
"Toxic"
};
public static final String [] HOURARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23"
};
public static final String [] MINUTESARRAY = {
"00",
"01",
"02",
"03",
"04",
"05",
"06",
"07",
"08",
"09",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"18",
"19",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34",
"35",
"36",
"37",
"38",
"39",
"40",
"41",
"42",
"43",
"44",
"45",
"46",
"47",
"48",
"49",
"50",
"51",
"52",
"53",
"54",
"55",
"56",
"57",
"58",
"59"
};
public static final String [] METHODARRAY = {
SELECT_OPTION,
"LN2",
"Dry Ice",
"Iso pentane"
};
public static final String [] EMBEDDINGMEDIUMARRAY = {
SELECT_OPTION,
"Plastic",
"Glass",
};
public static final String [] FROMSITEARRAY = {
SELECT_OPTION,
"site1",
"site2",
};
public static final String [] TOSITEARRAY = {
SELECT_OPTION,
"site1",
"site2",
};
public static final String [] ITEMARRAY = {
SELECT_OPTION,
"Item1",
"Item2",
};
public static final String UNIT_GM = "gm";
public static final String UNIT_ML = "ml";
public static final String UNIT_CC = "cc";
public static final String UNIT_MG = "mg";
public static final String [] PROCEDUREARRAY = {
SELECT_OPTION,
"Procedure 1",
"Procedure 2",
"Procedure 3"
};
public static final String [] CONTAINERARRAY = {
SELECT_OPTION,
"Container 1",
"Container 2",
"Container 3"
};
public static final String [] FIXATIONARRAY = {
SELECT_OPTION,
"FIXATION 1",
"FIXATION 2",
"FIXATION 3"
};
public static final HashMap STATIC_PROTECTION_GROUPS_FOR_OBJECT_TYPES = new HashMap();
} |
package api.impl;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import actions.scoringActions.ScoringSummStAction;
import api.ApiInterface;
import application.AppBean;
import beans.relation.summary.SummaryStatement;
import beans.scoring.ScoreBean;
import beans.scripts.PatientIllnessScript;
import controller.JsonCreator;
import controller.SummaryStatementController;
import database.DBClinReason;
import net.casus.util.CasusConfiguration;
import net.casus.util.StringUtilities;
import net.casus.util.Utility;
import util.CRTLogger;
/**
* simple JSON Webservice for simple API JSON framework
*
* <base>/crt/src/html/api/api.xhtml?impl=peerSync
* should either start a new thread, or return basic running thread data!
*
* @author Gulpi (=Martin Adler)
*/
public class SummaryStatementAPI implements ApiInterface {
AppBean appBean = null;
ReScoreThread thread = null;
ReScoreThread lastThread = null;
public SummaryStatementAPI() {
}
/**
* needs to be initialized, to be available alos from Threads, which do NOT have a Faces context!!!
* @return
*/
public AppBean getAppBean(){
if (appBean == null) {
ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
appBean = (AppBean) context.getAttribute(AppBean.APP_KEY);
}
return appBean;
}
@SuppressWarnings("unchecked")
@Override
public synchronized String handle() {
String result = null;
@SuppressWarnings("rawtypes")
Map resultObj = new TreeMap();
try {
this.getAppBean();
ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
new JsonCreator().initJsonExport(context);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ReScoreThread mythread = thread;
String status = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("status");
if (StringUtilities.isValidString(status) && status.equalsIgnoreCase("true")) {
if (mythread != null) {
fillStatus(resultObj, mythread);
}
else if (lastThread != null) {
fillStatus(resultObj, lastThread);
}
else {
resultObj.put("result", "no status available!");
}
}
else {
long id = StringUtilities.getLongFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("id"), -1);
if (id > 0) {
PatientIllnessScript userPatientIllnesScript = new DBClinReason().selectPatIllScriptById(id);
SummaryStatement st = this.handleByPatientIllnessScript(userPatientIllnesScript);
if (st != null) {
resultObj.put("status", "ok");
this.addSummaryStatementToResultObj(resultObj, userPatientIllnesScript, st);
PatientIllnessScript expScript = getAppBean().addExpertPatIllnessScriptForVpId(userPatientIllnesScript.getVpId());
if (expScript != null) {
this.addSummaryStatementToResultObj(resultObj, "ExpertPatientIllnesScript.", expScript);
this.addSummaryStatementToResultObj(resultObj, "ExpertSummaryStatement.", expScript.getSummSt());
}
}
else {
resultObj.put("status", "error");
resultObj.put("errorMsg", "no SummaryStatement object ?");
}
}
else {
if (mythread == null) {
thread = new ReScoreThread();
thread.setCtrl(this);
thread.setMax(StringUtilities.getIntegerFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("max"), 100));
thread.setType(StringUtilities.getIntegerFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("type"), PatientIllnessScript.TYPE_LEARNER_CREATED));
thread.setStartDate(StringUtilities.getDateFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("start_date"), null));
thread.setEndDate(StringUtilities.getDateFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("end_date"), null));
thread.setLoadNodes(StringUtilities.getBooleanFromString((String) ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("load_nodes"), false));
mythread = thread;
mythread.start();
resultObj.put("result", "started");
}
else {
fillStatus(resultObj, mythread);
}
}
}
ObjectMapper mapper = new ObjectMapper();
try {
if (CasusConfiguration.getGlobalBooleanValue("SummaryStatementAPI.prettyJSON", true)) {
result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultObj);
}
else {
result = mapper.writeValueAsString(resultObj);
}
} catch (JsonProcessingException e) {
result = e.getMessage();
}
return result;
}
@SuppressWarnings("unchecked")
public void fillStatus(@SuppressWarnings("rawtypes") Map resultObj, ReScoreThread mythread) {
resultObj.put("result", "running");
resultObj.put("started", mythread.getStarted().toString());
if (mythread.getFinished() != null) {
resultObj.put("finished", mythread.getFinished().toString());
}
resultObj.put("sync_max", mythread.getCount());
resultObj.put("sync_idx", mythread.getIdx());
resultObj.put("query_max", mythread.getMax());
resultObj.put("query_start_date", mythread.getStartDate());
resultObj.put("query_end_date", mythread.getEndDate());
String details = ((HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest()).getParameter("details");
if (details != null && details.equalsIgnoreCase("true")) {
resultObj.put("details", mythread.getResults());
}
}
public SummaryStatement handleByPatientIllnessScript(PatientIllnessScript userPatientIllnesScript) {
SummaryStatement st = null;
PatientIllnessScript expScript = getAppBean().addExpertPatIllnessScriptForVpId(userPatientIllnesScript.getVpId());
expScript.getSummStStage();
ScoreBean scoreBean = new ScoreBean(userPatientIllnesScript, userPatientIllnesScript.getSummStId(), ScoreBean.TYPE_SUMMST, userPatientIllnesScript.getCurrentStage());
if(expScript!=null && expScript.getSummSt()!=null){
ScoringSummStAction action = new ScoringSummStAction();
st = new SummaryStatementController().initSummStRating(expScript, userPatientIllnesScript, action);
action.doScoring(st, expScript.getSummSt());
}
return st;
}
void addToResultObj(Map resultObj, String key, Object value) {
resultObj.put(key, value != null ? value : "-");
}
void addSummaryStatementToResultObj(Map resultObj, String prefix, PatientIllnessScript userPatientIllnesScript) {
if (userPatientIllnesScript == null) {
this.addToResultObj(resultObj, prefix + "obj", "null");
return;
}
this.addToResultObj(resultObj, prefix + "id", userPatientIllnesScript.getId());
this.addToResultObj(resultObj, prefix + "userId", userPatientIllnesScript.getUserId());
this.addToResultObj(resultObj, prefix + "vpId", userPatientIllnesScript.getVpId());
this.addToResultObj(resultObj, prefix + "stage", userPatientIllnesScript.getCurrentStage());
}
void addSummaryStatementToResultObj(Map resultObj, String prefix, SummaryStatement st) {
if (st == null) {
this.addToResultObj(resultObj, prefix + "obj", "null");
return;
}
this.addToResultObj(resultObj, prefix + "text", st.getText());
this.addToResultObj(resultObj, prefix + "lang", st.getLang());
this.addToResultObj(resultObj, prefix + "analyzed", st.isAnalyzed());
this.addToResultObj(resultObj, prefix + "creationDate", st.getCreationDate());
//this.addToResultObj(resultObj, prefix + "sqHits", st.getSqHits() );
//this.addToResultObj(resultObj, prefix + "itemHits", st.getItemHits());
this.addToResultObj(resultObj, prefix + "sqScore", st.getSqScore());
this.addToResultObj(resultObj, prefix + "sqScoreBasic", st.getSqScoreBasic());
this.addToResultObj(resultObj, "SummaryStatement.sqScorePerc", st.getSqScorePerc());
this.addToResultObj(resultObj, prefix + "transformationScore", st.getTransformationScore());
this.addToResultObj(resultObj, prefix + "transformScorePerc", st.getTransformScorePerc());
this.addToResultObj(resultObj, prefix + "narrowingScore", st.getNarrowingScore());
this.addToResultObj(resultObj, prefix + "narr1Score", st.getNarr1Score());
this.addToResultObj(resultObj, prefix + "narr2Score", st.getNarr2Score());
this.addToResultObj(resultObj, prefix + "narrowingScoreNew", st.getNarrowingScoreNew());
this.addToResultObj(resultObj, prefix + "personScore", st.getPersonScore());
//this.addToResultObj(resultObj, "SummaryStatement.units", st.getUnits());
this.addToResultObj(resultObj, prefix + "transformNum", st.getTransformNum());
this.addToResultObj(resultObj, prefix + "accuracyScore", st.getAccuracyScore());
this.addToResultObj(resultObj, prefix + "globalScore", st.getGlobalScore());
}
void addSummaryStatementToResultObj(Map resultObj, PatientIllnessScript userPatientIllnesScript, SummaryStatement st) {
this.addSummaryStatementToResultObj(resultObj, "UserPatientIllnesScript.", userPatientIllnesScript);
this.addSummaryStatementToResultObj(resultObj, "UserSummaryStatement.", st);
}
class ReScoreThread extends Thread {
Date started = new Date();
Date finished = null;
int max = 100;
int type = PatientIllnessScript.TYPE_LEARNER_CREATED;
Date startDate = null;
Date endDate = null;
SummaryStatementAPI ctrl = null;
List<Map> results = new ArrayList<Map>();
boolean loadNodes = false;
int count = -1;
int idx = -1;
@Override
public void run() {
try{
List<PatientIllnessScript> userPatientIllnesScripts = new DBClinReason().selectLearnerPatIllScriptsByNotAnalyzedSummSt(max, startDate, endDate, type, loadNodes);
if (userPatientIllnesScripts != null) {
this.count = userPatientIllnesScripts.size();
this.idx = 0;
Iterator<PatientIllnessScript> it = userPatientIllnesScripts.iterator();
while (it.hasNext()) {
PatientIllnessScript userPatientIllnesScript = it.next();
idx++;
try {
SummaryStatement st = ctrl.handleByPatientIllnessScript(userPatientIllnesScript);
if (st != null) {
Map result1 = new HashMap();
ctrl.addSummaryStatementToResultObj(result1, userPatientIllnesScript, st);
results.add(result1);
}
} catch (Throwable e) {
Map result1 = new TreeMap();
ctrl.addSummaryStatementToResultObj(result1, "UserPatientIllnesScript.", userPatientIllnesScript);
ctrl.addToResultObj(result1, "exception", Utility.stackTraceToString(e));
results.add(result1);
}
}
}
}
catch(Exception e){
CRTLogger.out("PeerSyncAPIThread(): " +Utility.stackTraceToString(e), CRTLogger.LEVEL_ERROR);
}
this.setFinished(new Date());
lastThread = thread;
thread = null;
}
public Date getStarted() {
return started;
}
public void setStarted(Date started) {
this.started = started;
}
public Date getFinished() {
return finished;
}
public void setFinished(Date finished) {
this.finished = finished;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public SummaryStatementAPI getCtrl() {
return ctrl;
}
public void setCtrl(SummaryStatementAPI ctrl) {
this.ctrl = ctrl;
}
public List<Map> getResults() {
return results;
}
public void setResults(List<Map> results) {
this.results = results;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public int getIdx() {
return idx;
}
public void setIdx(int idx) {
this.idx = idx;
}
public boolean isLoadNodes() {
return loadNodes;
}
public void setLoadNodes(boolean loadNodes) {
this.loadNodes = loadNodes;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
} |
package edu.wustl.catissuecore.util.global;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.wustl.common.util.logger.Logger;
/**
* This Class contains the methods used for validation of the fields in the userform.
* @author gautam_shetty
*/
public class Validator
{
/**
* Checks that the input String is a valid email address.
* @param aEmailAddress String containing the email address to be checked.
* @return Returns true if its a valid email address, else returns false.
* */
public boolean isValidEmailAddress(String aEmailAddress)
{
boolean result = true;
try
{
if (isEmpty(aEmailAddress))
{
result = false;
}
else
{
result = isValidEmailId(aEmailAddress);
}
}
catch (Exception ex)
{
result = false;
}
return result;
}
/*
private boolean hasNameAndDomain(String aEmailAddress)
{
StringTokenizer token = new StringTokenizer(aEmailAddress, "@");
if (token.countTokens() == 2)
{
return true;
}
return false;
}
*/
/**
* Returns theValue of the given string or null.
*/
// public String getObjectValue(String obj)
// if(isEmpty(obj))
// return null;
// else
// return obj.toString();
/**
*
* @param ssn Social Security Number to check
* @return boolean depending on the value of ssn.
*/
public boolean isValidSSN(String ssn)
{
boolean result = true;
try
{
Pattern re = Pattern.compile("[0-9]{3}-[0-9]{2}-[0-9]{4}", Pattern.CASE_INSENSITIVE);
Matcher mat =re.matcher(ssn);
result = mat.matches();
System.out.println(result);
}
catch(Exception exp)
{
System.out.println("exp");
return false;
}
return result;
}
/**
* Checks whether a string is empty and adds an ActionError object in the ActionErrors object.
* @param componentName Component which is to be checked.
* @param labelName Label of the component on the jsp page which is checked.
* @param errors ActionErrors Object.
* @return Returns true if the componentName is empty else returns false.
*/
public boolean isEmpty(String str)
{
if (str == null || str.trim().length() == 0)
{
return true;
}
return false;
}
/**
* Checks that the input String contains only alphabetic characters.
* @param alphaString The string whose characters are to be checked.
* @return Returns false if the String contains any digit else returns true.
* */
public boolean isAlpha(String alphaString)
{
int i = 0;
while (i < alphaString.length())
{
if (!Character.isLetter(alphaString.charAt(i)))
{
return false;
}
i++;
}
return true;
}
/**
* Checks that the input String contains only numeric digits.
* @param numString The string whose characters are to be checked.
* @return Returns false if the String contains any alphabet else returns true.
* */
public boolean isNumeric(String numString)
{
try
{
long longValue = Long.parseLong(numString);
if (longValue <= 0)
{
return false;
}
return true;
}
catch(NumberFormatException exp)
{
return false;
}
}
/**
*
* Checks that the input String contains only numeric digits.
* @param numString The string whose characters are to be checked.
* @param positiveCheck Positive integer to check for positive number
* @return Returns false if the String contains any alphabet else returns true.
* Depending on the value of the positiveCheck will check for positive values
*
*/
public boolean isNumeric(String numString, int positiveCheck)
{
try
{
long longValue = Long.parseLong(numString);
if(positiveCheck >0 )
{
if (longValue <= 0)
{
return false;
}
}
else if(positiveCheck == 0 )
{
if (longValue < 0)
{
return false;
}
}
return true;
}
catch(NumberFormatException exp)
{
return false;
}
}
/**
* Checks the given String for double value.
*
* @param dblString
* @return boolean True if the string contains double number or false if any non numeric character is present.
*/
public boolean isDouble(String dblString)
{
try
{
double dblValue = Double.parseDouble(dblString);
if (dblValue <= 0 || Double.isNaN(dblValue))
{
return false;
}
return true;
}
catch(NumberFormatException exp)
{
System.out.println("Error : "+exp);
return false;
}
}
public boolean isDouble(String dblString,boolean positiveCheck)
{
try
{
double dblValue = Double.parseDouble(dblString);
if (Double.isNaN(dblValue))
{
return false;
}
if(positiveCheck)
{
if (dblValue < 0)
{
return false;
}
}
return true;
}
catch(NumberFormatException exp)
{
System.out.println("Error : "+exp);
return false;
}
}
public boolean isValidOption(String option)
{
Logger.out.debug("option value: "+option);
if(option != null)
{
if(option.trim().equals("-1") || option.equals(Constants.SELECT_OPTION))
return false;
else
return true;
}
return false;
}
private boolean isValidEmailId(String emailAddress)
{
boolean result = true;
try
{
Pattern re = Pattern.compile("^\\w(\\.?[\\w-])*@\\w(\\.?[-\\w])*\\.([a-z]{3}(\\.[a-z]{2})?|[a-z]{2}(\\.[a-z]{2})?)$", Pattern.CASE_INSENSITIVE);
Matcher mat =re.matcher(emailAddress);
result = mat.matches();
}
catch(Exception exp)
{
System.out.println("5");
return false;
}
return result;
}
public boolean containsSpecialCharacters( String mainString, String delimiter)
{
try
{
StringTokenizer st = new StringTokenizer(mainString, delimiter);
int count = st.countTokens();
if(count>1)
return true;
else
return false;
}
catch(Exception exp)
{
System.out.println("error : " + exp);
return true;
}
}
public String delimiterExcludingGiven(String ignoreList)
{
String spChars = "!@
// System.out.println("Original : " + spChars);
StringBuffer sb = new StringBuffer(spChars);
// System.out.println("SB : " +sb);
StringBuffer retStr = new StringBuffer();
try
{
char spIgnoreChars[] = ignoreList.toCharArray();
for(int spCharCount =0; spCharCount<spIgnoreChars.length ; spCharCount++)
{
char chkChar = spIgnoreChars[spCharCount];
// System.out.println(chkChar);
int chInd = sb.indexOf(""+chkChar );
while(chInd !=-1)
{
sb = sb.deleteCharAt(chInd );
chInd = sb.indexOf(""+chkChar );
// System.out.println("\t"+sb);
}
}
retStr = sb;
// System.out.println("\n\nRetStr : " + retStr);
}
catch(Exception exp)
{
System.out.println("error : " + exp);
}
return retStr.toString();
}
private boolean isValidDatePattern(String checkDate)
{
boolean result = true;
try
{
Pattern re = Pattern.compile("[0-9]{2}-[0-9]{2}-[0-9]{4}", Pattern.CASE_INSENSITIVE);
Matcher mat =re.matcher(checkDate);
result = mat.matches();
System.out.println("is Valid Date Pattern "+result);
}
catch(Exception exp)
{
Logger.out.error("IsValidDatePattern : exp : " + exp);
return false;
}
return result;
}
String dtCh= Constants.DATE_SEPARATOR;
int minYear = Integer.parseInt(Constants.MIN_YEAR);
int maxYear = Integer.parseInt(Constants.MAX_YEAR);
private int daysInFebruary (int year)
{
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
private int[] DaysArray(int n)
{
int dayArray[] = new int[n+1];
dayArray[0] = 0;
for (int i = 1; i <= n; i++)
{
dayArray[i] = 31;
if (i==4 || i==6 || i==9 || i==11)
{
dayArray [i] = 30;
}
if (i==2)
{
dayArray[i] = 29;
}
}
return dayArray;
}
private boolean isDate(String dtStr)
{
try
{
int []daysInMonth = DaysArray(12);
int pos1=dtStr.indexOf(dtCh);
int pos2=dtStr.indexOf(dtCh,pos1+1);
String strMonth=dtStr.substring(0,pos1);
String strDay=dtStr.substring(pos1+1,pos2);
String strYear=dtStr.substring(pos2+1);
String strYr=strYear;
if (strDay.charAt(0)=='0' && strDay.length()>1) strDay=strDay.substring(1);
if (strMonth.charAt(0)=='0' && strMonth.length()>1) strMonth=strMonth.substring(1);
for (int i = 1; i <= 3; i++)
{
if (strYr.charAt(0)=='0' && strYr.length()>1) strYr=strYr.substring(1);
}
int month=Integer.parseInt(strMonth);
int day=Integer.parseInt(strDay);
int year=Integer.parseInt(strYr);
if (pos1==-1 || pos2==-1){
Logger.out.debug("The date format should be : mm/dd/yyyy");
return false;
}
if (strMonth.length()<1 || month<1 || month>12)
{
Logger.out.debug("Please enter a valid month");
return false;
}
if (strDay.length()<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
{
Logger.out.debug("Please enter a valid day");
return false;
}
if (strYear.length() != 4 || year==0 || year<minYear || year>maxYear){
Logger.out.debug("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
return false;
}
return true;
}
catch(Exception exp)
{
Logger.out.error("exp in isDate : "+ exp);
exp.printStackTrace();
return false;
}
}
public boolean checkDate(String checkDate)
{
boolean result = true;
try
{
Logger.out.debug("checkDate : " + checkDate);
if(isEmpty(checkDate))
{
result = false;
}
else
{
if(isValidDatePattern(checkDate ))
{
result = isDate(checkDate );
}
else
result = false;
}
}
catch(Exception exp)
{
Logger.out.error("Check Date : exp : "+ exp);
result = false;
}
Logger.out.debug("CheckDate : "+result);
return result;
}
public boolean compareDateWithCurrent(String dateToCheck)
{
boolean result = true;
try
{
Date currentDate = Calendar.getInstance().getTime();
System.out.println("1 : -- "+ dateToCheck );
System.out.println("currentDate : "+ currentDate );
String pattern="MM-dd-yyyy";
SimpleDateFormat dF = new SimpleDateFormat(pattern);
Date toCheck = dF.parse(dateToCheck );
System.out.println("2");
System.out.println("toCheck : "+ toCheck);
int dateCheckResult = currentDate.compareTo(toCheck );
// Logger.out.debug("currentDate.compareTo(toCheck ) : " + dateCheckResult );
if(dateCheckResult < 0 )
result = false;
}
catch(Exception exp)
{
//Logger.out.error("compareDateWithCurrent : " + dateToCheck + " : exp : "+ exp);
result = false;
}
return result;
}
// Error messages for empty date, Invalid date, and Future dates are formatted .
public String validateDate(String strDate, boolean checkFutureDate)
{
String returnString = "";
Logger.out.debug("handleDateData checkDate : " + strDate);
if(isEmpty(strDate))
{
returnString = "errors.item.required";
}
else
{
if(isValidDatePattern(strDate ))
{
if(isDate(strDate) )
{
if(checkFutureDate)
{
if(!compareDateWithCurrent(strDate ))
{
returnString = "errors.invalid.date";
}
}
}
else
returnString = "errors.date.format";
}
else
returnString = "errors.date.format";
}
return returnString;
}
//Returns TRUE if operator is valid else return FALSE
public boolean isOperator(String value)
{
if(value == null)
{
return false;
}
else if(value.equals(Constants.ANY) || value.equals("-1"))
{
return false;
}
else
{
return true;
}
}
public boolean isValue(String value)
{
//Purposefully not checked for value==null.
if(value == null)
{
return true;
}
else if(value.trim().length() == 0)
{
return false;
}
else if(value.equals("-1") || value.equals(Constants.SELECT_OPTION))
{
return false;
}
else
{
return true;
}
}
// public void validateDateData(String checkDate,ActionErrors errors, String messageKey )
// Logger.out.debug("handleDateData checkDate : " + checkDate);
// if(isEmpty(checkDate))
// errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.required",ApplicationProperties.getValue(messageKey)));
// else
// if(isValidDatePattern(checkDate ))
// if(isDate(checkDate) )
// if(!compareDateWithCurrent(checkDate ))
// errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.invalid.date",ApplicationProperties.getValue(messageKey )));
// else
// errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(messageKey )));
// else
// errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.item.format",ApplicationProperties.getValue(messageKey )));
/**
* returns true if zip code is valid else returns false
*/
public boolean isValidZipCode(String zipCode)
{
boolean result=false;
try
{
// valid format for zip code are '99999-9999' or '99999'
Pattern p = Pattern.compile("\\d{5}\\-\\d{4}|\\d{5}");
Matcher m = p.matcher(zipCode);
result = m.matches();
}
catch(Exception exp)
{
Logger.out.error("Check Zip Code : exp : "+ exp);
result = false;
}
return result;
}
/**
* returns true if Phone/Fax number is valid else returns false
*/
public boolean isValidPhoneNumber(String phoneNumber)
{
boolean result=false;
try
{
// valid format for phone/fax number ar '(999)999-9999' or '999-999-9999'
Pattern p = Pattern.compile("\\(\\d{3}\\)\\d{3}-\\d{4}|\\d{3}\\-\\d{3}-\\d{4}"); // for fax and phone
Matcher m = p.matcher(phoneNumber);
result = m.matches();
}
catch(Exception exp)
{
Logger.out.error("Check Phone/Fax Number : exp : "+ exp);
result = false;
}
return result;
}
public static void main(String[] args)
{
Validator validator = new Validator();
// String ssn = "sdf-ss-dfds";
// System.out.println(ssn);
// validator.isValidSSN(ssn );
// ssn = "111-11-1111";
// String sdate = "00-00-0000";
// validator.checkDate(sdate );
// sdate = "18-13-1901";
// validator.checkDate(sdate );
// sdate = "12-43-1901";
// validator.checkDate(sdate );
// sdate = "02-30-1901";
// validator.checkDate(sdate );
// sdate = "02-13-1901";
// validator.checkDate(sdate );
// -- Check code for date comparison
// String dt = "12-12-2005";
// System.out.println("validator.compareDateWithCurrent(dt) : " + validator.compareDateWithCurrent(dt) );
// dt = "12-23-2005";
// System.out.println("validator.compareDateWithCurrent(dt) : " + validator.compareDateWithCurrent(dt) );
// dt = "10-23-2005";
// System.out.println("validator.compareDateWithCurrent(dt) : " + validator.compareDateWithCurrent(dt) );
// dt = "11-08-2005";
// System.out.println("validator.compareDateWithCurrent(dt) : " + validator.compareDateWithCurrent(dt) );
// dt = "ssf";
// System.out.println("validator.compareDateWithCurrent(dt) : " + validator.compareDateWithCurrent(dt) );
// String str = "mandar; deshmukh";
// String delim=";,";
// System.out.println("\nstr: "+str);
// System.out.println("\ndelim: "+delim);
// System.out.println("\nContains : " + validator.containsSpecialCharacters(str,delim ));
// String s= new String("- _");
// String delimitedString = validator.delimiterExcludingGiven(s );
// System.out.println("\n\n" + delimitedString );
// System.out.println(delimitedString.indexOf(s ));
// String str = new String("mandar_deshmukh@persistent.co.in");
// boolean boo = validator.isNumeric(str);
// System.out.println(boo);
// boo = validator.isValidEmailAddress(str);
// System.out.println(boo);
// str="mandar_deshmukh@persistent.co.in";
// boo = validator.isValidEmailId(str );
// System.out.println("\n\nEmail : " + str + " : " + boo );
// str="@persistent.co.in";
// boo = validator.isValidEmailId(str );
// System.out.println("\n\nEmail : " + str + " : " + boo );
// str="@pers@istent.co.in";
// boo = validator.isValidEmailId(str );
// System.out.println("\n\nEmail : " + str + " : " + boo );
// str="@@persistent.co.in";
// boo = validator.isValidEmailId(str );
// System.out.println("\n\nEmail : " + str + " : " + boo );
// str=".persi@stent.co.in";
// boo = validator.isValidEmailId(str );
// System.out.println("\n\nEmail : " + str + " : " + boo );
// str="@.persistent.co.in";
// boo = validator.isValidEmailId(str );
// System.out.println("\n\nEmail : " + str + " : " + boo );
// str="pers@istent..co.in";
// boo = validator.isValidEmailId(str );
// System.out.println("\n\nEmail : " + str + " : " + boo );
// try
// BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
// System.out.println("\nEnter N/n to Quit \n\n");
// System.out.print("\n\nDo you want to check the Email Address : ");
// String ch = br.readLine();
// while(!ch.equalsIgnoreCase("N") )
// System.out.println("\nEnter the Email Adress to Check: ");
// String email = br.readLine();
// boolean b = validator.isValidEmailAddress(email );
// System.out.println("\n Is Valid : " + b);
// System.out.print("Do you want to Continue : ");
// ch = br.readLine();
// catch(Exception exp)
// System.out.println("Error : " + exp);
}
} |
package nl.utwente.viskell.ui;
import com.google.common.base.Charsets;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.control.MenuItem;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.Window;
import nl.utwente.viskell.ui.components.Block;
import nl.utwente.viskell.ui.serialize.Exporter;
import nl.utwente.viskell.ui.serialize.Importer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* menu actions
*/
public class MenuActions {
/** The main overlay of which this menu is a part */
protected MainOverlay overlay;
/** The File we're currently working on, if any. */
private Optional<File> currentFile;
public MenuActions(MainOverlay overlay) {
this.overlay = overlay;
this.currentFile = Optional.empty();
}
protected List<MenuItem> fileMenuItems() {
List<MenuItem> list = new ArrayList<>();
MenuItem menuNew = new MenuItem("New");
menuNew.setOnAction(this::onNew);
list.add(menuNew);
MenuItem menuOpen = new MenuItem("Open...");
menuOpen.setOnAction(this::onOpen);
list.add(menuOpen);
MenuItem menuSave = new MenuItem("Save");
menuSave.setOnAction(this::onSave);
list.add(menuSave);
MenuItem menuSaveAs = new MenuItem("Save as...");
menuSaveAs.setOnAction(this::onSaveAs);
list.add(menuSaveAs);
return list;
}
@SuppressWarnings("UnusedParameters")
protected void showPreferences(ActionEvent actionEvent) {
this.overlay.showPreferences();
}
@SuppressWarnings("UnusedParameters")
protected void showInspector(ActionEvent actionEvent) {
this.overlay.showInspector();
}
protected void onNew(ActionEvent actionEvent) {
this.overlay.getMainPane().clearChildren();
this.currentFile = Optional.empty();
}
protected void onOpen(ActionEvent actionEvent) {
Window window = this.overlay.getScene().getWindow();
File file = new FileChooser().showOpenDialog(window);
if (file != null) {
addChildrenFrom(file, this.overlay.getMainPane());
}
}
protected void onSave(ActionEvent actionEvent) {
if (this.currentFile.isPresent()) {
saveTo(this.currentFile.get());
} else {
onSaveAs(actionEvent);
}
}
protected void onSaveAs(ActionEvent actionEvent) {
Window window = this.overlay.getScene().getWindow();
File file = new FileChooser().showSaveDialog(window);
if (file != null) {
saveTo(file);
this.currentFile = Optional.of(file);
}
}
protected void addChildrenFrom(File file, ToplevelPane pane) {
}
protected void saveTo(File file) {
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(Exporter.export(this.overlay.getMainPane()).getBytes(Charsets.UTF_8));
fos.close();
} catch (IOException e) {
// TODO do something sensible here
e.printStackTrace();
}
}
@SuppressWarnings("UnusedParameters")
protected void toggleFullScreen(ActionEvent actionEvent) {
Stage stage = Main.primaryStage;
if (stage.isFullScreen()) {
stage.setFullScreen(false);
} else {
stage.setMaximized(true);
stage.setFullScreen(true);
}
}
@SuppressWarnings("UnusedParameters")
protected void onQuit(ActionEvent actionEvent) {
Platform.exit();
}
} |
package org.voovan.http.server;
import org.voovan.Global;
import org.voovan.http.HttpSessionParam;
import org.voovan.http.HttpRequestType;
import org.voovan.http.message.HttpParser;
import org.voovan.http.message.HttpStatic;
import org.voovan.http.message.Request;
import org.voovan.http.message.Response;
import org.voovan.http.server.context.WebContext;
import org.voovan.http.server.exception.RequestTooLarge;
import org.voovan.http.websocket.WebSocketFrame;
import org.voovan.network.IoFilter;
import org.voovan.network.IoSession;
import org.voovan.network.aio.AioSocket;
import org.voovan.tools.ByteBufferChannel;
import org.voovan.tools.TByteBuffer;
import org.voovan.tools.hashwheeltimer.HashWheelTask;
import org.voovan.tools.log.Logger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentSkipListMap;
public class WebServerFilter implements IoFilter {
private static ThreadLocal<ByteBufferChannel> THREAD_BUFFER_CHANNEL = ThreadLocal.withInitial(()->new ByteBufferChannel(TByteBuffer.EMPTY_BYTE_BUFFER));
private static ConcurrentSkipListMap<String, byte[]> RESPONSE_CACHE = new ConcurrentSkipListMap<String, byte[]>();
static {
Global.getHashWheelTimer().addTask(new HashWheelTask() {
@Override
public void run() {
RESPONSE_CACHE.clear();
}
}, 1000);
}
/**
* HttpResponseByteBuffer
*/
@Override
public Object encode(IoSession session, Object object) {
session.enabledMessageSpliter(true);
// Websocket
if (object instanceof HttpResponse) {
HttpResponse httpResponse = (HttpResponse)object;
try{
if(httpResponse.isAutoSend()) {
byte[] cacheBytes = null;
String cacheMark = httpResponse.getCacheMark();
if(WebContext.isCache() && cacheMark!=null) {
cacheBytes = RESPONSE_CACHE.get(cacheMark);
}
if(cacheBytes==null) {
httpResponse.send();
if(cacheMark!=null) {
ByteBufferChannel sendByteBufferChannel = session.getSendByteBufferChannel();
cacheBytes = new byte[session.getSendByteBufferChannel().size()];
sendByteBufferChannel.get(cacheBytes);
RESPONSE_CACHE.put(cacheMark, cacheBytes);
}
} else {
session.sendByBuffer(ByteBuffer.wrap(cacheBytes));
httpResponse.clear();
}
}
}catch(Exception e){
Logger.error(e);
}
return null;
} else if(object instanceof WebSocketFrame){
WebSocketFrame webSocketFrame = (WebSocketFrame)object;
return webSocketFrame.toByteBuffer();
}
return null;
}
/**
* ByteBuffer HttpRequest
*/
@Override
public Object decode(IoSession session, Object object) {
if(!session.isConnected()){
return null;
}
ByteBuffer byteBuffer = (ByteBuffer)object;
ByteBufferChannel byteBufferChannel = null;
if(byteBuffer.limit()==0){
session.enabledMessageSpliter(false);
byteBufferChannel = session.getReadByteBufferChannel();
} else {
// http pipeline , GET
byteBufferChannel = THREAD_BUFFER_CHANNEL.get();
byteBufferChannel.init(byteBuffer);
}
if (HttpRequestType.HTTP.equals(WebServerHandler.getAttribute(session, HttpSessionParam.TYPE))) {
Request request = null;
try {
if (object instanceof ByteBuffer) {
request = HttpParser.parseRequest(byteBufferChannel, session.socketContext().getReadTimeout(), WebContext.getWebServerConfig().getMaxRequestSize());
if(request!=null){
return request;
}else{
session.close();
}
} else {
return null;
}
} catch (IOException e) {
Response response = new Response();
response.protocol().setStatus(500);
if(e instanceof RequestTooLarge){
response.protocol().setStatus(413);
response.body().write("false");
}
try {
response.send(session);
((AioSocket)session.socketContext()).socketChannel().shutdownInput();
} catch (IOException e1) {
e1.printStackTrace();
}
session.close();
Logger.error("ParseRequest failed",e);
return null;
}
}
//Type WebSocket WebSocket , WebSocketFrame
else if(HttpRequestType.WEBSOCKET.equals(WebServerHandler.getAttribute(session, HttpSessionParam.TYPE))){
if (object instanceof ByteBuffer && byteBuffer.limit()!=0) {
WebSocketFrame webSocketFrame = WebSocketFrame.parse(byteBuffer);
if(webSocketFrame.getErrorCode()==0){
return webSocketFrame;
}else{
session.close();
}
} else {
return null;
}
} else {
session.close();
}
return null;
}
} |
package de.kleppmann.maniation.dynamics;
import java.util.Map;
import java.util.Set;
import de.kleppmann.maniation.geometry.AnimateMesh;
import de.kleppmann.maniation.geometry.ArticulatedLimb;
import de.kleppmann.maniation.geometry.ArticulatedMesh;
import de.kleppmann.maniation.geometry.MeshVertex;
import de.kleppmann.maniation.maths.Vector3D;
import de.kleppmann.maniation.scene.AxisConstraint;
import de.kleppmann.maniation.scene.Bone;
import de.kleppmann.maniation.scene.Skeleton;
public class ArticulatedBody extends CompoundBody implements Collideable {
private World world;
private ArticulatedMesh mesh;
private Map<ArticulatedLimb, Set<Integer>> collisionTestLimbs;
private Map<SimulationObject, Set<Interaction>> links;
public ArticulatedBody(World world, ArticulatedMesh mesh) {
super(world, bodiesFromMesh(world, mesh));
this.world = world;
this.mesh = mesh;
mesh.setDynamicBody(this);
// Collect links between the limbs into a single map
links = new java.util.HashMap<SimulationObject, Set<Interaction>>();
for (int i=0; i<getBodies(); i++) {
Limb limb = (Limb) getBody(i);
links.put(limb, limb.links);
}
// Determine which bones should be tested for collision against each other.
// Tests should not be symmetric (if A is tested against B, B should not be tested
// against A), and any two bones whose triangle sets share a vertex (i.e. they are
// directly adjacent parts of the mesh) should not be tested against each other.
Skeleton skel = mesh.getSceneBody().getMesh().getSkeleton();
collisionTestLimbs = new java.util.HashMap<ArticulatedLimb, Set<Integer>>();
for (int i=0; i < skel.getBones().size(); i++) {
Bone bone = skel.getBones().get(i);
Set<Integer> limbSet = new java.util.HashSet<Integer>();
for (int j=0; j<i; j++) {
Bone other = skel.getBones().get(j);
Set<MeshVertex> intersect = new java.util.HashSet<MeshVertex>();
intersect.addAll(mesh.getBoneVerticesMap().get(bone));
intersect.retainAll(mesh.getBoneVerticesMap().get(other));
if (intersect.size() == 0) {
ArticulatedLimb l = mesh.getBoneLimbMap().get(other);
for (int k=0; k<getBodies(); k++) if (l == mesh.getLimbList()[k]) limbSet.add(k);
}
}
collisionTestLimbs.put(mesh.getBoneLimbMap().get(bone), limbSet);
}
}
private static GeneralizedBody[] bodiesFromMesh(World world, ArticulatedMesh mesh) {
Limb[] result = new Limb[mesh.getLimbList().length];
Map<ArticulatedLimb, Limb> bodyMap = new java.util.HashMap<ArticulatedLimb, Limb>();
for (int i=0; i<result.length; i++) {
ArticulatedLimb limb = mesh.getLimbList()[i];
result[i] = new Limb(world, limb);
bodyMap.put(limb, result[i]);
if (limb.getParent() != null) {
Limb parent = bodyMap.get(limb.getParent());
if (parent == null) throw new IllegalStateException();
Vector3D thispos = result[i].getInitialOrientation().getInverse().transform(
limb.getCurrentLocation().subtract(result[i].getInitialPosition()));
Vector3D parentpos = parent.getInitialOrientation().getInverse().transform(
limb.getCurrentLocation().subtract(parent.getInitialPosition()));
JointConstraint link = new JointConstraint(result[i], thispos, parent, parentpos);
parent.links.add(link);
result[i].links.add(link);
makeRotationConstraint(limb.getBone().getXAxis(), new Vector3D(1,0,0), parent, result[i]);
makeRotationConstraint(limb.getBone().getYAxis(), new Vector3D(0,1,0), parent, result[i]);
makeRotationConstraint(limb.getBone().getZAxis(), new Vector3D(0,0,1), parent, result[i]);
}
}
return result;
}
private static void makeRotationConstraint(AxisConstraint info, Vector3D axis, Limb parent, Limb child) {
if (info == null) return;
RotationConstraint constr = null;
if (Math.abs(info.getMaxExtreme() - info.getMinExtreme()) < 1e-6) {
constr = new RotationConstraint(null, child, axis, parent, 0);
parent.links.add(constr); child.links.add(constr);
} else {
constr = new RotationConstraint(null, child, axis, parent, info.getMaxExtreme());
parent.links.add(constr); child.links.add(constr);
constr = new RotationConstraint(null, child, axis, parent, info.getMinExtreme());
parent.links.add(constr); child.links.add(constr);
}
}
@Override
public MeshBody getBody(int index) {
return (MeshBody) super.getBody(index);
}
@Override
public StateVector getInitialState() {
return new StateVector(this, getBodyArray());
}
@Override
public void interaction(SimulationObject.State ownState, SimulationObject.State partnerState,
InteractionList result, boolean allowReverse) {
if (!(ownState instanceof StateVector)) throw new IllegalArgumentException();
StateVector me = (StateVector) ownState;
if (me.getOwner() != this) throw new IllegalArgumentException();
mesh.setDynamicState(me, null);
for (int i=0; i<getBodies(); i++) {
try {
MeshBody body = (MeshBody) getBody(i);
Body.State bstate = (Body.State) me.getSlice(i);
ArticulatedLimb limb = (ArticulatedLimb) body.getMesh();
// If interaction partner supports collision detection, check for collision.
if (partnerState.getOwner() instanceof Collideable) {
Collideable partner = (Collideable) partnerState.getOwner();
partner.collide((GeneralizedBody.State) partnerState, limb, result);
} else body.interaction(bstate, partnerState, result, true);
// If interacting with the world, we also test for collision amongst the limbs
// and include the joint links
if (partnerState.getOwner() == world) {
for (Integer testLimb : collisionTestLimbs.get(limb))
body.interaction(bstate, me.getSlice(testLimb), result, true);
for (Interaction link : links.get(body)) result.addInteraction(link);
}
} catch (ClassCastException e) {
throw new IllegalStateException(e);
}
}
}
public void collide(GeneralizedBody.State ownState, AnimateMesh partner, InteractionList result) {
if (!(ownState instanceof StateVector)) throw new IllegalArgumentException();
StateVector me = (StateVector) ownState;
if (me.getOwner() != this) throw new IllegalArgumentException();
try {
for (int i=0; i<getBodies(); i++) {
MeshBody body = (MeshBody) getBody(i);
Body.State state = (Body.State) me.getSlice(i);
body.collide(state, partner, result);
}
} catch (ClassCastException e) {
throw new IllegalStateException(e);
}
}
public static class Limb extends MeshBody {
private Set<Interaction> links;
private ArticulatedLimb limb;
private Limb(World world, ArticulatedLimb mesh) {
super(world, mesh);
links = new java.util.HashSet<Interaction>();
limb = mesh;
}
public String toString() {
return limb.getBone().getName();
}
}
} |
package com.podio.sdk.domain;
import com.podio.sdk.internal.Utils;
public class UserStatus {
private final User user = null;
private final Profile profile = null;
private final Integer inbox_new = null;
private final Integer message_unread_count = null;
private final String calendar_code = null;
private final String mailbox = null;
private final Push push = null;
private final Presence presence = null;
// TODO: Add support for these?
// private final Properties properties = null;
// private final Referral referral = null;
// private final Betas betas = null;
// private final List<String> flags = null;
public User getUser() {
return user;
}
public Profile getProfile() {
return profile;
}
//TODO rename this method as it delivers notification inbox count and not message count
public int getUnreadNotificationsCount() {
return Utils.getNative(inbox_new, -1);
}
public int getUnreadMessagesCount() {
return Utils.getNative(message_unread_count, -1);
}
public String getCalendarCode() {
return calendar_code;
}
public String getMailboxPrefix() {
return mailbox;
}
public Push getPush() {
return push;
}
public Presence getPresence() {
return presence;
}
} |
package com.wonderpush.sdk;
import junit.framework.Assert;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
public class JSONSyncTest {
private JSONSync sync;
private static class MockCallbacks implements JSONSync.Callbacks {
private MockServer server;
void setServer(MockServer server) {
this.server = server;
}
@Override
public void save(JSONObject state) {}
@Override
public void schedulePatchCall() {}
@Override
public void serverPatchInstallation(JSONObject diff, JSONSync.ResponseHandler handler) {
server.serverPatchInstallation(diff, handler);
}
}
private static abstract class MockServer {
private boolean called = false;
boolean isCalled() {
return called;
}
final void serverPatchInstallation(JSONObject diff, JSONSync.ResponseHandler handler) {
Assert.assertFalse("Server mock object must not be reused", called);
called = true;
_serverPatchInstallation_diff(diff);
try {
_serverPatchInstallation_do();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
_serverPatchInstallation_handler(handler);
}
protected void _serverPatchInstallation_diff(JSONObject diff) {}
protected void _serverPatchInstallation_do() throws Exception {}
protected void _serverPatchInstallation_handler(JSONSync.ResponseHandler handler) {}
}
private class ServerAssertNotCalled extends MockServer {
@Override
public void _serverPatchInstallation_diff(JSONObject diff) {
Assert.fail("serverPatchInstallation should not be called\nGot diff: " + diff + "\nSync state: " + sync);
}
}
private static class ServerAssertDiffAndSuccess extends MockServer {
private String message;
private JSONObject expectedDiff;
ServerAssertDiffAndSuccess(final String message, final JSONObject expectedDiff) {
this.message = message;
this.expectedDiff = expectedDiff;
}
@Override
public void _serverPatchInstallation_diff(JSONObject diff) {
JSONUtilTest.assertEquals(message, expectedDiff, diff);
}
@Override
public void _serverPatchInstallation_handler(JSONSync.ResponseHandler handler) {
handler.onSuccess();
}
}
private static class ServerAssertDiffAndFailure extends MockServer {
private final String message;
private final JSONObject expectedDiff;
ServerAssertDiffAndFailure(String message, JSONObject expectedDiff) {
this.message = message;
this.expectedDiff = expectedDiff;
}
@Override
public void _serverPatchInstallation_diff(JSONObject diff) {
JSONUtilTest.assertEquals(message, expectedDiff, diff);
}
@Override
public void _serverPatchInstallation_handler(JSONSync.ResponseHandler handler) {
handler.onFailure();
}
}
private MockCallbacks callbacks;
@Before
public void setup() {
callbacks = new MockCallbacks();
sync = new JSONSync(callbacks);
}
private void assertSynced() throws JSONException {
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertFalse(sync.hasScheduledPatchCall());
MockServer server = new ServerAssertNotCalled();
callbacks.setServer(server);
Assert.assertFalse(sync.performScheduledPatchCall());
Assert.assertFalse(server.isCalled());
}
private void assertSyncedPotentialNoopScheduledPatchCall() throws JSONException {
assertPotentialNoopScheduledPatchCall();
assertSynced();
}
private void assertPotentialNoopScheduledPatchCall() throws JSONException {
if (sync.hasScheduledPatchCall()) {
assertNoopScheduledPatchCall();
} else {
Assert.assertTrue(true);
}
}
private void assertNoopScheduledPatchCall() throws JSONException {
Assert.assertFalse(sync.hasInflightPatchCall());
MockServer server = new ServerAssertNotCalled();
callbacks.setServer(server);
Assert.assertTrue(sync.performScheduledPatchCall());
Assert.assertFalse(server.isCalled());
}
private void assertPerformScheduledPatchCallWith(MockServer server) throws JSONException {
callbacks.setServer(server);
Assert.assertTrue(sync.performScheduledPatchCall());
Assert.assertTrue(server.isCalled());
}
@Test
public void initialState() throws JSONException {
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
}
@Test
public void singlePutNullObject() throws JSONException {
sync.put(null);
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void singlePutNullField() throws JSONException {
sync.put(new JSONObject("{\"A\":null}"));
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void singlePutSuccess() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
}
@Test
public void singlePutFailure() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
}
@Test
public void subsequentSinglePutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
sync.put(new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void subsequentSinglePutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
sync.put(new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void pendingPutSuccess() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.put(new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void pendingPutFailure() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.put(new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void putWhileInflightSuccess() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.put(new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
@Test
public void putWhileInflightFailure() throws JSONException {
sync.put(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.put(new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
}
private void assertSyncedAfterRecvDiff() throws JSONException {
// Be laxer with this final state check
//assertNoopScheduledPatchCall();
//assertSynced();
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void recvDiffNullObject() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveDiff(null);
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedAfterRecvDiff();
}
@Test
public void recvDiffFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveDiff(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedAfterRecvDiff();
}
@Test
public void recvDiffFromNonEmptyState() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.receiveDiff(new JSONObject("{\"AA\":null,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedAfterRecvDiff();
}
@Test
public void recvDiffPendingPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":null, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.receiveDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff loses "AAA" and "BB" (common keys) when accepting this received diff
// Hence pending diff is now: {"AA":2, "B":2}
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvDiffPendingPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":null, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.receiveDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff loses "AAA" and "BB" (common keys) when accepting this received diff
// Hence pending diff is now: {"AA":2, "B":2}
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvDiffInflightPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":null, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff becomes: {"AAA":3, "BB":3} (keys common to inflight diff and received diff with values from received diff)
// instead of empty, because the inflight call has overwritten them
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff is: {"AAA":3, "BB":3} (see previous comment) because call succeeded
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AAA\":3,\"BB\":3}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedAfterRecvDiff();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvDiffInflightPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":null, "B":2, "BB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveDiff(new JSONObject("{\"AAA\":3,\"BB\":3,\"C\":3}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff becomes: {"AAA":3, "BB":3} (keys common to inflight diff and received diff with values from received diff)
// instead of empty, because the inflight call has overwritten them
// BUT we will fail this call
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
// Pending diff is: {"AA":2, "B":2}, the previous pending diff minus received keys ("AAA" and "BB")
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"B\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":3,\"B\":2,\"BB\":3,\"C\":3}"), sync.getSdkState());
}
private void assertSyncedAfterRecvState() throws JSONException {
// Be laxer with this final state check
//assertNoopScheduledPatchCall();
//assertSynced();
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void rectStateNullObject() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveState(null, false);
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedAfterRecvState();
}
@Test
public void rectStateNullFieldFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveState(new JSONObject("{\"A\":null}"), false);
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedAfterRecvState();
}
@Test
public void rectStateFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveState(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), false);
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedAfterRecvState();
}
@Test
public void recvStateFromNonEmptyState() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.receiveState(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), false);
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedAfterRecvState();
}
@Test
public void recvStatePendingPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":null,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":null, "AAA":null, "B":2, "BB":2, "BBB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.receiveState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), false);
// "A" is removed
// "AA" is removed even if part of the pending diff, because server state does not have it
// "AAA" is not updated because it's part of the pending diff
// "B" is not removed because it's part of the pending diff
// "BB" is not removed because it's part of the pending diff
// "BBB" is not updated because it's part of the pending diff
// "C" is added
// Pending diff is unchanged because it has the priority for conflict resolution
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStatePendingPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":null,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.receiveState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), false);
// "A" is removed
// "AA" is removed even if part of the pending diff, because server state does not have it
// "AAA" is not updated because it's part of the pending diff
// "B" is not removed because it's part of the pending diff
// "BB" is not removed because it's part of the pending diff
// "BBB" is not updated because it's part of the pending diff
// "C" is added
// Pending diff is unchanged because it has the priority for conflict resolution
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStateInflightPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":null,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":null,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), false);
// "A" is removed
// "AA" is not removed because it's part of the inflight diff
// "AAA" is not updated because it's part of the inflight diff
// "B" is not removed because it's part of the inflight diff
// "BB" is not removed because it's part of the inflight diff
// "BBB" is not updated because it's part of the inflight diff
// "C" is added
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedAfterRecvState();
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStateInflightPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":null,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":null,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), false);
// "A" is removed
// "AA" is removed even if part of the inflight diff, because server state does not have it
// "AAA" is not updated because it's part of the inflight diff
// "B" is not removed because it's part of the inflight diff
// "BB" is not removed because it's part of the inflight diff
// "BBB" is not updated because it's part of the inflight diff
// "C" is added
// Pending diff is unchanged because it has the priority for conflict resolution
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"B\":2,\"BB\":2,\"BBB\":2,\"C\":3}"), sync.getSdkState());
}
private void assertSyncedAfterRecvStateReset() throws JSONException {
// Be laxer with this final state check
//assertNoopScheduledPatchCall();
//assertSynced();
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void recvStateResetNullObject() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveState(null, true);
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedAfterRecvStateReset();
}
@Test
public void recvStateResetNullFieldFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveState(new JSONObject("{\"A\":null}"), true);
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedAfterRecvStateReset();
}
@Test
public void recvStateResetFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveState(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), true);
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedAfterRecvStateReset();
}
@Test
public void recvStateResetFromNonEmptyState() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.receiveState(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), true);
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"), sync.getSdkState());
assertSyncedAfterRecvStateReset();
}
@Test
public void recvStateResetPendingPut() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":null, "B":2, "BB":2, "BBB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
sync.receiveState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), true);
// Pending diff is discarded
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedAfterRecvStateReset();
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStateResetInflightPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), true);
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
// Called (unfortunately!) succeeded, we have to revert the changed fields
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":null,\"AAA\":3,\"B\":null,\"BB\":null,\"BBB\":3}")));
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
assertSyncedAfterRecvStateReset();
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
}
@Test
public void recvStateResetInflightPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveState(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), true);
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
// Called (hopefully!) failed, we have no change to send
assertSyncedPotentialNoopScheduledPatchCall();
JSONUtilTest.assertEquals(new JSONObject("{\"AAA\":3,\"BBB\":3,\"C\":3}"), sync.getSdkState());
}
private void assertSyncedAfterRecvSrvState() throws JSONException {
// Be laxer with this final state check
//assertNoopScheduledPatchCall();
//assertSynced();
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void recvSrvStateNullObject() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveServerState(null);
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void recvSrvStateNullField() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveServerState(new JSONObject("{\"A\":null}"));
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedPotentialNoopScheduledPatchCall();
}
@Test
public void recvSrvStateFromInitialState() throws JSONException {
assertSynced();
JSONUtilTest.assertEquals(new JSONObject(), sync.getSdkState());
sync.receiveServerState(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"));
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":null,\"AA\":null,\"AAA\":null}")));
JSONUtilTest.assertEquals(new JSONObject("{}"), sync.getSdkState());
assertSyncedAfterRecvSrvState();
}
@Test
public void recvSrvStateFromNonEmptyState() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.receiveServerState(new JSONObject("{\"A\":1,\"AAA\":2,\"B\":2,\"BB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":1,\"AAA\":1,\"B\":null,\"BB\":null}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSyncedAfterRecvSrvState();
}
@Test
public void recvSrvStatePendingPut() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
// Pending diff is: {"AA":2, "AAA":null, "B":2, "BB":2, "BBB":2}
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
sync.receiveServerState(new JSONObject("{\"AAA\":3,\"BB\":2,\"BBB\":3,\"C\":3}"));
// "A" is added because it has vanished
// "AA" is kept because it has vanished
// "AAA" is kept because the underlying value still has not the desired value
// "B" is kept because it has vanished
// "BB" is removed because it has now the desired value
// "C" is added because it has appeared
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":null,\"B\":2,\"BBB\":2,\"C\":null}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
assertSyncedAfterRecvSrvState();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
}
@Test
public void recvSrvStateInflightPutSuccess() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveServerState(new JSONObject("{\"AAA\":3,\"BB\":2,\"BBB\":3,\"C\":3}"));
// "A" is added because it has vanished
// "C" is added because it has appeared
// The rest will be properly applied and will be discarded on success
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"C\":null}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
assertSyncedAfterRecvSrvState();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
}
@Test
public void recvSrvStateInflightPutFailure() throws JSONException {
singlePutSuccess();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":1,\"AAA\":1}"), sync.getSdkState());
assertSynced();
sync.put(new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}"));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
Assert.assertFalse(sync.hasInflightPatchCall());
Assert.assertTrue(sync.hasScheduledPatchCall());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndFailure(null, new JSONObject("{\"AA\":2,\"AAA\":null,\"B\":2,\"BB\":2,\"BBB\":2}")) {
@Override
protected void _serverPatchInstallation_do() throws Exception {
sync.receiveServerState(new JSONObject("{\"AAA\":3,\"BB\":2,\"BBB\":3,\"C\":3}"));
// "A" is added because it has vanished
// "AA" is kept because it has vanished
// "AAA" is kept because the underlying value still has not the desired value
// "B" is kept because it has vanished
// "BB" is removed because it has now the desired value
// "C" is added because it has appeared
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
}
});
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
assertPerformScheduledPatchCallWith(new ServerAssertDiffAndSuccess(null, new JSONObject("{\"A\":1,\"AA\":2,\"AAA\":null,\"B\":2,\"BBB\":2,\"C\":null}")));
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
assertSyncedAfterRecvSrvState();
JSONUtilTest.assertEquals(new JSONObject("{\"A\":1,\"AA\":2,\"B\":2,\"BB\":2,\"BBB\":2}"), sync.getSdkState());
}
} |
package yuku.kpriviewer.fr;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import yuku.afw.V;
import yuku.alkitab.base.fr.base.BaseFragment;
import yuku.alkitab.debug.R;
import yuku.kpri.model.Lyric;
import yuku.kpri.model.Song;
import yuku.kpri.model.Verse;
import yuku.kpri.model.VerseKind;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;
public class SongFragment extends BaseFragment {
public static final String TAG = SongFragment.class.getSimpleName();
private static final String ARG_song = "song";
private static final String ARG_templateFile = "templateFile";
private static final String ARG_customVars = "customVars";
private WebView webview;
private Song song;
private String templateFile;
private Bundle customVars;
public interface ShouldOverrideUrlLoadingHandler {
boolean shouldOverrideUrlLoading(WebViewClient client, WebView view, String url);
}
public static SongFragment create(Song song, String templateFile, Bundle optionalCustomVars) {
SongFragment res = new SongFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_song, song);
args.putString(ARG_templateFile, templateFile);
if (optionalCustomVars != null) args.putBundle(ARG_customVars, optionalCustomVars);
res.setArguments(args);
return res;
}
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
song = getArguments().getParcelable(ARG_song);
templateFile = getArguments().getString(ARG_templateFile);
customVars = getArguments().getBundle(ARG_customVars);
}
@SuppressLint("SetJavaScriptEnabled")
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View res = inflater.inflate(R.layout.fragment_song, container, false);
webview = V.get(res, R.id.webview);
webview.setBackgroundColor(0x00000000);
webview.setWebViewClient(webViewClient);
final WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
settings.setDisplayZoomControls(false);
// prevent user system-wide display settings (sp scaling) from changing the actual text size inside webview.
settings.setTextZoom(100);
return res;
}
@Override public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
renderLagu(song);
}
final WebViewClient webViewClient = new WebViewClient() {
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
Activity activity = getActivity();
if (activity instanceof ShouldOverrideUrlLoadingHandler && ((ShouldOverrideUrlLoadingHandler)activity).shouldOverrideUrlLoading(this, view, url)) {
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
boolean pendingResize = false;
@Override
public void onScaleChanged(final WebView view, final float oldScale, final float newScale) {
super.onScaleChanged(view, oldScale, newScale);
// "restore" auto text-wrapping behavior from before KitKat
if (pendingResize) return;
pendingResize = true;
view.postDelayed(() -> {
final String script = "document.getElementsByTagName('body')[0].style.width = window.innerWidth + 'px';";
if (Build.VERSION.SDK_INT >= 19) {
view.evaluateJavascript(script, null);
} else {
view.loadUrl("javascript:" + script);
}
pendingResize = false;
}, 100);
}
};
private void renderLagu(Song song) {
try {
InputStream is = getResources().getAssets().open(templateFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[4096];
while (true) {
int read = is.read(buf);
if (read < 0) break;
baos.write(buf, 0, read);
}
String template = new String(baos.toByteArray(), "utf-8");
if (customVars != null) {
for (String key: customVars.keySet()) {
template = templateVarReplace(template, key, customVars.get(key));
}
}
template = templateDivReplace(template, "code", song.code);
template = templateDivReplace(template, "title", song.title);
template = templateDivReplace(template, "title_original", song.title_original);
template = templateDivReplace(template, "tune", song.tune);
template = templateDivReplace(template, "keySignature", song.keySignature);
template = templateDivReplace(template, "timeSignature", song.timeSignature);
template = templateDivReplace(template, "authors_lyric", song.authors_lyric);
template = templateDivReplace(template, "authors_music", song.authors_music);
template = templateDivReplace(template, "lyrics", songToHtml(song, false));
webview.loadDataWithBaseURL("file:///android_asset/" + templateFile, template, "text/html", "utf-8", null);
} catch (Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
webview.loadDataWithBaseURL(null, sw.toString(), "text/plain", "utf-8", null);
}
}
public static String songToHtml(final Song song, final boolean forPatchText) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < song.lyrics.size(); i++) {
Lyric lyric = song.lyrics.get(i);
sb.append("<div class='lyric'>");
if (song.lyrics.size() > 1 || lyric.caption != null) { // otherwise, only lyric and has no name
if (lyric.caption != null) {
sb.append("<div class='lyric_caption'>").append(lyric.caption).append("</div>");
} else {
sb.append("<div class='lyric_caption'>Versi ").append(i + 1).append("</div>");
}
}
int bait_normal_no = 0;
int bait_reff_no = 0;
for (Verse verse: lyric.verses) {
sb.append("<div class='verse" + (verse.kind == VerseKind.REFRAIN? " refrain": "") + "'>");
{
if (verse.kind == VerseKind.REFRAIN) {
bait_reff_no++;
} else {
bait_normal_no++;
}
if (forPatchText) {
sb.append(verse.kind == VerseKind.REFRAIN ? ("reff " + bait_reff_no) : bait_normal_no);
} else {
sb.append("<div class='verse_ordering'>" + (verse.kind == VerseKind.REFRAIN? bait_reff_no: bait_normal_no) + "</div>");
}
sb.append("<div class='verse_content'>");
for (String line : verse.lines) {
if (forPatchText) {
sb.append(line).append("<br/>");
} else {
sb.append("<p class='line'>").append(line).append("</p>");
}
}
sb.append("</div>");
}
sb.append("</div>");
}
sb.append("</div>");
}
return sb.toString();
}
private String templateDivReplace(String template, String name, String value) {
return template.replace("{{div:" + name + "}}", value == null ? "" : ("<div class='" + name + "'>" + value + "</div>"));
}
private String templateDivReplace(String template, String name, List<String> value) {
return templateDivReplace(template, name, value == null ? null : TextUtils.join("; ", value.toArray(new String[value.size()])));
}
private String templateVarReplace(String template, String name, Object value) {
return template.replace("{{$" + name + "}}", value == null ? "" : value.toString());
}
public int getWebViewTextZoom() {
if (webview == null) return 0; // not ready
return webview.getSettings().getTextZoom();
}
public void setWebViewTextZoom(final int percent) {
if (webview == null) return;
webview.getSettings().setTextZoom(percent);
}
} |
package edu.utah.sci.cyclist.ui.components;
import edu.utah.sci.cyclist.event.ui.FilterEvent;
import edu.utah.sci.cyclist.model.FieldProperties;
import edu.utah.sci.cyclist.model.Filter;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.geometry.Side;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
public class FilterGlyph extends HBox {
private Filter _filter;
private StackPane _button;
private boolean _remote;
private ObjectProperty<EventHandler<FilterEvent>> _action = new SimpleObjectProperty<>();
public FilterGlyph(Filter filter) {
this(filter, false);
}
public FilterGlyph(Filter filter, boolean remote) {
_filter = filter;
_remote = remote;
build();
}
public Filter getFilter() {
return _filter;
}
public ObjectProperty<EventHandler<FilterEvent>> onAction() {
return _action;
}
public void setOnAction( EventHandler<FilterEvent> handler) {
_action.set(handler);
}
public EventHandler<FilterEvent> getOnAction() {
return _action.get();
}
private void build() {
this.getStyleClass().add("filter-glyph");
this.setSpacing(5);
StackPane stackPane = new StackPane();
stackPane.setAlignment(Pos.CENTER);
getStyleClass().add("filter-glyph");
setSpacing(5);
if (_remote) {
setStyle("-fx-background-color: #d0ced1");
}
Label label = new Label(_filter.getName());
label.getStyleClass().add("text");
_button = new StackPane();
_button.getStyleClass().add("arrow");
_button.setMaxHeight(8);
_button.setMaxWidth(6);
stackPane.getChildren().add(_button);
this.getChildren().addAll(label,stackPane);
createMenu();
}
private void createMenu() {
final ContextMenu contextMenu = new ContextMenu();
MenuItem show = new MenuItem("Show");
show.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
if (getOnAction() != null) {
getOnAction().handle(new FilterEvent(FilterEvent.SHOW, _filter));
}
}
});
contextMenu.getItems().add(show);
if (!_remote) {
MenuItem delete = new MenuItem("Delete");
delete.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
if (getOnAction() != null) {
getOnAction().handle(new FilterEvent(FilterEvent.DELETE, _filter));
//This message is for removing the filter completely also from the field glyph.
if(_filter.getField().getString(FieldProperties.AGGREGATION_FUNC) != null)
{
getOnAction().handle(new FilterEvent(FilterEvent.REMOVE_FILTER_FIELD, _filter));
}
}
}
});
contextMenu.getItems().add(delete);
}
_button.setOnMousePressed(new EventHandler<Event>() {
@Override
public void handle(Event event) {
contextMenu.show(_button, Side.BOTTOM, 0, 0);
}
});
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.