diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/info/ata4/bspsrc/cli/BspSourceCli.java b/src/info/ata4/bspsrc/cli/BspSourceCli.java
index 256565a..79d6035 100644
--- a/src/info/ata4/bspsrc/cli/BspSourceCli.java
+++ b/src/info/ata4/bspsrc/cli/BspSourceCli.java
@@ -1,352 +1,352 @@
/*
** 2011 April 5
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
*/
package info.ata4.bspsrc.cli;
import info.ata4.bsplib.appid.AppID;
import info.ata4.bspsrc.*;
import java.io.File;
import java.util.Collection;
import java.util.Set;
import java.util.logging.Logger;
import org.apache.commons.cli.*;
import org.apache.commons.io.FileUtils;
/**
* Helper class for CLI parsing and handling.
*
* @author Nico Bergemann <barracuda415 at yahoo.de>
*/
public class BspSourceCli {
private static final Logger L = Logger.getLogger(BspSourceCli.class.getName());
private Options optsMain = new Options();
private Options optsEntity = new Options();
private Options optsWorld = new Options();
private Options optsTexture = new Options();
private Options optsOther = new Options();
private MultiOptions optsAll = new MultiOptions();
/**
* Prints application usage, then exits the app.
*/
private void printHelp() {
System.out.println("BSPSource " + BspSource.VERSION);
System.out.println("usage: bspsrc [options] <path> [path...]");
System.out.println();
OptionHelpFormatter clHelp = new OptionHelpFormatter();
clHelp.printHelp("Main options:", optsMain);
clHelp.printHelp("Entity options:", optsEntity);
clHelp.printHelp("World brush options:", optsWorld);
clHelp.printHelp("Texture options:", optsTexture);
clHelp.printHelp("Other options:", optsOther);
System.exit(0);
}
/**
* Prints application version, then exits the app.
*/
private void printVersion() {
System.out.println("BSPSource " + BspSource.VERSION);
System.out.println();
System.out.println("Based on VMEX v0.98g by Rof <[email protected]>");
System.out.println("Extended and modified by Nico Bergemann <[email protected]>");
System.exit(0);
}
private void printAppIDs() {
System.out.printf("%6s %-25s %s\n", "ID", "String ID", "Name");
AppID[] ids = AppID.values();
for (AppID id : ids) {
System.out.printf("%6d %-25s %s\n", id.getID(), id.name(), id);
}
System.exit(0);
}
/**
* Parses an arguments string and applies all settings to BSPSource.
*
* @param args arguments string
*/
@SuppressWarnings("static-access")
public BspSourceConfig getConfig(String[] args) {
BspSourceConfig config = new BspSourceConfig();
// basic options
Option helpOpt, versionOpt, debugOpt, outputOpt, recursiveOpt;
optsMain.addOption(helpOpt = new Option("h", "Print this help."));
optsMain.addOption(versionOpt = new Option("v", "Print version info."));
optsMain.addOption(debugOpt = new Option("d", "Enable debug mode. Increases verbosity and adds additional data to the VMF file."));
optsMain.addOption(recursiveOpt = new Option("r", "Decompile all files found in the given directory."));
optsMain.addOption(outputOpt = OptionBuilder
.hasArg()
.withArgName("file")
.withDescription("Override output path for VMF file(s). Treated as directory if multiple BSP files are provided. \ndefault: <mappath>/<mapname>_d.vmf")
.withType(String.class)
.create('o'));
// entity options
Option nbentsOpt, npentsOpt, npropsOpt, noverlOpt, ncubemOpt, ndetailsOpt, nareapOpt, nocclOpt, nrotfixOpt;
optsEntity.addOption(npentsOpt = new Option("no_point_ents", "Don't write any point entities."));
optsEntity.addOption(nbentsOpt = new Option("no_brush_ents", "Don't write any brush entities."));
optsEntity.addOption(npropsOpt = new Option("no_sprp", "Don't write prop_static entities."));
optsEntity.addOption(noverlOpt = new Option("no_overlays", "Don't write info_overlay entities."));
optsEntity.addOption(ncubemOpt = new Option("no_cubemaps", "Don't write env_cubemap entities."));
optsEntity.addOption(ndetailsOpt = new Option("no_details", "Don't write func_detail entities."));
optsEntity.addOption(nareapOpt = new Option("no_areaportals", "Don't write func_areaportal(_window) entities."));
optsEntity.addOption(nocclOpt = new Option("no_occluders", "Don't write func_occluder entities."));
optsEntity.addOption(nrotfixOpt = new Option("no_rotfix", "Don't fix instance entity brush rotations for Hammer."));
// world brush options
Option nbrushOpt, ndispOpt, bmodeOpt, thicknOpt;
optsWorld.addOption(nbrushOpt = new Option("no_brushes", "Don't write any world brushes."));
optsWorld.addOption(ndispOpt = new Option("no_disps", "Don't write displacement surfaces."));
optsWorld.addOption(bmodeOpt = OptionBuilder
.hasArg()
.withArgName("enum")
.withDescription("Brush decompiling mode:\n" +
BrushMode.BRUSHPLANES.name() + " - brushes and planes\n" +
BrushMode.ORIGFACE.name() + " - original faces only\n" +
BrushMode.ORIGFACE_PLUS.name() + " - original + split faces\n" +
BrushMode.SPLITFACE.name() + " - split faces only\n" +
"default: " + config.brushMode.name())
.create("brushmode"));
optsWorld.addOption(thicknOpt = OptionBuilder
.hasArg()
.withArgName("float")
.withDescription("Thickness of brushes created from flat faces in units.\n" +
"default: " + config.backfaceDepth)
.create("thickness"));
// texture options
Option ntexfixOpt, ftexOpt, bftexOpt;
optsTexture.addOption(ntexfixOpt = new Option("no_texfix", "Don't fix texture names."));
optsTexture.addOption(ftexOpt = OptionBuilder
.hasArg()
.withArgName("string")
.withDescription("Replace all face textures with this one.")
.create("facetex"));
optsTexture.addOption(bftexOpt = OptionBuilder
.hasArg()
.withArgName("string")
.withDescription("Replace all back-face textures with this one. Used in face-based decompiling modes only.")
.create("bfacetex"));
// other options
Option nvmfOpt, nlumpfilesOpt, nprotOpt, listappidsOpt, appidOpt, nvisgrpOpt, ncamsOpt, formatOpt;
optsOther.addOption(nvmfOpt = new Option("no_vmf", "Don't write any VMF files, read BSP only."));
optsOther.addOption(nlumpfilesOpt = new Option("no_lumpfiles", "Don't load lump files (.lmp) associated with the BSP file."));
optsOther.addOption(nprotOpt = new Option("no_prot", "Skip decompiling protection checking. Can increase speed when mass-decompiling unprotected maps."));
optsOther.addOption(listappidsOpt = new Option("appids", "List all available application IDs"));
optsOther.addOption(nvisgrpOpt = new Option("no_visgroups", "Don't group entities from instances into visgroups."));
optsOther.addOption(ncamsOpt = new Option("no_cams", "Don't create Hammer cameras above each player spawn."));
optsOther.addOption(appidOpt = OptionBuilder
.hasArg()
.withArgName("string/int")
.withDescription("Overrides game detection by using " +
"this Steam Application ID instead.\n" +
"Use -appids to list all known app-IDs.")
.create("appid"));
optsOther.addOption(formatOpt = OptionBuilder
.hasArg()
.withArgName("enum")
.withDescription("Sets the VMF format used for the decompiled maps:\n" +
SourceFormat.AUTO.name() + " - " + SourceFormat.AUTO + "\n" +
SourceFormat.OLD.name() + " - " + SourceFormat.OLD + "\n" +
SourceFormat.NEW.name() + " - " + SourceFormat.NEW + "\n" +
"default: " + config.sourceFormat.name())
.create("format"));
// all options
optsAll.addOptions(optsMain);
optsAll.addOptions(optsEntity);
optsAll.addOptions(optsWorld);
optsAll.addOptions(optsTexture);
optsAll.addOptions(optsOther);
if (args.length == 0) {
printHelp();
System.exit(0);
}
CommandLineParser clParser = new PosixParser();
CommandLine cl = null;
File outputFile = null;
boolean recursive = false;
try {
// parse the command line arguments
cl = clParser.parse(optsAll, args);
// help
if(cl.hasOption(helpOpt.getOpt())) {
printHelp();
}
// version
if (cl.hasOption(versionOpt.getOpt())) {
printVersion();
}
// list app-ids
if (cl.hasOption(listappidsOpt.getOpt())) {
printAppIDs();
}
// main options
config.setDebug(cl.hasOption(debugOpt.getOpt()));
if (cl.hasOption(outputOpt.getOpt())) {
outputFile = new File(cl.getOptionValue(outputOpt.getOpt()));
}
recursive = cl.hasOption(recursiveOpt.getOpt());
// entity options
config.writePointEntities = !cl.hasOption(npentsOpt.getOpt());
config.writeBrushEntities = !cl.hasOption(nbentsOpt.getOpt());
config.writeStaticProps = !cl.hasOption(npropsOpt.getOpt());
config.writeOverlays = !cl.hasOption(noverlOpt.getOpt());
config.writeDisp = !cl.hasOption(ndispOpt.getOpt());
config.writeAreaportals = !cl.hasOption(nareapOpt.getOpt());
config.writeOccluders = !cl.hasOption(nocclOpt.getOpt());
config.writeCubemaps = !cl.hasOption(ncubemOpt.getOpt());
config.writeDetails = !cl.hasOption(ndetailsOpt.getOpt());
// world options
config.writeWorldBrushes = !cl.hasOption(nbrushOpt.getOpt());
if (cl.hasOption(bmodeOpt.getOpt())) {
String modeStr = cl.getOptionValue(bmodeOpt.getOpt());
try {
config.brushMode = BrushMode.valueOf(modeStr);
} catch (IllegalArgumentException ex) {
// try again as ordinal enum value
try {
int mode = Integer.valueOf(modeStr.toUpperCase());
config.brushMode = BrushMode.fromOrdinal(mode);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid brush mode");
}
}
}
if (cl.hasOption(formatOpt.getOpt())) {
String formatStr = cl.getOptionValue(formatOpt.getOpt());
try {
config.sourceFormat = SourceFormat.valueOf(formatStr);
} catch (IllegalArgumentException ex) {
// try again as ordinal enum value
try {
int format = Integer.valueOf(formatStr.toUpperCase());
config.sourceFormat = SourceFormat.fromOrdinal(format);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid source format");
}
}
}
if (cl.hasOption(thicknOpt.getOpt())) {
float thickness = Float.valueOf(cl.getOptionValue(thicknOpt.getOpt()));
config.backfaceDepth = thickness;
}
// texture options
config.fixCubemapTextures = !cl.hasOption(ntexfixOpt.getOpt());
if (cl.hasOption(ftexOpt.getOpt())) {
config.faceTexture = cl.getOptionValue(ftexOpt.getOpt());
}
if (cl.hasOption(bftexOpt.getOpt())) {
config.backfaceTexture = cl.getOptionValue(bftexOpt.getOpt());
}
// other options
config.loadLumpFiles = !cl.hasOption(nlumpfilesOpt.getOpt());
config.skipProt = cl.hasOption(nprotOpt.getOpt());
config.fixEntityRot = !cl.hasOption(nrotfixOpt.getOpt());
config.nullOutput = cl.hasOption(nvmfOpt.getOpt());
config.writeVisgroups = !cl.hasOption(nvisgrpOpt.getOpt());
config.writeCameras = !cl.hasOption(ncamsOpt.getOpt());
if (cl.hasOption(appidOpt.getOpt())) {
- String appidStr = cl.getOptionValue(appidOpt.getOpt());
+ String appidStr = cl.getOptionValue(appidOpt.getOpt()).toUpperCase();
try {
config.defaultAppID = AppID.valueOf(appidStr);
} catch (IllegalArgumentException ex) {
// try again as integer ID
try {
- int appid = Integer.valueOf(appidStr.toUpperCase());
+ int appid = Integer.valueOf(appidStr);
config.defaultAppID = AppID.fromID(appid);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid default AppID");
}
}
}
} catch (Exception ex) {
L.severe(ex.getMessage());
System.exit(0);
}
// get non-recognized arguments, these are the BSP input files
String[] argsLeft = cl.getArgs();
Set<BspFileEntry> files = config.getFileSet();
if (argsLeft.length == 0) {
L.severe("No BSP file(s) specified");
System.exit(1);
} else if (argsLeft.length == 1 && outputFile != null) {
// set VMF file for one BSP
BspFileEntry entry = new BspFileEntry(new File(argsLeft[0]));
entry.setVmfFile(outputFile);
files.add(entry);
} else {
for (String arg : argsLeft) {
File file = new File(arg);
if (file.isDirectory()) {
Collection<File> subFiles = FileUtils.listFiles(file, new String[]{"bsp"}, recursive);
for (File subFile : subFiles) {
BspFileEntry entry = new BspFileEntry(subFile);
// override destination directory?
if (outputFile != null) {
entry.setVmfFile(new File(outputFile, entry.getVmfFile().getName()));
}
files.add(entry);
}
} else {
BspFileEntry entry = new BspFileEntry(file);
// override destination directory?
if (outputFile != null) {
entry.setVmfFile(new File(outputFile, entry.getVmfFile().getName()));
}
files.add(entry);
}
}
}
return config;
}
}
| false | true | public BspSourceConfig getConfig(String[] args) {
BspSourceConfig config = new BspSourceConfig();
// basic options
Option helpOpt, versionOpt, debugOpt, outputOpt, recursiveOpt;
optsMain.addOption(helpOpt = new Option("h", "Print this help."));
optsMain.addOption(versionOpt = new Option("v", "Print version info."));
optsMain.addOption(debugOpt = new Option("d", "Enable debug mode. Increases verbosity and adds additional data to the VMF file."));
optsMain.addOption(recursiveOpt = new Option("r", "Decompile all files found in the given directory."));
optsMain.addOption(outputOpt = OptionBuilder
.hasArg()
.withArgName("file")
.withDescription("Override output path for VMF file(s). Treated as directory if multiple BSP files are provided. \ndefault: <mappath>/<mapname>_d.vmf")
.withType(String.class)
.create('o'));
// entity options
Option nbentsOpt, npentsOpt, npropsOpt, noverlOpt, ncubemOpt, ndetailsOpt, nareapOpt, nocclOpt, nrotfixOpt;
optsEntity.addOption(npentsOpt = new Option("no_point_ents", "Don't write any point entities."));
optsEntity.addOption(nbentsOpt = new Option("no_brush_ents", "Don't write any brush entities."));
optsEntity.addOption(npropsOpt = new Option("no_sprp", "Don't write prop_static entities."));
optsEntity.addOption(noverlOpt = new Option("no_overlays", "Don't write info_overlay entities."));
optsEntity.addOption(ncubemOpt = new Option("no_cubemaps", "Don't write env_cubemap entities."));
optsEntity.addOption(ndetailsOpt = new Option("no_details", "Don't write func_detail entities."));
optsEntity.addOption(nareapOpt = new Option("no_areaportals", "Don't write func_areaportal(_window) entities."));
optsEntity.addOption(nocclOpt = new Option("no_occluders", "Don't write func_occluder entities."));
optsEntity.addOption(nrotfixOpt = new Option("no_rotfix", "Don't fix instance entity brush rotations for Hammer."));
// world brush options
Option nbrushOpt, ndispOpt, bmodeOpt, thicknOpt;
optsWorld.addOption(nbrushOpt = new Option("no_brushes", "Don't write any world brushes."));
optsWorld.addOption(ndispOpt = new Option("no_disps", "Don't write displacement surfaces."));
optsWorld.addOption(bmodeOpt = OptionBuilder
.hasArg()
.withArgName("enum")
.withDescription("Brush decompiling mode:\n" +
BrushMode.BRUSHPLANES.name() + " - brushes and planes\n" +
BrushMode.ORIGFACE.name() + " - original faces only\n" +
BrushMode.ORIGFACE_PLUS.name() + " - original + split faces\n" +
BrushMode.SPLITFACE.name() + " - split faces only\n" +
"default: " + config.brushMode.name())
.create("brushmode"));
optsWorld.addOption(thicknOpt = OptionBuilder
.hasArg()
.withArgName("float")
.withDescription("Thickness of brushes created from flat faces in units.\n" +
"default: " + config.backfaceDepth)
.create("thickness"));
// texture options
Option ntexfixOpt, ftexOpt, bftexOpt;
optsTexture.addOption(ntexfixOpt = new Option("no_texfix", "Don't fix texture names."));
optsTexture.addOption(ftexOpt = OptionBuilder
.hasArg()
.withArgName("string")
.withDescription("Replace all face textures with this one.")
.create("facetex"));
optsTexture.addOption(bftexOpt = OptionBuilder
.hasArg()
.withArgName("string")
.withDescription("Replace all back-face textures with this one. Used in face-based decompiling modes only.")
.create("bfacetex"));
// other options
Option nvmfOpt, nlumpfilesOpt, nprotOpt, listappidsOpt, appidOpt, nvisgrpOpt, ncamsOpt, formatOpt;
optsOther.addOption(nvmfOpt = new Option("no_vmf", "Don't write any VMF files, read BSP only."));
optsOther.addOption(nlumpfilesOpt = new Option("no_lumpfiles", "Don't load lump files (.lmp) associated with the BSP file."));
optsOther.addOption(nprotOpt = new Option("no_prot", "Skip decompiling protection checking. Can increase speed when mass-decompiling unprotected maps."));
optsOther.addOption(listappidsOpt = new Option("appids", "List all available application IDs"));
optsOther.addOption(nvisgrpOpt = new Option("no_visgroups", "Don't group entities from instances into visgroups."));
optsOther.addOption(ncamsOpt = new Option("no_cams", "Don't create Hammer cameras above each player spawn."));
optsOther.addOption(appidOpt = OptionBuilder
.hasArg()
.withArgName("string/int")
.withDescription("Overrides game detection by using " +
"this Steam Application ID instead.\n" +
"Use -appids to list all known app-IDs.")
.create("appid"));
optsOther.addOption(formatOpt = OptionBuilder
.hasArg()
.withArgName("enum")
.withDescription("Sets the VMF format used for the decompiled maps:\n" +
SourceFormat.AUTO.name() + " - " + SourceFormat.AUTO + "\n" +
SourceFormat.OLD.name() + " - " + SourceFormat.OLD + "\n" +
SourceFormat.NEW.name() + " - " + SourceFormat.NEW + "\n" +
"default: " + config.sourceFormat.name())
.create("format"));
// all options
optsAll.addOptions(optsMain);
optsAll.addOptions(optsEntity);
optsAll.addOptions(optsWorld);
optsAll.addOptions(optsTexture);
optsAll.addOptions(optsOther);
if (args.length == 0) {
printHelp();
System.exit(0);
}
CommandLineParser clParser = new PosixParser();
CommandLine cl = null;
File outputFile = null;
boolean recursive = false;
try {
// parse the command line arguments
cl = clParser.parse(optsAll, args);
// help
if(cl.hasOption(helpOpt.getOpt())) {
printHelp();
}
// version
if (cl.hasOption(versionOpt.getOpt())) {
printVersion();
}
// list app-ids
if (cl.hasOption(listappidsOpt.getOpt())) {
printAppIDs();
}
// main options
config.setDebug(cl.hasOption(debugOpt.getOpt()));
if (cl.hasOption(outputOpt.getOpt())) {
outputFile = new File(cl.getOptionValue(outputOpt.getOpt()));
}
recursive = cl.hasOption(recursiveOpt.getOpt());
// entity options
config.writePointEntities = !cl.hasOption(npentsOpt.getOpt());
config.writeBrushEntities = !cl.hasOption(nbentsOpt.getOpt());
config.writeStaticProps = !cl.hasOption(npropsOpt.getOpt());
config.writeOverlays = !cl.hasOption(noverlOpt.getOpt());
config.writeDisp = !cl.hasOption(ndispOpt.getOpt());
config.writeAreaportals = !cl.hasOption(nareapOpt.getOpt());
config.writeOccluders = !cl.hasOption(nocclOpt.getOpt());
config.writeCubemaps = !cl.hasOption(ncubemOpt.getOpt());
config.writeDetails = !cl.hasOption(ndetailsOpt.getOpt());
// world options
config.writeWorldBrushes = !cl.hasOption(nbrushOpt.getOpt());
if (cl.hasOption(bmodeOpt.getOpt())) {
String modeStr = cl.getOptionValue(bmodeOpt.getOpt());
try {
config.brushMode = BrushMode.valueOf(modeStr);
} catch (IllegalArgumentException ex) {
// try again as ordinal enum value
try {
int mode = Integer.valueOf(modeStr.toUpperCase());
config.brushMode = BrushMode.fromOrdinal(mode);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid brush mode");
}
}
}
if (cl.hasOption(formatOpt.getOpt())) {
String formatStr = cl.getOptionValue(formatOpt.getOpt());
try {
config.sourceFormat = SourceFormat.valueOf(formatStr);
} catch (IllegalArgumentException ex) {
// try again as ordinal enum value
try {
int format = Integer.valueOf(formatStr.toUpperCase());
config.sourceFormat = SourceFormat.fromOrdinal(format);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid source format");
}
}
}
if (cl.hasOption(thicknOpt.getOpt())) {
float thickness = Float.valueOf(cl.getOptionValue(thicknOpt.getOpt()));
config.backfaceDepth = thickness;
}
// texture options
config.fixCubemapTextures = !cl.hasOption(ntexfixOpt.getOpt());
if (cl.hasOption(ftexOpt.getOpt())) {
config.faceTexture = cl.getOptionValue(ftexOpt.getOpt());
}
if (cl.hasOption(bftexOpt.getOpt())) {
config.backfaceTexture = cl.getOptionValue(bftexOpt.getOpt());
}
// other options
config.loadLumpFiles = !cl.hasOption(nlumpfilesOpt.getOpt());
config.skipProt = cl.hasOption(nprotOpt.getOpt());
config.fixEntityRot = !cl.hasOption(nrotfixOpt.getOpt());
config.nullOutput = cl.hasOption(nvmfOpt.getOpt());
config.writeVisgroups = !cl.hasOption(nvisgrpOpt.getOpt());
config.writeCameras = !cl.hasOption(ncamsOpt.getOpt());
if (cl.hasOption(appidOpt.getOpt())) {
String appidStr = cl.getOptionValue(appidOpt.getOpt());
try {
config.defaultAppID = AppID.valueOf(appidStr);
} catch (IllegalArgumentException ex) {
// try again as integer ID
try {
int appid = Integer.valueOf(appidStr.toUpperCase());
config.defaultAppID = AppID.fromID(appid);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid default AppID");
}
}
}
} catch (Exception ex) {
L.severe(ex.getMessage());
System.exit(0);
}
// get non-recognized arguments, these are the BSP input files
String[] argsLeft = cl.getArgs();
Set<BspFileEntry> files = config.getFileSet();
if (argsLeft.length == 0) {
L.severe("No BSP file(s) specified");
System.exit(1);
} else if (argsLeft.length == 1 && outputFile != null) {
// set VMF file for one BSP
BspFileEntry entry = new BspFileEntry(new File(argsLeft[0]));
entry.setVmfFile(outputFile);
files.add(entry);
} else {
for (String arg : argsLeft) {
File file = new File(arg);
if (file.isDirectory()) {
Collection<File> subFiles = FileUtils.listFiles(file, new String[]{"bsp"}, recursive);
for (File subFile : subFiles) {
BspFileEntry entry = new BspFileEntry(subFile);
// override destination directory?
if (outputFile != null) {
entry.setVmfFile(new File(outputFile, entry.getVmfFile().getName()));
}
files.add(entry);
}
} else {
BspFileEntry entry = new BspFileEntry(file);
// override destination directory?
if (outputFile != null) {
entry.setVmfFile(new File(outputFile, entry.getVmfFile().getName()));
}
files.add(entry);
}
}
}
return config;
}
| public BspSourceConfig getConfig(String[] args) {
BspSourceConfig config = new BspSourceConfig();
// basic options
Option helpOpt, versionOpt, debugOpt, outputOpt, recursiveOpt;
optsMain.addOption(helpOpt = new Option("h", "Print this help."));
optsMain.addOption(versionOpt = new Option("v", "Print version info."));
optsMain.addOption(debugOpt = new Option("d", "Enable debug mode. Increases verbosity and adds additional data to the VMF file."));
optsMain.addOption(recursiveOpt = new Option("r", "Decompile all files found in the given directory."));
optsMain.addOption(outputOpt = OptionBuilder
.hasArg()
.withArgName("file")
.withDescription("Override output path for VMF file(s). Treated as directory if multiple BSP files are provided. \ndefault: <mappath>/<mapname>_d.vmf")
.withType(String.class)
.create('o'));
// entity options
Option nbentsOpt, npentsOpt, npropsOpt, noverlOpt, ncubemOpt, ndetailsOpt, nareapOpt, nocclOpt, nrotfixOpt;
optsEntity.addOption(npentsOpt = new Option("no_point_ents", "Don't write any point entities."));
optsEntity.addOption(nbentsOpt = new Option("no_brush_ents", "Don't write any brush entities."));
optsEntity.addOption(npropsOpt = new Option("no_sprp", "Don't write prop_static entities."));
optsEntity.addOption(noverlOpt = new Option("no_overlays", "Don't write info_overlay entities."));
optsEntity.addOption(ncubemOpt = new Option("no_cubemaps", "Don't write env_cubemap entities."));
optsEntity.addOption(ndetailsOpt = new Option("no_details", "Don't write func_detail entities."));
optsEntity.addOption(nareapOpt = new Option("no_areaportals", "Don't write func_areaportal(_window) entities."));
optsEntity.addOption(nocclOpt = new Option("no_occluders", "Don't write func_occluder entities."));
optsEntity.addOption(nrotfixOpt = new Option("no_rotfix", "Don't fix instance entity brush rotations for Hammer."));
// world brush options
Option nbrushOpt, ndispOpt, bmodeOpt, thicknOpt;
optsWorld.addOption(nbrushOpt = new Option("no_brushes", "Don't write any world brushes."));
optsWorld.addOption(ndispOpt = new Option("no_disps", "Don't write displacement surfaces."));
optsWorld.addOption(bmodeOpt = OptionBuilder
.hasArg()
.withArgName("enum")
.withDescription("Brush decompiling mode:\n" +
BrushMode.BRUSHPLANES.name() + " - brushes and planes\n" +
BrushMode.ORIGFACE.name() + " - original faces only\n" +
BrushMode.ORIGFACE_PLUS.name() + " - original + split faces\n" +
BrushMode.SPLITFACE.name() + " - split faces only\n" +
"default: " + config.brushMode.name())
.create("brushmode"));
optsWorld.addOption(thicknOpt = OptionBuilder
.hasArg()
.withArgName("float")
.withDescription("Thickness of brushes created from flat faces in units.\n" +
"default: " + config.backfaceDepth)
.create("thickness"));
// texture options
Option ntexfixOpt, ftexOpt, bftexOpt;
optsTexture.addOption(ntexfixOpt = new Option("no_texfix", "Don't fix texture names."));
optsTexture.addOption(ftexOpt = OptionBuilder
.hasArg()
.withArgName("string")
.withDescription("Replace all face textures with this one.")
.create("facetex"));
optsTexture.addOption(bftexOpt = OptionBuilder
.hasArg()
.withArgName("string")
.withDescription("Replace all back-face textures with this one. Used in face-based decompiling modes only.")
.create("bfacetex"));
// other options
Option nvmfOpt, nlumpfilesOpt, nprotOpt, listappidsOpt, appidOpt, nvisgrpOpt, ncamsOpt, formatOpt;
optsOther.addOption(nvmfOpt = new Option("no_vmf", "Don't write any VMF files, read BSP only."));
optsOther.addOption(nlumpfilesOpt = new Option("no_lumpfiles", "Don't load lump files (.lmp) associated with the BSP file."));
optsOther.addOption(nprotOpt = new Option("no_prot", "Skip decompiling protection checking. Can increase speed when mass-decompiling unprotected maps."));
optsOther.addOption(listappidsOpt = new Option("appids", "List all available application IDs"));
optsOther.addOption(nvisgrpOpt = new Option("no_visgroups", "Don't group entities from instances into visgroups."));
optsOther.addOption(ncamsOpt = new Option("no_cams", "Don't create Hammer cameras above each player spawn."));
optsOther.addOption(appidOpt = OptionBuilder
.hasArg()
.withArgName("string/int")
.withDescription("Overrides game detection by using " +
"this Steam Application ID instead.\n" +
"Use -appids to list all known app-IDs.")
.create("appid"));
optsOther.addOption(formatOpt = OptionBuilder
.hasArg()
.withArgName("enum")
.withDescription("Sets the VMF format used for the decompiled maps:\n" +
SourceFormat.AUTO.name() + " - " + SourceFormat.AUTO + "\n" +
SourceFormat.OLD.name() + " - " + SourceFormat.OLD + "\n" +
SourceFormat.NEW.name() + " - " + SourceFormat.NEW + "\n" +
"default: " + config.sourceFormat.name())
.create("format"));
// all options
optsAll.addOptions(optsMain);
optsAll.addOptions(optsEntity);
optsAll.addOptions(optsWorld);
optsAll.addOptions(optsTexture);
optsAll.addOptions(optsOther);
if (args.length == 0) {
printHelp();
System.exit(0);
}
CommandLineParser clParser = new PosixParser();
CommandLine cl = null;
File outputFile = null;
boolean recursive = false;
try {
// parse the command line arguments
cl = clParser.parse(optsAll, args);
// help
if(cl.hasOption(helpOpt.getOpt())) {
printHelp();
}
// version
if (cl.hasOption(versionOpt.getOpt())) {
printVersion();
}
// list app-ids
if (cl.hasOption(listappidsOpt.getOpt())) {
printAppIDs();
}
// main options
config.setDebug(cl.hasOption(debugOpt.getOpt()));
if (cl.hasOption(outputOpt.getOpt())) {
outputFile = new File(cl.getOptionValue(outputOpt.getOpt()));
}
recursive = cl.hasOption(recursiveOpt.getOpt());
// entity options
config.writePointEntities = !cl.hasOption(npentsOpt.getOpt());
config.writeBrushEntities = !cl.hasOption(nbentsOpt.getOpt());
config.writeStaticProps = !cl.hasOption(npropsOpt.getOpt());
config.writeOverlays = !cl.hasOption(noverlOpt.getOpt());
config.writeDisp = !cl.hasOption(ndispOpt.getOpt());
config.writeAreaportals = !cl.hasOption(nareapOpt.getOpt());
config.writeOccluders = !cl.hasOption(nocclOpt.getOpt());
config.writeCubemaps = !cl.hasOption(ncubemOpt.getOpt());
config.writeDetails = !cl.hasOption(ndetailsOpt.getOpt());
// world options
config.writeWorldBrushes = !cl.hasOption(nbrushOpt.getOpt());
if (cl.hasOption(bmodeOpt.getOpt())) {
String modeStr = cl.getOptionValue(bmodeOpt.getOpt());
try {
config.brushMode = BrushMode.valueOf(modeStr);
} catch (IllegalArgumentException ex) {
// try again as ordinal enum value
try {
int mode = Integer.valueOf(modeStr.toUpperCase());
config.brushMode = BrushMode.fromOrdinal(mode);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid brush mode");
}
}
}
if (cl.hasOption(formatOpt.getOpt())) {
String formatStr = cl.getOptionValue(formatOpt.getOpt());
try {
config.sourceFormat = SourceFormat.valueOf(formatStr);
} catch (IllegalArgumentException ex) {
// try again as ordinal enum value
try {
int format = Integer.valueOf(formatStr.toUpperCase());
config.sourceFormat = SourceFormat.fromOrdinal(format);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid source format");
}
}
}
if (cl.hasOption(thicknOpt.getOpt())) {
float thickness = Float.valueOf(cl.getOptionValue(thicknOpt.getOpt()));
config.backfaceDepth = thickness;
}
// texture options
config.fixCubemapTextures = !cl.hasOption(ntexfixOpt.getOpt());
if (cl.hasOption(ftexOpt.getOpt())) {
config.faceTexture = cl.getOptionValue(ftexOpt.getOpt());
}
if (cl.hasOption(bftexOpt.getOpt())) {
config.backfaceTexture = cl.getOptionValue(bftexOpt.getOpt());
}
// other options
config.loadLumpFiles = !cl.hasOption(nlumpfilesOpt.getOpt());
config.skipProt = cl.hasOption(nprotOpt.getOpt());
config.fixEntityRot = !cl.hasOption(nrotfixOpt.getOpt());
config.nullOutput = cl.hasOption(nvmfOpt.getOpt());
config.writeVisgroups = !cl.hasOption(nvisgrpOpt.getOpt());
config.writeCameras = !cl.hasOption(ncamsOpt.getOpt());
if (cl.hasOption(appidOpt.getOpt())) {
String appidStr = cl.getOptionValue(appidOpt.getOpt()).toUpperCase();
try {
config.defaultAppID = AppID.valueOf(appidStr);
} catch (IllegalArgumentException ex) {
// try again as integer ID
try {
int appid = Integer.valueOf(appidStr);
config.defaultAppID = AppID.fromID(appid);
} catch (IllegalArgumentException ex2) {
throw new RuntimeException("Invalid default AppID");
}
}
}
} catch (Exception ex) {
L.severe(ex.getMessage());
System.exit(0);
}
// get non-recognized arguments, these are the BSP input files
String[] argsLeft = cl.getArgs();
Set<BspFileEntry> files = config.getFileSet();
if (argsLeft.length == 0) {
L.severe("No BSP file(s) specified");
System.exit(1);
} else if (argsLeft.length == 1 && outputFile != null) {
// set VMF file for one BSP
BspFileEntry entry = new BspFileEntry(new File(argsLeft[0]));
entry.setVmfFile(outputFile);
files.add(entry);
} else {
for (String arg : argsLeft) {
File file = new File(arg);
if (file.isDirectory()) {
Collection<File> subFiles = FileUtils.listFiles(file, new String[]{"bsp"}, recursive);
for (File subFile : subFiles) {
BspFileEntry entry = new BspFileEntry(subFile);
// override destination directory?
if (outputFile != null) {
entry.setVmfFile(new File(outputFile, entry.getVmfFile().getName()));
}
files.add(entry);
}
} else {
BspFileEntry entry = new BspFileEntry(file);
// override destination directory?
if (outputFile != null) {
entry.setVmfFile(new File(outputFile, entry.getVmfFile().getName()));
}
files.add(entry);
}
}
}
return config;
}
|
diff --git a/service/src/main/java/com/pms/service/controller/interceptor/ApiFilter.java b/service/src/main/java/com/pms/service/controller/interceptor/ApiFilter.java
index 10dd869d..5f49069a 100644
--- a/service/src/main/java/com/pms/service/controller/interceptor/ApiFilter.java
+++ b/service/src/main/java/com/pms/service/controller/interceptor/ApiFilter.java
@@ -1,109 +1,111 @@
package com.pms.service.controller.interceptor;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.util.NestedServletException;
import com.pms.service.annotation.InitBean;
import com.pms.service.controller.AbstractController;
import com.pms.service.exception.ApiLoginException;
import com.pms.service.exception.ApiResponseException;
import com.pms.service.mockbean.UserBean;
import com.pms.service.service.IUserService;
import com.pms.service.util.ApiThreadLocal;
public class ApiFilter extends AbstractController implements Filter {
private static IUserService userService;
@Override
public void destroy() {
}
private static Logger logger = LogManager.getLogger(ApiFilter.class);
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest srequest = (HttpServletRequest) request;
if (srequest.getSession().getAttribute(UserBean.USER_ID) != null) {
ApiThreadLocal.set(UserBean.USER_ID, srequest.getSession().getAttribute(UserBean.USER_ID));
}
if (srequest.getSession().getAttribute(UserBean.USER_NAME) != null) {
ApiThreadLocal.set(UserBean.USER_NAME, srequest.getSession().getAttribute(UserBean.USER_NAME));
}
try {
loginCheck((HttpServletRequest) request);
roleCheck((HttpServletRequest) request);
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e instanceof NestedServletException) {
Throwable t = e.getCause();
if (t instanceof ApiResponseException) {
// do nothing
responseServerError(t, (HttpServletRequest) request, (HttpServletResponse) response);
} else {
- logger.error("Fatal error when user try to call API ", e);
+// logger.error("Fatal error when user try to call API ", e);
+ e.printStackTrace();
responseServerError(e, (HttpServletRequest) request, (HttpServletResponse) response);
}
} else if (e instanceof ApiLoginException) {
forceLogin((HttpServletRequest) request, (HttpServletResponse) response);
} else {
- logger.error("Fatal error when user try to call API ", e);
+// logger.error("Fatal error when user try to call API ", e);
+ e.printStackTrace();
responseServerError(e, (HttpServletRequest) request, (HttpServletResponse) response);
}
}
ApiThreadLocal.removeAll();
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
public static void initDao(IUserService userService) {
ApiFilter.userService = userService;
}
private void roleCheck(HttpServletRequest request) {
String uerId = null;
if (request.getSession().getAttribute(UserBean.USER_ID) != null) {
uerId = request.getSession().getAttribute(UserBean.USER_ID).toString();
}
if (InitBean.rolesValidationMap.get(request.getPathInfo()) != null) {
userService.checkUserRole(uerId, request.getPathInfo());
}
}
private void loginCheck(HttpServletRequest request) {
if(request.getPathInfo().indexOf("login") == -1){
// if (InitBean.loginPath.contains(request.getPathInfo())) {
if (request.getSession().getAttribute(UserBean.USER_ID) == null) {
logger.debug("Login requried for path : " + request.getPathInfo());
throw new ApiLoginException();
}
// }
}
}
}
| false | true | public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest srequest = (HttpServletRequest) request;
if (srequest.getSession().getAttribute(UserBean.USER_ID) != null) {
ApiThreadLocal.set(UserBean.USER_ID, srequest.getSession().getAttribute(UserBean.USER_ID));
}
if (srequest.getSession().getAttribute(UserBean.USER_NAME) != null) {
ApiThreadLocal.set(UserBean.USER_NAME, srequest.getSession().getAttribute(UserBean.USER_NAME));
}
try {
loginCheck((HttpServletRequest) request);
roleCheck((HttpServletRequest) request);
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e instanceof NestedServletException) {
Throwable t = e.getCause();
if (t instanceof ApiResponseException) {
// do nothing
responseServerError(t, (HttpServletRequest) request, (HttpServletResponse) response);
} else {
logger.error("Fatal error when user try to call API ", e);
responseServerError(e, (HttpServletRequest) request, (HttpServletResponse) response);
}
} else if (e instanceof ApiLoginException) {
forceLogin((HttpServletRequest) request, (HttpServletResponse) response);
} else {
logger.error("Fatal error when user try to call API ", e);
responseServerError(e, (HttpServletRequest) request, (HttpServletResponse) response);
}
}
ApiThreadLocal.removeAll();
}
| public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest srequest = (HttpServletRequest) request;
if (srequest.getSession().getAttribute(UserBean.USER_ID) != null) {
ApiThreadLocal.set(UserBean.USER_ID, srequest.getSession().getAttribute(UserBean.USER_ID));
}
if (srequest.getSession().getAttribute(UserBean.USER_NAME) != null) {
ApiThreadLocal.set(UserBean.USER_NAME, srequest.getSession().getAttribute(UserBean.USER_NAME));
}
try {
loginCheck((HttpServletRequest) request);
roleCheck((HttpServletRequest) request);
filterChain.doFilter(request, response);
} catch (Exception e) {
if (e instanceof NestedServletException) {
Throwable t = e.getCause();
if (t instanceof ApiResponseException) {
// do nothing
responseServerError(t, (HttpServletRequest) request, (HttpServletResponse) response);
} else {
// logger.error("Fatal error when user try to call API ", e);
e.printStackTrace();
responseServerError(e, (HttpServletRequest) request, (HttpServletResponse) response);
}
} else if (e instanceof ApiLoginException) {
forceLogin((HttpServletRequest) request, (HttpServletResponse) response);
} else {
// logger.error("Fatal error when user try to call API ", e);
e.printStackTrace();
responseServerError(e, (HttpServletRequest) request, (HttpServletResponse) response);
}
}
ApiThreadLocal.removeAll();
}
|
diff --git a/src/driver/GUIDriver.java b/src/driver/GUIDriver.java
index 0f8064f..4aaa5b5 100644
--- a/src/driver/GUIDriver.java
+++ b/src/driver/GUIDriver.java
@@ -1,593 +1,594 @@
package driver;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Random;
import javax.swing.JFrame;
import world.Character;
import world.Enemy;
import world.Forge;
import world.Grid;
import world.GridSpace;
import world.LivingThing;
import world.Magic;
import world.RangedWeapon;
import world.Terrain;
import world.Thing;
import world.World;
public class GUIDriver {
private static Grid g;
private static long gravityRate;
private static int lastKey;
private static long hangTime;
private static long value;
private static int stage = 1;
private static boolean keepGoing;
public static void main(String[] args) {
// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint(true);
canvas.setSize(1200, 480);
// Add canvas to game window...
app.add(canvas);
app.pack();
app.setVisible(true);
// Create BackBuffer...
canvas.createBufferStrategy(2);
BufferStrategy buffer = canvas.getBufferStrategy();
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage(1200, 480);
// Objects needed for rendering...
Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
// Variables for counting frames per seconds
int fps = 0;
int frames = 0;
long totalTime = 0;
long gravityTime = 0;
long enemyDamageTime = 0;
hangTime = 500;
gravityRate = 300;
value = gravityRate + hangTime;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
keepGoing = true;
g = new Grid(0);
g.makeDefaultGrid();
Character blue = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
System.out.println(blue.getRangedStore());
System.out.println(blue.getCloseStore());
stage = 1;
app.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
Forge f = new Forge();
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
if (g.getGrid()
.get(new Point((int) g.getCharacterLocation().getX(),
(int) g.getCharacterLocation().getY() + 1)).hasSolid()) {
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
value = gravityRate + hangTime;
}
} else if (keyCode == KeyEvent.VK_LEFT) {
g.moveCharacter(-1, 0, lastKey);
lastKey = KeyEvent.VK_LEFT;
} else if (keyCode == KeyEvent.VK_DOWN) {
g.moveCharacter(0, 1, lastKey);
} else if (keyCode == KeyEvent.VK_RIGHT) {
g.moveCharacter(1, 0, lastKey);
lastKey = KeyEvent.VK_RIGHT;
} else if (keyCode == KeyEvent.VK_A) {
lastKey = KeyEvent.VK_A;
g.useWeapon(lastKey);
} else if (keyCode == KeyEvent.VK_D) {
lastKey = KeyEvent.VK_D;
g.useWeapon(lastKey);
} else if (keyCode == KeyEvent.VK_P) {
String name = "Yo Mama";
Color col = Color.ORANGE;
Point p = g.findValidEnemyLocation();
- if (p != null) {
+ if (p != null && c.getMoney() >= 5) {
g.spawnNewEnemy(p, new Enemy(true, col, name, 10, 10, 10));
+ c.addMoney(-5);
} else {
System.out.println("Could not spawn a new enemy.");
}
} else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
if (c.getWeapon() instanceof RangedWeapon && !(c.getWeapon() instanceof Magic)) {
c.setWeapon((Magic) c.getMagicStore().get(c.getMagicStore().size()-1));
} else if (c.getWeapon() instanceof Magic) {
c.setWeapon(c.getCloseStore().get(c.getCloseStore().size()-1));
} else {
c.setWeapon((RangedWeapon) c.getRangedStore().get(c.getRangedStore().size()-1));
}
} else if (keyCode == KeyEvent.VK_SLASH) {
g.killAllEnemies();
} else if (keyCode == KeyEvent.VK_SEMICOLON) {
g.placeTerrain(lastKey);
} else if (keyCode == KeyEvent.VK_PERIOD) {
g.placeTerrain(keyCode);
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_1){
if (c.getBoughtWeapons().get(0) == true){
c.addWeapon(f.constructRangedWeapons(0, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 100){
c.addWeapon(f.constructRangedWeapons(0, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-100);
c.updateBoolean(0);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_2){
if (c.getBoughtWeapons().get(1) == true){
c.addWeapon(f.constructRangedWeapons(1, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(1, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(1);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_3){
if (c.getBoughtWeapons().get(2) == true){
c.addWeapon(f.constructRangedWeapons(2, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 400){
c.addWeapon(f.constructRangedWeapons(2, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-400);
c.updateBoolean(2);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_4){
if (c.getBoughtWeapons().get(3) == true){
c.addWeapon(f.constructRangedWeapons(3, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(3, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(3);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_5){
if (c.getBoughtWeapons().get(4) == true){
c.addWeapon(f.constructRangedWeapons(4, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(4, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(4);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_6){
if (c.getBoughtWeapons().get(5) == true){
c.addWeapon(f.constructRangedWeapons(5, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 200){
c.addWeapon(f.constructRangedWeapons(5, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-200);
c.updateBoolean(5);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_1){
if (c.getBoughtWeapons().get(7) == true){
c.addWeapon(f.constructRangedWeapons(7, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(7, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(7);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_2){
if (c.getBoughtWeapons().get(8) == true){
c.addWeapon(f.constructRangedWeapons(8, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(8, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(8);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_3){
if (c.getBoughtWeapons().get(9) == true){
c.addWeapon(f.constructRangedWeapons(9, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(9, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(9);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_4){
if (c.getBoughtWeapons().get(10) == true){
c.addWeapon(f.constructRangedWeapons(10, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(10, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(10);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_5){
if (c.getBoughtWeapons().get(11) == true){
c.addWeapon(f.constructRangedWeapons(11, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(11, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(11);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_6){
if (c.getBoughtWeapons().get(12) == true){
c.addWeapon(f.constructRangedWeapons(12, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(12, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(12);
}else{
System.out.println("You do not have enough money.");
}
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
}
}
});
while (keepGoing) {
try {
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
gravityTime += curTime - lastTime;
enemyDamageTime += curTime - lastTime;
if (keepGoing) {
if (gravityTime > value) {
value += gravityRate;
g.moveCharacter(0, 1, lastKey);
g.applyDot();
for (int a = 0; a < 2; a++) {
g.moveRangedWeapon();
}
Point charLoc = g.getCharacterLocation();
ArrayList<Point> enemyLocs = g.getEnemyLocation();
for (int j = 0; j < enemyLocs.size(); j++) {
if (charLoc.distance(enemyLocs.get(j)) <= 1) {
keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy());
if (!keepGoing) {
g.gameOver();
}
}
}
if (keepGoing) {
// check every instance of p
for (int i = 0; i < g.getEnemyLocation().size(); i++) {
Point p = g.getEnemyLocation().get(i);
Point q = new Point((int) p.getX(), (int) p.getY() + 1);
GridSpace gs = g.getGrid().get(q);
if (p.getX() - g.getCharacterLocation().getX() > 0) {
g.moveEnemy(-1, 0, p);
} else {
g.moveEnemy(1, 0, p);
}
if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) {
Point check = new Point((int) (p.getX() + 1), (int) (p.getY()));
GridSpace more = g.getGrid().get(check);
if (more.hasSolid()) {
for (Terrain t : more.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
for (LivingThing e : more.returnLivingThings()) {
if (e.getSolid() && !(e instanceof Character)) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
}
} else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) {
Point check = new Point((int) (p.getX() - 1), (int) (p.getY()));
GridSpace more = g.getGrid().get(check);
if (more.hasSolid()) {
for (Terrain t : more.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
for (LivingThing e : more.returnLivingThings()) {
if (e.getSolid() && !(e instanceof Character)) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
}
}
g.moveEnemy(0, 1, p);
}
if (gravityTime > 4 * gravityRate + hangTime) {
gravityTime = 0;
value = gravityRate + hangTime;
}
if (enemyDamageTime > 500) {
}
// clear back buffer...
if (g.getCharacterLocation().getX() >= 100) {
HashMap<Point, GridSpace> grid = g.getGrid();
Point oldLocation = g.getCharacterLocation();
Character c = grid.get(oldLocation).returnCharacter();
c.setHp(c.getMaxHp());
World w = new World();
int killed = g.getNumKilled();
g = w.drawWorld(1, killed);
stage++;
grid = g.getGrid();
g.setNumKilled(killed);
ArrayList<Thing> t = new ArrayList<Thing>();
t.add(c);
GridSpace gs = new GridSpace(t);
gs.sortArrayOfThings();
grid.put(new Point(1, (int) oldLocation.getY() - 1), gs);
g.setCharacterLocation(new Point(1, (int) oldLocation.getY() - 1));
Random r = new Random();
int numEnemies = r.nextInt(stage) + 1;
for (int i = 0; i < numEnemies; i++) {
String name = "Yo Mama";
Color d = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null) {
g.spawnNewEnemy(p, new Enemy(true, d, name, 10, 10, 10));
}
}
}
}
}
}
if (totalTime > 1000) {
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
g2d = bi.createGraphics();
g2d.setColor(background);
g2d.fillRect(0, 0, 639, 479);
HashMap<Point, GridSpace> grid = g.getGrid();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 25; j++) {
g2d.setColor(grid.get(new Point(i, j)).getColor());
g2d.fillRect(i * 10, j * 10, 10, 10);
}
}
// display frames per second...
g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
g2d.setColor(Color.GREEN);
g2d.drawString(String.format("FPS: %s", fps), 20, 20);
g2d.drawString(String.format("Stage: %s", stage), 100, 20);
g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20);
if (keepGoing) {
try {
g2d.drawString("Current weapon: "
+ g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon().getName(),
620, 20);
} catch (NullPointerException e) {
System.out.println("Caught null pointer error on HUD for weapon.");
} catch (ConcurrentModificationException c) {
System.out.println("Caught concurrent modification exception.");
}
try {
Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
g2d.drawString("Current level: " + c.getLevel(), 840, 20);
String healthString = "";
for (int i = 0; i < c.getMaxHp(); i += 5) {
if (c.getHp() > i) {
healthString += "* ";
} else {
healthString += "_ ";
}
}
g2d.drawString("Health: " + healthString, 320, 20);
} catch (NullPointerException e) {
System.out.println("Caught that error");
g2d.drawString("Health: Dead", 320, 20);
}
try{
//0=basic bow + arrows
//1=longbow + arrows
//2=basic crossbow + bolts
//3=finely crafted crossbow + bolts
//4=javelins
//5=throwing knive
g2d.drawString("WELCOME TO THE MARKET", 5, 270);
g2d.drawString("PRESS A NUMBER OR SYMBOL TO BUY A WEAPON FROM THE MERCHANT:", 5, 285);
g2d.drawString("1: Basic Bow ($100)", 5, 305);
g2d.drawString("2: Long Bow ($300)", 5, 320);
g2d.drawString("3: Cross Bow ($400)", 5, 335);
g2d.drawString("4: Cross Bow Plus ($1000)", 5, 350);
g2d.drawString("5: Javelin ($500)", 5, 365);
g2d.drawString("6: Throwing Knives ($200)", 5, 380);
g2d.drawString("!: Fire Magic 1 ($300)", 200, 305);
g2d.drawString("@: Fire Magic 2 ($500)", 200, 320);
g2d.drawString("#: Fire Magic 3 ($1000)", 200, 335);
g2d.drawString("$: Ice Magic 1 ($300)", 200, 350);
g2d.drawString("%: Ice Magic 2 ($500)", 200, 365);
g2d.drawString("^: Ice Magic 3 ($1000)", 200, 380);
}catch (Exception e){
System.out.println("Caught some error.");
}
}
// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage(bi, 0, 0, null);
if (!buffer.contentsLost()) {
buffer.show();
}
// Let the OS have a little time...
Thread.yield();
} finally {
// release resources
if (graphics != null)
graphics.dispose();
if (g2d != null)
g2d.dispose();
}
}
}
}
| false | true | public static void main(String[] args) {
// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint(true);
canvas.setSize(1200, 480);
// Add canvas to game window...
app.add(canvas);
app.pack();
app.setVisible(true);
// Create BackBuffer...
canvas.createBufferStrategy(2);
BufferStrategy buffer = canvas.getBufferStrategy();
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage(1200, 480);
// Objects needed for rendering...
Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
// Variables for counting frames per seconds
int fps = 0;
int frames = 0;
long totalTime = 0;
long gravityTime = 0;
long enemyDamageTime = 0;
hangTime = 500;
gravityRate = 300;
value = gravityRate + hangTime;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
keepGoing = true;
g = new Grid(0);
g.makeDefaultGrid();
Character blue = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
System.out.println(blue.getRangedStore());
System.out.println(blue.getCloseStore());
stage = 1;
app.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
Forge f = new Forge();
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
if (g.getGrid()
.get(new Point((int) g.getCharacterLocation().getX(),
(int) g.getCharacterLocation().getY() + 1)).hasSolid()) {
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
value = gravityRate + hangTime;
}
} else if (keyCode == KeyEvent.VK_LEFT) {
g.moveCharacter(-1, 0, lastKey);
lastKey = KeyEvent.VK_LEFT;
} else if (keyCode == KeyEvent.VK_DOWN) {
g.moveCharacter(0, 1, lastKey);
} else if (keyCode == KeyEvent.VK_RIGHT) {
g.moveCharacter(1, 0, lastKey);
lastKey = KeyEvent.VK_RIGHT;
} else if (keyCode == KeyEvent.VK_A) {
lastKey = KeyEvent.VK_A;
g.useWeapon(lastKey);
} else if (keyCode == KeyEvent.VK_D) {
lastKey = KeyEvent.VK_D;
g.useWeapon(lastKey);
} else if (keyCode == KeyEvent.VK_P) {
String name = "Yo Mama";
Color col = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null) {
g.spawnNewEnemy(p, new Enemy(true, col, name, 10, 10, 10));
} else {
System.out.println("Could not spawn a new enemy.");
}
} else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
if (c.getWeapon() instanceof RangedWeapon && !(c.getWeapon() instanceof Magic)) {
c.setWeapon((Magic) c.getMagicStore().get(c.getMagicStore().size()-1));
} else if (c.getWeapon() instanceof Magic) {
c.setWeapon(c.getCloseStore().get(c.getCloseStore().size()-1));
} else {
c.setWeapon((RangedWeapon) c.getRangedStore().get(c.getRangedStore().size()-1));
}
} else if (keyCode == KeyEvent.VK_SLASH) {
g.killAllEnemies();
} else if (keyCode == KeyEvent.VK_SEMICOLON) {
g.placeTerrain(lastKey);
} else if (keyCode == KeyEvent.VK_PERIOD) {
g.placeTerrain(keyCode);
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_1){
if (c.getBoughtWeapons().get(0) == true){
c.addWeapon(f.constructRangedWeapons(0, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 100){
c.addWeapon(f.constructRangedWeapons(0, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-100);
c.updateBoolean(0);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_2){
if (c.getBoughtWeapons().get(1) == true){
c.addWeapon(f.constructRangedWeapons(1, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(1, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(1);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_3){
if (c.getBoughtWeapons().get(2) == true){
c.addWeapon(f.constructRangedWeapons(2, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 400){
c.addWeapon(f.constructRangedWeapons(2, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-400);
c.updateBoolean(2);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_4){
if (c.getBoughtWeapons().get(3) == true){
c.addWeapon(f.constructRangedWeapons(3, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(3, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(3);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_5){
if (c.getBoughtWeapons().get(4) == true){
c.addWeapon(f.constructRangedWeapons(4, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(4, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(4);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_6){
if (c.getBoughtWeapons().get(5) == true){
c.addWeapon(f.constructRangedWeapons(5, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 200){
c.addWeapon(f.constructRangedWeapons(5, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-200);
c.updateBoolean(5);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_1){
if (c.getBoughtWeapons().get(7) == true){
c.addWeapon(f.constructRangedWeapons(7, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(7, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(7);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_2){
if (c.getBoughtWeapons().get(8) == true){
c.addWeapon(f.constructRangedWeapons(8, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(8, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(8);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_3){
if (c.getBoughtWeapons().get(9) == true){
c.addWeapon(f.constructRangedWeapons(9, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(9, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(9);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_4){
if (c.getBoughtWeapons().get(10) == true){
c.addWeapon(f.constructRangedWeapons(10, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(10, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(10);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_5){
if (c.getBoughtWeapons().get(11) == true){
c.addWeapon(f.constructRangedWeapons(11, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(11, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(11);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_6){
if (c.getBoughtWeapons().get(12) == true){
c.addWeapon(f.constructRangedWeapons(12, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(12, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(12);
}else{
System.out.println("You do not have enough money.");
}
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
}
}
});
while (keepGoing) {
try {
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
gravityTime += curTime - lastTime;
enemyDamageTime += curTime - lastTime;
if (keepGoing) {
if (gravityTime > value) {
value += gravityRate;
g.moveCharacter(0, 1, lastKey);
g.applyDot();
for (int a = 0; a < 2; a++) {
g.moveRangedWeapon();
}
Point charLoc = g.getCharacterLocation();
ArrayList<Point> enemyLocs = g.getEnemyLocation();
for (int j = 0; j < enemyLocs.size(); j++) {
if (charLoc.distance(enemyLocs.get(j)) <= 1) {
keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy());
if (!keepGoing) {
g.gameOver();
}
}
}
if (keepGoing) {
// check every instance of p
for (int i = 0; i < g.getEnemyLocation().size(); i++) {
Point p = g.getEnemyLocation().get(i);
Point q = new Point((int) p.getX(), (int) p.getY() + 1);
GridSpace gs = g.getGrid().get(q);
if (p.getX() - g.getCharacterLocation().getX() > 0) {
g.moveEnemy(-1, 0, p);
} else {
g.moveEnemy(1, 0, p);
}
if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) {
Point check = new Point((int) (p.getX() + 1), (int) (p.getY()));
GridSpace more = g.getGrid().get(check);
if (more.hasSolid()) {
for (Terrain t : more.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
for (LivingThing e : more.returnLivingThings()) {
if (e.getSolid() && !(e instanceof Character)) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
}
} else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) {
Point check = new Point((int) (p.getX() - 1), (int) (p.getY()));
GridSpace more = g.getGrid().get(check);
if (more.hasSolid()) {
for (Terrain t : more.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
for (LivingThing e : more.returnLivingThings()) {
if (e.getSolid() && !(e instanceof Character)) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
}
}
g.moveEnemy(0, 1, p);
}
if (gravityTime > 4 * gravityRate + hangTime) {
gravityTime = 0;
value = gravityRate + hangTime;
}
if (enemyDamageTime > 500) {
}
// clear back buffer...
if (g.getCharacterLocation().getX() >= 100) {
HashMap<Point, GridSpace> grid = g.getGrid();
Point oldLocation = g.getCharacterLocation();
Character c = grid.get(oldLocation).returnCharacter();
c.setHp(c.getMaxHp());
World w = new World();
int killed = g.getNumKilled();
g = w.drawWorld(1, killed);
stage++;
grid = g.getGrid();
g.setNumKilled(killed);
ArrayList<Thing> t = new ArrayList<Thing>();
t.add(c);
GridSpace gs = new GridSpace(t);
gs.sortArrayOfThings();
grid.put(new Point(1, (int) oldLocation.getY() - 1), gs);
g.setCharacterLocation(new Point(1, (int) oldLocation.getY() - 1));
Random r = new Random();
int numEnemies = r.nextInt(stage) + 1;
for (int i = 0; i < numEnemies; i++) {
String name = "Yo Mama";
Color d = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null) {
g.spawnNewEnemy(p, new Enemy(true, d, name, 10, 10, 10));
}
}
}
}
}
}
if (totalTime > 1000) {
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
g2d = bi.createGraphics();
g2d.setColor(background);
g2d.fillRect(0, 0, 639, 479);
HashMap<Point, GridSpace> grid = g.getGrid();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 25; j++) {
g2d.setColor(grid.get(new Point(i, j)).getColor());
g2d.fillRect(i * 10, j * 10, 10, 10);
}
}
// display frames per second...
g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
g2d.setColor(Color.GREEN);
g2d.drawString(String.format("FPS: %s", fps), 20, 20);
g2d.drawString(String.format("Stage: %s", stage), 100, 20);
g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20);
if (keepGoing) {
try {
g2d.drawString("Current weapon: "
+ g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon().getName(),
620, 20);
} catch (NullPointerException e) {
System.out.println("Caught null pointer error on HUD for weapon.");
} catch (ConcurrentModificationException c) {
System.out.println("Caught concurrent modification exception.");
}
try {
Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
g2d.drawString("Current level: " + c.getLevel(), 840, 20);
String healthString = "";
for (int i = 0; i < c.getMaxHp(); i += 5) {
if (c.getHp() > i) {
healthString += "* ";
} else {
healthString += "_ ";
}
}
g2d.drawString("Health: " + healthString, 320, 20);
} catch (NullPointerException e) {
System.out.println("Caught that error");
g2d.drawString("Health: Dead", 320, 20);
}
try{
//0=basic bow + arrows
//1=longbow + arrows
//2=basic crossbow + bolts
//3=finely crafted crossbow + bolts
//4=javelins
//5=throwing knive
g2d.drawString("WELCOME TO THE MARKET", 5, 270);
g2d.drawString("PRESS A NUMBER OR SYMBOL TO BUY A WEAPON FROM THE MERCHANT:", 5, 285);
g2d.drawString("1: Basic Bow ($100)", 5, 305);
g2d.drawString("2: Long Bow ($300)", 5, 320);
g2d.drawString("3: Cross Bow ($400)", 5, 335);
g2d.drawString("4: Cross Bow Plus ($1000)", 5, 350);
g2d.drawString("5: Javelin ($500)", 5, 365);
g2d.drawString("6: Throwing Knives ($200)", 5, 380);
g2d.drawString("!: Fire Magic 1 ($300)", 200, 305);
g2d.drawString("@: Fire Magic 2 ($500)", 200, 320);
g2d.drawString("#: Fire Magic 3 ($1000)", 200, 335);
g2d.drawString("$: Ice Magic 1 ($300)", 200, 350);
g2d.drawString("%: Ice Magic 2 ($500)", 200, 365);
g2d.drawString("^: Ice Magic 3 ($1000)", 200, 380);
}catch (Exception e){
System.out.println("Caught some error.");
}
}
// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage(bi, 0, 0, null);
if (!buffer.contentsLost()) {
buffer.show();
}
// Let the OS have a little time...
Thread.yield();
} finally {
// release resources
if (graphics != null)
graphics.dispose();
if (g2d != null)
g2d.dispose();
}
}
}
| public static void main(String[] args) {
// Create game window...
JFrame app = new JFrame();
app.setIgnoreRepaint(true);
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create canvas for painting...
Canvas canvas = new Canvas();
canvas.setIgnoreRepaint(true);
canvas.setSize(1200, 480);
// Add canvas to game window...
app.add(canvas);
app.pack();
app.setVisible(true);
// Create BackBuffer...
canvas.createBufferStrategy(2);
BufferStrategy buffer = canvas.getBufferStrategy();
// Get graphics configuration...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
// Create off-screen drawing surface
BufferedImage bi = gc.createCompatibleImage(1200, 480);
// Objects needed for rendering...
Graphics graphics = null;
Graphics2D g2d = null;
Color background = Color.BLACK;
// Variables for counting frames per seconds
int fps = 0;
int frames = 0;
long totalTime = 0;
long gravityTime = 0;
long enemyDamageTime = 0;
hangTime = 500;
gravityRate = 300;
value = gravityRate + hangTime;
long curTime = System.currentTimeMillis();
long lastTime = curTime;
keepGoing = true;
g = new Grid(0);
g.makeDefaultGrid();
Character blue = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
System.out.println(blue.getRangedStore());
System.out.println(blue.getCloseStore());
stage = 1;
app.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
Forge f = new Forge();
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_UP) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
if (g.getGrid()
.get(new Point((int) g.getCharacterLocation().getX(),
(int) g.getCharacterLocation().getY() + 1)).hasSolid()) {
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
g.moveCharacter(0, -1, lastKey);
value = gravityRate + hangTime;
}
} else if (keyCode == KeyEvent.VK_LEFT) {
g.moveCharacter(-1, 0, lastKey);
lastKey = KeyEvent.VK_LEFT;
} else if (keyCode == KeyEvent.VK_DOWN) {
g.moveCharacter(0, 1, lastKey);
} else if (keyCode == KeyEvent.VK_RIGHT) {
g.moveCharacter(1, 0, lastKey);
lastKey = KeyEvent.VK_RIGHT;
} else if (keyCode == KeyEvent.VK_A) {
lastKey = KeyEvent.VK_A;
g.useWeapon(lastKey);
} else if (keyCode == KeyEvent.VK_D) {
lastKey = KeyEvent.VK_D;
g.useWeapon(lastKey);
} else if (keyCode == KeyEvent.VK_P) {
String name = "Yo Mama";
Color col = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null && c.getMoney() >= 5) {
g.spawnNewEnemy(p, new Enemy(true, col, name, 10, 10, 10));
c.addMoney(-5);
} else {
System.out.println("Could not spawn a new enemy.");
}
} else if (keyCode == KeyEvent.VK_Q || keyCode == KeyEvent.VK_E) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
if (c.getWeapon() instanceof RangedWeapon && !(c.getWeapon() instanceof Magic)) {
c.setWeapon((Magic) c.getMagicStore().get(c.getMagicStore().size()-1));
} else if (c.getWeapon() instanceof Magic) {
c.setWeapon(c.getCloseStore().get(c.getCloseStore().size()-1));
} else {
c.setWeapon((RangedWeapon) c.getRangedStore().get(c.getRangedStore().size()-1));
}
} else if (keyCode == KeyEvent.VK_SLASH) {
g.killAllEnemies();
} else if (keyCode == KeyEvent.VK_SEMICOLON) {
g.placeTerrain(lastKey);
} else if (keyCode == KeyEvent.VK_PERIOD) {
g.placeTerrain(keyCode);
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_1){
if (c.getBoughtWeapons().get(0) == true){
c.addWeapon(f.constructRangedWeapons(0, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 100){
c.addWeapon(f.constructRangedWeapons(0, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-100);
c.updateBoolean(0);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_2){
if (c.getBoughtWeapons().get(1) == true){
c.addWeapon(f.constructRangedWeapons(1, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(1, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(1);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_3){
if (c.getBoughtWeapons().get(2) == true){
c.addWeapon(f.constructRangedWeapons(2, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if (c.getMoney() >= 400){
c.addWeapon(f.constructRangedWeapons(2, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-400);
c.updateBoolean(2);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_4){
if (c.getBoughtWeapons().get(3) == true){
c.addWeapon(f.constructRangedWeapons(3, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(3, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(3);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_5){
if (c.getBoughtWeapons().get(4) == true){
c.addWeapon(f.constructRangedWeapons(4, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(4, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(4);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (!e.isShiftDown() && keyCode == KeyEvent.VK_6){
if (c.getBoughtWeapons().get(5) == true){
c.addWeapon(f.constructRangedWeapons(5, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 200){
c.addWeapon(f.constructRangedWeapons(5, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-200);
c.updateBoolean(5);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_1){
if (c.getBoughtWeapons().get(7) == true){
c.addWeapon(f.constructRangedWeapons(7, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(7, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(7);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_2){
if (c.getBoughtWeapons().get(8) == true){
c.addWeapon(f.constructRangedWeapons(8, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(8, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(8);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_3){
if (c.getBoughtWeapons().get(9) == true){
c.addWeapon(f.constructRangedWeapons(9, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(9, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(9);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_4){
if (c.getBoughtWeapons().get(10) == true){
c.addWeapon(f.constructRangedWeapons(10, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 300){
c.addWeapon(f.constructRangedWeapons(10, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-300);
c.updateBoolean(10);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_5){
if (c.getBoughtWeapons().get(11) == true){
c.addWeapon(f.constructRangedWeapons(11, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 500){
c.addWeapon(f.constructRangedWeapons(11, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-500);
c.updateBoolean(11);
}else{
System.out.println("You do not have enough money.");
}
}
}else if (e.isShiftDown() && keyCode == KeyEvent.VK_6){
if (c.getBoughtWeapons().get(12) == true){
c.addWeapon(f.constructRangedWeapons(12, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
}else{
if(c.getMoney() >= 1000){
c.addWeapon(f.constructRangedWeapons(12, c));
c.setWeapon(c.getRangedStore().get(c.getRangedStore().size()-1));
c.setMoney(-1000);
c.updateBoolean(12);
}else{
System.out.println("You do not have enough money.");
}
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_A || keyCode == KeyEvent.VK_D) {
g.retractWeapon(KeyEvent.VK_A);
g.retractWeapon(KeyEvent.VK_D);
}
}
});
while (keepGoing) {
try {
lastTime = curTime;
curTime = System.currentTimeMillis();
totalTime += curTime - lastTime;
gravityTime += curTime - lastTime;
enemyDamageTime += curTime - lastTime;
if (keepGoing) {
if (gravityTime > value) {
value += gravityRate;
g.moveCharacter(0, 1, lastKey);
g.applyDot();
for (int a = 0; a < 2; a++) {
g.moveRangedWeapon();
}
Point charLoc = g.getCharacterLocation();
ArrayList<Point> enemyLocs = g.getEnemyLocation();
for (int j = 0; j < enemyLocs.size(); j++) {
if (charLoc.distance(enemyLocs.get(j)) <= 1) {
keepGoing = g.characterDamage(g.getGrid().get(enemyLocs.get(j)).returnEnemy());
if (!keepGoing) {
g.gameOver();
}
}
}
if (keepGoing) {
// check every instance of p
for (int i = 0; i < g.getEnemyLocation().size(); i++) {
Point p = g.getEnemyLocation().get(i);
Point q = new Point((int) p.getX(), (int) p.getY() + 1);
GridSpace gs = g.getGrid().get(q);
if (p.getX() - g.getCharacterLocation().getX() > 0) {
g.moveEnemy(-1, 0, p);
} else {
g.moveEnemy(1, 0, p);
}
if (g.getCharacterLocation().getX() > g.getEnemyLocation().get(i).getX()) {
Point check = new Point((int) (p.getX() + 1), (int) (p.getY()));
GridSpace more = g.getGrid().get(check);
if (more.hasSolid()) {
for (Terrain t : more.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
for (LivingThing e : more.returnLivingThings()) {
if (e.getSolid() && !(e instanceof Character)) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
}
} else if (g.getCharacterLocation().getX() < g.getEnemyLocation().get(i).getX()) {
Point check = new Point((int) (p.getX() - 1), (int) (p.getY()));
GridSpace more = g.getGrid().get(check);
if (more.hasSolid()) {
for (Terrain t : more.returnTerrain()) {
if (t.getSolid()) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
for (LivingThing e : more.returnLivingThings()) {
if (e.getSolid() && !(e instanceof Character)) {
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
g.moveEnemy(0, -1, p);
}
}
}
}
g.moveEnemy(0, 1, p);
}
if (gravityTime > 4 * gravityRate + hangTime) {
gravityTime = 0;
value = gravityRate + hangTime;
}
if (enemyDamageTime > 500) {
}
// clear back buffer...
if (g.getCharacterLocation().getX() >= 100) {
HashMap<Point, GridSpace> grid = g.getGrid();
Point oldLocation = g.getCharacterLocation();
Character c = grid.get(oldLocation).returnCharacter();
c.setHp(c.getMaxHp());
World w = new World();
int killed = g.getNumKilled();
g = w.drawWorld(1, killed);
stage++;
grid = g.getGrid();
g.setNumKilled(killed);
ArrayList<Thing> t = new ArrayList<Thing>();
t.add(c);
GridSpace gs = new GridSpace(t);
gs.sortArrayOfThings();
grid.put(new Point(1, (int) oldLocation.getY() - 1), gs);
g.setCharacterLocation(new Point(1, (int) oldLocation.getY() - 1));
Random r = new Random();
int numEnemies = r.nextInt(stage) + 1;
for (int i = 0; i < numEnemies; i++) {
String name = "Yo Mama";
Color d = Color.ORANGE;
Point p = g.findValidEnemyLocation();
if (p != null) {
g.spawnNewEnemy(p, new Enemy(true, d, name, 10, 10, 10));
}
}
}
}
}
}
if (totalTime > 1000) {
totalTime -= 1000;
fps = frames;
frames = 0;
}
++frames;
g2d = bi.createGraphics();
g2d.setColor(background);
g2d.fillRect(0, 0, 639, 479);
HashMap<Point, GridSpace> grid = g.getGrid();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 25; j++) {
g2d.setColor(grid.get(new Point(i, j)).getColor());
g2d.fillRect(i * 10, j * 10, 10, 10);
}
}
// display frames per second...
g2d.setFont(new Font("Courier New", Font.PLAIN, 12));
g2d.setColor(Color.GREEN);
g2d.drawString(String.format("FPS: %s", fps), 20, 20);
g2d.drawString(String.format("Stage: %s", stage), 100, 20);
g2d.drawString(String.format("Enemies killed: %s", g.getNumKilled()), 180, 20);
if (keepGoing) {
try {
g2d.drawString("Current weapon: "
+ g.getGrid().get(g.getCharacterLocation()).returnCharacter().getWeapon().getName(),
620, 20);
} catch (NullPointerException e) {
System.out.println("Caught null pointer error on HUD for weapon.");
} catch (ConcurrentModificationException c) {
System.out.println("Caught concurrent modification exception.");
}
try {
Character c = g.getGrid().get(g.getCharacterLocation()).returnCharacter();
g2d.drawString("Current level: " + c.getLevel(), 840, 20);
String healthString = "";
for (int i = 0; i < c.getMaxHp(); i += 5) {
if (c.getHp() > i) {
healthString += "* ";
} else {
healthString += "_ ";
}
}
g2d.drawString("Health: " + healthString, 320, 20);
} catch (NullPointerException e) {
System.out.println("Caught that error");
g2d.drawString("Health: Dead", 320, 20);
}
try{
//0=basic bow + arrows
//1=longbow + arrows
//2=basic crossbow + bolts
//3=finely crafted crossbow + bolts
//4=javelins
//5=throwing knive
g2d.drawString("WELCOME TO THE MARKET", 5, 270);
g2d.drawString("PRESS A NUMBER OR SYMBOL TO BUY A WEAPON FROM THE MERCHANT:", 5, 285);
g2d.drawString("1: Basic Bow ($100)", 5, 305);
g2d.drawString("2: Long Bow ($300)", 5, 320);
g2d.drawString("3: Cross Bow ($400)", 5, 335);
g2d.drawString("4: Cross Bow Plus ($1000)", 5, 350);
g2d.drawString("5: Javelin ($500)", 5, 365);
g2d.drawString("6: Throwing Knives ($200)", 5, 380);
g2d.drawString("!: Fire Magic 1 ($300)", 200, 305);
g2d.drawString("@: Fire Magic 2 ($500)", 200, 320);
g2d.drawString("#: Fire Magic 3 ($1000)", 200, 335);
g2d.drawString("$: Ice Magic 1 ($300)", 200, 350);
g2d.drawString("%: Ice Magic 2 ($500)", 200, 365);
g2d.drawString("^: Ice Magic 3 ($1000)", 200, 380);
}catch (Exception e){
System.out.println("Caught some error.");
}
}
// Blit image and flip...
graphics = buffer.getDrawGraphics();
graphics.drawImage(bi, 0, 0, null);
if (!buffer.contentsLost()) {
buffer.show();
}
// Let the OS have a little time...
Thread.yield();
} finally {
// release resources
if (graphics != null)
graphics.dispose();
if (g2d != null)
g2d.dispose();
}
}
}
|
diff --git a/src/uk/co/richardgoater/stats/persistence/DefenseGameData.java b/src/uk/co/richardgoater/stats/persistence/DefenseGameData.java
index 95e4d19..8bd98f6 100644
--- a/src/uk/co/richardgoater/stats/persistence/DefenseGameData.java
+++ b/src/uk/co/richardgoater/stats/persistence/DefenseGameData.java
@@ -1,211 +1,211 @@
package uk.co.richardgoater.stats.persistence;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Transient;
@Entity
@Table(name = "GAMEDATA_DEFENSE")
public class DefenseGameData extends GameData {
private int tckl;
private int solo;
private int assist;
private double sck;
private int sckYds;
private int qbHurry;
private int ints;
private int intYds;
private int bp;
private int ff;
private int fr;
private int frYds;
private int td;
private int safety;
private int bk;
@Transient
public String[] getVisibleColumns() {
String[] columns = new String[] {
"tckl",
"solo",
"assist",
"sck",
"sckYds",
"qbHurry",
"ints",
"intYds",
"bp",
"ff",
"fr",
"frYds",
"td",
"safety",
"bk" };
return combinedPlayerAndStatColumns(columns);
}
public DefenseGameData() {}
public DefenseGameData(Number playerid, Number tckl, Number solo,
Number assist, Number sck, Number sckYds, Number qbHurry,
Number ints, Number intYds, Number bp, Number ff, Number fr,
Number frYds, Number td, Number safety, Number bk)
{
this.playerid = playerid.intValue();
this.tckl = tckl.intValue();
this.solo = solo.intValue();
this.assist = assist.intValue();
this.sck = sck.doubleValue();
- this.sckYds = sck.intValue();
+ this.sckYds = sckYds.intValue();
this.qbHurry = qbHurry.intValue();
this.ints = ints.intValue();
this.intYds = intYds.intValue();
this.bp = bp.intValue();
this.ff = ff.intValue();
this.fr = fr.intValue();
this.frYds = frYds.intValue();
this.td = td.intValue();
this.safety = safety.intValue();
this.bk = bk.intValue();
}
@Column(name = "TCKL")
public int getTckl() {
return tckl;
}
public void setTckl(int tckl) {
this.tckl = tckl;
}
@Column(name = "SOLO")
public int getSolo() {
return solo;
}
public void setSolo(int solo) {
this.solo = solo;
}
@Column(name = "ASSIST")
public int getAssist() {
return assist;
}
public void setAssist(int assist) {
this.assist = assist;
}
@Column(name = "SCK")
public double getSck() {
return sck;
}
public void setSck(double sck) {
this.sck = sck;
}
@Column(name = "FF")
public int getFf() {
return ff;
}
public void setFf(int ff) {
this.ff = ff;
}
@Column(name = "FR")
public int getFr() {
return fr;
}
public void setFr(int fr) {
this.fr = fr;
}
@Column(name = "INTS")
public int getInts() {
return ints;
}
public void setInts(int ints) {
this.ints = ints;
}
@Column(name = "TD")
public int getTd() {
return td;
}
public void setTd(int td) {
this.td = td;
}
@Column(name = "SCKYDS")
public int getSckYds() {
return sckYds;
}
public void setSckYds(int sckYds) {
this.sckYds = sckYds;
}
@Column(name = "QBHURRY")
public int getQbHurry() {
return qbHurry;
}
public void setQbHurry(int qbHurry) {
this.qbHurry = qbHurry;
}
@Column(name = "INTYDS")
public int getIntYds() {
return intYds;
}
public void setIntYds(int intYds) {
this.intYds = intYds;
}
@Column(name = "BP")
public int getBp() {
return bp;
}
public void setBp(int bp) {
this.bp = bp;
}
@Column(name = "FRYDS")
public int getFrYds() {
return frYds;
}
public void setFrYds(int frYds) {
this.frYds = frYds;
}
@Column(name = "SAFETY")
public int getSafety() {
return safety;
}
public void setSafety(int safety) {
this.safety = safety;
}
@Column(name = "BK")
public int getBk() {
return bk;
}
public void setBk(int bk) {
this.bk = bk;
}
}
| true | true | public DefenseGameData(Number playerid, Number tckl, Number solo,
Number assist, Number sck, Number sckYds, Number qbHurry,
Number ints, Number intYds, Number bp, Number ff, Number fr,
Number frYds, Number td, Number safety, Number bk)
{
this.playerid = playerid.intValue();
this.tckl = tckl.intValue();
this.solo = solo.intValue();
this.assist = assist.intValue();
this.sck = sck.doubleValue();
this.sckYds = sck.intValue();
this.qbHurry = qbHurry.intValue();
this.ints = ints.intValue();
this.intYds = intYds.intValue();
this.bp = bp.intValue();
this.ff = ff.intValue();
this.fr = fr.intValue();
this.frYds = frYds.intValue();
this.td = td.intValue();
this.safety = safety.intValue();
this.bk = bk.intValue();
}
| public DefenseGameData(Number playerid, Number tckl, Number solo,
Number assist, Number sck, Number sckYds, Number qbHurry,
Number ints, Number intYds, Number bp, Number ff, Number fr,
Number frYds, Number td, Number safety, Number bk)
{
this.playerid = playerid.intValue();
this.tckl = tckl.intValue();
this.solo = solo.intValue();
this.assist = assist.intValue();
this.sck = sck.doubleValue();
this.sckYds = sckYds.intValue();
this.qbHurry = qbHurry.intValue();
this.ints = ints.intValue();
this.intYds = intYds.intValue();
this.bp = bp.intValue();
this.ff = ff.intValue();
this.fr = fr.intValue();
this.frYds = frYds.intValue();
this.td = td.intValue();
this.safety = safety.intValue();
this.bk = bk.intValue();
}
|
diff --git a/src/main/java/fr/ribesg/alix/api/bot/command/Command.java b/src/main/java/fr/ribesg/alix/api/bot/command/Command.java
index ca9506f..cfb1501 100644
--- a/src/main/java/fr/ribesg/alix/api/bot/command/Command.java
+++ b/src/main/java/fr/ribesg/alix/api/bot/command/Command.java
@@ -1,210 +1,210 @@
package fr.ribesg.alix.api.bot.command;
import fr.ribesg.alix.api.Channel;
import fr.ribesg.alix.api.Receiver;
import fr.ribesg.alix.api.Server;
import fr.ribesg.alix.api.Source;
import fr.ribesg.alix.api.enums.Codes;
import java.util.Set;
/**
* Represents a Command
*/
public abstract class Command {
/**
* The CommandManager this Command belongs to.
*/
protected final CommandManager manager;
/**
* The name of this Command, the main String that has to be written for
* the command to be used, without prefix.
*/
protected final String name;
/**
* Aliases of this Command, some Strings you can use instead of this
* Command's name.
*/
protected final String[] aliases;
/**
* Usage Strings, used by the help command.
* You can also use them to send error messages.
* <p>
* Note that the first line will be prepended with the
* Command prefix, followed by the command name and a space.
* All other lines are prepended by enough spaces to match the first line
* prefix length.
*/
protected final String[] usage;
/**
* If this Command is a restricted Command or not.
* A restricted Command cannot be ran by everybody, the nickname has to be
* a bot admin or in the {@link #allowedNickNames} Set.
*/
protected final boolean restricted;
/**
* Set of Nicknames allowed to use this Command.
* Nicknames have to be registered and identified with NickServ for this
* to be effective.
* This is not considered if {@link #restricted} is false.
*/
protected final Set<String> allowedNickNames;
/**
* Public Command constructor.
* Calls {@link #Command(CommandManager, String, String[], boolean, Set, String...)}.
*
* @param manager the CommandManager this Command belongs to
* @param name the name of this Command
* @param usage usage of this Command
*
* @see #Command(CommandManager, String, String[], boolean, Set, String...) for non-public Command
*/
public Command(final CommandManager manager, final String name, final String[] usage) {
this(manager, name, usage, false, null);
}
/**
* Public Command with aliases constructor.
* Calls {@link #Command(CommandManager, String, String[], boolean, Set, String...)}.
*
* @param manager the CommandManager this Command belongs to
* @param name the name of this Command
* @param usage usage of this Command
* @param aliases possible aliases for this Command
*
* @see #Command(CommandManager, String, String[], boolean, Set, String...) for non-public Command
*/
public Command(final CommandManager manager, final String name, final String[] usage, final String... aliases) {
this(manager, name, usage, false, null, aliases);
}
/**
* Complete Command constructor.
* Should be used for restricted Commands.
*
* @param manager the CommandManager this Command belongs to
* @param name the name of this Command
* @param usage usage of this Command
* @param restricted if this Command is restricted or public
* @param allowedNickNames a Set of allowed nicknames, all registered
* with the NickServ Service
* @param aliases possible aliases for this Command
*
* @throws IllegalArgumentException if the Command is public and a Set
* of allowedNickNames was provided
*/
public Command(final CommandManager manager, final String name, final String[] usage, final boolean restricted, final Set<String> allowedNickNames, final String... aliases) {
if (!restricted && allowedNickNames != null) {
throw new IllegalArgumentException("A public Command should not have allowedNickNames, did you do something wrong?");
}
this.manager = manager;
this.name = name.toLowerCase();
this.aliases = aliases;
this.restricted = restricted;
this.allowedNickNames = allowedNickNames;
// Make the aliases lowercase, too
for (int i = 0; i < this.aliases.length; i++) {
this.aliases[i] = this.aliases[i].toLowerCase();
}
if (usage == null) {
this.usage = null;
} else {
final String commandString = this.toString();
- this.usage = new String[usage.length + 1 + this.aliases.length > 0 ? 1 : 0];
+ this.usage = new String[usage.length + 1 + (this.aliases.length > 0 ? 1 : 0)];
this.usage[0] = Codes.RED + commandString;
if (usage.length > 0) {
for (int i = 1; i < usage.length + 1; i++) {
this.usage[i] = Codes.RED + " | " + usage[i - 1].replaceAll("##", commandString);
}
}
if (this.aliases.length > 0) {
final StringBuilder aliasesStringBuilder = new StringBuilder(Codes.RED + " | Aliases: " + this.aliases[0]);
for (int i = 1; i < this.aliases.length; i++) {
aliasesStringBuilder.append(", ").append(this.aliases[i]);
}
this.usage[this.usage.length - 1] = aliasesStringBuilder.toString();
}
}
}
/**
* Gets the name of this Command, the main String that has to be written
* for the command to be used, without prefix.
*
* @return the name of this Command
*/
public String getName() {
return name;
}
/**
* Gets the aliases of this Command, some Strings you can use instead of
* this Command's name.
*
* @return possible aliases for this Command, may be of length 0
*/
public String[] getAliases() {
return aliases;
}
/**
* Checks if this Command is a restricted Command or not.
* A restricted Command cannot be ran by everybody, the nickname has to be
* a bot admin or in the {@link #getAllowedNickNames()} Set.
*
* @return true if this Command is restricted, false otherwise
*/
public boolean isRestricted() {
return restricted;
}
/**
* Gets a Set of Nicknames allowed to use this Command.
* Nicknames have to be registered and identified with the NickServ
* Service for this to be effective.
* This should not be considered if {@link #isRestricted()} is false.
*
* @return a Set of allowed Nicknames if this Command is restricted,
* null otherwise
*/
public Set<String> getAllowedNickNames() {
return allowedNickNames;
}
/**
* Executes this Command.
*
* @param server the Server this Command has been called from
* @param channel the Channel this Command has been called in, or
* null if there's none (i.e. if it's a private message)
* @param user the User that wrote the Command
* @param primaryArgument argument passed as commandPrefix.primaryArgument
* @param args arguments passed the the Command
*/
public abstract void exec(final Server server, final Channel channel, final Source user, final String primaryArgument, final String[] args);
/**
* Sends the usage of this Command to a Receiver.
*
* @param receiver the receiver to send the usage to
*/
public void sendUsage(final Receiver receiver) {
receiver.sendMessage(this.usage);
}
/**
* @return commandPrefix + commandName
*/
public String toString() {
return this.manager.getCommandPrefix() + getName();
}
}
| true | true | public Command(final CommandManager manager, final String name, final String[] usage, final boolean restricted, final Set<String> allowedNickNames, final String... aliases) {
if (!restricted && allowedNickNames != null) {
throw new IllegalArgumentException("A public Command should not have allowedNickNames, did you do something wrong?");
}
this.manager = manager;
this.name = name.toLowerCase();
this.aliases = aliases;
this.restricted = restricted;
this.allowedNickNames = allowedNickNames;
// Make the aliases lowercase, too
for (int i = 0; i < this.aliases.length; i++) {
this.aliases[i] = this.aliases[i].toLowerCase();
}
if (usage == null) {
this.usage = null;
} else {
final String commandString = this.toString();
this.usage = new String[usage.length + 1 + this.aliases.length > 0 ? 1 : 0];
this.usage[0] = Codes.RED + commandString;
if (usage.length > 0) {
for (int i = 1; i < usage.length + 1; i++) {
this.usage[i] = Codes.RED + " | " + usage[i - 1].replaceAll("##", commandString);
}
}
if (this.aliases.length > 0) {
final StringBuilder aliasesStringBuilder = new StringBuilder(Codes.RED + " | Aliases: " + this.aliases[0]);
for (int i = 1; i < this.aliases.length; i++) {
aliasesStringBuilder.append(", ").append(this.aliases[i]);
}
this.usage[this.usage.length - 1] = aliasesStringBuilder.toString();
}
}
}
| public Command(final CommandManager manager, final String name, final String[] usage, final boolean restricted, final Set<String> allowedNickNames, final String... aliases) {
if (!restricted && allowedNickNames != null) {
throw new IllegalArgumentException("A public Command should not have allowedNickNames, did you do something wrong?");
}
this.manager = manager;
this.name = name.toLowerCase();
this.aliases = aliases;
this.restricted = restricted;
this.allowedNickNames = allowedNickNames;
// Make the aliases lowercase, too
for (int i = 0; i < this.aliases.length; i++) {
this.aliases[i] = this.aliases[i].toLowerCase();
}
if (usage == null) {
this.usage = null;
} else {
final String commandString = this.toString();
this.usage = new String[usage.length + 1 + (this.aliases.length > 0 ? 1 : 0)];
this.usage[0] = Codes.RED + commandString;
if (usage.length > 0) {
for (int i = 1; i < usage.length + 1; i++) {
this.usage[i] = Codes.RED + " | " + usage[i - 1].replaceAll("##", commandString);
}
}
if (this.aliases.length > 0) {
final StringBuilder aliasesStringBuilder = new StringBuilder(Codes.RED + " | Aliases: " + this.aliases[0]);
for (int i = 1; i < this.aliases.length; i++) {
aliasesStringBuilder.append(", ").append(this.aliases[i]);
}
this.usage[this.usage.length - 1] = aliasesStringBuilder.toString();
}
}
}
|
diff --git a/src/main/java/hudson/plugins/label_verifier/verifiers/ShellScriptVerifier.java b/src/main/java/hudson/plugins/label_verifier/verifiers/ShellScriptVerifier.java
index 6c255a1..5dd57be 100644
--- a/src/main/java/hudson/plugins/label_verifier/verifiers/ShellScriptVerifier.java
+++ b/src/main/java/hudson/plugins/label_verifier/verifiers/ShellScriptVerifier.java
@@ -1,51 +1,52 @@
package hudson.plugins.label_verifier.verifiers;
import hudson.AbortException;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Computer;
import hudson.model.TaskListener;
import hudson.model.label.LabelAtom;
import hudson.plugins.label_verifier.LabelVerifier;
import hudson.plugins.label_verifier.LabelVerifierDescriptor;
import hudson.remoting.Channel;
import hudson.tasks.Shell;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.IOException;
import java.util.Collections;
/**
* Verifies the label by running a shell script.
*
* @author Kohsuke Kawaguchi
*/
public class ShellScriptVerifier extends LabelVerifier {
public final String script;
@DataBoundConstructor
public ShellScriptVerifier(String script) {
this.script = script;
}
@Override
public void verify(LabelAtom label, Computer c, Channel channel, FilePath root, TaskListener listener) throws IOException, InterruptedException {
Shell shell = new Shell(this.script);
FilePath script = shell.createScriptFile(root);
shell.buildCommandLine(script);
+ listener.getLogger().println("Validating the label '"+label.getName()+"'");
int r = root.createLauncher(listener).launch().cmds(shell.buildCommandLine(script))
.envs(Collections.singletonMap("LABEL",label.getName()))
.stdout(listener).pwd(root).join();
if (r!=0)
- throw new AbortException("The script failed. Label "+label.getName()+" is refused.");
+ throw new AbortException("The script failed. Label '"+label.getName()+"' is refused.");
}
@Extension
public static class DescriptorImpl extends LabelVerifierDescriptor {
@Override
public String getDisplayName() {
return "Verify By Shell Script";
}
}
}
| false | true | public void verify(LabelAtom label, Computer c, Channel channel, FilePath root, TaskListener listener) throws IOException, InterruptedException {
Shell shell = new Shell(this.script);
FilePath script = shell.createScriptFile(root);
shell.buildCommandLine(script);
int r = root.createLauncher(listener).launch().cmds(shell.buildCommandLine(script))
.envs(Collections.singletonMap("LABEL",label.getName()))
.stdout(listener).pwd(root).join();
if (r!=0)
throw new AbortException("The script failed. Label "+label.getName()+" is refused.");
}
| public void verify(LabelAtom label, Computer c, Channel channel, FilePath root, TaskListener listener) throws IOException, InterruptedException {
Shell shell = new Shell(this.script);
FilePath script = shell.createScriptFile(root);
shell.buildCommandLine(script);
listener.getLogger().println("Validating the label '"+label.getName()+"'");
int r = root.createLauncher(listener).launch().cmds(shell.buildCommandLine(script))
.envs(Collections.singletonMap("LABEL",label.getName()))
.stdout(listener).pwd(root).join();
if (r!=0)
throw new AbortException("The script failed. Label '"+label.getName()+"' is refused.");
}
|
diff --git a/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceActionProposer.java b/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceActionProposer.java
index 12924d9f..897e84a0 100644
--- a/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceActionProposer.java
+++ b/java/src/eu/semaine/components/dialogue/actionproposers/UtteranceActionProposer.java
@@ -1,1271 +1,1271 @@
/**
* Copyright (C) 2009 University of Twente. All rights reserved.
* Use is subject to license terms -- see license.txt.
*/
package eu.semaine.components.dialogue.actionproposers;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jms.JMSException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import eu.semaine.components.Component;
import eu.semaine.components.dialogue.behaviourselection.TemplateController;
import eu.semaine.components.dialogue.behaviourselection.behaviours.BehaviourClass;
import eu.semaine.components.dialogue.behaviourselection.template.TemplateState;
import eu.semaine.components.dialogue.datastructures.DMProperties;
import eu.semaine.components.dialogue.datastructures.DialogueAct;
import eu.semaine.components.dialogue.datastructures.EmotionEvent;
import eu.semaine.components.dialogue.datastructures.Response;
import eu.semaine.components.dialogue.informationstate.InformationState;
import eu.semaine.components.dialogue.test.DMLogger;
import eu.semaine.datatypes.stateinfo.ContextStateInfo;
import eu.semaine.datatypes.stateinfo.DialogStateInfo;
import eu.semaine.datatypes.stateinfo.StateInfo;
import eu.semaine.datatypes.xml.BML;
import eu.semaine.datatypes.xml.FML;
import eu.semaine.datatypes.xml.SSML;
import eu.semaine.datatypes.xml.SemaineML;
import eu.semaine.jms.IOBase.Event;
import eu.semaine.jms.message.SEMAINEFeatureMessage;
import eu.semaine.jms.message.SEMAINEMessage;
import eu.semaine.jms.message.SEMAINEStateMessage;
import eu.semaine.jms.message.SEMAINEXMLMessage;
import eu.semaine.jms.receiver.FeatureReceiver;
import eu.semaine.jms.receiver.StateReceiver;
import eu.semaine.jms.receiver.XMLReceiver;
import eu.semaine.jms.sender.FMLSender;
import eu.semaine.jms.sender.Sender;
import eu.semaine.jms.sender.StateSender;
import eu.semaine.system.CharacterConfigInfo;
import eu.semaine.util.SEMAINEUtils;
import eu.semaine.util.XMLTool;
public class UtteranceActionProposer extends Component implements BehaviourClass
{
/* Senders and Receivers */
private StateReceiver agentStateReceiver;
private StateReceiver userStateReceiver;
private StateReceiver contextReceiver;
private XMLReceiver callbackReceiver;
private FeatureReceiver featureReceiver;
private StateSender dialogStateSender;
private StateSender contextSender;
private FMLSender fmlSender;
private FMLSender queuingFMLSender;
private Sender commandSender;
private XMLReceiver callbackReceiverAnimation;
/* A local copy of the current Information State */
private InformationState is;
/* The TemplateController manages all Templates */
private TemplateController templateController;
/*A list with all detected emotion events of the current UserTurn */
private ArrayList<EmotionEvent> detectedEmotions = new ArrayList<EmotionEvent>();
/* A list with all data to send when the agent finishes speaking */
private ArrayList<String[]> dataSendQueue = new ArrayList<String[]>();
/* List of all detected Dialogue Acts (generated by the UtteranceInterpreter) */
private ArrayList<DialogueAct> detectedDActs = new ArrayList<DialogueAct>();
private int dActIndex = 0;
/* All possible responses and response-groups, with their ID as the key */
private HashMap<String,Response> responses;
private HashMap<String,ArrayList<Response>> responseGroups;
private HashMap<String,ArrayList<Response>> responseGroupHistory = new HashMap<String,ArrayList<Response>>();
/* A list of responses that is prepared or being prepared, with the hashvalue of that response as key */
private HashMap<String,String> preparedResponses = new HashMap<String,String>();
private HashMap<String,String> preparingResponses = new HashMap<String,String>();
/* A list of all detected audio-features of this UserTurn */
private HashMap<String,ArrayList<Float>> detectedFeatures = new HashMap<String,ArrayList<Float>>();
private HashMap<String,Boolean> turnActionUnits = new HashMap<String,Boolean>();
/* To generate random numbers */
private Random random = new Random();
/* Keeps track if the system has started or not */
private boolean systemStarted = false;
/* The latest AgentResponse that was executed */
private Response latestResponse = null;
private Response currResponse = null;
private String currHash = null;
/* If audiofeatures have to be stored at this moment or not */
private boolean isStoringFeatures = false;
/* A counter to keep track of the number of FML-objects that is send */
private int output_counter = 1;
/* The BehaviourClass-instance of this class */
private static UtteranceActionProposer myClass;
private ArrayList<Response> history = new ArrayList<Response>();
private LinkedList<String> historyQueue = new LinkedList<String>();
private int queueWaitingCounter = 0;
private long prevTime;
private String feedbackId = "";
/**
* Constructor of ResponseActionProposer
* Initializes all Senders and Receivers, and initializes everything.
*
*/
public UtteranceActionProposer() throws JMSException
{
super("UtteranceActionProposer");
/* Initialize receivers */
agentStateReceiver = new StateReceiver( "semaine.data.state.agent", StateInfo.Type.AgentState );
receivers.add( agentStateReceiver );
userStateReceiver = new StateReceiver("semaine.data.state.user.behaviour", StateInfo.Type.UserState);
receivers.add(userStateReceiver);
contextReceiver = new StateReceiver("semaine.data.state.context", StateInfo.Type.ContextState);
receivers.add( contextReceiver );
callbackReceiver = new XMLReceiver("semaine.callback.output.audio");
receivers.add(callbackReceiver);
callbackReceiverAnimation = new XMLReceiver("semaine.callback.output.Animation");
receivers.add(callbackReceiverAnimation);
featureReceiver = new FeatureReceiver("semaine.data.analysis.features.voice");
receivers.add(featureReceiver);
/* Initialize senders */
dialogStateSender = new StateSender("semaine.data.state.dialog", StateInfo.Type.DialogState, getName());
senders.add(dialogStateSender);
contextSender = new StateSender("semaine.data.state.context", StateInfo.Type.ContextState, getName());
senders.add(contextSender);
fmlSender = new FMLSender("semaine.data.action.selected.function", getName());
senders.add(fmlSender);
queuingFMLSender = new FMLSender("semaine.data.action.prepare.function", getName());
senders.add(queuingFMLSender);
commandSender = new Sender("semaine.data.synthesis.lowlevel.command", "playCommand", getName());
senders.add(commandSender);
/* Create TemplateController */
templateController = new TemplateController();
for( String templateFile : DMProperties.getTemplateFiles() ) {
System.out.println("Loading TemplateFile: " + templateFile);
templateController.processTemplateFile(templateFile.trim());
}
templateController.addFunction(this);
is = new InformationState();
is.set("User.present", 0);
/* Initialize Responses */
String responseFile = DMProperties.getResponseFile();
ResponseReader reader = new ResponseReader( responseFile );
if( !reader.readData() ) {
System.out.println( "Error, could not load Responses." );
}
responses = reader.getResponses();
responseGroups = reader.getResponseGroups();
for( String group : responseGroups.keySet() ) {
responseGroupHistory.put(group, new ArrayList<Response>());
for( Response r : responseGroups.get(group) ) {
is.set("Responses." + group + "._addlast", r.getId());
}
}
System.out.println("Loading Responses --- " + responses.size() + " SAL-Responses loaded.");
/* Initializes detected AudioFeatures */
detectedFeatures.put("F0", new ArrayList<Float>());
detectedFeatures.put("pitchDirScore", new ArrayList<Float>());
detectedFeatures.put("RMSEnergy", new ArrayList<Float>());
detectedFeatures.put("LOGEnergy", new ArrayList<Float>());
myClass = this;
waitingTime = 50;
prevTime = meta.getTime();
summarizeEmotionEvents();
}
/**
* Returns the instance of this class.
*/
public static UtteranceActionProposer getMyClass()
{
return myClass;
}
/**
* Act method, called every 50ms. If the system is started and the Agent is not speaking at this moment,
* check all Templates and execute any fitting behaviour.
*/
public void act() throws JMSException
{
//System.out.println(is);
if( meta.getTime() < prevTime ) {
is.set("Agent.speakingState","listening");
is.set("Agent.speakingStateTime", (int)meta.getTime());
is.set("User.speakingState","waiting");
sendData("agentTurnState", "listening", "dialogstate");
preparedResponses.clear();
preparingResponses.clear();
}
prevTime = meta.getTime();
/* Summarize all detected AudioFeatures and put this in the InformationState */
summarizeFeatures();
String speakingState = is.getString("Agent.speakingState");
Integer agentSpeakingStateTime = is.getInteger("Agent.speakingStateTime");
if( speakingState != null && agentSpeakingStateTime != null && (speakingState.equals("speaking") || speakingState.equals("preparing")) && (meta.getTime() >= agentSpeakingStateTime + 8000 || meta.getTime() < agentSpeakingStateTime) ) {
// Timeout
log.debug("Timeout -- going back to listening state");
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtteranceStopped (timeout)" );
is.set("Agent.speakingState","listening");
is.set("Agent.speakingStateTime", (int)meta.getTime());
is.set("User.speakingState","waiting");
sendData("agentTurnState", "listening", "dialogstate");
for( String[] str : dataSendQueue ) {
if( str.length == 3 ) {
sendData(str[0], str[1], str[2]);
}
}
queueWaitingCounter = 5;
dataSendQueue.clear();
}
if( queueWaitingCounter == 0 && systemStarted && (speakingState == null || (speakingState != null && speakingState.equals("listening"))) ) {
//System.out.println(is);
is.set("currTime", (int)meta.getTime());
String context = is.toString();
TemplateState state = templateController.checkTemplates(is);
if( state != null ) {
DMLogger.getLogger().logUserTurn(meta.getTime(), latestResponse.getResponse() + "("+state.getTemplate().getId()+")", context);
detectedEmotions.clear();
dActIndex = detectedDActs.size();
for( String featureName : detectedFeatures.keySet() ) {
is.remove("UserTurn.AudioFeatures."+featureName+"_min");
is.remove("UserTurn.AudioFeatures."+featureName+"_max");
is.remove("UserTurn.AudioFeatures."+featureName+"_avg");
}
DMLogger.getLogger().log(meta.getTime(), "AgentAction:SendUtterance, type="+state.getTemplate().getId()+", utterance="+latestResponse.getResponse());
log.debug("action type: "+state.getTemplate().getId());
}
}
if( queueWaitingCounter > 0 ) queueWaitingCounter--;
}
/**
* Updates the InformationState based on the SemaineMessages it receives
*/
public void react( SEMAINEMessage m ) throws JMSException
{
if( m instanceof SEMAINEFeatureMessage ) {
/* Process AudioFeatures */
if( isStoringFeatures ) {
SEMAINEFeatureMessage fm = (SEMAINEFeatureMessage)m;
/* Reads the feature names and values */
String[] featureNames = fm.getFeatureNames();
float[] featureValues = fm.getFeatureVector();
for( int i=0; i<featureNames.length; i++ ) {
if( detectedFeatures.get(featureNames[i]) != null ) {
detectedFeatures.get(featureNames[i]).add(featureValues[i]);
} else {
ArrayList<Float> tempList = new ArrayList<Float>();
tempList.add(featureValues[i]);
detectedFeatures.put(featureNames[i],tempList);
}
}
}
} else if( m instanceof SEMAINEXMLMessage ){
SEMAINEXMLMessage xm = ((SEMAINEXMLMessage)m);
/* Process Agent-animation updates */
- if( !xm.getText().contains("fml_lip") ) {
+ if( !xm.getText().contains("fml_lip") && !xm.getText().contains("bml_lip") ) {
if( speechStarted(xm) ) {
log.debug("Agent is currently speaking");
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtteranceStarted" );
is.set("Agent.speakingState","speaking");
is.set("Agent.speakingStateTime", (int)meta.getTime());
sendData("agentTurnState", "speaking", "dialogstate");
isStoringFeatures = false;
for( ArrayList<Float> al : detectedFeatures.values() ) {
al.clear();
}
}
String speechReady = speechReady(xm);
if( speechReady != null && speechReady.equals(feedbackId) ) {
log.debug("Agent utterance has finished");
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtteranceStopped (feedback)");
is.set("Agent.speakingState","listening");
is.set("Agent.speakingStateTime", (int)meta.getTime());
is.set("User.speakingState","waiting");
is.remove("UserTurn");
turnActionUnits.clear();
sendData("agentTurnState", "listening", "dialogstate");
for( String[] str : dataSendQueue ) {
if( str.length == 3 ) {
sendData(str[0], str[1], str[2]);
}
}
dataSendQueue.clear();
queueWaitingCounter = 5;
}
}
if (xm.getDatatype().equals("FML")) {
Element fml = XMLTool.getChildElementByTagNameNS(xm.getDocument().getDocumentElement(), FML.E_FML, FML.namespaceURI);
if( fml != null ) {
Element backchannel = XMLTool.getChildElementByTagNameNS(fml, FML.E_BACKCHANNEL, FML.namespaceURI);
if( backchannel != null ) {
DMLogger.getLogger().log(meta.getTime(), "AgentAction:Backchannel" );
}
}
}
Document doc = xm.getDocument();
Element event = XMLTool.getChildElementByLocalNameNS(doc.getDocumentElement(), SemaineML.E_EVENT, SemaineML.namespaceURI);
if (event != null) {
String id = event.getAttribute(SemaineML.A_ID);
long time = Long.parseLong(event.getAttribute(SemaineML.A_TIME));
String type = event.getAttribute(SemaineML.A_TYPE);
if (type.equals(SemaineML.V_READY)) {
String keyToRemove = null;
for( String key : preparingResponses.keySet() ) {
if( preparingResponses.get(key).equals(id) ) {
log.debug("Preparation complete: "+id);
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtterancePrepared");
preparedResponses.put(key, id);
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparingResponses.remove(keyToRemove);
} else if (type.equals(SemaineML.V_DELETED)) {
System.out.println("\r\n\r\n\r\n\r\n\r\n\r\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
String keyToRemove = null;
for( String key : preparingResponses.keySet() ) {
if( preparingResponses.get(key).equals(id) ) {
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparingResponses.remove(keyToRemove);
keyToRemove = null;
for( String key : preparedResponses.keySet() ) {
if( preparedResponses.get(key).equals(id) ) {
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparedResponses.remove(keyToRemove);
} else {
// Do Nothing
}
}
}
/* Processes User state updates */
if( m instanceof SEMAINEStateMessage ) {
SEMAINEStateMessage sm = ((SEMAINEStateMessage)m);
StateInfo stateInfo = sm.getState();
StateInfo.Type stateInfoType = stateInfo.getType();
switch (stateInfoType) {
case UserState:
/* Updates user speaking state (speaking or silent) */
if( stateInfo.hasInfo("speaking") ) {
if( stateInfo.getInfo("speaking").equals("true") ) {
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("speaking") ) {
is.set("User.speakingState", "speaking");
is.set("User.speakingStateTime", (int)meta.getTime());
if(!isStoringFeatures) isStoringFeatures = true;
}
} else if( stateInfo.getInfo("speaking").equals("false") ) {
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("listening") ) {
is.set("User.speakingState", "listening");
is.set("User.speakingStateTime", (int)meta.getTime());
}
}
}
/* Updates detected emotions (valence, arousal, interest) */
if( stateInfo.hasInfo("valence") ) {
float valence = Float.parseFloat( stateInfo.getInfo("valence") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.VALENCE, valence );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("arousal") ) {
float arousal = Float.parseFloat( stateInfo.getInfo("arousal") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.AROUSAL, arousal );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("interest") ) {
float interest = Float.parseFloat( stateInfo.getInfo("interest") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.INTEREST, interest );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("potency") ) {
float potency = Float.parseFloat( stateInfo.getInfo("potency") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.POTENCY, potency );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("intensity") ) {
float intensity = Float.parseFloat( stateInfo.getInfo("intensity") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.INTENSITY, intensity );
detectedEmotions.add( ee );
summarizeEmotionEvents();
}
/* Updates the detected and analysed user utterances */
if( stateInfo.hasInfo("userUtterance") && stateInfo.hasInfo("userUtteranceStartTime") ) {
String utterance = stateInfo.getInfo("userUtterance");
long time = Long.parseLong(stateInfo.getInfo("userUtteranceStartTime"));
String f = stateInfo.getInfo("userUtteranceFeatures");
if( f == null ) {
f = "";
}
DialogueAct act = new DialogueAct( utterance, time );
act.setEndtime(meta.getTime());
if( f.contains("positive") ) act.setPositive(true);
if( f.contains("negative") ) act.setNegative(true);
if( f.contains("disagree") ) {
act.setDisagree(true);
f = f.replace("disagree", "");
}
if( f.contains("agree") ) act.setAgree(true);
if( f.contains("about_other_people") ) act.setAboutOtherPeople(true);
if( f.contains("about_other_character") ) act.setAboutOtherCharacter(true);
if( f.contains("about_current_character") ) act.setAboutCurrentCharacter(true);
if( f.contains("about_own_feelings") ) act.setAboutOwnFeelings(true);
if( f.contains("pragmatic") ) act.setPragmatic(true);
if( f.contains("abou_self") ) act.setTalkAboutSelf(true);
if( f.contains("future") ) act.setFuture(true);
if( f.contains("past") ) act.setPast(true);
if( f.contains("event") ) act.setEvent(true);
if( f.contains("action") ) act.setAction(true);
if( f.contains("laugh") ) act.setLaugh(true);
if( f.contains("change_speaker") ) act.setChangeSpeaker(true);
if( f.contains("target:") ) act.setTargetCharacter( f.substring(f.indexOf("target:")+7, Math.max(f.length(),f.indexOf(" ", f.indexOf("target:")+7))) );
if( f.contains("short") ) act.setLength(DialogueAct.Length.SHORT);
if( f.contains("long") ) act.setLength(DialogueAct.Length.LONG);
if( detectedDActs.size() > 1 && Math.abs(detectedDActs.get(detectedDActs.size()-1).getStarttime() - act.getStarttime()) < 10 ) {
// Same dialogueAct, so update the last DA in the list
detectedDActs.set(detectedDActs.size()-1, act);
} else {
detectedDActs.add(act);
}
getCombinedUserDialogueAct();
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("speaking") ) {
is.set("User.speakingState", "speaking");
is.set("User.speakingStateTime", (int)meta.getTime());
if(!isStoringFeatures) isStoringFeatures = true;
}
}
if( stateInfo.hasInfo("headGesture") && stateInfo.hasInfo("headGestureStarted") && stateInfo.hasInfo("headGestureStopped") ) {
String gesture = stateInfo.getInfo("headGesture");
Integer counter = is.getInteger("UserTurn.Head.nrOf" + gesture);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Head.nrOf" + gesture, counter);
is.set("UserTurn.Head.lastGesture", gesture);
}
if( stateInfo.hasInfo("pitchDirection") ) {
String pitch = stateInfo.getInfo("pitchDirection");
Integer counter = is.getInteger("UserTurn.Pitch.nrOf" + pitch);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Pitch.nrOf" + pitch, pitch);
is.set("UserTurn.Pitch.lastPitch", pitch);
}
if( stateInfo.hasInfo("vocalization") ) {
String vocalization = stateInfo.getInfo("vocalization");
Integer counter = is.getInteger("UserTurn.Vocalization.nrOf" + vocalization);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Vocalization.nrOf" + vocalization, vocalization);
}
if( stateInfo.hasInfo("facialActionUnits") ) {
String facialExpressions = stateInfo.getInfo("facialActionUnits");
List<String> aus = Arrays.asList(facialExpressions.split(" "));
for( String au : aus ) {
Boolean b = turnActionUnits.get(au);
if( b == null || (b != null && b == false) ) {
turnActionUnits.put(au,true);
Integer counter = is.getInteger("UserTurn.AU.nrOfAU" + au);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.AU.nrOfAU" + au, counter);
}
}
for( String au : turnActionUnits.keySet() ) {
if( !aus.contains(au) ) {
turnActionUnits.put(au,false);
}
}
}
break;
case ContextState:
/* Updates the current character and the user */
/* Update user presence */
if( stateInfo.hasInfo("userPresent") ) {
if( is.getInteger("User.present") == null ) {
is.set("User.present", 0);
}
if( stateInfo.getInfo("userPresent").equals("present") && is.getInteger("User.present") == 0 ) {
DMLogger.getLogger().log(meta.getTime(), "System:SystemStarted" );
is.set("User.present", 1);
is.set("User.presentStateChanged",1);
String agent = is.getString("Agent.character");
if( agent == null || agent.length() == 0 ) {
is.set("Agent.character", CharacterConfigInfo.getDefaultCharacter().getName());
}
systemStarted = true;
} else if( stateInfo.getInfo("userPresent").equals("absent") && is.getInteger("User.present") == 1 ) {
DMLogger.getLogger().log(meta.getTime(), "System:SystemStopped" );
is.set("User.present", 0);
is.set("User.presentStateChanged",1);
systemStarted = false;
is.set("currTime", (int)meta.getTime());
String context = is.toString();
TemplateState state = templateController.checkTemplates(is);
if( state != null ) {
DMLogger.getLogger().logUserTurn(meta.getTime(), latestResponse.getResponse() + "("+state.getTemplate().getId()+")", context);
detectedEmotions.clear();
dActIndex = detectedDActs.size();
for( String featureName : detectedFeatures.keySet() ) {
is.remove("UserTurn.AudioFeatures."+featureName+"_min");
is.remove("UserTurn.AudioFeatures."+featureName+"_max");
is.remove("UserTurn.AudioFeatures."+featureName+"_avg");
}
DMLogger.getLogger().log(meta.getTime(), "AgentAction:SendUtterance, type="+state.getTemplate().getId()+", utterance="+latestResponse.getResponse());
}
}
}
/* Update current character */
if( stateInfo.hasInfo("character") ) {
System.out.println("New Character: " + stateInfo.getInfo("character"));
is.set("Agent.character", stateInfo.getInfo("character"));
is.set("Agent.characterChanged", 1);
preparedResponses.clear();
preparingResponses.clear();
}
if( stateInfo.hasInfo("nextCharacter") ) {
String nextCharacter = stateInfo.getInfo("nextCharacter");
is.set("Agent.nextCharacter", nextCharacter);
}
if( stateInfo.hasInfo("dialogContext") ) {
String context = stateInfo.getInfo("dialogContext");
is.set("Agent.dialogContext", context);
}
break;
case AgentState:
String intention = stateInfo.getInfo("turnTakingIntention");
if( intention != null && intention.equals("startSpeaking") ) {
String currSpeakingState = is.getString("Agent.speakingState");
if( currSpeakingState != null && !currSpeakingState.equals("speaking") && !currSpeakingState.equals("preparing") ) {
String userSpeakingState = is.getString("User.speakingState");
if( userSpeakingState != null && userSpeakingState.equals("waiting") ) {
is.set("Agent.speakingIntention","retake_turn");
} else {
is.set("Agent.speakingIntention","want_turn");
}
}
}
break;
}
}
//is.print();
}
/**
* This method checks if the given message contains the start signal of the animation that the agent
* is going to play next.
* @param xm the message to check
* @return true if the message contains the start signal, false if it does not.
*/
public boolean speechStarted( SEMAINEXMLMessage xm )
{
Element callbackElem = XMLTool.getChildElementByLocalNameNS(xm.getDocument(), "callback", SemaineML.namespaceURI);
if( callbackElem != null ) {
Element eventElem = XMLTool.getChildElementByLocalNameNS(callbackElem, "event", SemaineML.namespaceURI);
if( eventElem != null ) {
String agentSpeakingState = is.getString("Agent.speakingState");
if( agentSpeakingState != null ) {
if( eventElem.hasAttribute("type") && eventElem.getAttribute("type").equals("start") && (agentSpeakingState.equals("preparing") || agentSpeakingState.equals("listening")) ) {
return true;
}
} else {
if( eventElem.hasAttribute("type") && eventElem.getAttribute("type").equals("start") ) {
return true;
}
}
}
}
return false;
}
/**
* This method checks if the given message contains the end signal of the animation that the agent
* is playing.
* @param xm the message to check
* @return true if the message contains the end signal, false if it does not.
*/
public String speechReady( SEMAINEXMLMessage xm ) throws JMSException
{
Element callbackElem = XMLTool.getChildElementByLocalNameNS(xm.getDocument(), "callback", SemaineML.namespaceURI);
if( callbackElem != null ) {
Element eventElem = XMLTool.getChildElementByLocalNameNS(callbackElem, "event", SemaineML.namespaceURI);
if( eventElem != null ) {
String agentSpeakingState = is.getString("Agent.speakingState");
DMLogger.getLogger().log(meta.getTime(), xm.getText());
if( agentSpeakingState != null ) {
if( eventElem.hasAttribute("type") && eventElem.getAttribute("type").equals("end") && (agentSpeakingState.equals("preparing") || agentSpeakingState.equals("speaking")) ) {
if( eventElem.hasAttribute("id") ) {
return eventElem.getAttribute("id");
}
}
} else {
if( eventElem.hasAttribute("type") && eventElem.getAttribute("type").equals("end") ) {
if( eventElem.hasAttribute("id") ) {
return eventElem.getAttribute("id");
}
}
}
}
}
return null;
}
/**
* Summarizes the detected Emotional events and puts this in the InformationState
*/
public void summarizeEmotionEvents()
{
ArrayList<Float> highArousals = new ArrayList<Float>();
ArrayList<Float> lowArousals = new ArrayList<Float>();
ArrayList<Float> highValence = new ArrayList<Float>();
ArrayList<Float> lowValence = new ArrayList<Float>();
ArrayList<Float> highInterest = new ArrayList<Float>();
ArrayList<Float> lowInterest = new ArrayList<Float>();
ArrayList<Float> highPotency = new ArrayList<Float>();
ArrayList<Float> lowPotency = new ArrayList<Float>();
ArrayList<Float> highIntensity = new ArrayList<Float>();
ArrayList<Float> lowIntensity = new ArrayList<Float>();
for( EmotionEvent event : detectedEmotions ) {
if( event.getType() == EmotionEvent.AROUSAL ) {
if( event.getIntensity() >= 0 ) {
highArousals.add(event.getIntensity());
} else {
lowArousals.add(event.getIntensity());
}
} else if( event.getType() == EmotionEvent.VALENCE ) {
if( event.getIntensity() >= 0 ) {
highValence.add(event.getIntensity());
} else {
lowValence.add(event.getIntensity());
}
} else if( event.getType() == EmotionEvent.INTEREST ) {
if( event.getIntensity() >= 0 ) {
highInterest.add(event.getIntensity());
} else {
lowInterest.add(event.getIntensity());
}
} else if( event.getType() == EmotionEvent.POTENCY ) {
if( event.getIntensity() >= 0 ) {
highPotency.add(event.getIntensity());
} else {
lowPotency.add(event.getIntensity());
}
} else if( event.getType() == EmotionEvent.INTENSITY ) {
if( event.getIntensity() >= 0 ) {
highIntensity.add(event.getIntensity());
} else {
lowIntensity.add(event.getIntensity());
}
}
}
setISEmotions("Valence", lowValence, highValence);
setISEmotions("Arousal", lowArousals, highArousals);
setISEmotions("Interest", lowInterest, highInterest);
setISEmotions("Potency", lowPotency, highPotency);
setISEmotions("Intensity", lowIntensity, highIntensity);
}
/**
* Based on the given emotion-name, and the list of low and high receives intensities,
* calculate the min,max and average values, and put this in the InformationState.
*
* @param emotion - the name of the Emotion this data belongs to
* @param nrLow - the number of low emotion-values (<0)
* @param nrHigh - the number of high emotion-values (>=0)
*/
public void setISEmotions( String emotion, ArrayList<Float> nrLow, ArrayList<Float> nrHigh )
{
if( nrLow.size() == 0 && nrHigh.size() == 0 ) {
is.set("UserTurn."+emotion+".nrLowEvents", 0);
is.set("UserTurn."+emotion+".nrHighEvents", 0);
is.set("UserTurn."+emotion+".average", 0);
is.set("UserTurn."+emotion+".min", 0);
is.set("UserTurn."+emotion+".max", 0);
} else {
float sum = 0f;
float max = -999f;
float min = 999f;
for( Float fl : nrHigh ) {
if( fl > max ) max = fl;
if( fl < min ) min = fl;
sum = sum + fl;
}
for( Float fl : nrLow ) {
if( fl > max ) max = fl;
if( fl < min ) min = fl;
sum = sum + fl;
}
is.set("UserTurn."+emotion+".nrLowEvents", nrLow.size());
is.set("UserTurn."+emotion+".nrHighEvents", nrHigh.size());
is.set("UserTurn."+emotion+".average", new Float(sum / (nrLow.size() + nrHigh.size())).doubleValue());
is.set("UserTurn."+emotion+".min", new Double(min));
is.set("UserTurn."+emotion+".max", new Double(max));
}
}
/**
* Summarizes the detected AudioFeatures and puts this in the InformationState
*/
public void summarizeFeatures()
{
for( String featureName : detectedFeatures.keySet() ) {
ArrayList<Float> features = detectedFeatures.get(featureName);
if( features.size() == 0 ) {
continue;
} else {
float min = 99999;
float max = -99999;
float avg = 0;
for( float fl : features ) {
avg = avg + fl;
if( fl < min ) min = fl;
if( fl > max ) max = fl;
}
avg = avg / features.size();
is.set("UserTurn.AudioFeatures."+featureName+"_min",new Float(min).doubleValue());
is.set("UserTurn.AudioFeatures."+featureName+"_max",new Float(max).doubleValue());
is.set("UserTurn.AudioFeatures."+featureName+"_avg",new Float(avg).doubleValue());
}
}
}
/**
* Combines all DialogueActs of the last UserTurn, and puts this in the InformationState
*/
public void getCombinedUserDialogueAct()
{
DialogueAct act = null;
for( int i=dActIndex; i<detectedDActs.size(); i++ ) {
if( detectedDActs.get(i).getFeatures().length() > 0 ) {
DMLogger.getLogger().log(meta.getTime(), "UserAction:ContentFeatures features="+detectedDActs.get(i).getFeatures().trim()+" starttime="+detectedDActs.get(i).getStarttime()+" endtime="+detectedDActs.get(i).getEndtime()+"");
}
if( act == null ) {
if( i == dActIndex ) {
act = detectedDActs.get(i);
} else {
// Something is wrong
// TODO: report error
}
} else {
act = new DialogueAct(act,detectedDActs.get(i));
}
}
if( act == null ) return;
is.set("UserTurn.utterance", act.getUtterance());
is.set("UserTurn.starttime",(int)act.getStarttime());
is.set("UserTurn.endtime",(int)act.getStarttime());
is.set("UserTurn.targetCharacter",act.getTargetCharacter());
is.remove("UserTurn.SemanticFeatures");
for( String contentFeature : act.getFeatureList() ) {
is.set("UserTurn.SemanticFeatures._addlast",contentFeature);
}
}
/**
* Updates the InformationState with the behaviour that the Agent is performing now
*/
public void sendSpeaking()
{
is.set("Agent.speakingState","preparing");
is.set("Agent.speakingIntention","null");
is.set("Agent.speakingStateTime", (int)meta.getTime());
is.set("ResponseHistory._addlast.id",latestResponse.getId());
is.set("ResponseHistory._last.response",latestResponse.getResponse());
}
/**
* Adds the given data to the list of data to send to Semaine at the end of the Agent's turn
*
* @param name - the name of the data-element to send.
* @param value - the value of the data-element to send.
* @param channel - the Semaine-channel to send the data too.
*/
public void sendDataAtEndOfTurn( String name, String value, String channel )
{
String[] queue = {name,value,channel};
dataSendQueue.add(queue);
}
/**
* Sends the given data to the other Semaine components
*
* @param name - the name of the data-element to send.
* @param value - the value of the data-element to send.
* @param channel - the Semaine-channel to send the data too (could be 'dialogstate' and 'contextstate')
*/
public void sendData( String name, String value, String channel ) throws JMSException
{
Map<String,String> info = new HashMap<String,String>();
info.put(name,value);
if( channel.toLowerCase().equals("dialogstate") ) {
DialogStateInfo dsi = new DialogStateInfo(info, null);
dialogStateSender.sendStateInfo(dsi, meta.getTime());
} else if( channel.toLowerCase().equals("contextstate") ) {
ContextStateInfo csi = new ContextStateInfo(info);
contextSender.sendStateInfo( csi, meta.getTime() );
}
}
/**
* Executes the Behaviour of a Template, with the given InformationState, and the given list of arguments.
*
* @param is - the current InformationState
* @param argNames - the list of names of the given arguments
* @param argValues - the list of values of the given arguments
*/
public void execute( InformationState is, ArrayList<String> argNames, ArrayList<String> argValues )
{
if( argNames == null ) argNames = new ArrayList<String>();
if( argValues == null ) argValues = new ArrayList<String>();
Document doc = constructFMLDocument(argNames, argValues);
System.out.println(docToString(doc));
if( doc == null ) return;
String id = preparedResponses.get(currHash);
if( id != null ) {
/* The Response has been prepared before, so it only has to be started. */
try {
latestResponse = currResponse;
history.add(latestResponse);
sendSpeaking();
DMLogger.getLogger().log(meta.getTime(), "Using Prepared Response " + id);
log.debug("Trigger prepared response "+id+" '"+currResponse.getResponse()+"'");
commandSender.sendTextMessage("STARTAT 0\nPRIORITY 0.5\nLIFETIME 5000\n", meta.getTime(), Event.single, id, meta.getTime());
preparedResponses.remove(currHash);
feedbackId = id;
}catch( JMSException e ){
// TODO: handle
}
} else {
/* The Response has not been prepared, so it has to be send directly. */
String contentID = "fml_uap_"+output_counter;
try {
latestResponse = currResponse;
history.add(latestResponse);
sendSpeaking();
System.out.println(docToString(doc));
log.debug("Generating directly: '"+currResponse.getResponse()+"'");
fmlSender.sendXML(doc, meta.getTime(), "bml_uap_"+output_counter, meta.getTime());
feedbackId = "bml_uap_"+output_counter;
}catch( JMSException e ) {
// Handle
}
output_counter++;
}
String queueString = "";
for( String str : historyQueue ) {
queueString = queueString + str + " ";
}
DMLogger.getLogger().log(meta.getTime(), "Queue = " + queueString);
historyQueue.addLast(latestResponse.getResponse());
if( historyQueue.size() > 10 ) historyQueue.removeFirst();
}
/**
* Executes the Behaviour of a Template, with the given InformationState, and the given list of arguments.
*
* @param is - the current InformationState
* @param argNames - the list of names of the given arguments
* @param argValues - the list of values of the given arguments
*/
public void prepare( InformationState is, ArrayList<String> argNames, ArrayList<String> argValues )
{
if( preparingResponses.size() == 0 ) {
if( argNames == null ) argNames = new ArrayList<String>();
if( argValues == null ) argValues = new ArrayList<String>();
Document doc = constructFMLDocument(argNames, argValues);
if( doc == null ) return;
String hash = currHash;
if( preparingResponses.get(hash) != null || preparedResponses.get(hash) != null ) {
return;
}
try {
// TODO: Uncomment and test
System.out.println(docToString(doc));
queuingFMLSender.sendXML(doc, meta.getTime(), "bml_uap_"+output_counter, meta.getTime());
String prepID = "bml_uap_"+output_counter;
preparingResponses.put(hash, prepID);
DMLogger.getLogger().log(meta.getTime(),"PreparationHash = " + hash);
DMLogger.getLogger().log(meta.getTime(), "AgentAction:PrepareUtterance, utterance=" + currResponse.getResponse() );
log.debug("Preparing response "+prepID+" '"+currResponse.getResponse()+"'");
}catch( JMSException e ){
// TODO Handle
}
output_counter++;
}
}
/**
* Constructs a FML-document from the given arguments
*
* @param argNames - the names of the given arguments.
* @param argValues - the values of the given arguments.
* @return the constructed FML-document.
*/
public Document constructFMLDocument( ArrayList<String> argNames, ArrayList<String> argValues )
{
Response response = getResponse(argNames, argValues);
if( response == null ) return null;
currHash = createHash(response,argNames,argValues);
currResponse = response;
String responseString = response.getResponse();
argNames.addAll(response.getArgNames());
argValues.addAll(response.getArgValues());
Document doc = XMLTool.newDocument("fml-apml", null, FML.version);
Element root = doc.getDocumentElement();
Element bml = XMLTool.appendChildElement(root, BML.E_BML, BML.namespaceURI);
bml.setPrefix("bml");
bml.setAttribute(BML.A_ID, "bml_uap_"+output_counter);
Element fml = XMLTool.appendChildElement(root, FML.E_FML, FML.namespaceURI);
fml.setPrefix("fml");
fml.setAttribute(FML.A_ID, "fml_uap_"+output_counter);
/* Speech Element */
Element speech = XMLTool.appendChildElement(bml, BML.E_SPEECH);
speech.setAttribute(BML.A_ID, "speech_uap_"+output_counter);
speech.setAttribute(BML.E_TEXT, responseString);
speech.setAttribute(BML.E_LANGUAGE, getCharacterLocale());
speech.setAttribute("voice", "activemary");
/* Mark Elements */
int counter=1;
String[] words = responseString.split(" ");
for( String word : words ) {
Element mark = XMLTool.appendChildElement(speech, SSML.E_MARK, SSML.namespaceURI);
mark.setPrefix("ssml");
mark.setAttribute(SSML.A_NAME, "speech_uap_"+output_counter+":tm"+counter);
Node text = doc.createTextNode(word);
speech.appendChild(text);
counter++;
}
Element mark = XMLTool.appendChildElement(speech, SSML.E_MARK, SSML.namespaceURI);
mark.setPrefix("ssml");
mark.setAttribute(SSML.A_NAME, "speech_uap_"+output_counter+":tm"+counter);
/* Add the arguments to the FML-document */
int tagCounter = 1;
for( int i=0; i<argNames.size(); i++ ) {
String argName = argNames.get(i);
if( !argName.equals("response") && !argName.equals("response2") && argName.contains(":") ) {
String[] tags = argName.split(":");
if( tags.length == 2 ) {
/* Determine start and endtime */
String starttime = null;
String endtime = null;
if( i >= argValues.size() ) {
System.out.println("Something is wrong in the Parameters of Response " + response.getId());
continue;
}
String argValue = argValues.get(i);
if( argValue.equals("_start") ) {
starttime = "speech_uap_"+output_counter+":tm1";
endtime = "speech_uap_"+output_counter+":tm"+(Math.min(3, counter));
} else if( argValue.equals("_end") ) {
starttime = "speech_uap_"+output_counter+":tm"+(Math.max(1,(counter-2)));
endtime = "speech_uap_"+output_counter+":tm"+counter;
} else if( argValue.equals("_all") ) {
starttime = "speech_uap_"+output_counter+":tm1";
endtime = "speech_uap_"+output_counter+":tm"+counter;
} else {
Pattern pattern = Pattern.compile("[\\s]"+argValue.trim()+"[\\s.,\\?!]");
Pattern patternStart = Pattern.compile("^"+argValue.trim()+"[\\s.,\\?!]");
Pattern patternEnd = Pattern.compile("[\\s]"+argValue.trim()+"[\\s.,\\?!]*$");
Matcher matcher = pattern.matcher(responseString);
int startIndex = 0;
int endIndex = 0;
int startMarker = 0;
int endMarker = 0;
if( matcher.find() ) {
//System.out.println("General match");
startIndex = matcher.start();
endIndex = matcher.end();
startMarker = responseString.substring(0,startIndex).split(" ").length + 1;
endMarker = responseString.substring(0,endIndex).split(" ").length + 1;
} else {
matcher = patternStart.matcher(responseString);
if( matcher.find() ) {
//System.out.println("Start match");
startIndex = matcher.start();
endIndex = matcher.end();
startMarker = 1;
endMarker = responseString.substring(0,endIndex).split(" ").length + 1;
} else {
matcher = patternEnd.matcher(responseString);
if( matcher.find() ) {
//System.out.println("End match");
startIndex = matcher.start();
endIndex = matcher.end();
startMarker = responseString.substring(0,startIndex).split(" ").length + 1;
endMarker = responseString.split(" ").length+1;
} else {
continue;
}
}
}
starttime = "speech_uap_"+output_counter+":tm" + startMarker;
endtime = "speech_uap_"+output_counter+":tm" + endMarker;
// for( int j=0; j<words.length; j++ ) {
// if( words[j].equals(argValue) ) {
// starttime = "speech_uap_"+output_counter+":tm"+(j+1);
// endtime = "speech_uap_"+output_counter+":tm"+(j+2);
// break;
// }
// }
}
Element targetElement;
if( tags[0].equals("pitchaccent") ) {
targetElement = bml;
} else {
targetElement = fml;
}
Element tagElement = XMLTool.appendChildElement(targetElement, tags[0]);
tagElement.setAttribute("id", "tag"+tagCounter);
tagElement.setAttribute("type", tags[1]);
tagElement.setAttribute("start", starttime);
tagElement.setAttribute("end", endtime);
tagElement.setAttribute("importance", ""+1);
tagCounter++;
}
}
}
return doc;
}
/**
* Get a String representation of the current character's locale, suitable for entering into XML.
* @return the current Character's locale, or "en-GB" as a default.
*/
private String getCharacterLocale() {
String charName = is.getString("Agent.character");
CharacterConfigInfo charInfo = CharacterConfigInfo.getInfo(charName);
String locale = charInfo != null ? SEMAINEUtils.locale2xmllang(charInfo.getVoiceLocale()) : "en-GB";
return locale;
}
/**
* Retrieves the Response from the given list of arguments. If two responses are present they are combined into 1.
*
* @param argNames - the names of the given arguments.
* @param argValues - the values of the given arguments.
* @return the found Response
*/
public Response getResponse( ArrayList<String> argNames, ArrayList<String> argValues )
{
int responseIndex = argNames.indexOf("response");
if( responseIndex == -1 ) {
System.out.println("Error, no response given.");
return null;
}
Response response = responses.get(argValues.get(responseIndex));
if( response == null ) {
response = getResponseFromGroup(argValues.get(responseIndex));
if( response == null ) {
System.out.println("Error, fitting Response ("+argValues.get(responseIndex)+") could not be found.");
return null;
}
}
int responseIndex2 = argNames.indexOf("response2");
if( responseIndex2 == -1 ) {
return response;
}
Response response2 = responses.get(argValues.get(responseIndex2));
if( response2 == null ) {
response2 = getResponseFromGroup(argValues.get(responseIndex2));
if( response2 == null ) {
System.out.println("Error, fitting Response ("+argValues.get(responseIndex2)+") could not be found.");
return response;
}
}
Response combinedResponse = new Response( response, response2 );
return combinedResponse;
}
public Response getResponseFromGroup( String group )
{
ArrayList<Response> responses = responseGroups.get(group);
if( responses == null ) {
return null;
}
ArrayList<Response> nonUsedResponses = new ArrayList<Response>();
for( Response r : responses ) {
if( !history.contains(r) ) {
nonUsedResponses.add(r);
}
}
if( nonUsedResponses.size() > 0 ) {
return nonUsedResponses.get(random.nextInt(nonUsedResponses.size()));
} else {
Response[] pastResponses = new Response[3];
int[] lastIndex = new int[3];
lastIndex[0] = 9999; lastIndex[1] = 9999; lastIndex[2] = 9999;
int minIndex = 9999;
int minIndexPlace = 0;
for( Response r : responses ) {
int i = history.lastIndexOf(r);
if( i < minIndex ) {
pastResponses[minIndexPlace] = r;
lastIndex[minIndexPlace] = i;
minIndex = Math.max(lastIndex[0], Math.max(lastIndex[1],lastIndex[2]));
if( lastIndex[0] == minIndex ) minIndexPlace = 0;
if( lastIndex[1] == minIndex ) minIndexPlace = 1;
if( lastIndex[2] == minIndex ) minIndexPlace = 2;
}
}
if( pastResponses[0] != null && pastResponses[1] != null && pastResponses[2] != null ) {
return pastResponses[random.nextInt(3)];
} else if( pastResponses[0] != null && pastResponses[1] != null ) {
return pastResponses[random.nextInt(2)];
} else {
return pastResponses[0];
}
}
}
/**
* Creates a unique Hash from the given list of arguments, to make a unique identifier of this particular Response.
*
* @param argNames - the names of the given arguments.
* @param argValues - the values of the given arguments.
* @return the Hash-string creates from the list of arguments.
*/
public String createHash( Response r, ArrayList<String> argNames, ArrayList<String> argValues )
{
ArrayList<String> argNamesCopy = (ArrayList<String>)argNames.clone();
ArrayList<String> argValuesCopy = (ArrayList<String>)argValues.clone();
String hash = r.getResponse();
Collections.sort(argNamesCopy);
Collections.sort(argValuesCopy);
ArrayList<String> nameToRemove = new ArrayList<String>();
ArrayList<String> valueToRemove = new ArrayList<String>();
for( int i=0; i<argNames.size(); i++ ) {
if( argNames.get(i).startsWith("response") ) {
nameToRemove.add(argNames.get(i));
valueToRemove.add(argValues.get(i));
}
}
for( String name : nameToRemove ) {
argNamesCopy.remove(name);
}
for( String value : valueToRemove ) {
argValuesCopy.remove(value);
}
for(String str : argNamesCopy ) {
hash = hash + str;
}
for(String str : argValuesCopy ) {
hash = hash + str;
}
return hash;
}
/**
* Prints the given Document to the Console (debugging-method).
*
* @param doc - the Document to print
*/
private String docToString( Document doc )
{
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//initialize StreamResult with File object to save to file
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
return xmlString;
}catch( Exception e ){}
return null;
}
}
| true | true | public void react( SEMAINEMessage m ) throws JMSException
{
if( m instanceof SEMAINEFeatureMessage ) {
/* Process AudioFeatures */
if( isStoringFeatures ) {
SEMAINEFeatureMessage fm = (SEMAINEFeatureMessage)m;
/* Reads the feature names and values */
String[] featureNames = fm.getFeatureNames();
float[] featureValues = fm.getFeatureVector();
for( int i=0; i<featureNames.length; i++ ) {
if( detectedFeatures.get(featureNames[i]) != null ) {
detectedFeatures.get(featureNames[i]).add(featureValues[i]);
} else {
ArrayList<Float> tempList = new ArrayList<Float>();
tempList.add(featureValues[i]);
detectedFeatures.put(featureNames[i],tempList);
}
}
}
} else if( m instanceof SEMAINEXMLMessage ){
SEMAINEXMLMessage xm = ((SEMAINEXMLMessage)m);
/* Process Agent-animation updates */
if( !xm.getText().contains("fml_lip") ) {
if( speechStarted(xm) ) {
log.debug("Agent is currently speaking");
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtteranceStarted" );
is.set("Agent.speakingState","speaking");
is.set("Agent.speakingStateTime", (int)meta.getTime());
sendData("agentTurnState", "speaking", "dialogstate");
isStoringFeatures = false;
for( ArrayList<Float> al : detectedFeatures.values() ) {
al.clear();
}
}
String speechReady = speechReady(xm);
if( speechReady != null && speechReady.equals(feedbackId) ) {
log.debug("Agent utterance has finished");
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtteranceStopped (feedback)");
is.set("Agent.speakingState","listening");
is.set("Agent.speakingStateTime", (int)meta.getTime());
is.set("User.speakingState","waiting");
is.remove("UserTurn");
turnActionUnits.clear();
sendData("agentTurnState", "listening", "dialogstate");
for( String[] str : dataSendQueue ) {
if( str.length == 3 ) {
sendData(str[0], str[1], str[2]);
}
}
dataSendQueue.clear();
queueWaitingCounter = 5;
}
}
if (xm.getDatatype().equals("FML")) {
Element fml = XMLTool.getChildElementByTagNameNS(xm.getDocument().getDocumentElement(), FML.E_FML, FML.namespaceURI);
if( fml != null ) {
Element backchannel = XMLTool.getChildElementByTagNameNS(fml, FML.E_BACKCHANNEL, FML.namespaceURI);
if( backchannel != null ) {
DMLogger.getLogger().log(meta.getTime(), "AgentAction:Backchannel" );
}
}
}
Document doc = xm.getDocument();
Element event = XMLTool.getChildElementByLocalNameNS(doc.getDocumentElement(), SemaineML.E_EVENT, SemaineML.namespaceURI);
if (event != null) {
String id = event.getAttribute(SemaineML.A_ID);
long time = Long.parseLong(event.getAttribute(SemaineML.A_TIME));
String type = event.getAttribute(SemaineML.A_TYPE);
if (type.equals(SemaineML.V_READY)) {
String keyToRemove = null;
for( String key : preparingResponses.keySet() ) {
if( preparingResponses.get(key).equals(id) ) {
log.debug("Preparation complete: "+id);
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtterancePrepared");
preparedResponses.put(key, id);
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparingResponses.remove(keyToRemove);
} else if (type.equals(SemaineML.V_DELETED)) {
System.out.println("\r\n\r\n\r\n\r\n\r\n\r\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
String keyToRemove = null;
for( String key : preparingResponses.keySet() ) {
if( preparingResponses.get(key).equals(id) ) {
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparingResponses.remove(keyToRemove);
keyToRemove = null;
for( String key : preparedResponses.keySet() ) {
if( preparedResponses.get(key).equals(id) ) {
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparedResponses.remove(keyToRemove);
} else {
// Do Nothing
}
}
}
/* Processes User state updates */
if( m instanceof SEMAINEStateMessage ) {
SEMAINEStateMessage sm = ((SEMAINEStateMessage)m);
StateInfo stateInfo = sm.getState();
StateInfo.Type stateInfoType = stateInfo.getType();
switch (stateInfoType) {
case UserState:
/* Updates user speaking state (speaking or silent) */
if( stateInfo.hasInfo("speaking") ) {
if( stateInfo.getInfo("speaking").equals("true") ) {
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("speaking") ) {
is.set("User.speakingState", "speaking");
is.set("User.speakingStateTime", (int)meta.getTime());
if(!isStoringFeatures) isStoringFeatures = true;
}
} else if( stateInfo.getInfo("speaking").equals("false") ) {
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("listening") ) {
is.set("User.speakingState", "listening");
is.set("User.speakingStateTime", (int)meta.getTime());
}
}
}
/* Updates detected emotions (valence, arousal, interest) */
if( stateInfo.hasInfo("valence") ) {
float valence = Float.parseFloat( stateInfo.getInfo("valence") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.VALENCE, valence );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("arousal") ) {
float arousal = Float.parseFloat( stateInfo.getInfo("arousal") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.AROUSAL, arousal );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("interest") ) {
float interest = Float.parseFloat( stateInfo.getInfo("interest") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.INTEREST, interest );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("potency") ) {
float potency = Float.parseFloat( stateInfo.getInfo("potency") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.POTENCY, potency );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("intensity") ) {
float intensity = Float.parseFloat( stateInfo.getInfo("intensity") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.INTENSITY, intensity );
detectedEmotions.add( ee );
summarizeEmotionEvents();
}
/* Updates the detected and analysed user utterances */
if( stateInfo.hasInfo("userUtterance") && stateInfo.hasInfo("userUtteranceStartTime") ) {
String utterance = stateInfo.getInfo("userUtterance");
long time = Long.parseLong(stateInfo.getInfo("userUtteranceStartTime"));
String f = stateInfo.getInfo("userUtteranceFeatures");
if( f == null ) {
f = "";
}
DialogueAct act = new DialogueAct( utterance, time );
act.setEndtime(meta.getTime());
if( f.contains("positive") ) act.setPositive(true);
if( f.contains("negative") ) act.setNegative(true);
if( f.contains("disagree") ) {
act.setDisagree(true);
f = f.replace("disagree", "");
}
if( f.contains("agree") ) act.setAgree(true);
if( f.contains("about_other_people") ) act.setAboutOtherPeople(true);
if( f.contains("about_other_character") ) act.setAboutOtherCharacter(true);
if( f.contains("about_current_character") ) act.setAboutCurrentCharacter(true);
if( f.contains("about_own_feelings") ) act.setAboutOwnFeelings(true);
if( f.contains("pragmatic") ) act.setPragmatic(true);
if( f.contains("abou_self") ) act.setTalkAboutSelf(true);
if( f.contains("future") ) act.setFuture(true);
if( f.contains("past") ) act.setPast(true);
if( f.contains("event") ) act.setEvent(true);
if( f.contains("action") ) act.setAction(true);
if( f.contains("laugh") ) act.setLaugh(true);
if( f.contains("change_speaker") ) act.setChangeSpeaker(true);
if( f.contains("target:") ) act.setTargetCharacter( f.substring(f.indexOf("target:")+7, Math.max(f.length(),f.indexOf(" ", f.indexOf("target:")+7))) );
if( f.contains("short") ) act.setLength(DialogueAct.Length.SHORT);
if( f.contains("long") ) act.setLength(DialogueAct.Length.LONG);
if( detectedDActs.size() > 1 && Math.abs(detectedDActs.get(detectedDActs.size()-1).getStarttime() - act.getStarttime()) < 10 ) {
// Same dialogueAct, so update the last DA in the list
detectedDActs.set(detectedDActs.size()-1, act);
} else {
detectedDActs.add(act);
}
getCombinedUserDialogueAct();
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("speaking") ) {
is.set("User.speakingState", "speaking");
is.set("User.speakingStateTime", (int)meta.getTime());
if(!isStoringFeatures) isStoringFeatures = true;
}
}
if( stateInfo.hasInfo("headGesture") && stateInfo.hasInfo("headGestureStarted") && stateInfo.hasInfo("headGestureStopped") ) {
String gesture = stateInfo.getInfo("headGesture");
Integer counter = is.getInteger("UserTurn.Head.nrOf" + gesture);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Head.nrOf" + gesture, counter);
is.set("UserTurn.Head.lastGesture", gesture);
}
if( stateInfo.hasInfo("pitchDirection") ) {
String pitch = stateInfo.getInfo("pitchDirection");
Integer counter = is.getInteger("UserTurn.Pitch.nrOf" + pitch);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Pitch.nrOf" + pitch, pitch);
is.set("UserTurn.Pitch.lastPitch", pitch);
}
if( stateInfo.hasInfo("vocalization") ) {
String vocalization = stateInfo.getInfo("vocalization");
Integer counter = is.getInteger("UserTurn.Vocalization.nrOf" + vocalization);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Vocalization.nrOf" + vocalization, vocalization);
}
if( stateInfo.hasInfo("facialActionUnits") ) {
String facialExpressions = stateInfo.getInfo("facialActionUnits");
List<String> aus = Arrays.asList(facialExpressions.split(" "));
for( String au : aus ) {
Boolean b = turnActionUnits.get(au);
if( b == null || (b != null && b == false) ) {
turnActionUnits.put(au,true);
Integer counter = is.getInteger("UserTurn.AU.nrOfAU" + au);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.AU.nrOfAU" + au, counter);
}
}
for( String au : turnActionUnits.keySet() ) {
if( !aus.contains(au) ) {
turnActionUnits.put(au,false);
}
}
}
break;
case ContextState:
/* Updates the current character and the user */
/* Update user presence */
if( stateInfo.hasInfo("userPresent") ) {
if( is.getInteger("User.present") == null ) {
is.set("User.present", 0);
}
if( stateInfo.getInfo("userPresent").equals("present") && is.getInteger("User.present") == 0 ) {
DMLogger.getLogger().log(meta.getTime(), "System:SystemStarted" );
is.set("User.present", 1);
is.set("User.presentStateChanged",1);
String agent = is.getString("Agent.character");
if( agent == null || agent.length() == 0 ) {
is.set("Agent.character", CharacterConfigInfo.getDefaultCharacter().getName());
}
systemStarted = true;
} else if( stateInfo.getInfo("userPresent").equals("absent") && is.getInteger("User.present") == 1 ) {
DMLogger.getLogger().log(meta.getTime(), "System:SystemStopped" );
is.set("User.present", 0);
is.set("User.presentStateChanged",1);
systemStarted = false;
is.set("currTime", (int)meta.getTime());
String context = is.toString();
TemplateState state = templateController.checkTemplates(is);
if( state != null ) {
DMLogger.getLogger().logUserTurn(meta.getTime(), latestResponse.getResponse() + "("+state.getTemplate().getId()+")", context);
detectedEmotions.clear();
dActIndex = detectedDActs.size();
for( String featureName : detectedFeatures.keySet() ) {
is.remove("UserTurn.AudioFeatures."+featureName+"_min");
is.remove("UserTurn.AudioFeatures."+featureName+"_max");
is.remove("UserTurn.AudioFeatures."+featureName+"_avg");
}
DMLogger.getLogger().log(meta.getTime(), "AgentAction:SendUtterance, type="+state.getTemplate().getId()+", utterance="+latestResponse.getResponse());
}
}
}
/* Update current character */
if( stateInfo.hasInfo("character") ) {
System.out.println("New Character: " + stateInfo.getInfo("character"));
is.set("Agent.character", stateInfo.getInfo("character"));
is.set("Agent.characterChanged", 1);
preparedResponses.clear();
preparingResponses.clear();
}
if( stateInfo.hasInfo("nextCharacter") ) {
String nextCharacter = stateInfo.getInfo("nextCharacter");
is.set("Agent.nextCharacter", nextCharacter);
}
if( stateInfo.hasInfo("dialogContext") ) {
String context = stateInfo.getInfo("dialogContext");
is.set("Agent.dialogContext", context);
}
break;
case AgentState:
String intention = stateInfo.getInfo("turnTakingIntention");
if( intention != null && intention.equals("startSpeaking") ) {
String currSpeakingState = is.getString("Agent.speakingState");
if( currSpeakingState != null && !currSpeakingState.equals("speaking") && !currSpeakingState.equals("preparing") ) {
String userSpeakingState = is.getString("User.speakingState");
if( userSpeakingState != null && userSpeakingState.equals("waiting") ) {
is.set("Agent.speakingIntention","retake_turn");
} else {
is.set("Agent.speakingIntention","want_turn");
}
}
}
break;
}
}
//is.print();
}
| public void react( SEMAINEMessage m ) throws JMSException
{
if( m instanceof SEMAINEFeatureMessage ) {
/* Process AudioFeatures */
if( isStoringFeatures ) {
SEMAINEFeatureMessage fm = (SEMAINEFeatureMessage)m;
/* Reads the feature names and values */
String[] featureNames = fm.getFeatureNames();
float[] featureValues = fm.getFeatureVector();
for( int i=0; i<featureNames.length; i++ ) {
if( detectedFeatures.get(featureNames[i]) != null ) {
detectedFeatures.get(featureNames[i]).add(featureValues[i]);
} else {
ArrayList<Float> tempList = new ArrayList<Float>();
tempList.add(featureValues[i]);
detectedFeatures.put(featureNames[i],tempList);
}
}
}
} else if( m instanceof SEMAINEXMLMessage ){
SEMAINEXMLMessage xm = ((SEMAINEXMLMessage)m);
/* Process Agent-animation updates */
if( !xm.getText().contains("fml_lip") && !xm.getText().contains("bml_lip") ) {
if( speechStarted(xm) ) {
log.debug("Agent is currently speaking");
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtteranceStarted" );
is.set("Agent.speakingState","speaking");
is.set("Agent.speakingStateTime", (int)meta.getTime());
sendData("agentTurnState", "speaking", "dialogstate");
isStoringFeatures = false;
for( ArrayList<Float> al : detectedFeatures.values() ) {
al.clear();
}
}
String speechReady = speechReady(xm);
if( speechReady != null && speechReady.equals(feedbackId) ) {
log.debug("Agent utterance has finished");
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtteranceStopped (feedback)");
is.set("Agent.speakingState","listening");
is.set("Agent.speakingStateTime", (int)meta.getTime());
is.set("User.speakingState","waiting");
is.remove("UserTurn");
turnActionUnits.clear();
sendData("agentTurnState", "listening", "dialogstate");
for( String[] str : dataSendQueue ) {
if( str.length == 3 ) {
sendData(str[0], str[1], str[2]);
}
}
dataSendQueue.clear();
queueWaitingCounter = 5;
}
}
if (xm.getDatatype().equals("FML")) {
Element fml = XMLTool.getChildElementByTagNameNS(xm.getDocument().getDocumentElement(), FML.E_FML, FML.namespaceURI);
if( fml != null ) {
Element backchannel = XMLTool.getChildElementByTagNameNS(fml, FML.E_BACKCHANNEL, FML.namespaceURI);
if( backchannel != null ) {
DMLogger.getLogger().log(meta.getTime(), "AgentAction:Backchannel" );
}
}
}
Document doc = xm.getDocument();
Element event = XMLTool.getChildElementByLocalNameNS(doc.getDocumentElement(), SemaineML.E_EVENT, SemaineML.namespaceURI);
if (event != null) {
String id = event.getAttribute(SemaineML.A_ID);
long time = Long.parseLong(event.getAttribute(SemaineML.A_TIME));
String type = event.getAttribute(SemaineML.A_TYPE);
if (type.equals(SemaineML.V_READY)) {
String keyToRemove = null;
for( String key : preparingResponses.keySet() ) {
if( preparingResponses.get(key).equals(id) ) {
log.debug("Preparation complete: "+id);
DMLogger.getLogger().log(meta.getTime(), "AgentAction:UtterancePrepared");
preparedResponses.put(key, id);
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparingResponses.remove(keyToRemove);
} else if (type.equals(SemaineML.V_DELETED)) {
System.out.println("\r\n\r\n\r\n\r\n\r\n\r\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
String keyToRemove = null;
for( String key : preparingResponses.keySet() ) {
if( preparingResponses.get(key).equals(id) ) {
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparingResponses.remove(keyToRemove);
keyToRemove = null;
for( String key : preparedResponses.keySet() ) {
if( preparedResponses.get(key).equals(id) ) {
keyToRemove = key;
break;
}
}
if( keyToRemove != null ) preparedResponses.remove(keyToRemove);
} else {
// Do Nothing
}
}
}
/* Processes User state updates */
if( m instanceof SEMAINEStateMessage ) {
SEMAINEStateMessage sm = ((SEMAINEStateMessage)m);
StateInfo stateInfo = sm.getState();
StateInfo.Type stateInfoType = stateInfo.getType();
switch (stateInfoType) {
case UserState:
/* Updates user speaking state (speaking or silent) */
if( stateInfo.hasInfo("speaking") ) {
if( stateInfo.getInfo("speaking").equals("true") ) {
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("speaking") ) {
is.set("User.speakingState", "speaking");
is.set("User.speakingStateTime", (int)meta.getTime());
if(!isStoringFeatures) isStoringFeatures = true;
}
} else if( stateInfo.getInfo("speaking").equals("false") ) {
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("listening") ) {
is.set("User.speakingState", "listening");
is.set("User.speakingStateTime", (int)meta.getTime());
}
}
}
/* Updates detected emotions (valence, arousal, interest) */
if( stateInfo.hasInfo("valence") ) {
float valence = Float.parseFloat( stateInfo.getInfo("valence") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.VALENCE, valence );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("arousal") ) {
float arousal = Float.parseFloat( stateInfo.getInfo("arousal") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.AROUSAL, arousal );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("interest") ) {
float interest = Float.parseFloat( stateInfo.getInfo("interest") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.INTEREST, interest );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("potency") ) {
float potency = Float.parseFloat( stateInfo.getInfo("potency") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.POTENCY, potency );
detectedEmotions.add( ee );
summarizeEmotionEvents();
} else if( stateInfo.hasInfo("intensity") ) {
float intensity = Float.parseFloat( stateInfo.getInfo("intensity") );
EmotionEvent ee = new EmotionEvent( meta.getTime(), 0, EmotionEvent.INTENSITY, intensity );
detectedEmotions.add( ee );
summarizeEmotionEvents();
}
/* Updates the detected and analysed user utterances */
if( stateInfo.hasInfo("userUtterance") && stateInfo.hasInfo("userUtteranceStartTime") ) {
String utterance = stateInfo.getInfo("userUtterance");
long time = Long.parseLong(stateInfo.getInfo("userUtteranceStartTime"));
String f = stateInfo.getInfo("userUtteranceFeatures");
if( f == null ) {
f = "";
}
DialogueAct act = new DialogueAct( utterance, time );
act.setEndtime(meta.getTime());
if( f.contains("positive") ) act.setPositive(true);
if( f.contains("negative") ) act.setNegative(true);
if( f.contains("disagree") ) {
act.setDisagree(true);
f = f.replace("disagree", "");
}
if( f.contains("agree") ) act.setAgree(true);
if( f.contains("about_other_people") ) act.setAboutOtherPeople(true);
if( f.contains("about_other_character") ) act.setAboutOtherCharacter(true);
if( f.contains("about_current_character") ) act.setAboutCurrentCharacter(true);
if( f.contains("about_own_feelings") ) act.setAboutOwnFeelings(true);
if( f.contains("pragmatic") ) act.setPragmatic(true);
if( f.contains("abou_self") ) act.setTalkAboutSelf(true);
if( f.contains("future") ) act.setFuture(true);
if( f.contains("past") ) act.setPast(true);
if( f.contains("event") ) act.setEvent(true);
if( f.contains("action") ) act.setAction(true);
if( f.contains("laugh") ) act.setLaugh(true);
if( f.contains("change_speaker") ) act.setChangeSpeaker(true);
if( f.contains("target:") ) act.setTargetCharacter( f.substring(f.indexOf("target:")+7, Math.max(f.length(),f.indexOf(" ", f.indexOf("target:")+7))) );
if( f.contains("short") ) act.setLength(DialogueAct.Length.SHORT);
if( f.contains("long") ) act.setLength(DialogueAct.Length.LONG);
if( detectedDActs.size() > 1 && Math.abs(detectedDActs.get(detectedDActs.size()-1).getStarttime() - act.getStarttime()) < 10 ) {
// Same dialogueAct, so update the last DA in the list
detectedDActs.set(detectedDActs.size()-1, act);
} else {
detectedDActs.add(act);
}
getCombinedUserDialogueAct();
if( is.getString("User.speakingState") == null || !is.getString("User.speakingState").equals("speaking") ) {
is.set("User.speakingState", "speaking");
is.set("User.speakingStateTime", (int)meta.getTime());
if(!isStoringFeatures) isStoringFeatures = true;
}
}
if( stateInfo.hasInfo("headGesture") && stateInfo.hasInfo("headGestureStarted") && stateInfo.hasInfo("headGestureStopped") ) {
String gesture = stateInfo.getInfo("headGesture");
Integer counter = is.getInteger("UserTurn.Head.nrOf" + gesture);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Head.nrOf" + gesture, counter);
is.set("UserTurn.Head.lastGesture", gesture);
}
if( stateInfo.hasInfo("pitchDirection") ) {
String pitch = stateInfo.getInfo("pitchDirection");
Integer counter = is.getInteger("UserTurn.Pitch.nrOf" + pitch);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Pitch.nrOf" + pitch, pitch);
is.set("UserTurn.Pitch.lastPitch", pitch);
}
if( stateInfo.hasInfo("vocalization") ) {
String vocalization = stateInfo.getInfo("vocalization");
Integer counter = is.getInteger("UserTurn.Vocalization.nrOf" + vocalization);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.Vocalization.nrOf" + vocalization, vocalization);
}
if( stateInfo.hasInfo("facialActionUnits") ) {
String facialExpressions = stateInfo.getInfo("facialActionUnits");
List<String> aus = Arrays.asList(facialExpressions.split(" "));
for( String au : aus ) {
Boolean b = turnActionUnits.get(au);
if( b == null || (b != null && b == false) ) {
turnActionUnits.put(au,true);
Integer counter = is.getInteger("UserTurn.AU.nrOfAU" + au);
if( counter == null ) counter = new Integer(0);
counter = counter + 1;
is.set("UserTurn.AU.nrOfAU" + au, counter);
}
}
for( String au : turnActionUnits.keySet() ) {
if( !aus.contains(au) ) {
turnActionUnits.put(au,false);
}
}
}
break;
case ContextState:
/* Updates the current character and the user */
/* Update user presence */
if( stateInfo.hasInfo("userPresent") ) {
if( is.getInteger("User.present") == null ) {
is.set("User.present", 0);
}
if( stateInfo.getInfo("userPresent").equals("present") && is.getInteger("User.present") == 0 ) {
DMLogger.getLogger().log(meta.getTime(), "System:SystemStarted" );
is.set("User.present", 1);
is.set("User.presentStateChanged",1);
String agent = is.getString("Agent.character");
if( agent == null || agent.length() == 0 ) {
is.set("Agent.character", CharacterConfigInfo.getDefaultCharacter().getName());
}
systemStarted = true;
} else if( stateInfo.getInfo("userPresent").equals("absent") && is.getInteger("User.present") == 1 ) {
DMLogger.getLogger().log(meta.getTime(), "System:SystemStopped" );
is.set("User.present", 0);
is.set("User.presentStateChanged",1);
systemStarted = false;
is.set("currTime", (int)meta.getTime());
String context = is.toString();
TemplateState state = templateController.checkTemplates(is);
if( state != null ) {
DMLogger.getLogger().logUserTurn(meta.getTime(), latestResponse.getResponse() + "("+state.getTemplate().getId()+")", context);
detectedEmotions.clear();
dActIndex = detectedDActs.size();
for( String featureName : detectedFeatures.keySet() ) {
is.remove("UserTurn.AudioFeatures."+featureName+"_min");
is.remove("UserTurn.AudioFeatures."+featureName+"_max");
is.remove("UserTurn.AudioFeatures."+featureName+"_avg");
}
DMLogger.getLogger().log(meta.getTime(), "AgentAction:SendUtterance, type="+state.getTemplate().getId()+", utterance="+latestResponse.getResponse());
}
}
}
/* Update current character */
if( stateInfo.hasInfo("character") ) {
System.out.println("New Character: " + stateInfo.getInfo("character"));
is.set("Agent.character", stateInfo.getInfo("character"));
is.set("Agent.characterChanged", 1);
preparedResponses.clear();
preparingResponses.clear();
}
if( stateInfo.hasInfo("nextCharacter") ) {
String nextCharacter = stateInfo.getInfo("nextCharacter");
is.set("Agent.nextCharacter", nextCharacter);
}
if( stateInfo.hasInfo("dialogContext") ) {
String context = stateInfo.getInfo("dialogContext");
is.set("Agent.dialogContext", context);
}
break;
case AgentState:
String intention = stateInfo.getInfo("turnTakingIntention");
if( intention != null && intention.equals("startSpeaking") ) {
String currSpeakingState = is.getString("Agent.speakingState");
if( currSpeakingState != null && !currSpeakingState.equals("speaking") && !currSpeakingState.equals("preparing") ) {
String userSpeakingState = is.getString("User.speakingState");
if( userSpeakingState != null && userSpeakingState.equals("waiting") ) {
is.set("Agent.speakingIntention","retake_turn");
} else {
is.set("Agent.speakingIntention","want_turn");
}
}
}
break;
}
}
//is.print();
}
|
diff --git a/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalScene.java b/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalScene.java
index 772edc5f..58d67d25 100644
--- a/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalScene.java
+++ b/E-Adventure/src/es/eucm/eadventure/engine/core/control/functionaldata/FunctionalScene.java
@@ -1,937 +1,937 @@
/*******************************************************************************
* <e-Adventure> (formerly <e-Game>) is a research project of the <e-UCM>
* research group.
*
* Copyright 2005-2010 <e-UCM> research group.
*
* You can access a list of all the contributors to <e-Adventure> at:
* http://e-adventure.e-ucm.es/contributors
*
* <e-UCM> is a research group of the Department of Software Engineering
* and Artificial Intelligence at the Complutense University of Madrid
* (School of Computer Science).
*
* C Profesor Jose Garcia Santesmases sn,
* 28040 Madrid (Madrid), Spain.
*
* For more info please visit: <http://e-adventure.e-ucm.es> or
* <http://www.e-ucm.es>
*
* ****************************************************************************
*
* This file is part of <e-Adventure>, version 1.2.
*
* <e-Adventure> is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* <e-Adventure> is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with <e-Adventure>. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package es.eucm.eadventure.engine.core.control.functionaldata;
import java.awt.Image;
import java.awt.Transparency;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import es.eucm.eadventure.common.data.chapter.Chapter;
import es.eucm.eadventure.common.data.chapter.ElementReference;
import es.eucm.eadventure.common.data.chapter.Exit;
import es.eucm.eadventure.common.data.chapter.elements.ActiveArea;
import es.eucm.eadventure.common.data.chapter.elements.Atrezzo;
import es.eucm.eadventure.common.data.chapter.elements.Barrier;
import es.eucm.eadventure.common.data.chapter.elements.Item;
import es.eucm.eadventure.common.data.chapter.elements.NPC;
import es.eucm.eadventure.common.data.chapter.resources.Asset;
import es.eucm.eadventure.common.data.chapter.resources.Resources;
import es.eucm.eadventure.common.data.chapter.scenes.Scene;
import es.eucm.eadventure.engine.core.control.ActionManager;
import es.eucm.eadventure.engine.core.control.Game;
import es.eucm.eadventure.engine.core.control.ItemSummary;
import es.eucm.eadventure.engine.core.control.functionaldata.functionalactions.FunctionalExit;
import es.eucm.eadventure.engine.core.control.functionaldata.functionalactions.FunctionalGoTo;
import es.eucm.eadventure.engine.core.gui.GUI;
import es.eucm.eadventure.engine.multimedia.MultimediaManager;
import es.eucm.eadventure.engine.resourcehandler.ResourceHandler;
/**
* A scene in the game
*/
public class FunctionalScene implements Renderable {
/**
* Margins of the scene (for use in the scroll)
*/
private final static int MAX_OFFSET_X = 300;
private final static int OFFSET_ARROW_AREA_RADIUS = 30;
/**
* Scene data
*/
private Scene scene;
/**
* Resources being used in the scene
*/
private Resources resources;
/**
* Background image for the scene
*/
private Image background;
/**
* Foreground image for the scene
*/
private Image foreground;
/**
* Background music
*/
private long backgroundMusicId = -1;
/**
* Functional player present in the scene
*/
private FunctionalPlayer player;
/**
* Functional items present in the scene
*/
private ArrayList<FunctionalItem> items;
/**
* Functional characters present in the scene
*/
private ArrayList<FunctionalNPC> npcs;
/**
* Functional areas present in the scene
*/
private ArrayList<FunctionalActiveArea> areas;
/**
* Functional barriers present in the scene;
*/
private ArrayList<FunctionalBarrier> barriers;
/**
* Functional atrezzo items present in the scene
*/
private ArrayList<FunctionalAtrezzo> atrezzo;
private FunctionalTrajectory trajectory;
/**
* Offset of the scroll.
*/
private int offsetX;
private boolean moveOffsetRight = false;
private boolean moveOffsetLeft = false;
private boolean showsOffsetArrows = false;
/**
* Element references list for the scene. This element references list will keep the position of the items even they
* were being moved with drag&drop. They only will be changed when the scene is loaded again
*/
//NOTE: the nextscene game state has been changed to avoid recharge the scene elements if the next scene will be the same as the
//previous scene
private List<ElementReference> itemReferences;
private List<ElementReference> NPCReferences;
/**
* Creates a new FunctionalScene loading the background music.
*
* @param scene
* the scene's data
* @param player
* the reference to the player
*/
public FunctionalScene( Scene scene, FunctionalPlayer player ) {
this( scene, player, -1 );
}
/**
* Creates a new FunctionalScene with the given background music.
*
* @param scene
* the scene's data
* @param player
* the reference to the player
* @param backgroundMusicId
* Background music identifier
*/
public FunctionalScene( Scene scene, FunctionalPlayer player, long backgroundMusicId ) {
this.scene = scene;
this.player = player;
// Create lists for the characters, items and active areas
npcs = new ArrayList<FunctionalNPC>( );
items = new ArrayList<FunctionalItem>( );
atrezzo = new ArrayList<FunctionalAtrezzo>( );
areas = new ArrayList<FunctionalActiveArea>( );
barriers = new ArrayList<FunctionalBarrier>( );
trajectory = new FunctionalTrajectory( scene.getTrajectory( ), barriers );
restartElementReferencesPositions();
// Pick the item summary
Chapter gameData = Game.getInstance( ).getCurrentChapterData( );
ItemSummary itemSummary = Game.getInstance( ).getItemSummary( );
// Select the resources
resources = createResourcesBlock( );
// Load the background image
background = null;
if( resources.existAsset( Scene.RESOURCE_TYPE_BACKGROUND ) )
background = MultimediaManager.getInstance( ).loadImageFromZip( resources.getAssetPath( Scene.RESOURCE_TYPE_BACKGROUND ), MultimediaManager.IMAGE_SCENE );
if( Game.getInstance( ).isTransparent( ) && background != null && background.getWidth( null ) > GUI.WINDOW_WIDTH ) {
showsOffsetArrows = true;
}
// Load the foreground image
foreground = null;
if( background != null && resources.existAsset( Scene.RESOURCE_TYPE_FOREGROUND ) ) {
BufferedImage bufferedBackground = (BufferedImage) background;
BufferedImage foregroundHardMap = (BufferedImage) MultimediaManager.getInstance( ).loadImageFromZip( resources.getAssetPath( Scene.RESOURCE_TYPE_FOREGROUND ), MultimediaManager.IMAGE_SCENE );
BufferedImage bufferedForeground = GUI.getInstance( ).getGraphicsConfiguration( ).createCompatibleImage( foregroundHardMap.getWidth( null ), foregroundHardMap.getHeight( null ), Transparency.TRANSLUCENT );
for( int i = 0; i < foregroundHardMap.getWidth( null ); i++ ) {
for( int j = 0; j < foregroundHardMap.getHeight( null ); j++ ) {
if( foregroundHardMap.getRGB( i, j ) == 0xFFFFFFFF )
bufferedForeground.setRGB( i, j, 0x00000000 );
else
bufferedForeground.setRGB( i, j, bufferedBackground.getRGB( i, j ) );
}
}
foreground = bufferedForeground;
}
// Load the background music (if it is not loaded)
this.backgroundMusicId = backgroundMusicId;
if( backgroundMusicId == -1 )
playBackgroundMusic( );
// Add the functional items
for( ElementReference itemReference : scene.getItemReferences( ) )
if( new FunctionalConditions( itemReference.getConditions( ) ).allConditionsOk( ) )
if( itemSummary.isItemNormal( itemReference.getTargetId( ) ) )
for( Item currentItem : gameData.getItems( ) )
if( itemReference.getTargetId( ).equals( currentItem.getId( ) ) ) {
FunctionalItem fitem = new FunctionalItem( currentItem, itemReference );
items.add( fitem );
}
// Add the functional characters
for( ElementReference npcReference : scene.getCharacterReferences( ) )
if( new FunctionalConditions( npcReference.getConditions( ) ).allConditionsOk( ) )
for( NPC currentNPC : gameData.getCharacters( ) )
if( npcReference.getTargetId( ).equals( currentNPC.getId( ) ) ) {
FunctionalNPC fnpc = new FunctionalNPC( currentNPC, npcReference );
npcs.add( fnpc );
}
// Add the functional active areas
for( ActiveArea activeArea : scene.getActiveAreas( ) )
if( new FunctionalConditions( activeArea.getConditions( ) ).allConditionsOk( ) )
this.areas.add( new FunctionalActiveArea( activeArea, activeArea.getInfluenceArea( ) ) );
// Add the functional barriers
for( Barrier barrier : scene.getBarriers( ) )
if( new FunctionalConditions( barrier.getConditions( ) ).allConditionsOk( ) )
this.barriers.add( new FunctionalBarrier( barrier ) );
// Add the functional atrezzo items
for( ElementReference atrezzoReference : scene.getAtrezzoReferences( ) )
if( new FunctionalConditions( atrezzoReference.getConditions( ) ).allConditionsOk( ) )
for( Atrezzo currentAtrezzo : gameData.getAtrezzo( ) )
if( atrezzoReference.getTargetId( ).equals( currentAtrezzo.getId( ) ) ) {
FunctionalAtrezzo fatrezzo = new FunctionalAtrezzo( currentAtrezzo, atrezzoReference );
atrezzo.add( fatrezzo );
}
updateOffset( );
}
/**
* Creates a new FunctionalScene only with a given background music.
*
* @param backgroundMusicId
* Background music identifier
*/
public FunctionalScene( long backgroundMusicId ) {
// Load the background music (if it is not loaded)
this.backgroundMusicId = backgroundMusicId;
if( backgroundMusicId == -1 )
playBackgroundMusic( );
}
/**
* Update the resources and elements of the scene, depending on the state of
* the flags.
*/
public void updateScene( ) {
// Update the resources and the player's resources
updateResources( );
player.updateResources( );
// Pick the game data
Chapter gameData = Game.getInstance( ).getCurrentChapterData( );
// Check the item references of the scene
for( ElementReference itemReference : itemReferences ) {
// For every item that should be there
if( new FunctionalConditions( itemReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional item is present, update its resources
for( FunctionalItem currentItem : items ) {
if( itemReference.getTargetId( ).equals( currentItem.getElement( ).getId( ) )) {
currentItem.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
if( Game.getInstance( ).getItemSummary( ).isItemNormal( itemReference.getTargetId( ) ) ) {
for( Item currentItem : gameData.getItems( ) ) {
if( itemReference.getTargetId( ).equals( currentItem.getId( ) ) ) {
FunctionalItem fItem = new FunctionalItem( currentItem, itemReference );
items.add( fItem );
}
}
}
}
}
else {
FunctionalItem remove = null;
for( FunctionalItem currentItem : items ) {
- if( currentItem.getReference( ) == itemReference )
+ if( currentItem.getItem( ).getId( ).equals( itemReference.getTargetId( ) ) )
remove = currentItem;
}
if( remove != null ){
itemReference.setPosition( (int) remove.getX( ), (int) remove.getY( ) );
items.remove( remove );
}
}
}
// Check the character references of the scene
for( ElementReference npcReference : NPCReferences ) {
// For every item that should be there
if( new FunctionalConditions( npcReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional character is present, update its resources
for( FunctionalNPC currentNPC : npcs ) {
if( npcReference.getTargetId( ).equals( currentNPC.getElement( ).getId( )) ) {
currentNPC.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
for( NPC currentNPC : gameData.getCharacters( ) ) {
if( npcReference.getTargetId( ).equals( currentNPC.getId( ) ) ) {
FunctionalNPC fNPC = new FunctionalNPC( currentNPC, npcReference );
npcs.add( fNPC );
}
}
}
}
else {
FunctionalNPC remove = null;
for( FunctionalNPC currentNPC : npcs ) {
- if( currentNPC.getReference( ) == npcReference )
+ if( currentNPC.getElement( ).getId( ).equals( npcReference.getTargetId( ) ))
remove = currentNPC;
}
if( remove != null )
npcs.remove( remove );
}
}
// Check the active areas of the scene
for( ActiveArea activeArea : scene.getActiveAreas( ) ) {
// For every item that should be there
if( new FunctionalConditions( activeArea.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional item is present, update its resources
for( FunctionalActiveArea currentFunctionalActiveArea : areas ) {
if( activeArea.getId( ).equals( currentFunctionalActiveArea.getItem( ).getId( ) ) ) {
found = true;
break;
}
}
// If it was not found, search for it and add it
if( !found ) {
areas.add( new FunctionalActiveArea( activeArea, activeArea.getInfluenceArea( ) ) );
}
}
}
// Check the barriers of the scene
barriers.clear( );
for( Barrier barrier : scene.getBarriers( ) ) {
// For every barrier that should be there
if( new FunctionalConditions( barrier.getConditions( ) ).allConditionsOk( ) ) {
barriers.add( new FunctionalBarrier( barrier ) );
}
}
// Check the atrezzo item references of the scene
for( ElementReference atrezzoReference : scene.getAtrezzoReferences( ) ) {
// For every atrezzo item that should be there
if( new FunctionalConditions( atrezzoReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional atrezzo item is present, update its resources
for( FunctionalAtrezzo currentAtrezzo : atrezzo ) {
if( atrezzoReference == currentAtrezzo.getReference( ) ) {
currentAtrezzo.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
for( Atrezzo currentAtrezzo : gameData.getAtrezzo( ) ) {
if( atrezzoReference.getTargetId( ).equals( currentAtrezzo.getId( ) ) ) {
FunctionalAtrezzo fAtrezzo = new FunctionalAtrezzo( currentAtrezzo, atrezzoReference );
atrezzo.add( fAtrezzo );
}
}
}
}
else {
FunctionalAtrezzo remove = null;
for( FunctionalAtrezzo currentAtrezzo : atrezzo ) {
if( currentAtrezzo.getReference( ) == atrezzoReference )
remove = currentAtrezzo;
}
if( remove != null )
atrezzo.remove( remove );
}
}
// Create a list with the active areas to remove
ArrayList<FunctionalActiveArea> activeAreasToRemove = new ArrayList<FunctionalActiveArea>( );
for( FunctionalActiveArea currentActiveArea : areas ) {
boolean keepActiveArea = false;
// For every present item, check if it must be kept
for( ActiveArea activeArea : scene.getActiveAreas( ) ) {
if( activeArea.getId( ).equals( currentActiveArea.getItem( ).getId( ) ) && new FunctionalConditions( activeArea.getConditions( ) ).allConditionsOk( ) ) {
keepActiveArea = true;
}
}
// If it must not be kept, add it to the remove list
if( !keepActiveArea )
activeAreasToRemove.add( currentActiveArea );
}
// Remove the elements
for( FunctionalActiveArea areaToRemove : activeAreasToRemove )
areas.remove( areaToRemove );
}
/**
* Updates the resources of the scene (if the current resources and the new
* one are different)
*/
public void updateResources( ) {
// Get the new resources
Resources newResources = createResourcesBlock( );
// If the resources have changed, load the new one
if( resources != newResources ) {
resources = newResources;
showsOffsetArrows = false;
if( resources.existAsset( Scene.RESOURCE_TYPE_BACKGROUND ) )
background = MultimediaManager.getInstance( ).loadImageFromZip( resources.getAssetPath( Scene.RESOURCE_TYPE_BACKGROUND ), MultimediaManager.IMAGE_SCENE );
if( Game.getInstance( ).isTransparent( ) && background != null && background.getWidth( null ) > GUI.WINDOW_WIDTH ) {
showsOffsetArrows = true;
}
// If there was a foreground, delete it
if( foreground != null )
foreground.flush( );
// Load the foreground image
foreground = null;
if( background != null && resources.existAsset( Scene.RESOURCE_TYPE_FOREGROUND ) ) {
BufferedImage bufferedBackground = (BufferedImage) background;
BufferedImage foregroundHardMap = (BufferedImage) MultimediaManager.getInstance( ).loadImageFromZip( resources.getAssetPath( Scene.RESOURCE_TYPE_FOREGROUND ), MultimediaManager.IMAGE_SCENE );
BufferedImage bufferedForeground = GUI.getInstance( ).getGraphicsConfiguration( ).createCompatibleImage( foregroundHardMap.getWidth( null ), foregroundHardMap.getHeight( null ), Transparency.TRANSLUCENT );
for( int i = 0; i < foregroundHardMap.getWidth( null ); i++ ) {
for( int j = 0; j < foregroundHardMap.getHeight( null ); j++ ) {
if( foregroundHardMap.getRGB( i, j ) == 0xFFFFFFFF )
bufferedForeground.setRGB( i, j, 0x00000000 );
else
bufferedForeground.setRGB( i, j, bufferedBackground.getRGB( i, j ) );
}
}
foreground = bufferedForeground;
}
playBackgroundMusic( );
}
}
/**
* Reset the original positions of the element references
*/
public void restartElementReferencesPositions(){
itemReferences = new ArrayList<ElementReference>();
NPCReferences = new ArrayList<ElementReference>();
items = new ArrayList<FunctionalItem>();
npcs = new ArrayList<FunctionalNPC>();
try {
for (ElementReference element: scene.getItemReferences( ))
itemReferences.add( (ElementReference)element.clone() );
for (ElementReference element: scene.getCharacterReferences( ))
NPCReferences.add( (ElementReference)element.clone() );
}
catch( CloneNotSupportedException e ) {
}
}
/**
* Returns the contained scene
*
* @return Contained scene
*/
public Scene getScene( ) {
return scene;
}
/**
* Returns the npc with the given id
*
* @param npcId
* the id of the npc
* @return the npc with the given id
*/
public FunctionalNPC getNPC( String npcId ) {
FunctionalNPC npc = null;
if( npcId != null ) {
for( FunctionalNPC currentNPC : npcs )
if( currentNPC.getElement( ).getId( ).equals( npcId ) )
npc = currentNPC;
}
return npc;
}
/**
* Returns the list of npcs in this scene
*
* @return the list of npcs in this scene
*/
public ArrayList<FunctionalNPC> getNPCs( ) {
return npcs;
}
/**
* Returns the list of items in this scene
*
* @return the list of items in this scene
*/
public ArrayList<FunctionalItem> getItems( ) {
return items;
}
/**
* Returns the list of items in this scene
*
* @return the list of items in this scene
*/
public ArrayList<FunctionalActiveArea> getActiveAreas( ) {
return areas;
}
/*
* (non-Javadoc)
* @see es.eucm.eadventure.engine.engine.control.functionaldata.Renderable#update(long)
*/
public void update( long elapsedTime ) {
playBackgroundMusic( );
// Update the items
for( FunctionalItem item : items )
item.update( elapsedTime );
// Update the active areas
for( FunctionalActiveArea activeArea : areas )
activeArea.update( elapsedTime );
// Update the characters
for( FunctionalNPC npc : npcs )
npc.update( elapsedTime );
// Update the player
player.update( elapsedTime );
// Update the offset
if( updateOffset( ) && Game.getInstance( ).getLastMouseEvent( ) != null && Game.getInstance( ).getLastMouseEvent( ).getID( ) != MouseEvent.MOUSE_DRAGGED )
Game.getInstance( ).mouseMoved( Game.getInstance( ).getLastMouseEvent( ) );
else if( updateOffset( ) && Game.getInstance( ).getLastMouseEvent( ) != null)
Game.getInstance( ).mouseDragged( Game.getInstance( ).getLastMouseEvent( ) );
}
/**
* Returns the offset of the scroll.
*
* @return Offset of the scroll
*/
public int getOffsetX( ) {
return offsetX;
}
/**
* Updates the offset value of the screen.
*
* @return True if the offset has changed, false otherwise
*/
private boolean updateOffset( ) {
// TODO Francis: Comentar
if( Game.getInstance( ).isTransparent( ) )
return false;
boolean updated = false;
// Scroll
int iw = background.getWidth( null );
if( player.getX( ) - offsetX > ( GUI.WINDOW_WIDTH - MAX_OFFSET_X ) ) {
updated = true;
offsetX += player.getX( ) - offsetX - ( GUI.WINDOW_WIDTH - MAX_OFFSET_X );
if( offsetX + GUI.WINDOW_WIDTH > iw )
offsetX = iw - GUI.WINDOW_WIDTH;
}
else if( player.getX( ) - offsetX < MAX_OFFSET_X ) {
updated = true;
offsetX -= MAX_OFFSET_X - player.getX( ) + offsetX;
if( offsetX < 0 )
offsetX = 0;
}
return updated;
}
public void updateOffset( boolean right ) {
int iw = background.getWidth( null );
if( right ) {
offsetX += 10;
if( offsetX + GUI.WINDOW_WIDTH > iw )
offsetX = iw - GUI.WINDOW_WIDTH;
}
else {
offsetX -= 10;
if( offsetX < 0 )
offsetX = 0;
}
}
/*
* (non-Javadoc)
* @see es.eucm.eadventure.engine.engine.control.functionaldata.Renderable#draw(java.awt.Graphics2D)
*/
public void draw( ) {
GUI.getInstance( ).addBackgroundToDraw( background, offsetX );
for( FunctionalItem item : items )
item.draw( );
for( FunctionalNPC npc : npcs )
npc.draw( );
for( FunctionalAtrezzo at : atrezzo )
at.draw( );
player.draw( );
if( foreground != null )
GUI.getInstance( ).addForegroundToDraw( foreground, offsetX );
GUI.getInstance( ).setShowsOffestArrows( showsOffsetArrows, moveOffsetRight, moveOffsetLeft );
}
/**
* Returns the element in the given position. If there is no element, null
* is returned
*
* @param x
* the horizontal position
* @param y
* the vertical position
* @return the element in the given position
*/
public FunctionalElement getElementInside( int x, int y, FunctionalElement exclude ) {
FunctionalElement element = null;
if( isInsideOffsetArrow( x, y ) )
return null;
List<FunctionalElement> er = GUI.getInstance( ).getElementsToInteract( );
int i=er.size( )-1;
while( i>=0 && element == null ) {
FunctionalElement currentElement = er.get( i );
i--;
if( currentElement != exclude && currentElement.isPointInside( x + Game.getInstance( ).getFunctionalScene( ).getOffsetX( ), y ) )
element = currentElement;
}
Iterator<FunctionalActiveArea> ita = areas.iterator( );
while( ita.hasNext( ) && element == null ) {
FunctionalActiveArea currentActiveArea = ita.next( );
if( currentActiveArea != exclude && currentActiveArea.isPointInside( x + Game.getInstance( ).getFunctionalScene( ).getOffsetX( ), y ) )
element = currentActiveArea;
}
/* Iterator<FunctionalNPC> itp = npcs.iterator( );
while( itp.hasNext( ) && element == null ) {
FunctionalNPC currentNPC = itp.next( );
if( currentNPC != exclude && currentNPC.isPointInside( x + Game.getInstance( ).getFunctionalScene( ).getOffsetX( ), y ) )
element = currentNPC;
}*/
return element;
}
public boolean isInsideOffsetArrow( int x, int y ) {
moveOffsetRight = false;
moveOffsetLeft = false;
if( showsOffsetArrows ) {
int ypos = GUI.WINDOW_HEIGHT / 2;
if( y >= ypos - OFFSET_ARROW_AREA_RADIUS && y <= ypos + OFFSET_ARROW_AREA_RADIUS ) {
int max_x = (int) Math.ceil( Math.sqrt( OFFSET_ARROW_AREA_RADIUS * OFFSET_ARROW_AREA_RADIUS - Math.pow( y - ypos, 2 ) ) );
if( x <= max_x )
moveOffsetLeft = true;
if( x >= GUI.WINDOW_WIDTH - max_x )
moveOffsetRight = true;
}
}
return moveOffsetLeft || moveOffsetRight;
}
public FunctionalTrajectory getTrajectory( ) {
return trajectory;
}
/**
* Returns the exit in the given position. If there is no exit, null is
* returned.
*
* @param x
* the horizontal position
* @param y
* the vertical position
* @return the exit in the given position
*/
public Exit getExitInside( int x, int y ) {
if( this.isInsideOffsetArrow( x, y ) )
return null;
for( Exit exit : scene.getExits( ) ) {
if( exit.isPointInside( x + offsetX, y ) && ( new FunctionalConditions( exit.getConditions( ) ).allConditionsOk( ) || exit.isHasNotEffects( ) ) )
return exit;
}
return null;
}
/**
* Notify that the user has clicked the scene
*
* @param x
* the horizontal position of the click
* @param y
* the vertical position of the click
* @param actionSelected
* the current action selected (use, give, grab, look, ...)
*/
public void mouseClicked( int x, int y ) {
// FIXME Francis: Aclarar el uso del offset, ya que se a�ade en sitios que no deberia y viceversa
if( isInsideOffsetArrow( x, y ) ) {
System.out.println( "Is inside offset arrow" );
if( moveOffsetRight )
updateOffset( true );
if( moveOffsetLeft )
updateOffset( false );
}
FunctionalElement element = getElementInside( x + offsetX, y , null);
if( Game.getInstance( ).getActionManager( ).getActionSelected( ) == ActionManager.ACTION_GOTO || element == null ) {
int destX = x + offsetX;
int destY = y;
FunctionalGoTo functionalGoTo = new FunctionalGoTo( null, destX, destY );
int finalX = functionalGoTo.getPosX( );
int finalY = functionalGoTo.getPosY( );
Exit exit = getExitInside( finalX - offsetX, finalY );
player.cancelActions( );
if( exit == null && !player.isTransparent( ) ) {
player.addAction( functionalGoTo );
}
else {
if( !player.isTransparent( ) && this.getTrajectory( ).hasTrajectory( ) ) {
functionalGoTo = new FunctionalGoTo( null, destX, destY, Game.getInstance( ).getFunctionalPlayer( ), new FunctionalExitArea( exit, exit.getInfluenceArea( ) ) );
if( functionalGoTo.canGetTo( ) ) {
player.addAction( new FunctionalExit( exit ) );
player.addAction( functionalGoTo );
}
}
else {
if( !player.isTransparent( ) && functionalGoTo.canGetTo( ) ) {
player.addAction( new FunctionalExit( exit ) );
player.addAction( functionalGoTo );
}
else if( player.isTransparent( ) ) {
player.addAction( new FunctionalExit( exit ) );
}
}
}
Game.getInstance( ).getActionManager( ).setActionSelected( ActionManager.ACTION_GOTO );
}
else {
Game.getInstance( ).getFunctionalPlayer( ).performActionInElement( element );
}
}
//private static final float SEC_GAP = 5;
public int[] checkPlayerAgainstBarriers( int destX, int destY ) {
int[] finalPos = new int[ 2 ];
finalPos[0] = destX;
finalPos[1] = destY;
for( FunctionalBarrier barrier : barriers ) {
int[] newDest = barrier.checkPlayerAgainstBarrier( player, finalPos[0], finalPos[1] );
finalPos[0] = newDest[0];
finalPos[1] = newDest[1];
}
return finalPos;
}
/**
* Returns the identifier of the backgrounds music.
*
* @return Identifier number of the background music
*/
public long getBackgroundMusicId( ) {
return backgroundMusicId;
}
/**
* Stops the background music of the scene
*/
public void stopBackgroundMusic( ) {
MultimediaManager.getInstance( ).stopPlaying( backgroundMusicId );
}
/**
* Load and play the background music if is not active. If its the first
* time it loads, it obtains the ID of the background music to be able to
* identify itself from other sounds.
*/
public void playBackgroundMusic( ) {
if( Game.getInstance( ).getOptions( ).isMusicActive( ) ) {
if (resources.existAsset( Scene.RESOURCE_TYPE_MUSIC )){
if( !MultimediaManager.getInstance( ).isPlaying( backgroundMusicId ) ) {
backgroundMusicId = MultimediaManager.getInstance( ).loadMusic( resources.getAssetPath( Scene.RESOURCE_TYPE_MUSIC ), true );
MultimediaManager.getInstance( ).startPlaying( backgroundMusicId );
}
} else
MultimediaManager.getInstance( ).stopPlayingMusic( );
}
}
/**
* Creates the current resource block to be used
*/
public Resources createResourcesBlock( ) {
// Get the active resources block
Resources newResources = null;
for( int i = 0; i < scene.getResources( ).size( ) && newResources == null; i++ )
if( new FunctionalConditions( scene.getResources( ).get( i ).getConditions( ) ).allConditionsOk( ) )
newResources = scene.getResources( ).get( i );
// If no resource block is available, create a default one
if( newResources == null ) {
newResources = new Resources( );
newResources.addAsset( new Asset( Scene.RESOURCE_TYPE_BACKGROUND, ResourceHandler.DEFAULT_BACKGROUND ) );
newResources.addAsset( new Asset( Scene.RESOURCE_TYPE_FOREGROUND, ResourceHandler.DEFAULT_FOREGROUND ) );
newResources.addAsset( new Asset( Scene.RESOURCE_TYPE_HARDMAP, ResourceHandler.DEFAULT_HARDMAP ) );
}
return newResources;
}
public void freeMemory( ) {
this.resources = null;
this.background = null;
this.foreground = null;
this.trajectory = null;
this.areas = null;
this.atrezzo = null;
this.barriers = null;
this.items = null;
this.npcs = null;
}
}
| false | true | public void updateScene( ) {
// Update the resources and the player's resources
updateResources( );
player.updateResources( );
// Pick the game data
Chapter gameData = Game.getInstance( ).getCurrentChapterData( );
// Check the item references of the scene
for( ElementReference itemReference : itemReferences ) {
// For every item that should be there
if( new FunctionalConditions( itemReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional item is present, update its resources
for( FunctionalItem currentItem : items ) {
if( itemReference.getTargetId( ).equals( currentItem.getElement( ).getId( ) )) {
currentItem.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
if( Game.getInstance( ).getItemSummary( ).isItemNormal( itemReference.getTargetId( ) ) ) {
for( Item currentItem : gameData.getItems( ) ) {
if( itemReference.getTargetId( ).equals( currentItem.getId( ) ) ) {
FunctionalItem fItem = new FunctionalItem( currentItem, itemReference );
items.add( fItem );
}
}
}
}
}
else {
FunctionalItem remove = null;
for( FunctionalItem currentItem : items ) {
if( currentItem.getReference( ) == itemReference )
remove = currentItem;
}
if( remove != null ){
itemReference.setPosition( (int) remove.getX( ), (int) remove.getY( ) );
items.remove( remove );
}
}
}
// Check the character references of the scene
for( ElementReference npcReference : NPCReferences ) {
// For every item that should be there
if( new FunctionalConditions( npcReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional character is present, update its resources
for( FunctionalNPC currentNPC : npcs ) {
if( npcReference.getTargetId( ).equals( currentNPC.getElement( ).getId( )) ) {
currentNPC.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
for( NPC currentNPC : gameData.getCharacters( ) ) {
if( npcReference.getTargetId( ).equals( currentNPC.getId( ) ) ) {
FunctionalNPC fNPC = new FunctionalNPC( currentNPC, npcReference );
npcs.add( fNPC );
}
}
}
}
else {
FunctionalNPC remove = null;
for( FunctionalNPC currentNPC : npcs ) {
if( currentNPC.getReference( ) == npcReference )
remove = currentNPC;
}
if( remove != null )
npcs.remove( remove );
}
}
// Check the active areas of the scene
for( ActiveArea activeArea : scene.getActiveAreas( ) ) {
// For every item that should be there
if( new FunctionalConditions( activeArea.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional item is present, update its resources
for( FunctionalActiveArea currentFunctionalActiveArea : areas ) {
if( activeArea.getId( ).equals( currentFunctionalActiveArea.getItem( ).getId( ) ) ) {
found = true;
break;
}
}
// If it was not found, search for it and add it
if( !found ) {
areas.add( new FunctionalActiveArea( activeArea, activeArea.getInfluenceArea( ) ) );
}
}
}
// Check the barriers of the scene
barriers.clear( );
for( Barrier barrier : scene.getBarriers( ) ) {
// For every barrier that should be there
if( new FunctionalConditions( barrier.getConditions( ) ).allConditionsOk( ) ) {
barriers.add( new FunctionalBarrier( barrier ) );
}
}
// Check the atrezzo item references of the scene
for( ElementReference atrezzoReference : scene.getAtrezzoReferences( ) ) {
// For every atrezzo item that should be there
if( new FunctionalConditions( atrezzoReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional atrezzo item is present, update its resources
for( FunctionalAtrezzo currentAtrezzo : atrezzo ) {
if( atrezzoReference == currentAtrezzo.getReference( ) ) {
currentAtrezzo.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
for( Atrezzo currentAtrezzo : gameData.getAtrezzo( ) ) {
if( atrezzoReference.getTargetId( ).equals( currentAtrezzo.getId( ) ) ) {
FunctionalAtrezzo fAtrezzo = new FunctionalAtrezzo( currentAtrezzo, atrezzoReference );
atrezzo.add( fAtrezzo );
}
}
}
}
else {
FunctionalAtrezzo remove = null;
for( FunctionalAtrezzo currentAtrezzo : atrezzo ) {
if( currentAtrezzo.getReference( ) == atrezzoReference )
remove = currentAtrezzo;
}
if( remove != null )
atrezzo.remove( remove );
}
}
// Create a list with the active areas to remove
ArrayList<FunctionalActiveArea> activeAreasToRemove = new ArrayList<FunctionalActiveArea>( );
for( FunctionalActiveArea currentActiveArea : areas ) {
boolean keepActiveArea = false;
// For every present item, check if it must be kept
for( ActiveArea activeArea : scene.getActiveAreas( ) ) {
if( activeArea.getId( ).equals( currentActiveArea.getItem( ).getId( ) ) && new FunctionalConditions( activeArea.getConditions( ) ).allConditionsOk( ) ) {
keepActiveArea = true;
}
}
// If it must not be kept, add it to the remove list
if( !keepActiveArea )
activeAreasToRemove.add( currentActiveArea );
}
// Remove the elements
for( FunctionalActiveArea areaToRemove : activeAreasToRemove )
areas.remove( areaToRemove );
}
| public void updateScene( ) {
// Update the resources and the player's resources
updateResources( );
player.updateResources( );
// Pick the game data
Chapter gameData = Game.getInstance( ).getCurrentChapterData( );
// Check the item references of the scene
for( ElementReference itemReference : itemReferences ) {
// For every item that should be there
if( new FunctionalConditions( itemReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional item is present, update its resources
for( FunctionalItem currentItem : items ) {
if( itemReference.getTargetId( ).equals( currentItem.getElement( ).getId( ) )) {
currentItem.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
if( Game.getInstance( ).getItemSummary( ).isItemNormal( itemReference.getTargetId( ) ) ) {
for( Item currentItem : gameData.getItems( ) ) {
if( itemReference.getTargetId( ).equals( currentItem.getId( ) ) ) {
FunctionalItem fItem = new FunctionalItem( currentItem, itemReference );
items.add( fItem );
}
}
}
}
}
else {
FunctionalItem remove = null;
for( FunctionalItem currentItem : items ) {
if( currentItem.getItem( ).getId( ).equals( itemReference.getTargetId( ) ) )
remove = currentItem;
}
if( remove != null ){
itemReference.setPosition( (int) remove.getX( ), (int) remove.getY( ) );
items.remove( remove );
}
}
}
// Check the character references of the scene
for( ElementReference npcReference : NPCReferences ) {
// For every item that should be there
if( new FunctionalConditions( npcReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional character is present, update its resources
for( FunctionalNPC currentNPC : npcs ) {
if( npcReference.getTargetId( ).equals( currentNPC.getElement( ).getId( )) ) {
currentNPC.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
for( NPC currentNPC : gameData.getCharacters( ) ) {
if( npcReference.getTargetId( ).equals( currentNPC.getId( ) ) ) {
FunctionalNPC fNPC = new FunctionalNPC( currentNPC, npcReference );
npcs.add( fNPC );
}
}
}
}
else {
FunctionalNPC remove = null;
for( FunctionalNPC currentNPC : npcs ) {
if( currentNPC.getElement( ).getId( ).equals( npcReference.getTargetId( ) ))
remove = currentNPC;
}
if( remove != null )
npcs.remove( remove );
}
}
// Check the active areas of the scene
for( ActiveArea activeArea : scene.getActiveAreas( ) ) {
// For every item that should be there
if( new FunctionalConditions( activeArea.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional item is present, update its resources
for( FunctionalActiveArea currentFunctionalActiveArea : areas ) {
if( activeArea.getId( ).equals( currentFunctionalActiveArea.getItem( ).getId( ) ) ) {
found = true;
break;
}
}
// If it was not found, search for it and add it
if( !found ) {
areas.add( new FunctionalActiveArea( activeArea, activeArea.getInfluenceArea( ) ) );
}
}
}
// Check the barriers of the scene
barriers.clear( );
for( Barrier barrier : scene.getBarriers( ) ) {
// For every barrier that should be there
if( new FunctionalConditions( barrier.getConditions( ) ).allConditionsOk( ) ) {
barriers.add( new FunctionalBarrier( barrier ) );
}
}
// Check the atrezzo item references of the scene
for( ElementReference atrezzoReference : scene.getAtrezzoReferences( ) ) {
// For every atrezzo item that should be there
if( new FunctionalConditions( atrezzoReference.getConditions( ) ).allConditionsOk( ) ) {
boolean found = false;
// If the functional atrezzo item is present, update its resources
for( FunctionalAtrezzo currentAtrezzo : atrezzo ) {
if( atrezzoReference == currentAtrezzo.getReference( ) ) {
currentAtrezzo.updateResources( );
found = true;
}
}
// If it was not found, search for it and add it
if( !found ) {
for( Atrezzo currentAtrezzo : gameData.getAtrezzo( ) ) {
if( atrezzoReference.getTargetId( ).equals( currentAtrezzo.getId( ) ) ) {
FunctionalAtrezzo fAtrezzo = new FunctionalAtrezzo( currentAtrezzo, atrezzoReference );
atrezzo.add( fAtrezzo );
}
}
}
}
else {
FunctionalAtrezzo remove = null;
for( FunctionalAtrezzo currentAtrezzo : atrezzo ) {
if( currentAtrezzo.getReference( ) == atrezzoReference )
remove = currentAtrezzo;
}
if( remove != null )
atrezzo.remove( remove );
}
}
// Create a list with the active areas to remove
ArrayList<FunctionalActiveArea> activeAreasToRemove = new ArrayList<FunctionalActiveArea>( );
for( FunctionalActiveArea currentActiveArea : areas ) {
boolean keepActiveArea = false;
// For every present item, check if it must be kept
for( ActiveArea activeArea : scene.getActiveAreas( ) ) {
if( activeArea.getId( ).equals( currentActiveArea.getItem( ).getId( ) ) && new FunctionalConditions( activeArea.getConditions( ) ).allConditionsOk( ) ) {
keepActiveArea = true;
}
}
// If it must not be kept, add it to the remove list
if( !keepActiveArea )
activeAreasToRemove.add( currentActiveArea );
}
// Remove the elements
for( FunctionalActiveArea areaToRemove : activeAreasToRemove )
areas.remove( areaToRemove );
}
|
diff --git a/src/joshua/tools/GrammarPacker.java b/src/joshua/tools/GrammarPacker.java
index f0ba85d4..06e8ae65 100644
--- a/src/joshua/tools/GrammarPacker.java
+++ b/src/joshua/tools/GrammarPacker.java
@@ -1,753 +1,753 @@
package joshua.tools;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.TreeMap;
import java.util.logging.Logger;
import joshua.corpus.Vocabulary;
import joshua.util.FormatUtils;
import joshua.util.io.LineReader;
import joshua.util.quantization.QuantizerConfiguration;
public class GrammarPacker {
private static final Logger logger =
Logger.getLogger(GrammarPacker.class.getName());
private static int FANOUT;
private static int CHUNK_SIZE;
private static int AVERAGE_NUM_FEATURES;
private static String WORKING_DIRECTORY;
private List<String> grammars;
private QuantizerConfiguration quantization;
static {
FANOUT = 2;
CHUNK_SIZE = 100000;
AVERAGE_NUM_FEATURES = 20;
WORKING_DIRECTORY = System.getProperty("user.dir")
+ File.separator + "packing";
}
public GrammarPacker(String config_filename,
List<String> grammars) throws IOException {
this.grammars = grammars;
this.quantization = new QuantizerConfiguration();
initialize();
readConfig(config_filename);
}
private void initialize() {
}
private void readConfig(String config_filename) throws IOException {
LineReader reader = new LineReader(config_filename);
while (reader.hasNext()) {
// Clean up line, chop comments off and skip if the result is empty.
String line = reader.next().trim();
if (line.indexOf('#') != -1)
line = line.substring(0, line.indexOf('#'));
if (line.isEmpty())
continue;
String[] fields = line.split("[\t]+");
if (fields.length < 2) {
logger.severe("Incomplete line in config.");
System.exit(0);
}
if ("chunk_size".equals(fields[0])) {
// Number of records to concurrently load into memory for sorting.
CHUNK_SIZE = Integer.parseInt(fields[1]);
} else if ("fanout".equals(fields[0])) {
// Number of sorted chunks to concurrently merge.
FANOUT = Integer.parseInt(fields[1]);
} else if ("quantizer".equals(fields[0])) {
// Adding a quantizer to the mix.
if (fields.length < 3) {
logger.severe("Incomplete quantizer line in config.");
System.exit(0);
}
String quantizer_key = fields[1];
String[] feature_names = fields[2].split(",");
ArrayList<Integer> feature_ids = new ArrayList<Integer>();
for (String feature_name : feature_names)
feature_ids.add(Vocabulary.id(feature_name));
quantization.add(quantizer_key, feature_ids);
}
}
reader.close();
File working_dir = new File(WORKING_DIRECTORY);
if (!working_dir.exists() && !working_dir.mkdirs()) {
logger.severe("Failed creating working directory.");
System.exit(0);
}
}
/**
* Executes the packing.
* @throws IOException
*/
public void pack() throws IOException {
logger.info("Beginning exploration pass.");
// Explore pass. Learn vocabulary and quantizer histograms.
for (String grammar_file : grammars) {
logger.info("Exploring: " + grammar_file);
LineReader reader = new LineReader(grammar_file);
explore(reader);
}
logger.info("Exploration pass complete. Freezing vocabulary and " +
"finalizing quantizers.");
quantization.write(WORKING_DIRECTORY + File.separator + "quantization");
Vocabulary.freeze();
Vocabulary.write(WORKING_DIRECTORY + File.separator + "vocabulary");
quantization.read(WORKING_DIRECTORY + File.separator + "quantization");
logger.info("Beginning chunking pass.");
Queue<PackedChunk> chunks = new PriorityQueue<PackedChunk>();
// Chunking pass. Split and binarize source, target and features into
for (String grammar_file : grammars) {
LineReader reader = new LineReader(grammar_file);
binarize(reader, chunks);
}
logger.info("Chunking pass complete.");
logger.info("Beginning merge phase.");
// Merge loop.
while (chunks.size() > 1) {
List<PackedChunk> to_merge = new ArrayList<PackedChunk>();
while (to_merge.size() < FANOUT && !chunks.isEmpty())
to_merge.add(chunks.poll());
chunks.add(merge(to_merge));
}
logger.info("Merge phase complete.");
}
// TODO: add javadoc.
private void explore(LineReader grammar) {
int counter = 0;
while (grammar.hasNext()) {
String line = grammar.next().trim();
counter++;
String[] fields = line.split("\\s\\|{3}\\s");
if (fields.length < 4) {
logger.warning("Incomplete grammar line at line " + counter);
continue;
}
String lhs = fields[0];
String[] source = fields[1].split("\\s");
String[] target = fields[2].split("\\s");
String[] features = fields[3].split("\\s");
Vocabulary.id(lhs);
// Add symbols to vocabulary.
for (String source_word : source) {
if (FormatUtils.isNonterminal(source_word))
Vocabulary.id(FormatUtils.stripNt(source_word));
else
Vocabulary.id(source_word);
}
for (String target_word : target) {
if (FormatUtils.isNonterminal(target_word))
Vocabulary.id(FormatUtils.stripNt(target_word));
else
Vocabulary.id(target_word);
}
// Add feature names to vocabulary and pass the value through the
// appropriate quantizer.
for (String feature_entry : features) {
String[] fe = feature_entry.split("=");
quantization.get(Vocabulary.id(fe[0])).add(Float.parseFloat(fe[1]));
}
}
}
private void binarize(LineReader grammar, Queue<PackedChunk> chunks)
throws IOException {
int counter = 0;
int chunk_counter = 0;
int num_chunks = 0;
boolean ready_to_flush = false;
String last_source = null;
PackingTrie<SourceValue> source_trie = new PackingTrie<SourceValue>();
PackingTrie<TargetValue> target_trie = new PackingTrie<TargetValue>();
PackingBuffer data_buffer = new PackingBuffer();
TreeMap<Integer, Float> features = new TreeMap<Integer, Float>();
while (grammar.hasNext()) {
String line = grammar.next().trim();
counter++;
chunk_counter++;
String[] fields = line.split("\\s\\|{3}\\s");
if (fields.length < 4) {
logger.warning("Incomplete grammar line at line " + counter);
continue;
}
String lhs_word = fields[0];
String[] source_words = fields[1].split("\\s");
String[] target_words = fields[2].split("\\s");
String[] feature_entries = fields[3].split("\\s");
// Reached chunk limit size, indicate that we're closing up.
if (!ready_to_flush && chunk_counter > CHUNK_SIZE) {
ready_to_flush = true;
last_source = fields[1];
}
// Finished closing up.
if (ready_to_flush && !last_source.equals(fields[1])) {
chunks.add(flush(source_trie, target_trie, data_buffer, num_chunks));
source_trie.clear();
target_trie.clear();
data_buffer.clear();
num_chunks++;
chunk_counter = 0;
ready_to_flush = false;
}
// Process features.
// Implicitly sort via TreeMap, write to data buffer, remember position
// to pass on to the source trie node.
features.clear();
for (String feature_entry : feature_entries) {
String[] parts = feature_entry.split("=");
features.put(Vocabulary.id(parts[0]),
Float.parseFloat(parts[1]));
}
int features_index = data_buffer.add(features);
// Process source side.
SourceValue sv = new SourceValue(Vocabulary.id(lhs_word), features_index);
int[] source = new int[source_words.length];
for (int i = 0; i < source_words.length; i++) {
if (FormatUtils.isNonterminal(source_words[i]))
source[i] = Vocabulary.id(FormatUtils.stripNt(source_words[i]));
else
source[i] = Vocabulary.id(source_words[i]);
}
source_trie.add(source, sv);
// Process target side.
TargetValue tv = new TargetValue(sv);
int[] target = new int[target_words.length];
for (int i = target_words.length - 1; i >= 0; i--) {
if (FormatUtils.isNonterminal(target_words[i]))
target[i] = -FormatUtils.getNonterminalIndex(target_words[i]);
else
target[i] = Vocabulary.id(target_words[i]);
}
target_trie.add(target, tv);
}
chunks.add(flush(source_trie, target_trie, data_buffer, num_chunks));
}
/**
* Serializes the source, target and feature data structures into interlinked
* binary files. Target is written first, into a skeletal (node don't carry
* any data) upward-pointing trie, updating the linking source trie nodes
* with the position once it is known. Source and feature data are written
* simultaneously. The source structure is written into a downward-pointing
* trie and stores the rule's lhs as well as links to the target and feature
* stream. The feature stream is prompted to write out a block
*
* @param source_trie
* @param target_trie
* @param data_buffer
* @param id
* @throws IOException
*/
private PackedChunk flush(PackingTrie<SourceValue> source_trie,
PackingTrie<TargetValue> target_trie, PackingBuffer data_buffer,
int id) throws IOException {
// Make a chunk object for this piece of the grammar.
PackedChunk chunk = new PackedChunk("chunk_" + String.format("%05d", id));
// Pull out the streams for source, target and data output.
DataOutputStream source_stream = chunk.getSourceOutput();
DataOutputStream target_stream = chunk.getTargetOutput();
DataOutputStream data_stream = chunk.getDataOutput();
Queue<PackingTrie<TargetValue>> target_queue;
Queue<PackingTrie<SourceValue>> source_queue;
// The number of bytes both written into the source stream and
// buffered in the source queue.
int source_position;
// The number of bytes written into the target stream.
int target_position;
// Add trie root into queue, set target position to 0 and set cumulated
// size to size of trie root.
target_queue = new LinkedList<PackingTrie<TargetValue>>();
target_queue.add(target_trie);
target_position = 0;
// Packing loop for upwards-pointing target trie.
while (!target_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<TargetValue> node = target_queue.poll();
// Register that this is where we're writing the node to.
node.address = target_position;
// Tell source nodes that we're writing to this position in the file.
for (TargetValue tv : node.values)
tv.parent.target = node.address;
// Write link to parent.
if (node.parent != null)
target_stream.writeInt(node.parent.address);
else
target_stream.writeInt(-1);
target_stream.writeInt(node.symbol);
// Enqueue children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<TargetValue> child = node.children.get(k);
target_queue.add(child);
}
target_position += node.size(false, true);
}
// Setting up for source and data writing.
source_queue = new LinkedList<PackingTrie<SourceValue>>();
source_queue.add(source_trie);
source_position = source_trie.size(true, false);
source_trie.address = target_position;
// Ready data buffer for writing.
data_buffer.initialize();
// Packing loop for downwards-pointing source trie.
while (!source_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<SourceValue> node = source_queue.poll();
// Write number of children.
source_stream.writeInt(node.children.size());
// Write links to children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<SourceValue> child = node.children.get(k);
// Enqueue child.
source_queue.add(child);
// Child's address will be at the current end of the queue.
child.address = source_position;
// Advance cumulated size by child's size.
source_position += child.size(true, false);
// Write the link.
source_stream.writeInt(k);
- source_stream.write(child.address);
+ source_stream.writeInt(child.address);
}
// Write number of data items.
source_stream.writeInt(node.values.size());
// Write lhs and links to target and data.
for (SourceValue sv : node.values) {
sv.data = data_buffer.write(sv.data);
source_stream.writeInt(sv.lhs);
source_stream.writeInt(sv.target);
source_stream.writeInt(sv.data);
}
}
// Flush the data stream.
data_buffer.flush(data_stream);
target_stream.close();
source_stream.close();
data_stream.close();
return chunk;
}
private PackedChunk merge(List<PackedChunk> chunks) {
return null;
}
public static void main(String[] args) throws IOException {
if (args.length >= 3) {
String config_filename = args[0];
WORKING_DIRECTORY = args[1];
List<String> grammar_files = new ArrayList<String>();
for (int i = 2; i < args.length; i++)
grammar_files.add(args[i]);
GrammarPacker packer = new GrammarPacker(config_filename, grammar_files);
packer.pack();
} else {
System.err.println("Expecting at least two arguments: ");
System.err.println("\tjoshua.tools.GrammarPacker config_file " +
"output_directory grammar_file ...");
}
}
/**
* Integer-labeled, doubly-linked trie with some provisions for packing.
* @author Juri Ganitkevitch
*
* @param <D> The trie's value type.
*/
class PackingTrie<D extends PackingTrieValue> {
int symbol;
PackingTrie<D> parent;
TreeMap<Integer, PackingTrie<D>> children;
List<D> values;
int address;
PackingTrie() {
address = -1;
symbol = 0;
parent = null;
children = new TreeMap<Integer, PackingTrie<D>>();
values = new ArrayList<D>();
}
PackingTrie(PackingTrie<D> parent, int symbol) {
this();
this.parent = parent;
this.symbol = symbol;
}
void add(int[] path, D value) {
add(path, 0, value);
}
private void add(int[] path, int index, D value) {
if (index == path.length)
this.values.add(value);
else {
PackingTrie<D> child = children.get(path[index]);
if (child == null) {
child = new PackingTrie<D>(this, path[index]);
children.put(path[index], child);
}
child.add(path, index + 1, value);
}
}
void pack(ByteBuffer out, boolean skeletal) {
}
/**
* Calculate the size (in bytes) of a packed trie node. Distinguishes
* downwards pointing (parent points to children) from upwards pointing
* (children point to parent) tries, as well as skeletal (no data, just the
* labeled links) and non-skeletal (nodes have a data block) packing.
*
* @param downwards Are we packing into a downwards-pointing trie?
* @param skeletal Are we packing into a skeletal trie?
*
* @return Number of bytes the trie node would occupy.
*/
int size(boolean downwards, boolean skeletal) {
int size = 0;
if (downwards) {
// Number of children and links to children.
size = 1 + 2 * children.size();
} else {
// Link to parent.
size += 2;
}
// Non-skeletal packing: number of data items.
if (!skeletal)
size += 1;
// Non-skeletal packing: write size taken up by data items.
if (!skeletal && !values.isEmpty())
size += values.size() * values.get(0).size();
return size * 4;
}
void clear() {
children.clear();
values.clear();
}
}
interface PackingTrieValue {
void pack(ByteBuffer out);
int size();
}
class SourceValue implements PackingTrieValue {
int lhs;
int data;
int target;
public SourceValue() {
}
SourceValue(int lhs, int data) {
this.lhs = lhs;
this.data = data;
}
void setTarget(int target) {
this.target = target;
}
@Override
public void pack(ByteBuffer out) {
// TODO Auto-generated method stub
}
public int size() {
return 3;
}
}
class TargetValue implements PackingTrieValue {
SourceValue parent;
TargetValue(SourceValue parent) {
this.parent = parent;
}
@Override
public void pack(ByteBuffer out) {
// TODO Auto-generated method stub
}
public int size() {
return 0;
}
}
// TODO: abstract away from features, use generic type for in-memory
// structure. PackingBuffers are to implement structure to in-memory bytes
// and flushing in-memory bytes to on-disk bytes.
class PackingBuffer {
private byte[] backing;
private ByteBuffer buffer;
private ArrayList<Integer> memoryLookup;
private int totalSize;
private ArrayList<Integer> onDiskOrder;
PackingBuffer() throws IOException {
allocate();
memoryLookup = new ArrayList<Integer>();
onDiskOrder = new ArrayList<Integer>();
totalSize = 0;
}
// Allocate a reasonably-sized buffer for the feature data.
private void allocate() {
backing = new byte[CHUNK_SIZE * AVERAGE_NUM_FEATURES];
buffer = ByteBuffer.wrap(backing);
}
// Reallocate the backing array and buffer, copies data over.
private void reallocate() {
byte[] new_backing = new byte[backing.length * 2];
System.arraycopy(backing, 0, new_backing, 0, backing.length);
int old_position = buffer.position();
ByteBuffer new_buffer = ByteBuffer.wrap(new_backing);
new_buffer.position(old_position);
buffer = new_buffer;
backing = new_backing;
}
/**
* Add a block of features to the buffer.
* @param features TreeMap with the features for one rule.
* @return The index of the resulting data block.
*/
int add(TreeMap<Integer, Float> features) {
int data_position = buffer.position();
// Over-estimate how much room this addition will need: 12 bytes per
// feature (4 for label, "upper bound" of 8 for the value), plus 4 for
// the number of features. If this won't fit, reallocate the buffer.
int size_estimate = 12 * features.size() + 4;
if (buffer.capacity() - buffer.position() <= size_estimate)
reallocate();
// Write features to buffer.
buffer.putInt(features.size());
for (Integer k : features.descendingKeySet()) {
float v = features.get(k);
// Sparse features.
if (v != 0.0) {
buffer.putInt(k);
quantization.get(k).write(buffer, v);
}
}
// Store position the block was written to.
memoryLookup.add(data_position);
// Update total size (in bytes).
totalSize = buffer.position();
// Return block index.
return memoryLookup.size() - 1;
}
/**
* Prepare the data buffer for disk writing.
*/
void initialize() {
onDiskOrder.clear();
}
/**
* Enqueue a data block for later writing.
* @param block_index The index of the data block to add to writing queue.
* @return The to-be-written block's output index.
*/
int write(int block_index) {
onDiskOrder.add(block_index);
return onDiskOrder.size() - 1;
}
/**
* Performs the actual writing to disk in the order specified by calls to
* write() since the last call to initialize().
* @param out
* @throws IOException
*/
void flush(DataOutputStream out) throws IOException {
writeHeader(out);
int size;
int block_address;
for (int block_index : onDiskOrder) {
block_address = memoryLookup.get(block_index);
size = blockSize(block_index);
out.write(backing, block_address, size);
}
}
void clear() {
buffer.clear();
memoryLookup.clear();
onDiskOrder.clear();
}
private void writeHeader(DataOutputStream out) throws IOException {
if (out.size() == 0) {
out.writeInt(onDiskOrder.size());
out.writeInt(totalSize);
int disk_position = headerSize();
for (int block_index : onDiskOrder) {
out.writeInt(disk_position);
disk_position += blockSize(block_index);
}
} else {
throw new RuntimeException("Got a used stream for header writing.");
}
}
private int headerSize() {
// One integer for each data block, plus number of blocks and total size.
return 4 * (onDiskOrder.size() + 2);
}
private int blockSize(int block_index) {
int block_address = memoryLookup.get(block_index);
return (block_index < memoryLookup.size() - 1 ?
memoryLookup.get(block_index + 1) : totalSize) - block_address;
}
}
class PackedChunk implements Comparable<PackedChunk> {
private File sourceFile;
private File targetFile;
private File dataFile;
PackedChunk(String prefix) {
sourceFile = new File(WORKING_DIRECTORY + File.separator
+ prefix + ".source");
targetFile = new File(WORKING_DIRECTORY + File.separator
+ prefix + ".target");
dataFile = new File(WORKING_DIRECTORY + File.separator
+ prefix + ".data");
logger.info("Allocated chunk: " + sourceFile.getAbsolutePath());
}
DataOutputStream getSourceOutput() throws IOException {
return getOutput(sourceFile);
}
DataOutputStream getTargetOutput() throws IOException {
return getOutput(targetFile);
}
DataOutputStream getDataOutput() throws IOException {
return getOutput(dataFile);
}
private DataOutputStream getOutput(File file) throws IOException {
if (file.createNewFile()) {
return new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(file)));
} else {
throw new RuntimeException("File doesn't exist: " + file.getName());
}
}
ByteBuffer getSourceBuffer() throws IOException {
return getBuffer(sourceFile);
}
ByteBuffer getTargetBuffer() throws IOException {
return getBuffer(targetFile);
}
ByteBuffer getDataBuffer() throws IOException {
return getBuffer(dataFile);
}
private ByteBuffer getBuffer(File file) throws IOException {
if (file.exists()) {
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
return channel.map(MapMode.READ_WRITE, 0, channel.size());
} else {
throw new RuntimeException("File doesn't exist: " + file.getName());
}
}
long getSize() {
return sourceFile.length() + targetFile.length() + dataFile.length();
}
@Override
public int compareTo(PackedChunk o) {
if (getSize() > o.getSize()) {
return -1;
} else if (getSize() < o.getSize()) {
return 1;
} else {
return 0;
}
}
}
}
| true | true | private PackedChunk flush(PackingTrie<SourceValue> source_trie,
PackingTrie<TargetValue> target_trie, PackingBuffer data_buffer,
int id) throws IOException {
// Make a chunk object for this piece of the grammar.
PackedChunk chunk = new PackedChunk("chunk_" + String.format("%05d", id));
// Pull out the streams for source, target and data output.
DataOutputStream source_stream = chunk.getSourceOutput();
DataOutputStream target_stream = chunk.getTargetOutput();
DataOutputStream data_stream = chunk.getDataOutput();
Queue<PackingTrie<TargetValue>> target_queue;
Queue<PackingTrie<SourceValue>> source_queue;
// The number of bytes both written into the source stream and
// buffered in the source queue.
int source_position;
// The number of bytes written into the target stream.
int target_position;
// Add trie root into queue, set target position to 0 and set cumulated
// size to size of trie root.
target_queue = new LinkedList<PackingTrie<TargetValue>>();
target_queue.add(target_trie);
target_position = 0;
// Packing loop for upwards-pointing target trie.
while (!target_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<TargetValue> node = target_queue.poll();
// Register that this is where we're writing the node to.
node.address = target_position;
// Tell source nodes that we're writing to this position in the file.
for (TargetValue tv : node.values)
tv.parent.target = node.address;
// Write link to parent.
if (node.parent != null)
target_stream.writeInt(node.parent.address);
else
target_stream.writeInt(-1);
target_stream.writeInt(node.symbol);
// Enqueue children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<TargetValue> child = node.children.get(k);
target_queue.add(child);
}
target_position += node.size(false, true);
}
// Setting up for source and data writing.
source_queue = new LinkedList<PackingTrie<SourceValue>>();
source_queue.add(source_trie);
source_position = source_trie.size(true, false);
source_trie.address = target_position;
// Ready data buffer for writing.
data_buffer.initialize();
// Packing loop for downwards-pointing source trie.
while (!source_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<SourceValue> node = source_queue.poll();
// Write number of children.
source_stream.writeInt(node.children.size());
// Write links to children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<SourceValue> child = node.children.get(k);
// Enqueue child.
source_queue.add(child);
// Child's address will be at the current end of the queue.
child.address = source_position;
// Advance cumulated size by child's size.
source_position += child.size(true, false);
// Write the link.
source_stream.writeInt(k);
source_stream.write(child.address);
}
// Write number of data items.
source_stream.writeInt(node.values.size());
// Write lhs and links to target and data.
for (SourceValue sv : node.values) {
sv.data = data_buffer.write(sv.data);
source_stream.writeInt(sv.lhs);
source_stream.writeInt(sv.target);
source_stream.writeInt(sv.data);
}
}
// Flush the data stream.
data_buffer.flush(data_stream);
target_stream.close();
source_stream.close();
data_stream.close();
return chunk;
}
| private PackedChunk flush(PackingTrie<SourceValue> source_trie,
PackingTrie<TargetValue> target_trie, PackingBuffer data_buffer,
int id) throws IOException {
// Make a chunk object for this piece of the grammar.
PackedChunk chunk = new PackedChunk("chunk_" + String.format("%05d", id));
// Pull out the streams for source, target and data output.
DataOutputStream source_stream = chunk.getSourceOutput();
DataOutputStream target_stream = chunk.getTargetOutput();
DataOutputStream data_stream = chunk.getDataOutput();
Queue<PackingTrie<TargetValue>> target_queue;
Queue<PackingTrie<SourceValue>> source_queue;
// The number of bytes both written into the source stream and
// buffered in the source queue.
int source_position;
// The number of bytes written into the target stream.
int target_position;
// Add trie root into queue, set target position to 0 and set cumulated
// size to size of trie root.
target_queue = new LinkedList<PackingTrie<TargetValue>>();
target_queue.add(target_trie);
target_position = 0;
// Packing loop for upwards-pointing target trie.
while (!target_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<TargetValue> node = target_queue.poll();
// Register that this is where we're writing the node to.
node.address = target_position;
// Tell source nodes that we're writing to this position in the file.
for (TargetValue tv : node.values)
tv.parent.target = node.address;
// Write link to parent.
if (node.parent != null)
target_stream.writeInt(node.parent.address);
else
target_stream.writeInt(-1);
target_stream.writeInt(node.symbol);
// Enqueue children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<TargetValue> child = node.children.get(k);
target_queue.add(child);
}
target_position += node.size(false, true);
}
// Setting up for source and data writing.
source_queue = new LinkedList<PackingTrie<SourceValue>>();
source_queue.add(source_trie);
source_position = source_trie.size(true, false);
source_trie.address = target_position;
// Ready data buffer for writing.
data_buffer.initialize();
// Packing loop for downwards-pointing source trie.
while (!source_queue.isEmpty()) {
// Pop top of queue.
PackingTrie<SourceValue> node = source_queue.poll();
// Write number of children.
source_stream.writeInt(node.children.size());
// Write links to children.
for (int k : node.children.descendingKeySet()) {
PackingTrie<SourceValue> child = node.children.get(k);
// Enqueue child.
source_queue.add(child);
// Child's address will be at the current end of the queue.
child.address = source_position;
// Advance cumulated size by child's size.
source_position += child.size(true, false);
// Write the link.
source_stream.writeInt(k);
source_stream.writeInt(child.address);
}
// Write number of data items.
source_stream.writeInt(node.values.size());
// Write lhs and links to target and data.
for (SourceValue sv : node.values) {
sv.data = data_buffer.write(sv.data);
source_stream.writeInt(sv.lhs);
source_stream.writeInt(sv.target);
source_stream.writeInt(sv.data);
}
}
// Flush the data stream.
data_buffer.flush(data_stream);
target_stream.close();
source_stream.close();
data_stream.close();
return chunk;
}
|
diff --git a/AE-go_GameServer/src/com/aionemu/gameserver/ShutdownHook.java b/AE-go_GameServer/src/com/aionemu/gameserver/ShutdownHook.java
index 5000c271..7b338910 100644
--- a/AE-go_GameServer/src/com/aionemu/gameserver/ShutdownHook.java
+++ b/AE-go_GameServer/src/com/aionemu/gameserver/ShutdownHook.java
@@ -1,179 +1,182 @@
/*
* This file is part of aion-emu <aion-emu.com>.
*
* aion-emu is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* aion-emu is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with aion-emu. If not, see <http://www.gnu.org/licenses/>.
*/
package com.aionemu.gameserver;
import java.util.Iterator;
import org.apache.log4j.Logger;
import com.aionemu.commons.utils.ExitCode;
import com.aionemu.gameserver.configs.Config;
import com.aionemu.gameserver.model.gameobjects.player.Player;
import com.aionemu.gameserver.network.aion.serverpackets.SM_SYSTEM_MESSAGE;
import com.aionemu.gameserver.network.loginserver.LoginServer;
import com.aionemu.gameserver.services.PlayerService;
import com.aionemu.gameserver.utils.gametime.GameTimeManager;
import com.aionemu.gameserver.world.World;
import com.google.inject.Injector;
/**
* @author lord_rex
*
*/
public class ShutdownHook extends Thread
{
private static final Logger log = Logger.getLogger(ShutdownHook.class);
private static World world;
private static PlayerService playerService;
private static LoginServer loginServer;
public ShutdownHook(Injector injector)
{
world = injector.getInstance(World.class);
playerService = injector.getInstance(PlayerService.class);
loginServer = injector.getInstance(LoginServer.class);
}
public static ShutdownHook getInstance(Injector injector)
{
return new ShutdownHook(injector);
}
@Override
public void run()
{
if(Config.SHUTDOWN_HOOK_MODE == 1)
shutdownHook(Config.SHUTDOWN_HOOK_DELAY, Config.SHUTDOWN_ANNOUNCE_INTERVAL, ShutdownMode.SHUTDOWN);
else if(Config.SHUTDOWN_HOOK_MODE == 2)
shutdownHook(Config.SHUTDOWN_HOOK_DELAY, Config.SHUTDOWN_ANNOUNCE_INTERVAL, ShutdownMode.RESTART);
}
public static enum ShutdownMode
{
NONE("terminating"),
SHUTDOWN("shutting down"),
RESTART("restarting");
private final String text;
private ShutdownMode(String text)
{
this.text = text;
}
public String getText()
{
return text;
}
}
private static void sendShutdownMessage(int seconds)
{
Iterator<Player> onlinePlayers = world.getPlayersIterator();
if(!onlinePlayers.hasNext())
return;
while(onlinePlayers.hasNext())
{
Player player = onlinePlayers.next();
if(player != null && player.getClientConnection() != null)
player.getClientConnection().sendPacket(SM_SYSTEM_MESSAGE.SERVER_SHUTDOWN(seconds));
}
}
private static void sendShutdownStatus(boolean status)
{
Iterator<Player> onlinePlayers = world.getPlayersIterator();
if(!onlinePlayers.hasNext())
return;
while(onlinePlayers.hasNext())
{
Player player = onlinePlayers.next();
if(player != null && player.getClientConnection() != null)
onlinePlayers.next().getController().setInShutdownProgress(status);
}
}
private static void shutdownHook(int duration, int interval, ShutdownMode mode)
{
for(int i = duration; i >= interval; i -= interval)
{
- log.info("System is closing in " + i + " seconds.");
- sendShutdownMessage(i);
- sendShutdownStatus(true);
try
- {
- if(!world.getPlayersIterator().hasNext())
+ {
+ if(world.getPlayersIterator().hasNext())
{
- log.info("Counter is stopped because there are no players in the server.");
+ log.info("Runtime is closing in " + i + " seconds.");
+ sendShutdownMessage(i);
+ sendShutdownStatus(true);
+ }
+ else
+ {
+ log.info("Runtime is closing now ...");
break;
}
if(i > interval)
{
Thread.sleep(interval * 1000);
}
else
{
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
return;
}
}
// Disconnect login server from game.
loginServer.gameServerDisconnected();
// Disconnect all players.
Iterator<Player> onlinePlayers;
onlinePlayers = world.getPlayersIterator();
while(onlinePlayers.hasNext())
{
Player activePlayer = onlinePlayers.next();
try
{
playerService.playerLoggedOut(activePlayer);
}
catch (Exception e)
{
log.error("Error while saving player " + e.getMessage());
}
}
log.info("All players are disconnected...");
// Save game time.
GameTimeManager.saveTime();
// Do system exit.
if(mode == ShutdownMode.RESTART)
Runtime.getRuntime().halt(ExitCode.CODE_RESTART);
else
Runtime.getRuntime().halt(ExitCode.CODE_NORMAL);
log.info("Runtime is closing now...");
}
public static void doShutdown(int delay, int announceInterval, ShutdownMode mode)
{
shutdownHook(delay, announceInterval, mode);
}
}
| false | true | private static void shutdownHook(int duration, int interval, ShutdownMode mode)
{
for(int i = duration; i >= interval; i -= interval)
{
log.info("System is closing in " + i + " seconds.");
sendShutdownMessage(i);
sendShutdownStatus(true);
try
{
if(!world.getPlayersIterator().hasNext())
{
log.info("Counter is stopped because there are no players in the server.");
break;
}
if(i > interval)
{
Thread.sleep(interval * 1000);
}
else
{
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
return;
}
}
// Disconnect login server from game.
loginServer.gameServerDisconnected();
// Disconnect all players.
Iterator<Player> onlinePlayers;
onlinePlayers = world.getPlayersIterator();
while(onlinePlayers.hasNext())
{
Player activePlayer = onlinePlayers.next();
try
{
playerService.playerLoggedOut(activePlayer);
}
catch (Exception e)
{
log.error("Error while saving player " + e.getMessage());
}
}
log.info("All players are disconnected...");
// Save game time.
GameTimeManager.saveTime();
// Do system exit.
if(mode == ShutdownMode.RESTART)
Runtime.getRuntime().halt(ExitCode.CODE_RESTART);
else
Runtime.getRuntime().halt(ExitCode.CODE_NORMAL);
log.info("Runtime is closing now...");
}
| private static void shutdownHook(int duration, int interval, ShutdownMode mode)
{
for(int i = duration; i >= interval; i -= interval)
{
try
{
if(world.getPlayersIterator().hasNext())
{
log.info("Runtime is closing in " + i + " seconds.");
sendShutdownMessage(i);
sendShutdownStatus(true);
}
else
{
log.info("Runtime is closing now ...");
break;
}
if(i > interval)
{
Thread.sleep(interval * 1000);
}
else
{
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
return;
}
}
// Disconnect login server from game.
loginServer.gameServerDisconnected();
// Disconnect all players.
Iterator<Player> onlinePlayers;
onlinePlayers = world.getPlayersIterator();
while(onlinePlayers.hasNext())
{
Player activePlayer = onlinePlayers.next();
try
{
playerService.playerLoggedOut(activePlayer);
}
catch (Exception e)
{
log.error("Error while saving player " + e.getMessage());
}
}
log.info("All players are disconnected...");
// Save game time.
GameTimeManager.saveTime();
// Do system exit.
if(mode == ShutdownMode.RESTART)
Runtime.getRuntime().halt(ExitCode.CODE_RESTART);
else
Runtime.getRuntime().halt(ExitCode.CODE_NORMAL);
log.info("Runtime is closing now...");
}
|
diff --git a/project-set/core/core-lib/src/test/java/com/rackspace/papi/filter/RequestFilterChainStateTest.java b/project-set/core/core-lib/src/test/java/com/rackspace/papi/filter/RequestFilterChainStateTest.java
index 5afbf107c4..f03b70e36a 100644
--- a/project-set/core/core-lib/src/test/java/com/rackspace/papi/filter/RequestFilterChainStateTest.java
+++ b/project-set/core/core-lib/src/test/java/com/rackspace/papi/filter/RequestFilterChainStateTest.java
@@ -1,67 +1,67 @@
package com.rackspace.papi.filter;
import com.rackspace.papi.domain.ReposeInstanceInfo;
import com.rackspace.papi.filter.resource.ResourceMonitor;
import com.rackspace.papi.service.context.ServletContextHelper;
import com.rackspace.papi.service.context.container.ContainerConfigurationService;
import com.rackspace.papi.service.context.impl.RoutingServiceContext;
import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import javax.naming.NamingException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Mockito.*;
/**
* @author fran
*/
@RunWith(Enclosed.class)
public class RequestFilterChainStateTest {
public static class WhenUsingPowerFilterChain {
@Test
public void shouldDoFilter() throws IOException, ServletException, NamingException, PowerFilterChainException {
List<FilterContext> filterContextList = new ArrayList<FilterContext>();
Filter mockedFilter = mock(Filter.class);
FilterContext mockedFilterContext = mock(FilterContext.class);
ClassLoader mockedClassLoader = mock(ClassLoader.class);
ServletContext context = mock(ServletContext.class);
ApplicationContext appContext = mock(ApplicationContext.class);
RoutingServiceContext routingContext = mock(RoutingServiceContext.class);
ContainerConfigurationService containerConfigurationService = mock(ContainerConfigurationService.class);
when(containerConfigurationService.getVia()).thenReturn("");
when(mockedFilterContext.getFilter()).thenReturn(mockedFilter);
when(mockedFilterContext.getFilterClassLoader()).thenReturn(mockedClassLoader);
when(appContext.getBean(anyString())).thenReturn(routingContext);
filterContextList.add(mockedFilterContext);
FilterChain mockedFilterChain = mock(FilterChain.class);
ServletContextHelper instance = ServletContextHelper.configureInstance(context, appContext);
when(context.getAttribute(ServletContextHelper.SERVLET_CONTEXT_HELPER)).thenReturn(instance);
ReposeInstanceInfo instanceInfo = new ReposeInstanceInfo("repose", "node");
- PowerFilterChain powerFilterChainState = new PowerFilterChain(filterContextList, mockedFilterChain, mock(ResourceMonitor.class), mock(PowerFilterRouter.class),instanceInfo);
+ PowerFilterChain powerFilterChainState = new PowerFilterChain(filterContextList, mockedFilterChain, mock(ResourceMonitor.class), mock(PowerFilterRouter.class), instanceInfo, null);
HttpServletRequest mockedServletRequest = mock(HttpServletRequest.class);
HttpServletResponse mockedServletResponse = mock(HttpServletResponse.class);
when(mockedServletRequest.getRequestURL()).thenReturn(new StringBuffer());
powerFilterChainState.startFilterChain(mockedServletRequest, mockedServletResponse);
powerFilterChainState.startFilterChain(mockedServletRequest, mockedServletResponse);
}
}
}
| true | true | public void shouldDoFilter() throws IOException, ServletException, NamingException, PowerFilterChainException {
List<FilterContext> filterContextList = new ArrayList<FilterContext>();
Filter mockedFilter = mock(Filter.class);
FilterContext mockedFilterContext = mock(FilterContext.class);
ClassLoader mockedClassLoader = mock(ClassLoader.class);
ServletContext context = mock(ServletContext.class);
ApplicationContext appContext = mock(ApplicationContext.class);
RoutingServiceContext routingContext = mock(RoutingServiceContext.class);
ContainerConfigurationService containerConfigurationService = mock(ContainerConfigurationService.class);
when(containerConfigurationService.getVia()).thenReturn("");
when(mockedFilterContext.getFilter()).thenReturn(mockedFilter);
when(mockedFilterContext.getFilterClassLoader()).thenReturn(mockedClassLoader);
when(appContext.getBean(anyString())).thenReturn(routingContext);
filterContextList.add(mockedFilterContext);
FilterChain mockedFilterChain = mock(FilterChain.class);
ServletContextHelper instance = ServletContextHelper.configureInstance(context, appContext);
when(context.getAttribute(ServletContextHelper.SERVLET_CONTEXT_HELPER)).thenReturn(instance);
ReposeInstanceInfo instanceInfo = new ReposeInstanceInfo("repose", "node");
PowerFilterChain powerFilterChainState = new PowerFilterChain(filterContextList, mockedFilterChain, mock(ResourceMonitor.class), mock(PowerFilterRouter.class),instanceInfo);
HttpServletRequest mockedServletRequest = mock(HttpServletRequest.class);
HttpServletResponse mockedServletResponse = mock(HttpServletResponse.class);
when(mockedServletRequest.getRequestURL()).thenReturn(new StringBuffer());
powerFilterChainState.startFilterChain(mockedServletRequest, mockedServletResponse);
powerFilterChainState.startFilterChain(mockedServletRequest, mockedServletResponse);
}
| public void shouldDoFilter() throws IOException, ServletException, NamingException, PowerFilterChainException {
List<FilterContext> filterContextList = new ArrayList<FilterContext>();
Filter mockedFilter = mock(Filter.class);
FilterContext mockedFilterContext = mock(FilterContext.class);
ClassLoader mockedClassLoader = mock(ClassLoader.class);
ServletContext context = mock(ServletContext.class);
ApplicationContext appContext = mock(ApplicationContext.class);
RoutingServiceContext routingContext = mock(RoutingServiceContext.class);
ContainerConfigurationService containerConfigurationService = mock(ContainerConfigurationService.class);
when(containerConfigurationService.getVia()).thenReturn("");
when(mockedFilterContext.getFilter()).thenReturn(mockedFilter);
when(mockedFilterContext.getFilterClassLoader()).thenReturn(mockedClassLoader);
when(appContext.getBean(anyString())).thenReturn(routingContext);
filterContextList.add(mockedFilterContext);
FilterChain mockedFilterChain = mock(FilterChain.class);
ServletContextHelper instance = ServletContextHelper.configureInstance(context, appContext);
when(context.getAttribute(ServletContextHelper.SERVLET_CONTEXT_HELPER)).thenReturn(instance);
ReposeInstanceInfo instanceInfo = new ReposeInstanceInfo("repose", "node");
PowerFilterChain powerFilterChainState = new PowerFilterChain(filterContextList, mockedFilterChain, mock(ResourceMonitor.class), mock(PowerFilterRouter.class), instanceInfo, null);
HttpServletRequest mockedServletRequest = mock(HttpServletRequest.class);
HttpServletResponse mockedServletResponse = mock(HttpServletResponse.class);
when(mockedServletRequest.getRequestURL()).thenReturn(new StringBuffer());
powerFilterChainState.startFilterChain(mockedServletRequest, mockedServletResponse);
powerFilterChainState.startFilterChain(mockedServletRequest, mockedServletResponse);
}
|
diff --git a/src/org/mozilla/javascript/optimizer/Optimizer.java b/src/org/mozilla/javascript/optimizer/Optimizer.java
index 55294307..746bd0dd 100644
--- a/src/org/mozilla/javascript/optimizer/Optimizer.java
+++ b/src/org/mozilla/javascript/optimizer/Optimizer.java
@@ -1,507 +1,510 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Norris Boyd
* Roger Lawrence
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.optimizer;
import org.mozilla.javascript.*;
import org.mozilla.javascript.ast.ScriptNode;
class Optimizer
{
static final int NoType = 0;
static final int NumberType = 1;
static final int AnyType = 3;
// It is assumed that (NumberType | AnyType) == AnyType
void optimize(ScriptNode scriptOrFn)
{
// run on one function at a time for now
int functionCount = scriptOrFn.getFunctionCount();
for (int i = 0; i != functionCount; ++i) {
OptFunctionNode f = OptFunctionNode.get(scriptOrFn, i);
optimizeFunction(f);
}
}
private void optimizeFunction(OptFunctionNode theFunction)
{
if (theFunction.fnode.requiresActivation()) return;
inDirectCallFunction = theFunction.isTargetOfDirectCall();
this.theFunction = theFunction;
ObjArray statementsArray = new ObjArray();
buildStatementList_r(theFunction.fnode, statementsArray);
Node[] theStatementNodes = new Node[statementsArray.size()];
statementsArray.toArray(theStatementNodes);
Block.runFlowAnalyzes(theFunction, theStatementNodes);
if (!theFunction.fnode.requiresActivation()) {
/*
* Now that we know which local vars are in fact always
* Numbers, we re-write the tree to take advantage of
* that. Any arithmetic or assignment op involving just
* Number typed vars is marked so that the codegen will
* generate non-object code.
*/
parameterUsedInNumberContext = false;
for (int i = 0; i < theStatementNodes.length; i++) {
rewriteForNumberVariables(theStatementNodes[i], NumberType);
}
theFunction.setParameterNumberContext(parameterUsedInNumberContext);
}
}
/*
Each directCall parameter is passed as a pair of values - an object
and a double. The value passed depends on the type of value available at
the call site. If a double is available, the object in java/lang/Void.TYPE
is passed as the object value, and if an object value is available, then
0.0 is passed as the double value.
The receiving routine always tests the object value before proceeding.
If the parameter is being accessed in a 'Number Context' then the code
sequence is :
if ("parameter_objectValue" == java/lang/Void.TYPE)
...fine..., use the parameter_doubleValue
else
toNumber(parameter_objectValue)
and if the parameter is being referenced in an Object context, the code is
if ("parameter_objectValue" == java/lang/Void.TYPE)
new Double(parameter_doubleValue)
else
...fine..., use the parameter_objectValue
If the receiving code never uses the doubleValue, it is converted on
entry to a Double instead.
*/
/*
We're referencing a node in a Number context (i.e. we'd prefer it
was a double value). If the node is a parameter in a directCall
function, mark it as being referenced in this context.
*/
private void markDCPNumberContext(Node n)
{
if (inDirectCallFunction && n.getType() == Token.GETVAR) {
int varIndex = theFunction.getVarIndex(n);
if (theFunction.isParameter(varIndex)) {
parameterUsedInNumberContext = true;
}
}
}
private boolean convertParameter(Node n)
{
if (inDirectCallFunction && n.getType() == Token.GETVAR) {
int varIndex = theFunction.getVarIndex(n);
if (theFunction.isParameter(varIndex)) {
n.removeProp(Node.ISNUMBER_PROP);
return true;
}
}
return false;
}
private int rewriteForNumberVariables(Node n, int desired)
{
switch (n.getType()) {
case Token.EXPR_VOID : {
Node child = n.getFirstChild();
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType)
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NoType;
}
case Token.NUMBER :
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
case Token.GETVAR :
{
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex)
&& desired == NumberType)
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else if (theFunction.isNumberVar(varIndex)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
return NoType;
}
case Token.INC :
case Token.DEC : {
Node child = n.getFirstChild();
// "child" will be GETVAR or GETPROP or GETELEM
if (child.getType() == Token.GETVAR) {
- if (rewriteForNumberVariables(child, NumberType) == NumberType) {
+ ;
+ if (rewriteForNumberVariables(child, NumberType) == NumberType &&
+ !convertParameter(child))
+ {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(child);
return NumberType;
}
return NoType;
}
else if (child.getType() == Token.GETELEM) {
return rewriteForNumberVariables(child, NumberType);
}
return NoType;
}
case Token.SETVAR : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int rType = rewriteForNumberVariables(rChild, NumberType);
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex))
{
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
markDCPNumberContext(rChild);
return NoType;
}
else
return rType;
}
else if (theFunction.isNumberVar(varIndex)) {
if (rType != NumberType) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(rChild);
return NumberType;
}
else {
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_OBJECT, rChild));
}
}
return NoType;
}
}
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
} else if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
else if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
// we actually build a boolean value
return NoType;
}
case Token.ADD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
else {
if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP,
Node.RIGHT);
}
}
}
}
return NoType;
}
case Token.BITXOR :
case Token.BITOR :
case Token.BITAND :
case Token.RSH :
case Token.LSH :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
}
else {
if (rType == NumberType) {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
else {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
}
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
}
}
case Token.SETELEM :
case Token.SETELEM_OP : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
Node rValue = arrayIndex.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.setObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
int rValueType = rewriteForNumberVariables(rValue, NumberType);
if (rValueType == NumberType) {
if (!convertParameter(rValue)) {
n.removeChild(rValue);
n.addChildToBack(
new Node(Token.TO_OBJECT, rValue));
}
}
return NoType;
}
case Token.GETELEM : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.getObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
return NoType;
}
case Token.CALL :
{
Node child = n.getFirstChild(); // the function node
// must be an object
rewriteAsObjectChildren(child, child.getFirstChild());
child = child.getNext(); // the first arg
OptFunctionNode target
= (OptFunctionNode)n.getProp(Node.DIRECTCALL_PROP);
if (target != null) {
/*
we leave each child as a Number if it can be. The codegen will
handle moving the pairs of parameters.
*/
while (child != null) {
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType) {
markDCPNumberContext(child);
}
child = child.getNext();
}
} else {
rewriteAsObjectChildren(n, child);
}
return NoType;
}
default : {
rewriteAsObjectChildren(n, n.getFirstChild());
return NoType;
}
}
}
private void rewriteAsObjectChildren(Node n, Node child)
{
// Force optimized children to be objects
while (child != null) {
Node nextChild = child.getNext();
int type = rewriteForNumberVariables(child, NoType);
if (type == NumberType) {
if (!convertParameter(child)) {
n.removeChild(child);
Node nuChild = new Node(Token.TO_OBJECT, child);
if (nextChild == null)
n.addChildToBack(nuChild);
else
n.addChildBefore(nuChild, nextChild);
}
}
child = nextChild;
}
}
private static void buildStatementList_r(Node node, ObjArray statements)
{
int type = node.getType();
if (type == Token.BLOCK
|| type == Token.LOCAL_BLOCK
|| type == Token.LOOP
|| type == Token.FUNCTION)
{
Node child = node.getFirstChild();
while (child != null) {
buildStatementList_r(child, statements);
child = child.getNext();
}
} else {
statements.add(node);
}
}
private boolean inDirectCallFunction;
OptFunctionNode theFunction;
private boolean parameterUsedInNumberContext;
}
| true | true | private int rewriteForNumberVariables(Node n, int desired)
{
switch (n.getType()) {
case Token.EXPR_VOID : {
Node child = n.getFirstChild();
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType)
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NoType;
}
case Token.NUMBER :
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
case Token.GETVAR :
{
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex)
&& desired == NumberType)
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else if (theFunction.isNumberVar(varIndex)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
return NoType;
}
case Token.INC :
case Token.DEC : {
Node child = n.getFirstChild();
// "child" will be GETVAR or GETPROP or GETELEM
if (child.getType() == Token.GETVAR) {
if (rewriteForNumberVariables(child, NumberType) == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(child);
return NumberType;
}
return NoType;
}
else if (child.getType() == Token.GETELEM) {
return rewriteForNumberVariables(child, NumberType);
}
return NoType;
}
case Token.SETVAR : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int rType = rewriteForNumberVariables(rChild, NumberType);
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex))
{
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
markDCPNumberContext(rChild);
return NoType;
}
else
return rType;
}
else if (theFunction.isNumberVar(varIndex)) {
if (rType != NumberType) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(rChild);
return NumberType;
}
else {
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_OBJECT, rChild));
}
}
return NoType;
}
}
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
} else if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
else if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
// we actually build a boolean value
return NoType;
}
case Token.ADD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
else {
if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP,
Node.RIGHT);
}
}
}
}
return NoType;
}
case Token.BITXOR :
case Token.BITOR :
case Token.BITAND :
case Token.RSH :
case Token.LSH :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
}
else {
if (rType == NumberType) {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
else {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
}
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
}
}
case Token.SETELEM :
case Token.SETELEM_OP : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
Node rValue = arrayIndex.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.setObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
int rValueType = rewriteForNumberVariables(rValue, NumberType);
if (rValueType == NumberType) {
if (!convertParameter(rValue)) {
n.removeChild(rValue);
n.addChildToBack(
new Node(Token.TO_OBJECT, rValue));
}
}
return NoType;
}
case Token.GETELEM : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.getObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
return NoType;
}
case Token.CALL :
{
Node child = n.getFirstChild(); // the function node
// must be an object
rewriteAsObjectChildren(child, child.getFirstChild());
child = child.getNext(); // the first arg
OptFunctionNode target
= (OptFunctionNode)n.getProp(Node.DIRECTCALL_PROP);
if (target != null) {
/*
we leave each child as a Number if it can be. The codegen will
handle moving the pairs of parameters.
*/
while (child != null) {
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType) {
markDCPNumberContext(child);
}
child = child.getNext();
}
} else {
rewriteAsObjectChildren(n, child);
}
return NoType;
}
default : {
rewriteAsObjectChildren(n, n.getFirstChild());
return NoType;
}
}
}
| private int rewriteForNumberVariables(Node n, int desired)
{
switch (n.getType()) {
case Token.EXPR_VOID : {
Node child = n.getFirstChild();
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType)
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NoType;
}
case Token.NUMBER :
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
case Token.GETVAR :
{
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex)
&& desired == NumberType)
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else if (theFunction.isNumberVar(varIndex)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
return NoType;
}
case Token.INC :
case Token.DEC : {
Node child = n.getFirstChild();
// "child" will be GETVAR or GETPROP or GETELEM
if (child.getType() == Token.GETVAR) {
;
if (rewriteForNumberVariables(child, NumberType) == NumberType &&
!convertParameter(child))
{
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(child);
return NumberType;
}
return NoType;
}
else if (child.getType() == Token.GETELEM) {
return rewriteForNumberVariables(child, NumberType);
}
return NoType;
}
case Token.SETVAR : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int rType = rewriteForNumberVariables(rChild, NumberType);
int varIndex = theFunction.getVarIndex(n);
if (inDirectCallFunction
&& theFunction.isParameter(varIndex))
{
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
markDCPNumberContext(rChild);
return NoType;
}
else
return rType;
}
else if (theFunction.isNumberVar(varIndex)) {
if (rType != NumberType) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
markDCPNumberContext(rChild);
return NumberType;
}
else {
if (rType == NumberType) {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_OBJECT, rChild));
}
}
return NoType;
}
}
case Token.LE :
case Token.LT :
case Token.GE :
case Token.GT : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
} else if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
else if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
// we actually build a boolean value
return NoType;
}
case Token.ADD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
if (convertParameter(lChild)) {
if (convertParameter(rChild)) {
return NoType;
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
}
else {
if (convertParameter(rChild)) {
if (lType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
else {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP,
Node.RIGHT);
}
}
}
}
return NoType;
}
case Token.BITXOR :
case Token.BITOR :
case Token.BITAND :
case Token.RSH :
case Token.LSH :
case Token.SUB :
case Token.MUL :
case Token.DIV :
case Token.MOD : {
Node lChild = n.getFirstChild();
Node rChild = lChild.getNext();
int lType = rewriteForNumberVariables(lChild, NumberType);
int rType = rewriteForNumberVariables(rChild, NumberType);
markDCPNumberContext(lChild);
markDCPNumberContext(rChild);
if (lType == NumberType) {
if (rType == NumberType) {
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
else {
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
}
else {
if (rType == NumberType) {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
}
return NumberType;
}
else {
if (!convertParameter(lChild)) {
n.removeChild(lChild);
n.addChildToFront(
new Node(Token.TO_DOUBLE, lChild));
}
if (!convertParameter(rChild)) {
n.removeChild(rChild);
n.addChildToBack(
new Node(Token.TO_DOUBLE, rChild));
}
n.putIntProp(Node.ISNUMBER_PROP, Node.BOTH);
return NumberType;
}
}
}
case Token.SETELEM :
case Token.SETELEM_OP : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
Node rValue = arrayIndex.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.setObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.LEFT);
}
}
int rValueType = rewriteForNumberVariables(rValue, NumberType);
if (rValueType == NumberType) {
if (!convertParameter(rValue)) {
n.removeChild(rValue);
n.addChildToBack(
new Node(Token.TO_OBJECT, rValue));
}
}
return NoType;
}
case Token.GETELEM : {
Node arrayBase = n.getFirstChild();
Node arrayIndex = arrayBase.getNext();
int baseType = rewriteForNumberVariables(arrayBase, NumberType);
if (baseType == NumberType) {// can never happen ???
if (!convertParameter(arrayBase)) {
n.removeChild(arrayBase);
n.addChildToFront(
new Node(Token.TO_OBJECT, arrayBase));
}
}
int indexType = rewriteForNumberVariables(arrayIndex, NumberType);
if (indexType == NumberType) {
if (!convertParameter(arrayIndex)) {
// setting the ISNUMBER_PROP signals the codegen
// to use the OptRuntime.getObjectIndex that takes
// a double index
n.putIntProp(Node.ISNUMBER_PROP, Node.RIGHT);
}
}
return NoType;
}
case Token.CALL :
{
Node child = n.getFirstChild(); // the function node
// must be an object
rewriteAsObjectChildren(child, child.getFirstChild());
child = child.getNext(); // the first arg
OptFunctionNode target
= (OptFunctionNode)n.getProp(Node.DIRECTCALL_PROP);
if (target != null) {
/*
we leave each child as a Number if it can be. The codegen will
handle moving the pairs of parameters.
*/
while (child != null) {
int type = rewriteForNumberVariables(child, NumberType);
if (type == NumberType) {
markDCPNumberContext(child);
}
child = child.getNext();
}
} else {
rewriteAsObjectChildren(n, child);
}
return NoType;
}
default : {
rewriteAsObjectChildren(n, n.getFirstChild());
return NoType;
}
}
}
|
diff --git a/src/minecraft/dark/core/network/fluid/NetworkFluidContainers.java b/src/minecraft/dark/core/network/fluid/NetworkFluidContainers.java
index c0a8f277..cc15da7a 100644
--- a/src/minecraft/dark/core/network/fluid/NetworkFluidContainers.java
+++ b/src/minecraft/dark/core/network/fluid/NetworkFluidContainers.java
@@ -1,151 +1,155 @@
package dark.core.network.fluid;
import java.util.ArrayList;
import java.util.List;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.IFluidHandler;
import dark.api.ColorCode;
import dark.api.INetworkPart;
import dark.api.fluid.INetworkFluidPart;
import dark.core.tile.network.NetworkTileEntities;
/** Side note: the network should act like this when done {@link http
* ://www.e4training.com/hydraulic_calculators/B1.htm} as well as stay compatible with the forge
* Liquids
*
* @author Rseifert */
public class NetworkFluidContainers extends NetworkFluidTiles
{
public NetworkFluidContainers(ColorCode color, INetworkPart... parts)
{
super(color, parts);
}
@Override
public NetworkTileEntities newInstance()
{
return new NetworkFluidContainers(this.color);
}
@Override
public void writeDataToTiles()
{
+ if(this.combinedStorage() == null || this.combinedStorage().getFluid() == null)
+ {
+ return;
+ }
int fluid = this.combinedStorage().getFluid().fluidID;
int volume = Math.abs(this.combinedStorage().getFluid().amount);
NBTTagCompound tag = this.combinedStorage().getFluid().tag;
int lowestY = 255;
int highestY = 0;
this.cleanUpMembers();
if (this.combinedStorage().getFluid() != null && this.getNetworkMemebers().size() > 0)
{
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof IFluidHandler)
{
((INetworkFluidPart) part).setTankContent(null);
}
if (part instanceof TileEntity && ((TileEntity) part).yCoord < lowestY)
{
lowestY = ((TileEntity) part).yCoord;
}
if (part instanceof TileEntity && ((TileEntity) part).yCoord > highestY)
{
highestY = ((TileEntity) part).yCoord;
}
}
//TODO change this to use hydraulics to not only place fluid at the lowest but as well not move it to another side if there is no path there threw fluid
for (int y = lowestY; y <= highestY; y++)
{
/** List of parts for this Y level */
List<INetworkFluidPart> parts = new ArrayList<INetworkFluidPart>();
/* Grab all parts that share this Y level*/
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof INetworkFluidPart && ((TileEntity) part).yCoord == y)
{
parts.add((INetworkFluidPart) part);
}
}
if (!parts.isEmpty())
{
/* Div out the volume for this level. TODO change this to use a percent system for even filling */
int fillvolume = Math.abs(volume / parts.size());
/* Fill all tanks on this level */
for (INetworkFluidPart part : parts)
{
int fill = Math.min(fillvolume, part.getTank().getCapacity());
part.setTankContent(new FluidStack(fluid, fill, tag));
volume -= fill;
}
}
if (volume <= 0)
{
break;
}
}
}
}
@Override
public int storeFluidInSystem(FluidStack stack, boolean doFill)
{
int vol = this.combinedStorage().getFluid() != null ? this.combinedStorage().getFluid().amount : 0;
int filled = super.storeFluidInSystem(stack, doFill);
if (vol != filled)
{
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof TileEntity)
{
TileEntity ent = ((TileEntity) part);
ent.worldObj.markBlockForUpdate(ent.xCoord, ent.yCoord, ent.zCoord);
}
}
}
return filled;
}
@Override
public FluidStack drainFluidFromSystem(int maxDrain, boolean doDrain)
{
FluidStack vol = this.combinedStorage().getFluid();
FluidStack stack = super.drainFluidFromSystem(maxDrain, doDrain);
boolean flag = false;
if (vol != null)
{
if (stack == null)
{
flag = true;
}
else if (stack.amount != vol.amount)
{
flag = true;
}
}
if (flag)
{
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof TileEntity)
{
TileEntity ent = ((TileEntity) part);
ent.worldObj.markBlockForUpdate(ent.xCoord, ent.yCoord, ent.zCoord);
}
}
}
return stack;
}
}
| true | true | public void writeDataToTiles()
{
int fluid = this.combinedStorage().getFluid().fluidID;
int volume = Math.abs(this.combinedStorage().getFluid().amount);
NBTTagCompound tag = this.combinedStorage().getFluid().tag;
int lowestY = 255;
int highestY = 0;
this.cleanUpMembers();
if (this.combinedStorage().getFluid() != null && this.getNetworkMemebers().size() > 0)
{
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof IFluidHandler)
{
((INetworkFluidPart) part).setTankContent(null);
}
if (part instanceof TileEntity && ((TileEntity) part).yCoord < lowestY)
{
lowestY = ((TileEntity) part).yCoord;
}
if (part instanceof TileEntity && ((TileEntity) part).yCoord > highestY)
{
highestY = ((TileEntity) part).yCoord;
}
}
//TODO change this to use hydraulics to not only place fluid at the lowest but as well not move it to another side if there is no path there threw fluid
for (int y = lowestY; y <= highestY; y++)
{
/** List of parts for this Y level */
List<INetworkFluidPart> parts = new ArrayList<INetworkFluidPart>();
/* Grab all parts that share this Y level*/
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof INetworkFluidPart && ((TileEntity) part).yCoord == y)
{
parts.add((INetworkFluidPart) part);
}
}
if (!parts.isEmpty())
{
/* Div out the volume for this level. TODO change this to use a percent system for even filling */
int fillvolume = Math.abs(volume / parts.size());
/* Fill all tanks on this level */
for (INetworkFluidPart part : parts)
{
int fill = Math.min(fillvolume, part.getTank().getCapacity());
part.setTankContent(new FluidStack(fluid, fill, tag));
volume -= fill;
}
}
if (volume <= 0)
{
break;
}
}
}
}
| public void writeDataToTiles()
{
if(this.combinedStorage() == null || this.combinedStorage().getFluid() == null)
{
return;
}
int fluid = this.combinedStorage().getFluid().fluidID;
int volume = Math.abs(this.combinedStorage().getFluid().amount);
NBTTagCompound tag = this.combinedStorage().getFluid().tag;
int lowestY = 255;
int highestY = 0;
this.cleanUpMembers();
if (this.combinedStorage().getFluid() != null && this.getNetworkMemebers().size() > 0)
{
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof IFluidHandler)
{
((INetworkFluidPart) part).setTankContent(null);
}
if (part instanceof TileEntity && ((TileEntity) part).yCoord < lowestY)
{
lowestY = ((TileEntity) part).yCoord;
}
if (part instanceof TileEntity && ((TileEntity) part).yCoord > highestY)
{
highestY = ((TileEntity) part).yCoord;
}
}
//TODO change this to use hydraulics to not only place fluid at the lowest but as well not move it to another side if there is no path there threw fluid
for (int y = lowestY; y <= highestY; y++)
{
/** List of parts for this Y level */
List<INetworkFluidPart> parts = new ArrayList<INetworkFluidPart>();
/* Grab all parts that share this Y level*/
for (INetworkPart part : this.getNetworkMemebers())
{
if (part instanceof INetworkFluidPart && ((TileEntity) part).yCoord == y)
{
parts.add((INetworkFluidPart) part);
}
}
if (!parts.isEmpty())
{
/* Div out the volume for this level. TODO change this to use a percent system for even filling */
int fillvolume = Math.abs(volume / parts.size());
/* Fill all tanks on this level */
for (INetworkFluidPart part : parts)
{
int fill = Math.min(fillvolume, part.getTank().getCapacity());
part.setTankContent(new FluidStack(fluid, fill, tag));
volume -= fill;
}
}
if (volume <= 0)
{
break;
}
}
}
}
|
diff --git a/src/main/java/net/pms/network/RequestHandler.java b/src/main/java/net/pms/network/RequestHandler.java
index 937cdb9b9..8a4a145a1 100644
--- a/src/main/java/net/pms/network/RequestHandler.java
+++ b/src/main/java/net/pms/network/RequestHandler.java
@@ -1,288 +1,288 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.network;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.StringTokenizer;
import net.pms.PMS;
import net.pms.configuration.RendererConfiguration;
import net.pms.external.StartStopListenerDelegate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RequestHandler implements Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(RequestHandler.class);
public final static int SOCKET_BUF_SIZE = 32768;
private Socket socket;
private OutputStream output;
private BufferedReader br;
// Used to filter out known headers when the renderer is not recognized
private final static String[] KNOWN_HEADERS = {
"Accept",
"Accept-Language",
"Accept-Encoding",
"Callback",
"Connection",
"Content-Length",
"Content-Type",
"Date",
"Host",
"Nt",
"Sid",
"Timeout",
"User-Agent"
};
public RequestHandler(Socket socket) throws IOException {
this.socket = socket;
this.output = socket.getOutputStream();
this.br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
@Override
public void run() {
Request request = null;
StartStopListenerDelegate startStopListenerDelegate = new StartStopListenerDelegate(socket.getInetAddress().getHostAddress());
try {
int receivedContentLength = -1;
String headerLine = br.readLine();
String userAgentString = null;
StringBuilder unknownHeaders = new StringBuilder();
String separator = "";
RendererConfiguration renderer = null;
InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
InetAddress ia = remoteAddress.getAddress();
// Apply the IP filter
if (filterIp(ia)) {
throw new IOException("Access denied for address " + ia + " based on IP filter");
}
LOGGER.trace("Opened request handler on socket " + socket);
PMS.get().getRegistry().disableGoToSleep();
while (headerLine != null && headerLine.length() > 0) {
LOGGER.trace("Received on socket: " + headerLine);
// The request object is created inside the while loop.
if (request != null && request.getMediaRenderer() == null) {
// The handler makes a couple of attempts to recognize a renderer from its requests.
// IP address matches from previous requests are preferred, when that fails request
// header matches are attempted and if those fail as well we're stuck with the
// default renderer.
// Attempt 1: try to recognize the renderer by its socket address from previous requests
renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(ia);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on address " + ia);
}
}
if (renderer == null && headerLine != null
&& headerLine.toUpperCase().startsWith("USER-AGENT")
&& request != null) {
userAgentString = headerLine.substring(headerLine.indexOf(":") + 1).trim();
// Attempt 2: try to recognize the renderer by matching the "User-Agent" header
renderer = RendererConfiguration.getRendererConfigurationByUA(userAgentString);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
renderer.associateIP(ia); // Associate IP address for later requests
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on header \"" + headerLine + "\"");
}
}
if (renderer == null && headerLine != null && request != null) {
// Attempt 3: try to recognize the renderer by matching an additional header
renderer = RendererConfiguration.getRendererConfigurationByUAAHH(headerLine);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
renderer.associateIP(ia); // Associate IP address for later requests
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on header \"" + headerLine + "\"");
}
}
try {
StringTokenizer s = new StringTokenizer(headerLine);
String temp = s.nextToken();
if (temp.equals("SUBSCRIBE") || temp.equals("GET") || temp.equals("POST") || temp.equals("HEAD")) {
request = new Request(temp, s.nextToken().substring(1));
if (s.hasMoreTokens() && s.nextToken().equals("HTTP/1.0")) {
request.setHttp10(true);
}
} else if (request != null && temp.toUpperCase().equals("CALLBACK:")) {
request.setSoapaction(s.nextToken());
} else if (request != null && temp.toUpperCase().equals("SOAPACTION:")) {
request.setSoapaction(s.nextToken());
} else if (headerLine.toUpperCase().contains("CONTENT-LENGTH:")) {
receivedContentLength = Integer.parseInt(headerLine.substring(headerLine.toUpperCase().indexOf("CONTENT-LENGTH: ") + 16));
} else if (headerLine.toUpperCase().indexOf("RANGE: BYTES=") > -1) {
String nums = headerLine.substring(headerLine.toUpperCase().indexOf("RANGE: BYTES=") + 13).trim();
StringTokenizer st = new StringTokenizer(nums, "-");
if (!nums.startsWith("-")) {
request.setLowRange(Long.parseLong(st.nextToken()));
}
if (!nums.startsWith("-") && !nums.endsWith("-")) {
request.setHighRange(Long.parseLong(st.nextToken()));
} else {
request.setHighRange(-1);
}
} else if (headerLine.toLowerCase().indexOf("transfermode.dlna.org:") > -1) {
request.setTransferMode(headerLine.substring(headerLine.toLowerCase().indexOf("transfermode.dlna.org:") + 22).trim());
} else if (headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") > -1) {
request.setContentFeatures(headerLine.substring(headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") + 28).trim());
} else if (headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") > -1) { // firmware 2.50+
String timeseek = headerLine.substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") + 28);
if (timeseek.endsWith("-")) {
timeseek = timeseek.substring(0, timeseek.length() - 1);
} else if (timeseek.indexOf("-") > -1) {
timeseek = timeseek.substring(0, timeseek.indexOf("-"));
}
request.setTimeseek(Double.parseDouble(timeseek));
} else if (headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") > -1) { // firmware 2.40
String timeseek = headerLine.substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") + 29);
if (timeseek.endsWith("-")) {
timeseek = timeseek.substring(0, timeseek.length() - 1);
} else if (timeseek.indexOf("-") > -1) {
timeseek = timeseek.substring(0, timeseek.indexOf("-"));
}
request.setTimeseek(Double.parseDouble(timeseek));
} else {
/*
* If we made it to here, none of the previous header checks matched.
* Unknown headers make interesting logging info when we cannot recognize
* the media renderer, so keep track of the truly unknown ones.
*/
boolean isKnown = false;
// Try to match possible known headers.
for (String knownHeaderString : KNOWN_HEADERS) {
if (headerLine.toLowerCase().startsWith(knownHeaderString.toLowerCase())) {
isKnown = true;
break;
}
}
if (!isKnown) {
// Truly unknown header, therefore interesting. Save for later use.
unknownHeaders.append(separator).append(headerLine);
separator = ", ";
}
}
} catch (Exception e) {
LOGGER.error("Error in parsing HTTP headers", e);
}
headerLine = br.readLine();
}
if (request != null) {
// Still no media renderer recognized?
if (request.getMediaRenderer() == null) {
// Attempt 4: Not really an attempt; all other attempts to recognize
// the renderer have failed. The only option left is to assume the
// default renderer.
request.setMediaRenderer(RendererConfiguration.getDefaultConf());
LOGGER.trace("Using default media renderer " + request.getMediaRenderer().getRendererName());
if (userAgentString != null && !userAgentString.equals("FDSSDP")) {
// We have found an unknown renderer
LOGGER.info("Media renderer was not recognized. Possible identifying HTTP headers: User-Agent: " + userAgentString
+ ("".equals(unknownHeaders.toString()) ? "" : ", " + unknownHeaders.toString()));
PMS.get().setRendererfound(request.getMediaRenderer());
}
} else {
if (userAgentString != null) {
LOGGER.trace("HTTP User-Agent: " + userAgentString);
}
LOGGER.trace("Recognized media renderer " + request.getMediaRenderer().getRendererName());
}
}
if (receivedContentLength > 0) {
char buf[] = new char[receivedContentLength];
br.read(buf);
if (request != null) {
request.setTextContent(new String(buf));
}
}
if (request != null) {
LOGGER.trace("HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-" + request.getHighRange());
}
if (request != null) {
request.answer(output, startStopListenerDelegate);
}
if (request != null && request.getInputStream() != null) {
request.getInputStream().close();
}
} catch (IOException e) {
LOGGER.trace("Unexpected IO error: " + e.getClass().getName() + ": " + e.getMessage());
if (request != null && request.getInputStream() != null) {
try {
LOGGER.trace("Closing input stream: " + request.getInputStream());
request.getInputStream().close();
} catch (IOException e1) {
- LOGGER.error("Error closing input stream", e);
+ LOGGER.error("Error closing input stream", e1);
}
}
} finally {
try {
PMS.get().getRegistry().reenableGoToSleep();
output.close();
br.close();
socket.close();
} catch (IOException e) {
LOGGER.error("Error closing connection: ", e);
}
startStopListenerDelegate.stop();
LOGGER.trace("Close connection");
}
}
/**
* Applies the IP filter to the specified internet address. Returns true
* if the address is not allowed and therefore should be filtered out,
* false otherwise.
*
* @param inetAddress The internet address to verify.
* @return True when not allowed, false otherwise.
*/
private boolean filterIp(InetAddress inetAddress) {
return !PMS.getConfiguration().getIpFiltering().allowed(inetAddress);
}
}
| true | true | public void run() {
Request request = null;
StartStopListenerDelegate startStopListenerDelegate = new StartStopListenerDelegate(socket.getInetAddress().getHostAddress());
try {
int receivedContentLength = -1;
String headerLine = br.readLine();
String userAgentString = null;
StringBuilder unknownHeaders = new StringBuilder();
String separator = "";
RendererConfiguration renderer = null;
InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
InetAddress ia = remoteAddress.getAddress();
// Apply the IP filter
if (filterIp(ia)) {
throw new IOException("Access denied for address " + ia + " based on IP filter");
}
LOGGER.trace("Opened request handler on socket " + socket);
PMS.get().getRegistry().disableGoToSleep();
while (headerLine != null && headerLine.length() > 0) {
LOGGER.trace("Received on socket: " + headerLine);
// The request object is created inside the while loop.
if (request != null && request.getMediaRenderer() == null) {
// The handler makes a couple of attempts to recognize a renderer from its requests.
// IP address matches from previous requests are preferred, when that fails request
// header matches are attempted and if those fail as well we're stuck with the
// default renderer.
// Attempt 1: try to recognize the renderer by its socket address from previous requests
renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(ia);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on address " + ia);
}
}
if (renderer == null && headerLine != null
&& headerLine.toUpperCase().startsWith("USER-AGENT")
&& request != null) {
userAgentString = headerLine.substring(headerLine.indexOf(":") + 1).trim();
// Attempt 2: try to recognize the renderer by matching the "User-Agent" header
renderer = RendererConfiguration.getRendererConfigurationByUA(userAgentString);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
renderer.associateIP(ia); // Associate IP address for later requests
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on header \"" + headerLine + "\"");
}
}
if (renderer == null && headerLine != null && request != null) {
// Attempt 3: try to recognize the renderer by matching an additional header
renderer = RendererConfiguration.getRendererConfigurationByUAAHH(headerLine);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
renderer.associateIP(ia); // Associate IP address for later requests
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on header \"" + headerLine + "\"");
}
}
try {
StringTokenizer s = new StringTokenizer(headerLine);
String temp = s.nextToken();
if (temp.equals("SUBSCRIBE") || temp.equals("GET") || temp.equals("POST") || temp.equals("HEAD")) {
request = new Request(temp, s.nextToken().substring(1));
if (s.hasMoreTokens() && s.nextToken().equals("HTTP/1.0")) {
request.setHttp10(true);
}
} else if (request != null && temp.toUpperCase().equals("CALLBACK:")) {
request.setSoapaction(s.nextToken());
} else if (request != null && temp.toUpperCase().equals("SOAPACTION:")) {
request.setSoapaction(s.nextToken());
} else if (headerLine.toUpperCase().contains("CONTENT-LENGTH:")) {
receivedContentLength = Integer.parseInt(headerLine.substring(headerLine.toUpperCase().indexOf("CONTENT-LENGTH: ") + 16));
} else if (headerLine.toUpperCase().indexOf("RANGE: BYTES=") > -1) {
String nums = headerLine.substring(headerLine.toUpperCase().indexOf("RANGE: BYTES=") + 13).trim();
StringTokenizer st = new StringTokenizer(nums, "-");
if (!nums.startsWith("-")) {
request.setLowRange(Long.parseLong(st.nextToken()));
}
if (!nums.startsWith("-") && !nums.endsWith("-")) {
request.setHighRange(Long.parseLong(st.nextToken()));
} else {
request.setHighRange(-1);
}
} else if (headerLine.toLowerCase().indexOf("transfermode.dlna.org:") > -1) {
request.setTransferMode(headerLine.substring(headerLine.toLowerCase().indexOf("transfermode.dlna.org:") + 22).trim());
} else if (headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") > -1) {
request.setContentFeatures(headerLine.substring(headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") + 28).trim());
} else if (headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") > -1) { // firmware 2.50+
String timeseek = headerLine.substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") + 28);
if (timeseek.endsWith("-")) {
timeseek = timeseek.substring(0, timeseek.length() - 1);
} else if (timeseek.indexOf("-") > -1) {
timeseek = timeseek.substring(0, timeseek.indexOf("-"));
}
request.setTimeseek(Double.parseDouble(timeseek));
} else if (headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") > -1) { // firmware 2.40
String timeseek = headerLine.substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") + 29);
if (timeseek.endsWith("-")) {
timeseek = timeseek.substring(0, timeseek.length() - 1);
} else if (timeseek.indexOf("-") > -1) {
timeseek = timeseek.substring(0, timeseek.indexOf("-"));
}
request.setTimeseek(Double.parseDouble(timeseek));
} else {
/*
* If we made it to here, none of the previous header checks matched.
* Unknown headers make interesting logging info when we cannot recognize
* the media renderer, so keep track of the truly unknown ones.
*/
boolean isKnown = false;
// Try to match possible known headers.
for (String knownHeaderString : KNOWN_HEADERS) {
if (headerLine.toLowerCase().startsWith(knownHeaderString.toLowerCase())) {
isKnown = true;
break;
}
}
if (!isKnown) {
// Truly unknown header, therefore interesting. Save for later use.
unknownHeaders.append(separator).append(headerLine);
separator = ", ";
}
}
} catch (Exception e) {
LOGGER.error("Error in parsing HTTP headers", e);
}
headerLine = br.readLine();
}
if (request != null) {
// Still no media renderer recognized?
if (request.getMediaRenderer() == null) {
// Attempt 4: Not really an attempt; all other attempts to recognize
// the renderer have failed. The only option left is to assume the
// default renderer.
request.setMediaRenderer(RendererConfiguration.getDefaultConf());
LOGGER.trace("Using default media renderer " + request.getMediaRenderer().getRendererName());
if (userAgentString != null && !userAgentString.equals("FDSSDP")) {
// We have found an unknown renderer
LOGGER.info("Media renderer was not recognized. Possible identifying HTTP headers: User-Agent: " + userAgentString
+ ("".equals(unknownHeaders.toString()) ? "" : ", " + unknownHeaders.toString()));
PMS.get().setRendererfound(request.getMediaRenderer());
}
} else {
if (userAgentString != null) {
LOGGER.trace("HTTP User-Agent: " + userAgentString);
}
LOGGER.trace("Recognized media renderer " + request.getMediaRenderer().getRendererName());
}
}
if (receivedContentLength > 0) {
char buf[] = new char[receivedContentLength];
br.read(buf);
if (request != null) {
request.setTextContent(new String(buf));
}
}
if (request != null) {
LOGGER.trace("HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-" + request.getHighRange());
}
if (request != null) {
request.answer(output, startStopListenerDelegate);
}
if (request != null && request.getInputStream() != null) {
request.getInputStream().close();
}
} catch (IOException e) {
LOGGER.trace("Unexpected IO error: " + e.getClass().getName() + ": " + e.getMessage());
if (request != null && request.getInputStream() != null) {
try {
LOGGER.trace("Closing input stream: " + request.getInputStream());
request.getInputStream().close();
} catch (IOException e1) {
LOGGER.error("Error closing input stream", e);
}
}
} finally {
try {
PMS.get().getRegistry().reenableGoToSleep();
output.close();
br.close();
socket.close();
} catch (IOException e) {
LOGGER.error("Error closing connection: ", e);
}
startStopListenerDelegate.stop();
LOGGER.trace("Close connection");
}
}
| public void run() {
Request request = null;
StartStopListenerDelegate startStopListenerDelegate = new StartStopListenerDelegate(socket.getInetAddress().getHostAddress());
try {
int receivedContentLength = -1;
String headerLine = br.readLine();
String userAgentString = null;
StringBuilder unknownHeaders = new StringBuilder();
String separator = "";
RendererConfiguration renderer = null;
InetSocketAddress remoteAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
InetAddress ia = remoteAddress.getAddress();
// Apply the IP filter
if (filterIp(ia)) {
throw new IOException("Access denied for address " + ia + " based on IP filter");
}
LOGGER.trace("Opened request handler on socket " + socket);
PMS.get().getRegistry().disableGoToSleep();
while (headerLine != null && headerLine.length() > 0) {
LOGGER.trace("Received on socket: " + headerLine);
// The request object is created inside the while loop.
if (request != null && request.getMediaRenderer() == null) {
// The handler makes a couple of attempts to recognize a renderer from its requests.
// IP address matches from previous requests are preferred, when that fails request
// header matches are attempted and if those fail as well we're stuck with the
// default renderer.
// Attempt 1: try to recognize the renderer by its socket address from previous requests
renderer = RendererConfiguration.getRendererConfigurationBySocketAddress(ia);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on address " + ia);
}
}
if (renderer == null && headerLine != null
&& headerLine.toUpperCase().startsWith("USER-AGENT")
&& request != null) {
userAgentString = headerLine.substring(headerLine.indexOf(":") + 1).trim();
// Attempt 2: try to recognize the renderer by matching the "User-Agent" header
renderer = RendererConfiguration.getRendererConfigurationByUA(userAgentString);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
renderer.associateIP(ia); // Associate IP address for later requests
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on header \"" + headerLine + "\"");
}
}
if (renderer == null && headerLine != null && request != null) {
// Attempt 3: try to recognize the renderer by matching an additional header
renderer = RendererConfiguration.getRendererConfigurationByUAAHH(headerLine);
if (renderer != null) {
PMS.get().setRendererfound(renderer);
request.setMediaRenderer(renderer);
renderer.associateIP(ia); // Associate IP address for later requests
LOGGER.trace("Matched media renderer \"" + renderer.getRendererName() + "\" based on header \"" + headerLine + "\"");
}
}
try {
StringTokenizer s = new StringTokenizer(headerLine);
String temp = s.nextToken();
if (temp.equals("SUBSCRIBE") || temp.equals("GET") || temp.equals("POST") || temp.equals("HEAD")) {
request = new Request(temp, s.nextToken().substring(1));
if (s.hasMoreTokens() && s.nextToken().equals("HTTP/1.0")) {
request.setHttp10(true);
}
} else if (request != null && temp.toUpperCase().equals("CALLBACK:")) {
request.setSoapaction(s.nextToken());
} else if (request != null && temp.toUpperCase().equals("SOAPACTION:")) {
request.setSoapaction(s.nextToken());
} else if (headerLine.toUpperCase().contains("CONTENT-LENGTH:")) {
receivedContentLength = Integer.parseInt(headerLine.substring(headerLine.toUpperCase().indexOf("CONTENT-LENGTH: ") + 16));
} else if (headerLine.toUpperCase().indexOf("RANGE: BYTES=") > -1) {
String nums = headerLine.substring(headerLine.toUpperCase().indexOf("RANGE: BYTES=") + 13).trim();
StringTokenizer st = new StringTokenizer(nums, "-");
if (!nums.startsWith("-")) {
request.setLowRange(Long.parseLong(st.nextToken()));
}
if (!nums.startsWith("-") && !nums.endsWith("-")) {
request.setHighRange(Long.parseLong(st.nextToken()));
} else {
request.setHighRange(-1);
}
} else if (headerLine.toLowerCase().indexOf("transfermode.dlna.org:") > -1) {
request.setTransferMode(headerLine.substring(headerLine.toLowerCase().indexOf("transfermode.dlna.org:") + 22).trim());
} else if (headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") > -1) {
request.setContentFeatures(headerLine.substring(headerLine.toLowerCase().indexOf("getcontentfeatures.dlna.org:") + 28).trim());
} else if (headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") > -1) { // firmware 2.50+
String timeseek = headerLine.substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG: NPT=") + 28);
if (timeseek.endsWith("-")) {
timeseek = timeseek.substring(0, timeseek.length() - 1);
} else if (timeseek.indexOf("-") > -1) {
timeseek = timeseek.substring(0, timeseek.indexOf("-"));
}
request.setTimeseek(Double.parseDouble(timeseek));
} else if (headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") > -1) { // firmware 2.40
String timeseek = headerLine.substring(headerLine.toUpperCase().indexOf("TIMESEEKRANGE.DLNA.ORG : NPT=") + 29);
if (timeseek.endsWith("-")) {
timeseek = timeseek.substring(0, timeseek.length() - 1);
} else if (timeseek.indexOf("-") > -1) {
timeseek = timeseek.substring(0, timeseek.indexOf("-"));
}
request.setTimeseek(Double.parseDouble(timeseek));
} else {
/*
* If we made it to here, none of the previous header checks matched.
* Unknown headers make interesting logging info when we cannot recognize
* the media renderer, so keep track of the truly unknown ones.
*/
boolean isKnown = false;
// Try to match possible known headers.
for (String knownHeaderString : KNOWN_HEADERS) {
if (headerLine.toLowerCase().startsWith(knownHeaderString.toLowerCase())) {
isKnown = true;
break;
}
}
if (!isKnown) {
// Truly unknown header, therefore interesting. Save for later use.
unknownHeaders.append(separator).append(headerLine);
separator = ", ";
}
}
} catch (Exception e) {
LOGGER.error("Error in parsing HTTP headers", e);
}
headerLine = br.readLine();
}
if (request != null) {
// Still no media renderer recognized?
if (request.getMediaRenderer() == null) {
// Attempt 4: Not really an attempt; all other attempts to recognize
// the renderer have failed. The only option left is to assume the
// default renderer.
request.setMediaRenderer(RendererConfiguration.getDefaultConf());
LOGGER.trace("Using default media renderer " + request.getMediaRenderer().getRendererName());
if (userAgentString != null && !userAgentString.equals("FDSSDP")) {
// We have found an unknown renderer
LOGGER.info("Media renderer was not recognized. Possible identifying HTTP headers: User-Agent: " + userAgentString
+ ("".equals(unknownHeaders.toString()) ? "" : ", " + unknownHeaders.toString()));
PMS.get().setRendererfound(request.getMediaRenderer());
}
} else {
if (userAgentString != null) {
LOGGER.trace("HTTP User-Agent: " + userAgentString);
}
LOGGER.trace("Recognized media renderer " + request.getMediaRenderer().getRendererName());
}
}
if (receivedContentLength > 0) {
char buf[] = new char[receivedContentLength];
br.read(buf);
if (request != null) {
request.setTextContent(new String(buf));
}
}
if (request != null) {
LOGGER.trace("HTTP: " + request.getArgument() + " / " + request.getLowRange() + "-" + request.getHighRange());
}
if (request != null) {
request.answer(output, startStopListenerDelegate);
}
if (request != null && request.getInputStream() != null) {
request.getInputStream().close();
}
} catch (IOException e) {
LOGGER.trace("Unexpected IO error: " + e.getClass().getName() + ": " + e.getMessage());
if (request != null && request.getInputStream() != null) {
try {
LOGGER.trace("Closing input stream: " + request.getInputStream());
request.getInputStream().close();
} catch (IOException e1) {
LOGGER.error("Error closing input stream", e1);
}
}
} finally {
try {
PMS.get().getRegistry().reenableGoToSleep();
output.close();
br.close();
socket.close();
} catch (IOException e) {
LOGGER.error("Error closing connection: ", e);
}
startStopListenerDelegate.stop();
LOGGER.trace("Close connection");
}
}
|
diff --git a/stella-boleto/src/main/java/br/com/caelum/stella/boleto/transformer/PNGPDFTransformerHelper.java b/stella-boleto/src/main/java/br/com/caelum/stella/boleto/transformer/PNGPDFTransformerHelper.java
index 9ed8e95d..a355f6f1 100644
--- a/stella-boleto/src/main/java/br/com/caelum/stella/boleto/transformer/PNGPDFTransformerHelper.java
+++ b/stella-boleto/src/main/java/br/com/caelum/stella/boleto/transformer/PNGPDFTransformerHelper.java
@@ -1,217 +1,217 @@
package br.com.caelum.stella.boleto.transformer;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.Calendar;
import javax.imageio.ImageIO;
import br.com.caelum.stella.boleto.Boleto;
import br.com.caelum.stella.boleto.CriacaoBoletoException;
import br.com.caelum.stella.boleto.GeracaoBoletoException;
import br.com.caelum.stella.boleto.bancos.LinhaDigitavelGenerator;
/**
* Classe que centraliza a cria��o dos boletos que tem como template o
* template.png e antes ficava no BoletoTransformer
*
*
*/
class PNGPDFTransformerHelper {
/*Ainda precisa de um nome melhor!!*/
public static final float IMAGEM_BOLETO_WIDTH = 2144;
public static final float IMAGEM_BOLETO_HEIGHT = 1604;
public static final double BOLETO_TEMPLATE_SCALE = 1 / 2d;
private static final float LINHA1 = 434;
private static final float LINHA2 = 412;
private static final float LINHA3 = 391;
private static final float LINHA4 = 319;
private static final float LINHA5 = 291;
private static final float LINHA6 = 271;
private static final float LINHA7 = 250;
private static final float LINHA8 = 227;
private static final float LINHA9 = 205;
private static final float LINHA10 = 132;
private static final float LINHA11 = 97;
private static final float LINHA12 = 87;
private static final float LINHA13 = 77;
private TextWriter writer;
private URL imagemTitulo;
public PNGPDFTransformerHelper(TextWriter writer) {
super();
this.writer = writer;
this.imagemTitulo = PNGPDFTransformerHelper.class
.getResource("/br/com/caelum/stella/boleto/img/template.png");
}
/**
*
* @param boleto
* @return
*/
public TextWriter transform(Boleto boleto) {
// gera template com o fundo do boleto
try {
this.writer.writeImage(0, 55, imageFor(imagemTitulo), 514.22f,
385.109f);
this.writer.writeImage(0, 805 - 486, imageFor(boleto.getBanco()
.getImage()), 100, 23);
} catch (IOException e) {
throw new GeracaoBoletoException(
"Erro na leitura das imagens do boleto", e);
}
for (int i = 0; i < boleto.getDescricoes().size(); i++) {
this.writer.writeBold(5, 805 - 70 - i * 15, boleto.getDescricoes()
.get(i));
}
this.writer.write(50, LINHA1, boleto.getEmissor().getCedente());
this.writer.write(5, LINHA2, boleto.getSacado().getNome());
this.writer.write(230, LINHA2, formatDate(boleto.getDatas()
.getVencimento()));
this.writer.write(400, LINHA2, BoletoFormatter.formatValue(boleto
.getValorBoleto().doubleValue()));
this.writer.write(5, LINHA3, boleto.getEmissor().getAgenciaFormatado()
+ "-"
+ boleto.getEmissor().getDvAgencia()
+ " / "
+ boleto.getBanco().getContaCorrenteDoEmissorFormatado(
boleto.getEmissor()) + "-"
+ boleto.getEmissor().getDvContaCorrente());
this.writer.write(146, LINHA3, boleto.getBanco()
.getNossoNumeroDoEmissorFormatado(boleto.getEmissor()));
this.writer.writeBold(125, LINHA4, boleto.getBanco()
.getNumeroFormatado());
LinhaDigitavelGenerator linhaDigitavelGenerator = new LinhaDigitavelGenerator();
this.writer.writeBold(175, LINHA4, linhaDigitavelGenerator
.geraLinhaDigitavelPara(boleto));
for (int i = 0; i < boleto.getLocaisDePagamento().size(); i++) {
this.writer.write(5, LINHA5 - (i - 1) * 10, boleto
.getLocaisDePagamento().get(i));
}
this.writer.write(425, LINHA5, formatDate(boleto.getDatas()
.getVencimento()));
this.writer.write(5, LINHA6, boleto.getEmissor().getCedente());
this.writer.write(420, LINHA6, boleto.getEmissor()
.getAgenciaFormatado()
+ " - "
+ boleto.getEmissor().getDvAgencia()
+ " / "
+ boleto.getBanco().getContaCorrenteDoEmissorFormatado(
boleto.getEmissor())
+ "-"
+ boleto.getEmissor().getDvContaCorrente());
this.writer.write(5, LINHA7, formatDate(boleto.getDatas()
.getDocumento()));
this.writer.write(70, LINHA7,
!boleto.getNoDocumento().equals("") ? boleto
.getNoDocumentoFormatado() : boleto.getBanco()
.getNossoNumeroDoEmissorFormatado(boleto.getEmissor()));
this.writer.write(180, LINHA7, boleto.getEspecieDocumento());
this.writer.write(250, LINHA7, boleto.getAceite() ? "S" : "N");
this.writer.write(300, LINHA7, formatDate(boleto.getDatas()
.getProcessamento()));
this.writer.write(410, LINHA7, boleto.getEmissor().getCarteira()
+ " / "
+ boleto.getBanco().getNossoNumeroDoEmissorFormatado(
boleto.getEmissor()));
this.writer.write(122, LINHA8, boleto.getBanco()
.getCarteiraDoEmissorFormatado(boleto.getEmissor()));
this.writer.write(190, LINHA8, boleto.getEspecieMoeda());
this.writer.write(430, LINHA8, BoletoFormatter.formatValue(boleto
.getValorBoleto().doubleValue()));
for (int i = 0; i < boleto.getInstrucoes().size(); i++) {
this.writer
.write(5, LINHA9 - i * 10, boleto.getInstrucoes().get(i));
}
this.writer.write(5, LINHA10, boleto.getEmissor().getCedente());
- this.writer.write(100, LINHA11, boleto.getSacado().getNome() + " "
- + boleto.getSacado().getCpf());
+ this.writer.write(100, LINHA11, (boleto.getSacado().getNome() != null ? boleto.getSacado().getNome() : "") + " "
+ + (boleto.getSacado().getCpf() != null ? boleto.getSacado().getCpf() : ""));
- this.writer.write(100, LINHA12, boleto.getSacado().getEndereco());
+ this.writer.write(100, LINHA12, (boleto.getSacado().getEndereco() != null ? boleto.getSacado().getEndereco() : ""));
- this.writer.write(100, LINHA13, boleto.getSacado().getCep() + " "
- + boleto.getSacado().getBairro() + " - "
- + boleto.getSacado().getCidade() + " "
- + boleto.getSacado().getUf());
+ this.writer.write(100, LINHA13, (boleto.getSacado().getCep() != null ? boleto.getSacado().getCep() : "") + " "
+ + (boleto.getSacado().getBairro() != null ? boleto.getSacado().getBairro() : "") + " - "
+ + (boleto.getSacado().getCidade() != null ? boleto.getSacado().getCidade() : "") + " "
+ + (boleto.getSacado().getUf() != null ? boleto.getSacado().getUf() : ""));
Image imagemDoCodigoDeBarras = BarcodeGenerator
.generateBarcodeFor(boleto.getBanco().geraCodigoDeBarrasPara(
boleto),37.00f);
try {
this.writer.writeImage(40, 10, toBufferedImage(
imagemDoCodigoDeBarras, BufferedImage.TYPE_INT_ARGB),
imagemDoCodigoDeBarras.getWidth(null),
imagemDoCodigoDeBarras.getHeight(null));
} catch (IOException e) {
throw new CriacaoBoletoException(
"Erro na geração do código de barras", e);
}
return writer;
}
/**
* Converte um Image em um BufferedImage
*
* @param image
* @param type
*/
private BufferedImage toBufferedImage(Image image, int type) {
return BufferedImageGenerator.generateBufferedImageFor(image,type);
}
/**
* Abre um arquivo em um BufferedImage
*
* @param file
* @return
* @throws IOException
*/
private BufferedImage imageFor(URL file) throws IOException {
return ImageIO.read(file);
}
/**
* Formata uma data para dd/mm/yyyy
*
* @param date
* @return
*/
private String formatDate(Calendar date) {
return BoletoFormatter.formatDate(date);
}
}
| false | true | public TextWriter transform(Boleto boleto) {
// gera template com o fundo do boleto
try {
this.writer.writeImage(0, 55, imageFor(imagemTitulo), 514.22f,
385.109f);
this.writer.writeImage(0, 805 - 486, imageFor(boleto.getBanco()
.getImage()), 100, 23);
} catch (IOException e) {
throw new GeracaoBoletoException(
"Erro na leitura das imagens do boleto", e);
}
for (int i = 0; i < boleto.getDescricoes().size(); i++) {
this.writer.writeBold(5, 805 - 70 - i * 15, boleto.getDescricoes()
.get(i));
}
this.writer.write(50, LINHA1, boleto.getEmissor().getCedente());
this.writer.write(5, LINHA2, boleto.getSacado().getNome());
this.writer.write(230, LINHA2, formatDate(boleto.getDatas()
.getVencimento()));
this.writer.write(400, LINHA2, BoletoFormatter.formatValue(boleto
.getValorBoleto().doubleValue()));
this.writer.write(5, LINHA3, boleto.getEmissor().getAgenciaFormatado()
+ "-"
+ boleto.getEmissor().getDvAgencia()
+ " / "
+ boleto.getBanco().getContaCorrenteDoEmissorFormatado(
boleto.getEmissor()) + "-"
+ boleto.getEmissor().getDvContaCorrente());
this.writer.write(146, LINHA3, boleto.getBanco()
.getNossoNumeroDoEmissorFormatado(boleto.getEmissor()));
this.writer.writeBold(125, LINHA4, boleto.getBanco()
.getNumeroFormatado());
LinhaDigitavelGenerator linhaDigitavelGenerator = new LinhaDigitavelGenerator();
this.writer.writeBold(175, LINHA4, linhaDigitavelGenerator
.geraLinhaDigitavelPara(boleto));
for (int i = 0; i < boleto.getLocaisDePagamento().size(); i++) {
this.writer.write(5, LINHA5 - (i - 1) * 10, boleto
.getLocaisDePagamento().get(i));
}
this.writer.write(425, LINHA5, formatDate(boleto.getDatas()
.getVencimento()));
this.writer.write(5, LINHA6, boleto.getEmissor().getCedente());
this.writer.write(420, LINHA6, boleto.getEmissor()
.getAgenciaFormatado()
+ " - "
+ boleto.getEmissor().getDvAgencia()
+ " / "
+ boleto.getBanco().getContaCorrenteDoEmissorFormatado(
boleto.getEmissor())
+ "-"
+ boleto.getEmissor().getDvContaCorrente());
this.writer.write(5, LINHA7, formatDate(boleto.getDatas()
.getDocumento()));
this.writer.write(70, LINHA7,
!boleto.getNoDocumento().equals("") ? boleto
.getNoDocumentoFormatado() : boleto.getBanco()
.getNossoNumeroDoEmissorFormatado(boleto.getEmissor()));
this.writer.write(180, LINHA7, boleto.getEspecieDocumento());
this.writer.write(250, LINHA7, boleto.getAceite() ? "S" : "N");
this.writer.write(300, LINHA7, formatDate(boleto.getDatas()
.getProcessamento()));
this.writer.write(410, LINHA7, boleto.getEmissor().getCarteira()
+ " / "
+ boleto.getBanco().getNossoNumeroDoEmissorFormatado(
boleto.getEmissor()));
this.writer.write(122, LINHA8, boleto.getBanco()
.getCarteiraDoEmissorFormatado(boleto.getEmissor()));
this.writer.write(190, LINHA8, boleto.getEspecieMoeda());
this.writer.write(430, LINHA8, BoletoFormatter.formatValue(boleto
.getValorBoleto().doubleValue()));
for (int i = 0; i < boleto.getInstrucoes().size(); i++) {
this.writer
.write(5, LINHA9 - i * 10, boleto.getInstrucoes().get(i));
}
this.writer.write(5, LINHA10, boleto.getEmissor().getCedente());
this.writer.write(100, LINHA11, boleto.getSacado().getNome() + " "
+ boleto.getSacado().getCpf());
this.writer.write(100, LINHA12, boleto.getSacado().getEndereco());
this.writer.write(100, LINHA13, boleto.getSacado().getCep() + " "
+ boleto.getSacado().getBairro() + " - "
+ boleto.getSacado().getCidade() + " "
+ boleto.getSacado().getUf());
Image imagemDoCodigoDeBarras = BarcodeGenerator
.generateBarcodeFor(boleto.getBanco().geraCodigoDeBarrasPara(
boleto),37.00f);
try {
this.writer.writeImage(40, 10, toBufferedImage(
imagemDoCodigoDeBarras, BufferedImage.TYPE_INT_ARGB),
imagemDoCodigoDeBarras.getWidth(null),
imagemDoCodigoDeBarras.getHeight(null));
} catch (IOException e) {
throw new CriacaoBoletoException(
"Erro na geração do código de barras", e);
}
return writer;
}
| public TextWriter transform(Boleto boleto) {
// gera template com o fundo do boleto
try {
this.writer.writeImage(0, 55, imageFor(imagemTitulo), 514.22f,
385.109f);
this.writer.writeImage(0, 805 - 486, imageFor(boleto.getBanco()
.getImage()), 100, 23);
} catch (IOException e) {
throw new GeracaoBoletoException(
"Erro na leitura das imagens do boleto", e);
}
for (int i = 0; i < boleto.getDescricoes().size(); i++) {
this.writer.writeBold(5, 805 - 70 - i * 15, boleto.getDescricoes()
.get(i));
}
this.writer.write(50, LINHA1, boleto.getEmissor().getCedente());
this.writer.write(5, LINHA2, boleto.getSacado().getNome());
this.writer.write(230, LINHA2, formatDate(boleto.getDatas()
.getVencimento()));
this.writer.write(400, LINHA2, BoletoFormatter.formatValue(boleto
.getValorBoleto().doubleValue()));
this.writer.write(5, LINHA3, boleto.getEmissor().getAgenciaFormatado()
+ "-"
+ boleto.getEmissor().getDvAgencia()
+ " / "
+ boleto.getBanco().getContaCorrenteDoEmissorFormatado(
boleto.getEmissor()) + "-"
+ boleto.getEmissor().getDvContaCorrente());
this.writer.write(146, LINHA3, boleto.getBanco()
.getNossoNumeroDoEmissorFormatado(boleto.getEmissor()));
this.writer.writeBold(125, LINHA4, boleto.getBanco()
.getNumeroFormatado());
LinhaDigitavelGenerator linhaDigitavelGenerator = new LinhaDigitavelGenerator();
this.writer.writeBold(175, LINHA4, linhaDigitavelGenerator
.geraLinhaDigitavelPara(boleto));
for (int i = 0; i < boleto.getLocaisDePagamento().size(); i++) {
this.writer.write(5, LINHA5 - (i - 1) * 10, boleto
.getLocaisDePagamento().get(i));
}
this.writer.write(425, LINHA5, formatDate(boleto.getDatas()
.getVencimento()));
this.writer.write(5, LINHA6, boleto.getEmissor().getCedente());
this.writer.write(420, LINHA6, boleto.getEmissor()
.getAgenciaFormatado()
+ " - "
+ boleto.getEmissor().getDvAgencia()
+ " / "
+ boleto.getBanco().getContaCorrenteDoEmissorFormatado(
boleto.getEmissor())
+ "-"
+ boleto.getEmissor().getDvContaCorrente());
this.writer.write(5, LINHA7, formatDate(boleto.getDatas()
.getDocumento()));
this.writer.write(70, LINHA7,
!boleto.getNoDocumento().equals("") ? boleto
.getNoDocumentoFormatado() : boleto.getBanco()
.getNossoNumeroDoEmissorFormatado(boleto.getEmissor()));
this.writer.write(180, LINHA7, boleto.getEspecieDocumento());
this.writer.write(250, LINHA7, boleto.getAceite() ? "S" : "N");
this.writer.write(300, LINHA7, formatDate(boleto.getDatas()
.getProcessamento()));
this.writer.write(410, LINHA7, boleto.getEmissor().getCarteira()
+ " / "
+ boleto.getBanco().getNossoNumeroDoEmissorFormatado(
boleto.getEmissor()));
this.writer.write(122, LINHA8, boleto.getBanco()
.getCarteiraDoEmissorFormatado(boleto.getEmissor()));
this.writer.write(190, LINHA8, boleto.getEspecieMoeda());
this.writer.write(430, LINHA8, BoletoFormatter.formatValue(boleto
.getValorBoleto().doubleValue()));
for (int i = 0; i < boleto.getInstrucoes().size(); i++) {
this.writer
.write(5, LINHA9 - i * 10, boleto.getInstrucoes().get(i));
}
this.writer.write(5, LINHA10, boleto.getEmissor().getCedente());
this.writer.write(100, LINHA11, (boleto.getSacado().getNome() != null ? boleto.getSacado().getNome() : "") + " "
+ (boleto.getSacado().getCpf() != null ? boleto.getSacado().getCpf() : ""));
this.writer.write(100, LINHA12, (boleto.getSacado().getEndereco() != null ? boleto.getSacado().getEndereco() : ""));
this.writer.write(100, LINHA13, (boleto.getSacado().getCep() != null ? boleto.getSacado().getCep() : "") + " "
+ (boleto.getSacado().getBairro() != null ? boleto.getSacado().getBairro() : "") + " - "
+ (boleto.getSacado().getCidade() != null ? boleto.getSacado().getCidade() : "") + " "
+ (boleto.getSacado().getUf() != null ? boleto.getSacado().getUf() : ""));
Image imagemDoCodigoDeBarras = BarcodeGenerator
.generateBarcodeFor(boleto.getBanco().geraCodigoDeBarrasPara(
boleto),37.00f);
try {
this.writer.writeImage(40, 10, toBufferedImage(
imagemDoCodigoDeBarras, BufferedImage.TYPE_INT_ARGB),
imagemDoCodigoDeBarras.getWidth(null),
imagemDoCodigoDeBarras.getHeight(null));
} catch (IOException e) {
throw new CriacaoBoletoException(
"Erro na geração do código de barras", e);
}
return writer;
}
|
diff --git a/src/com/android/gallery3d/ui/TileImageView.java b/src/com/android/gallery3d/ui/TileImageView.java
index eb5da891..7e811fc0 100644
--- a/src/com/android/gallery3d/ui/TileImageView.java
+++ b/src/com/android/gallery3d/ui/TileImageView.java
@@ -1,757 +1,757 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.gallery3d.ui;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.FloatMath;
import android.util.LongSparseArray;
import com.android.gallery3d.app.GalleryContext;
import com.android.gallery3d.common.Utils;
import com.android.gallery3d.data.DecodeUtils;
import com.android.gallery3d.util.Future;
import com.android.gallery3d.util.ThreadPool;
import com.android.gallery3d.util.ThreadPool.CancelListener;
import com.android.gallery3d.util.ThreadPool.JobContext;
import java.util.concurrent.atomic.AtomicBoolean;
public class TileImageView extends GLView {
public static final int SIZE_UNKNOWN = -1;
@SuppressWarnings("unused")
private static final String TAG = "TileImageView";
// TILE_SIZE must be 2^N - 2. We put one pixel border in each side of the
// texture to avoid seams between tiles.
private static final int TILE_SIZE = 254;
private static final int TILE_BORDER = 1;
private static final int UPLOAD_LIMIT = 1;
/*
* This is the tile state in the CPU side.
* Life of a Tile:
* ACTIVATED (initial state)
* --> IN_QUEUE - by queueForDecode()
* --> RECYCLED - by recycleTile()
* IN_QUEUE --> DECODING - by decodeTile()
* --> RECYCLED - by recycleTile)
* DECODING --> RECYCLING - by recycleTile()
* --> DECODED - by decodeTile()
* --> DECODE_FAIL - by decodeTile()
* RECYCLING --> RECYCLED - by decodeTile()
* DECODED --> ACTIVATED - (after the decoded bitmap is uploaded)
* DECODED --> RECYCLED - by recycleTile()
* DECODE_FAIL -> RECYCLED - by recycleTile()
* RECYCLED --> ACTIVATED - by obtainTile()
*/
private static final int STATE_ACTIVATED = 0x01;
private static final int STATE_IN_QUEUE = 0x02;
private static final int STATE_DECODING = 0x04;
private static final int STATE_DECODED = 0x08;
private static final int STATE_DECODE_FAIL = 0x10;
private static final int STATE_RECYCLING = 0x20;
private static final int STATE_RECYCLED = 0x40;
private Model mModel;
private ScreenNail mScreenNail;
protected int mLevelCount; // cache the value of mScaledBitmaps.length
// The mLevel variable indicates which level of bitmap we should use.
// Level 0 means the original full-sized bitmap, and a larger value means
// a smaller scaled bitmap (The width and height of each scaled bitmap is
// half size of the previous one). If the value is in [0, mLevelCount), we
// use the bitmap in mScaledBitmaps[mLevel] for display, otherwise the value
// is mLevelCount, and that means we use mScreenNail for display.
private int mLevel = 0;
// The offsets of the (left, top) of the upper-left tile to the (left, top)
// of the view.
private int mOffsetX;
private int mOffsetY;
private int mUploadQuota;
private boolean mRenderComplete;
private final RectF mSourceRect = new RectF();
private final RectF mTargetRect = new RectF();
private final LongSparseArray<Tile> mActiveTiles = new LongSparseArray<Tile>();
// The following three queue is guarded by TileImageView.this
private TileQueue mRecycledQueue = new TileQueue();
private TileQueue mUploadQueue = new TileQueue();
private TileQueue mDecodeQueue = new TileQueue();
// The width and height of the full-sized bitmap
protected int mImageWidth = SIZE_UNKNOWN;
protected int mImageHeight = SIZE_UNKNOWN;
protected int mCenterX;
protected int mCenterY;
protected float mScale;
protected int mRotation;
protected float mAlpha = 1.0f;
// Temp variables to avoid memory allocation
private final Rect mTileRange = new Rect();
private final Rect mActiveRange[] = {new Rect(), new Rect()};
private final TileUploader mTileUploader = new TileUploader();
private boolean mIsTextureFreed;
private Future<Void> mTileDecoder;
private ThreadPool mThreadPool;
private boolean mBackgroundTileUploaded;
public static interface Model {
public int getLevelCount();
public ScreenNail getScreenNail();
public int getImageWidth();
public int getImageHeight();
// The tile returned by this method can be specified this way: Assuming
// the image size is (width, height), first take the intersection of (0,
// 0) - (width, height) and (x, y) - (x + tileSize, y + tileSize). Then
// extend this intersection region by borderSize pixels on each side. If
// in extending the region, we found some part of the region are outside
// the image, those pixels are filled with black.
//
// If level > 0, it does the same operation on a down-scaled version of
// the original image (down-scaled by a factor of 2^level), but (x, y)
// still refers to the coordinate on the original image.
//
// The method would be called in another thread.
public Bitmap getTile(int level, int x, int y, int tileSize,
int borderSize);
public boolean isFailedToLoad();
}
public TileImageView(GalleryContext context) {
mThreadPool = context.getThreadPool();
mTileDecoder = mThreadPool.submit(new TileDecoder());
}
public void setModel(Model model) {
mModel = model;
if (model != null) notifyModelInvalidated();
}
public void setScreenNail(ScreenNail s) {
mScreenNail = s;
}
public void notifyModelInvalidated() {
invalidateTiles();
if (mModel == null) {
mScreenNail = null;
mImageWidth = 0;
mImageHeight = 0;
mLevelCount = 0;
} else {
setScreenNail(mModel.getScreenNail());
mImageWidth = mModel.getImageWidth();
mImageHeight = mModel.getImageHeight();
mLevelCount = mModel.getLevelCount();
}
layoutTiles(mCenterX, mCenterY, mScale, mRotation);
invalidate();
}
@Override
protected void onLayout(
boolean changeSize, int left, int top, int right, int bottom) {
super.onLayout(changeSize, left, top, right, bottom);
if (changeSize) layoutTiles(mCenterX, mCenterY, mScale, mRotation);
}
// Prepare the tiles we want to use for display.
//
// 1. Decide the tile level we want to use for display.
// 2. Decide the tile levels we want to keep as texture (in addition to
// the one we use for display).
// 3. Recycle unused tiles.
// 4. Activate the tiles we want.
private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
// The width and height of this view.
int width = getWidth();
int height = getHeight();
// The tile levels we want to keep as texture is in the range
// [fromLevel, endLevel).
int fromLevel;
int endLevel;
// We want to use a texture larger than or equal to the display size.
mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
// We want to keep one more tile level as texture in addition to what
// we use for display. So it can be faster when the scale moves to the
// next level. We choose a level closer to the current scale.
if (mLevel != mLevelCount) {
Rect range = mTileRange;
getRange(range, centerX, centerY, mLevel, scale, rotation);
mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
} else {
// Activate the tiles of the smallest two levels.
fromLevel = mLevel - 2;
mOffsetX = Math.round(width / 2f - centerX * scale);
mOffsetY = Math.round(height / 2f - centerY * scale);
}
fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
endLevel = Math.min(fromLevel + 2, mLevelCount);
Rect range[] = mActiveRange;
for (int i = fromLevel; i < endLevel; ++i) {
getRange(range[i - fromLevel], centerX, centerY, i, rotation);
}
// If rotation is transient, don't update the tile.
if (rotation % 90 != 0) return;
synchronized (this) {
mDecodeQueue.clean();
mUploadQueue.clean();
mBackgroundTileUploaded = false;
- }
- // Recycle unused tiles: if the level of the active tile is outside the
- // range [fromLevel, endLevel) or not in the visible range.
- int n = mActiveTiles.size();
- for (int i = 0; i < n; i++) {
- Tile tile = mActiveTiles.valueAt(i);
- int level = tile.mTileLevel;
- if (level < fromLevel || level >= endLevel
- || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
- mActiveTiles.removeAt(i);
- i--;
- n--;
- recycleTile(tile);
+ // Recycle unused tiles: if the level of the active tile is outside the
+ // range [fromLevel, endLevel) or not in the visible range.
+ int n = mActiveTiles.size();
+ for (int i = 0; i < n; i++) {
+ Tile tile = mActiveTiles.valueAt(i);
+ int level = tile.mTileLevel;
+ if (level < fromLevel || level >= endLevel
+ || !range[level - fromLevel].contains(tile.mX, tile.mY)) {
+ mActiveTiles.removeAt(i);
+ i--;
+ n--;
+ recycleTile(tile);
+ }
}
}
for (int i = fromLevel; i < endLevel; ++i) {
int size = TILE_SIZE << i;
Rect r = range[i - fromLevel];
for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
for (int x = r.left, right = r.right; x < right; x += size) {
activateTile(x, y, i);
}
}
}
invalidate();
}
protected synchronized void invalidateTiles() {
mDecodeQueue.clean();
mUploadQueue.clean();
// TODO disable decoder
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
recycleTile(tile);
}
mActiveTiles.clear();
}
private void getRange(Rect out, int cX, int cY, int level, int rotation) {
getRange(out, cX, cY, level, 1f / (1 << (level + 1)), rotation);
}
// If the bitmap is scaled by the given factor "scale", return the
// rectangle containing visible range. The left-top coordinate returned is
// aligned to the tile boundary.
//
// (cX, cY) is the point on the original bitmap which will be put in the
// center of the ImageViewer.
private void getRange(Rect out,
int cX, int cY, int level, float scale, int rotation) {
double radians = Math.toRadians(-rotation);
double w = getWidth();
double h = getHeight();
double cos = Math.cos(radians);
double sin = Math.sin(radians);
int width = (int) Math.ceil(Math.max(
Math.abs(cos * w - sin * h), Math.abs(cos * w + sin * h)));
int height = (int) Math.ceil(Math.max(
Math.abs(sin * w + cos * h), Math.abs(sin * w - cos * h)));
int left = (int) FloatMath.floor(cX - width / (2f * scale));
int top = (int) FloatMath.floor(cY - height / (2f * scale));
int right = (int) FloatMath.ceil(left + width / scale);
int bottom = (int) FloatMath.ceil(top + height / scale);
// align the rectangle to tile boundary
int size = TILE_SIZE << level;
left = Math.max(0, size * (left / size));
top = Math.max(0, size * (top / size));
right = Math.min(mImageWidth, right);
bottom = Math.min(mImageHeight, bottom);
out.set(left, top, right, bottom);
}
// Calculate where the center of the image is, in the view coordinates.
public void getImageCenter(Point center) {
// The width and height of this view.
int viewW = getWidth();
int viewH = getHeight();
// The distance between the center of the view to the center of the
// bitmap, in bitmap units. (mCenterX and mCenterY are the bitmap
// coordinates correspond to the center of view)
int distW, distH;
if (mRotation % 180 == 0) {
distW = mImageWidth / 2 - mCenterX;
distH = mImageHeight / 2 - mCenterY;
} else {
distW = mImageHeight / 2 - mCenterY;
distH = mImageWidth / 2 - mCenterX;
}
// Convert to view coordinates. mScale translates from bitmap units to
// view units.
center.x = Math.round(viewW / 2f + distW * mScale);
center.y = Math.round(viewH / 2f + distH * mScale);
}
public boolean setPosition(int centerX, int centerY, float scale, int rotation) {
if (mCenterX == centerX && mCenterY == centerY
&& mScale == scale && mRotation == rotation) return false;
mCenterX = centerX;
mCenterY = centerY;
mScale = scale;
mRotation = rotation;
layoutTiles(centerX, centerY, scale, rotation);
invalidate();
return true;
}
public boolean setAlpha(float alpha) {
if (mAlpha == alpha) return false;
mAlpha = alpha;
invalidate();
return true;
}
public void freeTextures() {
mIsTextureFreed = true;
if (mTileDecoder != null) {
mTileDecoder.cancel();
mTileDecoder.get();
mTileDecoder = null;
}
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile texture = mActiveTiles.valueAt(i);
texture.recycle();
}
mActiveTiles.clear();
mTileRange.set(0, 0, 0, 0);
synchronized (this) {
mUploadQueue.clean();
mDecodeQueue.clean();
Tile tile = mRecycledQueue.pop();
while (tile != null) {
tile.recycle();
tile = mRecycledQueue.pop();
}
}
setScreenNail(null);
}
public void prepareTextures() {
if (mTileDecoder == null) {
mTileDecoder = mThreadPool.submit(new TileDecoder());
}
if (mIsTextureFreed) {
layoutTiles(mCenterX, mCenterY, mScale, mRotation);
mIsTextureFreed = false;
setScreenNail(mModel == null ? null : mModel.getScreenNail());
}
}
@Override
protected void render(GLCanvas canvas) {
mUploadQuota = UPLOAD_LIMIT;
mRenderComplete = true;
int level = mLevel;
int rotation = mRotation;
int flags = 0;
if (rotation != 0) flags |= GLCanvas.SAVE_FLAG_MATRIX;
if (mAlpha != 1.0f) flags |= GLCanvas.SAVE_FLAG_ALPHA;
if (flags != 0) {
canvas.save(flags);
if (rotation != 0) {
int centerX = getWidth() / 2, centerY = getHeight() / 2;
canvas.translate(centerX, centerY);
canvas.rotate(rotation, 0, 0, 1);
canvas.translate(-centerX, -centerY);
}
if (mAlpha != 1.0f) canvas.multiplyAlpha(mAlpha);
}
try {
if (level != mLevelCount) {
if (mScreenNail != null) {
mScreenNail.noDraw();
}
int size = (TILE_SIZE << level);
float length = size * mScale;
Rect r = mTileRange;
for (int ty = r.top, i = 0; ty < r.bottom; ty += size, i++) {
float y = mOffsetY + i * length;
for (int tx = r.left, j = 0; tx < r.right; tx += size, j++) {
float x = mOffsetX + j * length;
drawTile(canvas, tx, ty, level, x, y, length);
}
}
} else if (mScreenNail != null) {
mScreenNail.draw(canvas, mOffsetX, mOffsetY,
Math.round(mImageWidth * mScale),
Math.round(mImageHeight * mScale));
}
} finally {
if (flags != 0) canvas.restore();
}
if (mRenderComplete) {
if (!mBackgroundTileUploaded) uploadBackgroundTiles(canvas);
} else {
invalidate();
}
}
private void uploadBackgroundTiles(GLCanvas canvas) {
mBackgroundTileUploaded = true;
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
if (!tile.isContentValid(canvas)) queueForDecode(tile);
}
}
void queueForUpload(Tile tile) {
synchronized (this) {
mUploadQueue.push(tile);
}
if (mTileUploader.mActive.compareAndSet(false, true)) {
getGLRoot().addOnGLIdleListener(mTileUploader);
}
}
synchronized void queueForDecode(Tile tile) {
if (tile.mTileState == STATE_ACTIVATED) {
tile.mTileState = STATE_IN_QUEUE;
if (mDecodeQueue.push(tile)) notifyAll();
}
}
boolean decodeTile(Tile tile) {
synchronized (this) {
if (tile.mTileState != STATE_IN_QUEUE) return false;
tile.mTileState = STATE_DECODING;
}
boolean decodeComplete = tile.decode();
synchronized (this) {
if (tile.mTileState == STATE_RECYCLING) {
tile.mTileState = STATE_RECYCLED;
tile.mDecodedTile = null;
mRecycledQueue.push(tile);
return false;
}
tile.mTileState = decodeComplete ? STATE_DECODED : STATE_DECODE_FAIL;
return decodeComplete;
}
}
private synchronized Tile obtainTile(int x, int y, int level) {
Tile tile = mRecycledQueue.pop();
if (tile != null) {
tile.mTileState = STATE_ACTIVATED;
tile.update(x, y, level);
return tile;
}
return new Tile(x, y, level);
}
synchronized void recycleTile(Tile tile) {
if (tile.mTileState == STATE_DECODING) {
tile.mTileState = STATE_RECYCLING;
return;
}
tile.mTileState = STATE_RECYCLED;
tile.mDecodedTile = null;
mRecycledQueue.push(tile);
}
private void activateTile(int x, int y, int level) {
long key = makeTileKey(x, y, level);
Tile tile = mActiveTiles.get(key);
if (tile != null) {
if (tile.mTileState == STATE_IN_QUEUE) {
tile.mTileState = STATE_ACTIVATED;
}
return;
}
tile = obtainTile(x, y, level);
mActiveTiles.put(key, tile);
}
private Tile getTile(int x, int y, int level) {
return mActiveTiles.get(makeTileKey(x, y, level));
}
private static long makeTileKey(int x, int y, int level) {
long result = x;
result = (result << 16) | y;
result = (result << 16) | level;
return result;
}
private class TileUploader implements GLRoot.OnGLIdleListener {
AtomicBoolean mActive = new AtomicBoolean(false);
@Override
public boolean onGLIdle(GLCanvas canvas, boolean renderRequested) {
if (renderRequested) return false;
int quota = UPLOAD_LIMIT;
Tile tile;
while (true) {
synchronized (TileImageView.this) {
tile = mUploadQueue.pop();
}
if (tile == null || quota <= 0) break;
if (!tile.isContentValid(canvas)) {
Utils.assertTrue(tile.mTileState == STATE_DECODED);
tile.updateContent(canvas);
--quota;
}
}
mActive.set(tile != null);
return tile != null;
}
}
// Draw the tile to a square at canvas that locates at (x, y) and
// has a side length of length.
public void drawTile(GLCanvas canvas,
int tx, int ty, int level, float x, float y, float length) {
RectF source = mSourceRect;
RectF target = mTargetRect;
target.set(x, y, x + length, y + length);
source.set(0, 0, TILE_SIZE, TILE_SIZE);
Tile tile = getTile(tx, ty, level);
if (tile != null) {
if (!tile.isContentValid(canvas)) {
if (tile.mTileState == STATE_DECODED) {
if (mUploadQuota > 0) {
--mUploadQuota;
tile.updateContent(canvas);
} else {
mRenderComplete = false;
}
} else if (tile.mTileState != STATE_DECODE_FAIL){
mRenderComplete = false;
queueForDecode(tile);
}
}
if (drawTile(tile, canvas, source, target)) return;
}
if (mScreenNail != null) {
int size = TILE_SIZE << level;
float scaleX = (float) mScreenNail.getWidth() / mImageWidth;
float scaleY = (float) mScreenNail.getHeight() / mImageHeight;
source.set(tx * scaleX, ty * scaleY, (tx + size) * scaleX,
(ty + size) * scaleY);
mScreenNail.draw(canvas, source, target);
}
}
// TODO: avoid drawing the unused part of the textures.
static boolean drawTile(
Tile tile, GLCanvas canvas, RectF source, RectF target) {
while (true) {
if (tile.isContentValid(canvas)) {
// offset source rectangle for the texture border.
source.offset(TILE_BORDER, TILE_BORDER);
canvas.drawTexture(tile, source, target);
return true;
}
// Parent can be divided to four quads and tile is one of the four.
Tile parent = tile.getParentTile();
if (parent == null) return false;
if (tile.mX == parent.mX) {
source.left /= 2f;
source.right /= 2f;
} else {
source.left = (TILE_SIZE + source.left) / 2f;
source.right = (TILE_SIZE + source.right) / 2f;
}
if (tile.mY == parent.mY) {
source.top /= 2f;
source.bottom /= 2f;
} else {
source.top = (TILE_SIZE + source.top) / 2f;
source.bottom = (TILE_SIZE + source.bottom) / 2f;
}
tile = parent;
}
}
private class Tile extends UploadedTexture {
int mX;
int mY;
int mTileLevel;
Tile mNext;
Bitmap mDecodedTile;
volatile int mTileState = STATE_ACTIVATED;
public Tile(int x, int y, int level) {
mX = x;
mY = y;
mTileLevel = level;
}
@Override
protected void onFreeBitmap(Bitmap bitmap) {
bitmap.recycle();
}
boolean decode() {
// Get a tile from the original image. The tile is down-scaled
// by (1 << mTilelevel) from a region in the original image.
try {
mDecodedTile = DecodeUtils.ensureGLCompatibleBitmap(mModel.getTile(
mTileLevel, mX, mY, TILE_SIZE, TILE_BORDER));
} catch (Throwable t) {
Log.w(TAG, "fail to decode tile", t);
}
return mDecodedTile != null;
}
@Override
protected Bitmap onGetBitmap() {
Utils.assertTrue(mTileState == STATE_DECODED);
Bitmap bitmap = mDecodedTile;
mDecodedTile = null;
mTileState = STATE_ACTIVATED;
return bitmap;
}
// We override getTextureWidth() and getTextureHeight() here, so the
// texture can be re-used for different tiles regardless of the actual
// size of the tile (which may be small because it is a tile at the
// boundary).
@Override
public int getTextureWidth() {
return TILE_SIZE + TILE_BORDER * 2;
}
@Override
public int getTextureHeight() {
return TILE_SIZE + TILE_BORDER * 2;
}
public void update(int x, int y, int level) {
mX = x;
mY = y;
mTileLevel = level;
invalidateContent();
}
public Tile getParentTile() {
if (mTileLevel + 1 == mLevelCount) return null;
int size = TILE_SIZE << (mTileLevel + 1);
int x = size * (mX / size);
int y = size * (mY / size);
return getTile(x, y, mTileLevel + 1);
}
@Override
public String toString() {
return String.format("tile(%s, %s, %s / %s)",
mX / TILE_SIZE, mY / TILE_SIZE, mLevel, mLevelCount);
}
}
private static class TileQueue {
private Tile mHead;
public Tile pop() {
Tile tile = mHead;
if (tile != null) mHead = tile.mNext;
return tile;
}
public boolean push(Tile tile) {
boolean wasEmpty = mHead == null;
tile.mNext = mHead;
mHead = tile;
return wasEmpty;
}
public void clean() {
mHead = null;
}
}
private class TileDecoder implements ThreadPool.Job<Void> {
private CancelListener mNotifier = new CancelListener() {
@Override
public void onCancel() {
synchronized (TileImageView.this) {
TileImageView.this.notifyAll();
}
}
};
@Override
public Void run(JobContext jc) {
jc.setMode(ThreadPool.MODE_NONE);
jc.setCancelListener(mNotifier);
while (!jc.isCancelled()) {
Tile tile = null;
synchronized(TileImageView.this) {
tile = mDecodeQueue.pop();
if (tile == null && !jc.isCancelled()) {
Utils.waitWithoutInterrupt(TileImageView.this);
}
}
if (tile == null) continue;
if (decodeTile(tile)) queueForUpload(tile);
}
return null;
}
}
}
| false | true | private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
// The width and height of this view.
int width = getWidth();
int height = getHeight();
// The tile levels we want to keep as texture is in the range
// [fromLevel, endLevel).
int fromLevel;
int endLevel;
// We want to use a texture larger than or equal to the display size.
mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
// We want to keep one more tile level as texture in addition to what
// we use for display. So it can be faster when the scale moves to the
// next level. We choose a level closer to the current scale.
if (mLevel != mLevelCount) {
Rect range = mTileRange;
getRange(range, centerX, centerY, mLevel, scale, rotation);
mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
} else {
// Activate the tiles of the smallest two levels.
fromLevel = mLevel - 2;
mOffsetX = Math.round(width / 2f - centerX * scale);
mOffsetY = Math.round(height / 2f - centerY * scale);
}
fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
endLevel = Math.min(fromLevel + 2, mLevelCount);
Rect range[] = mActiveRange;
for (int i = fromLevel; i < endLevel; ++i) {
getRange(range[i - fromLevel], centerX, centerY, i, rotation);
}
// If rotation is transient, don't update the tile.
if (rotation % 90 != 0) return;
synchronized (this) {
mDecodeQueue.clean();
mUploadQueue.clean();
mBackgroundTileUploaded = false;
}
// Recycle unused tiles: if the level of the active tile is outside the
// range [fromLevel, endLevel) or not in the visible range.
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
int level = tile.mTileLevel;
if (level < fromLevel || level >= endLevel
|| !range[level - fromLevel].contains(tile.mX, tile.mY)) {
mActiveTiles.removeAt(i);
i--;
n--;
recycleTile(tile);
}
}
for (int i = fromLevel; i < endLevel; ++i) {
int size = TILE_SIZE << i;
Rect r = range[i - fromLevel];
for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
for (int x = r.left, right = r.right; x < right; x += size) {
activateTile(x, y, i);
}
}
}
invalidate();
}
| private void layoutTiles(int centerX, int centerY, float scale, int rotation) {
// The width and height of this view.
int width = getWidth();
int height = getHeight();
// The tile levels we want to keep as texture is in the range
// [fromLevel, endLevel).
int fromLevel;
int endLevel;
// We want to use a texture larger than or equal to the display size.
mLevel = Utils.clamp(Utils.floorLog2(1f / scale), 0, mLevelCount);
// We want to keep one more tile level as texture in addition to what
// we use for display. So it can be faster when the scale moves to the
// next level. We choose a level closer to the current scale.
if (mLevel != mLevelCount) {
Rect range = mTileRange;
getRange(range, centerX, centerY, mLevel, scale, rotation);
mOffsetX = Math.round(width / 2f + (range.left - centerX) * scale);
mOffsetY = Math.round(height / 2f + (range.top - centerY) * scale);
fromLevel = scale * (1 << mLevel) > 0.75f ? mLevel - 1 : mLevel;
} else {
// Activate the tiles of the smallest two levels.
fromLevel = mLevel - 2;
mOffsetX = Math.round(width / 2f - centerX * scale);
mOffsetY = Math.round(height / 2f - centerY * scale);
}
fromLevel = Math.max(0, Math.min(fromLevel, mLevelCount - 2));
endLevel = Math.min(fromLevel + 2, mLevelCount);
Rect range[] = mActiveRange;
for (int i = fromLevel; i < endLevel; ++i) {
getRange(range[i - fromLevel], centerX, centerY, i, rotation);
}
// If rotation is transient, don't update the tile.
if (rotation % 90 != 0) return;
synchronized (this) {
mDecodeQueue.clean();
mUploadQueue.clean();
mBackgroundTileUploaded = false;
// Recycle unused tiles: if the level of the active tile is outside the
// range [fromLevel, endLevel) or not in the visible range.
int n = mActiveTiles.size();
for (int i = 0; i < n; i++) {
Tile tile = mActiveTiles.valueAt(i);
int level = tile.mTileLevel;
if (level < fromLevel || level >= endLevel
|| !range[level - fromLevel].contains(tile.mX, tile.mY)) {
mActiveTiles.removeAt(i);
i--;
n--;
recycleTile(tile);
}
}
}
for (int i = fromLevel; i < endLevel; ++i) {
int size = TILE_SIZE << i;
Rect r = range[i - fromLevel];
for (int y = r.top, bottom = r.bottom; y < bottom; y += size) {
for (int x = r.left, right = r.right; x < right; x += size) {
activateTile(x, y, i);
}
}
}
invalidate();
}
|
diff --git a/src/com/bjorsond/android/timeline/TimelineActivity.java b/src/com/bjorsond/android/timeline/TimelineActivity.java
index ec3246d..6cab076 100644
--- a/src/com/bjorsond/android/timeline/TimelineActivity.java
+++ b/src/com/bjorsond/android/timeline/TimelineActivity.java
@@ -1,1440 +1,1440 @@
/*******************************************************************************
* Copyright (c) 2011 Andreas Storlien and Anders Kristiansen.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Andreas Storlien and Anders Kristiansen - initial API and implementation
******************************************************************************/
package com.bjorsond.android.timeline;
import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import net.sondbjor.android.ActionItem;
import net.sondbjor.android.QuickAction;
import android.accounts.Account;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Video;
import android.provider.MediaStore.Video.Media;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;
import com.bjorsond.android.timeline.SimpleGestureFilter.SimpleGestureListener;
import com.bjorsond.android.timeline.adapters.TimelineGridAdapter;
import com.bjorsond.android.timeline.barcode.IntentIntegrator;
import com.bjorsond.android.timeline.barcode.IntentResult;
import com.bjorsond.android.timeline.database.DatabaseHelper;
import com.bjorsond.android.timeline.database.TimelineDatabaseHelper;
import com.bjorsond.android.timeline.database.contentmanagers.ContentAdder;
import com.bjorsond.android.timeline.database.contentmanagers.ContentDeleter;
import com.bjorsond.android.timeline.database.contentmanagers.ContentLoader;
import com.bjorsond.android.timeline.database.contentmanagers.ContentUpdater;
import com.bjorsond.android.timeline.dialogs.AttachmentAdder;
import com.bjorsond.android.timeline.dialogs.EventDialog;
import com.bjorsond.android.timeline.dialogs.MoodDialog;
import com.bjorsond.android.timeline.exceptions.MaxZoomedOutException;
import com.bjorsond.android.timeline.map.TimelineMapView;
import com.bjorsond.android.timeline.models.BaseEvent;
import com.bjorsond.android.timeline.models.Event;
import com.bjorsond.android.timeline.models.EventItem;
import com.bjorsond.android.timeline.models.Experience;
import com.bjorsond.android.timeline.models.MoodEvent;
import com.bjorsond.android.timeline.models.SimpleNote;
import com.bjorsond.android.timeline.models.ReflectionNote;
import com.bjorsond.android.timeline.models.SimplePicture;
import com.bjorsond.android.timeline.models.SimpleRecording;
import com.bjorsond.android.timeline.models.SimpleVideo;
import com.bjorsond.android.timeline.models.Zoom;
import com.bjorsond.android.timeline.models.MoodEvent.MoodEnum;
import com.bjorsond.android.timeline.sync.GoogleAppEngineHandler;
import com.bjorsond.android.timeline.utilities.Constants;
import com.bjorsond.android.timeline.utilities.MyLocation;
import com.bjorsond.android.timeline.utilities.Utilities;
import com.bjorsond.android.timeline.R;
import com.bjorsond.android.timeline.DashboardActivity;
import com.swarmconnect.Swarm;
import com.swarmconnect.SwarmAchievement;
import com.swarmconnect.SwarmActivity;
/**
*
* This is the main timeline {@linkplain Activity}.
*
* This is where the {@link Event}s and {@link EventItem}s are accessed, and where new
* {@link Event}s and {@link EventItem}s can be added.
*
*
* @author andekr
*
*/
public class TimelineActivity extends SwarmActivity implements SimpleGestureListener {
private LinearLayout cameraButton, videoCameraButton, audioRecorderButton, createNoteButton, attachmentButton, moodButton, sumDayButton;
private TextView screenTitle, timelineTitleTextView;
private TimelineGridAdapter EventAdapter;
private Event selectedEvent;
private ContentAdder contentAdder;
private ContentLoader contentLoader;
private ContentUpdater contentUpdater;
private ContentDeleter contentDeleter;
private HorizontalScrollView scrollview;
private GridView gridview;
private ZoomControls zoomControls;
private Animation slideLeftIn;
private Animation slideLeftOut;
private Animation slideRightIn;
private Animation slideRightOut;
private ImageButton homeButton;
private int backCounter = 0;
private String intentFilename;
private QuickAction qa;
public String databaseName, experienceID, experienceCreator;
public boolean sharedExperience;
private DatabaseHelper dbHelper;
private ArrayList<BaseEvent> loadedEvents;
private Experience timeline;
private Uri imageUri;
private Uri videoUri;
private Uri audioUri;
private MyLocation myLocation;
private SimpleGestureFilter detector;
private EventDialog eventDialog;
private MoodDialog moodDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.timelinescreen);
selectedEvent = null; //No event selected by default
detector = new SimpleGestureFilter(this,this); //Creates swipe gesture for the activity
setupZoom();
myLocation = MyLocation.getInstance(this);
createNewDatabaseIfTimeLineIsNew();
//Instantiate content managers
contentAdder = new ContentAdder(getApplicationContext());
contentUpdater = new ContentUpdater(getApplicationContext());
contentDeleter = new ContentDeleter(getApplicationContext());
//Get intent content
databaseName = getIntent().getExtras().getString(Constants.DATABASENAME_REQUEST);
experienceID = getIntent().getExtras().getString(Constants.EXPERIENCEID_REQUEST);
experienceCreator = getIntent().getExtras().getString(Constants.EXPERIENCECREATOR_REQUEST);
sharedExperience = getIntent().getExtras().getBoolean(Constants.SHARED_REQUEST);
Log.i(this.getClass().getSimpleName(), "****Got DB: "+databaseName+" from Intent****");
Log.i(this.getClass().getSimpleName(), "Experience ID: "+experienceID);
Log.i(this.getClass().getSimpleName(), "Created by: "+experienceCreator);
Log.i(this.getClass().getSimpleName(), "Experience is shared: "+sharedExperience);
Log.i(this.getClass().getSimpleName(), "*******************************************");
//Instantiates database helper and loads events from database
new DatabaseHelper(this, databaseName);
new TimelineDatabaseHelper(this, Constants.ALL_TIMELINES_DATABASE_NAME);
loadedEvents = loadEventItemsFromDatabase();
TimelineDatabaseHelper.getCurrentTimeLineDatabase().close();
//Creates the experience and loads it with events
timeline = new Experience(experienceID, databaseName, sharedExperience, new Account(experienceCreator, "com.google"));
timeline.setEvents(loadedEvents);
System.out.println("ANTALL HENTEDE EVENTS! : " + timeline.getEvents().size());
//setting this activity active -- Swarm
Swarm.setActive(this);
Swarm.setAchievementNotificationsEnabled(true);
setupViews();
setupMoodButtonQuickAction();
//If the activity is started with a send-Intent(e.g. via share button in the Gallery), the item is added to the Timeline
if(getIntent().getAction().equals(Constants.INTENT_ACTION_ADD_TO_TIMELINE)){
if(getIntent().getType().contains("image/")){
imageUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+".jpg";
Utilities.copyFile(Utilities.getRealPathFromURI(imageUri, this), Constants.IMAGE_STORAGE_FILEPATH, filename);
addPictureToTimeline(filename);
}
else if(getIntent().getType().contains("video/")){
videoUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(videoUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(videoUri, this), Constants.VIDEO_STORAGE_FILEPATH, filename);
addVideoToTimeline(filename);
}else if(getIntent().getType().contains("audio/")){
audioUri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(audioUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(audioUri, this), Constants.RECORDING_STORAGE_FILEPATH, filename);
addAudioToTimeline(filename);
}
else if(getIntent().getType().contains("text/plain")){
if(getIntent().getExtras().containsKey("NOTE_ID")){
addNoteToTimeline(getIntent());
}
else if(getIntent().getExtras().containsKey("REFLECTION_ID")){
addReflectionToTimeline(getIntent());
}
}
}
}
private void setupZoom() {
Zoom.WEEK.setNext(Zoom.DAY);
Zoom.DAY.setNext(Zoom.HOUR);
Zoom.HOUR.setNext(Zoom.MONTH);
Zoom.MONTH.setNext(null);
}
private void createNewDatabaseIfTimeLineIsNew() {
}
public void setDbHelper(DatabaseHelper dbHelper) {
this.dbHelper = dbHelper;
}
public DatabaseHelper getDbHelper() {
return dbHelper;
}
private ArrayList<BaseEvent> loadEventItemsFromDatabase() {
contentLoader = new ContentLoader(getApplicationContext());
return contentLoader.LoadAllEventsFromDatabase();
}
private void cancelNotifications(){
getBaseContext();
//// AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
//
// Intent intent = new Intent(this, TimeAlarm.class);
// intent.setAction("notify");
notificationManager.cancel(1);
notificationManager.cancel(2);
notificationManager.cancel(3);
notificationManager.cancel(4);
}
//TODO createScheduleNotification method
/**
* This method sets the notification to pop up
*/
public void createScheduledNotification(int days, String intentAction, int hourOfDay, int id){
if (days != -1) {
// Get new calendar object and set the date to now
Calendar calendar = Calendar.getInstance();
// Setting time for alarm/notification
calendar.add(Calendar.DAY_OF_MONTH, days);
calendar.add(Calendar.MINUTE, -1);
// calendar.set(Calendar.MINUTE, 0);
// calendar.set(Calendar.SECOND, 0);
// calendar.set(Calendar.MILLISECOND, 0);
// calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
Log.i("CALENDAR TESTING", "day of month: " + calendar.get(Calendar.DAY_OF_MONTH) +" hour of day: " + calendar.get(Calendar.HOUR_OF_DAY));
Log.i("CALENDAR TESTING", "month: " + calendar.get(Calendar.MONTH) +" year: " + calendar.get(Calendar.YEAR));
// else calendar.add(Calendar.MINUTE, 3);
// Retrieve alarm manager from the system
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); //getApplicationContext()
Log.i("CALENDAR TESTING", "Made alarmManager");
// Every scheduled intent needs a different ID, else it is just executed once
// int id = (int) System.currentTimeMillis();
// Prepare the intent which should be launched at the date
Intent intent = new Intent(this, TimeAlarm.class);
intent.setAction(intentAction);
Log.i("CALENDAR TESTING", "Made intent");
// Prepare the pending intent
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); //getApplicationContext()
Log.i("CALENDAR TESTING", "Made pendingIntent");
// Register the alert in the system. You have the option to define if the device has to wake up on the alert or not
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Log.i("CALENDAR TESTING", "Set alarmManager");
Log.i("CALENDAR TESTING", "" + new Date(calendar.getTimeInMillis()));
}
}
// public void createScheduledNotification(int days, String intentAction){
//
// if (days != -1) {
//
// int hour = -1;
//
// // Get new calendar object and set the date to now
// Calendar calendar = Calendar.getInstance();
// calendar.setTimeInMillis(System.currentTimeMillis());
//
// //setting current day, hour, minute
// hour = calendar.get(Calendar.HOUR_OF_DAY);
//
// // Setting time for alarm/notification
// calendar.add(Calendar.DAY_OF_MONTH, days);
// calendar.set(Calendar.MINUTE, 0);
// calendar.set(Calendar.SECOND, 0);
// if (hour < 12 && hour != -1) calendar.set(Calendar.HOUR_OF_DAY, 12);
// else if (hour < 14 && 12 >= hour && hour != -1) calendar.set(Calendar.HOUR_OF_DAY, 14);
// else if (hour < 16 && 14 >= hour && hour != -1) calendar.set(Calendar.HOUR_OF_DAY, 16);
// else if (hour < 18 && 16 >= hour && hour != -1) calendar.set(Calendar.HOUR_OF_DAY, 18);
//
// // else calendar.add(Calendar.MINUTE, 3);
//
// // Retrieve alarm manager from the system
// getBaseContext();
// AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
//
// // Every scheduled intent needs a different ID, else it is just executed once
// int id = (int) System.currentTimeMillis();
//
// // Prepare the intent which should be launched at the date
// Intent intent = new Intent(this, TimeAlarm.class);
// intent.setAction(intentAction);
//
// // Prepare the pending intent
// PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//
// // Register the alert in the system. You have the option to define if the device has to wake up on the alert or not
// alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
// }
// }
//
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* PICTURE CREATED **************");
- Toast.makeText(this, R.string.Pic_created_toast, Toast.LENGTH_SHORT).show();
+ Toast.makeText(this, getString(R.string.Pic_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.PicturePoints, Toast.LENGTH_SHORT).show();
//Adding to picture count
DashboardActivity.addPictureCounter();
//Adding points for picture
DashboardActivity.addPointsCounter(Constants.PicturePoints);
//Adding achievement
if (DashboardActivity.getPictureCounter() == 1){
SwarmAchievement.unlock(Constants.PictureAchievement);
Toast.makeText(this, R.string.First_pic_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getPictureCounter() == 10){
SwarmAchievement.unlock(Constants.PictureTenAchievement);
Toast.makeText(this, R.string.Tenth_pic_achi_toast, Toast.LENGTH_LONG).show();
}
addPictureToTimeline(intentFilename);
intentFilename="";
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Pic_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Pic_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* VIDEO RECORDING CREATED **************");
- Toast.makeText(this, R.string.Video_created_toast, Toast.LENGTH_SHORT).show();
+ Toast.makeText(this, getString(R.string.Video_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.VideoPoints, Toast.LENGTH_SHORT).show();
//Adding to video count
DashboardActivity.addVideoCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.VideoPoints);
//Adding achievement
if (DashboardActivity.getVideoCounter() == 1){
SwarmAchievement.unlock(Constants.VideoAchievement);
Toast.makeText(this, R.string.First_video_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getVideoCounter() == 10){
SwarmAchievement.unlock(Constants.VideoTenAchievement);
Toast.makeText(this, R.string.Tenth_video_achi_toast, Toast.LENGTH_LONG).show();
}
videoUri = data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(videoUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(videoUri, this), Constants.VIDEO_STORAGE_FILEPATH, filename);
addVideoToTimeline(filename);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Video_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Video_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.RECORD_AUDIO_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* AUDIO RECORDING CREATED **************");
- Toast.makeText(this, R.string.Audio_created_toast, Toast.LENGTH_SHORT).show();
+ Toast.makeText(this, getString(R.string.Audio_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.AudioPoints, Toast.LENGTH_SHORT).show();
//Adding to audio count
DashboardActivity.addAudioCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.AudioPoints);
//Adding achievement
if (DashboardActivity.getAudioCounter() == 1){
SwarmAchievement.unlock(Constants.AudioAchievement);
Toast.makeText(this, R.string.First_audio_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getAudioCounter() == 10){
SwarmAchievement.unlock(Constants.AudioTenAchievement);
Toast.makeText(this, R.string.Tenth_audio_achi_toast, Toast.LENGTH_LONG).show();
}
audioUri = data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(audioUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(audioUri, this), Constants.RECORDING_STORAGE_FILEPATH, filename);
addAudioToTimeline(filename);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Audio_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Audio_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.CREATE_NOTE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* NOTE CREATED **************");
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "*************************************");
- Toast.makeText(this, R.string.Note_created_toast, Toast.LENGTH_SHORT).show();
+ Toast.makeText(this, getString(R.string.Note_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.NotePoints, Toast.LENGTH_SHORT).show();
//Adding to note count
DashboardActivity.addNoteCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.NotePoints);
//Adding achievement
if (DashboardActivity.getNoteCounter() == 1){
SwarmAchievement.unlock(Constants.NoteAchievement);
Toast.makeText(this, R.string.First_note_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getNoteCounter() == 10){
SwarmAchievement.unlock(Constants.NoteTenAchievement);
Toast.makeText(this, R.string.Tenth_note_achi_toast, Toast.LENGTH_LONG).show();
}
addNoteToTimeline(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Note_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Note_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
//TODO To see REF NOTE place in code...
// REFLECTION NOTE ADDED
case Constants.CREATE_REFLECTION_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* REFLECTION NOTE CREATED **************");
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "************************************************");
//Adding to reflection count
DashboardActivity.addReflectionCounter();
//Adding points
int points = DashboardActivity.checkAndSetRefNotePoints();
- Toast.makeText(this, getString(R.string.Reflection_added_toast) + " Points rewarded for Reflection note is: "+points, Toast.LENGTH_SHORT).show();
+ Toast.makeText(this, getString(R.string.Reflection_added_toast) + " " + getString(R.string.Points_rewarded_toast)+points, Toast.LENGTH_SHORT).show();
//Setting date and time for ref note
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
DashboardActivity.setLastRefDate(calendar);
//Canceling former notifications
cancelNotifications();
//Setting alarm for notification
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 12, 1);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 14, 2);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 16, 3);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 18, 4);
//Adding achievement
if (DashboardActivity.getReflectionCounter() == 1){
SwarmAchievement.unlock(Constants.ReflectionNoteAchievement);
Toast.makeText(this, R.string.First_reflection_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getReflectionCounter() == 10){
SwarmAchievement.unlock(Constants.ReflectionNoteTenAchievement);
Toast.makeText(this, R.string.Tenth_reflection_achi_toast, Toast.LENGTH_LONG).show();
}
addReflectionToTimeline(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Reflection_not_added_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Reflection_not_added_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.EDIT_NOTE:
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.Note_edited_toast , Toast.LENGTH_SHORT).show();
updateNote(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Note_not_edited_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Note_not_edited_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.EDIT_REFLECTION:
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.Reflection_edited_toast , Toast.LENGTH_SHORT).show();
updateReflection(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Reflection_not_edited_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Reflection_not_edited_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.NEW_TAG_REQUESTCODE:
if (resultCode == RESULT_OK) {
updateTags();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Tag_not_added_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Tag_not_added_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.SELECT_PICTURE:
if(resultCode == Activity.RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* PICTURE SELECTED **************");
imageUri = (Uri) data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+".jpg";
Utilities.copyFile(Utilities.getRealPathFromURI(imageUri, this), Constants.IMAGE_STORAGE_FILEPATH, filename);
addPictureToTimeline(filename);
}
break;
case Constants.SELECT_VIDEO:
if(resultCode == Activity.RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* VIDEO SELECTED **************");
Toast.makeText(this, R.string.Video_selected_toast, Toast.LENGTH_SHORT).show();
videoUri = (Uri) data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(videoUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(videoUri, this), Constants.VIDEO_STORAGE_FILEPATH, filename);
addVideoToTimeline(filename);
}
case Constants.CAPTURE_BARCODE:
Log.i(this.getClass().getSimpleName(), "********* BARCODE SCANNED **************");
getBarcodeResults(requestCode, resultCode, data);
break;
case Constants.MAP_VIEW_ACTIVITY_REQUEST_CODE:
if(resultCode == RESULT_OK) {
String id = data.getExtras().getString("EVENT_ID");
BaseEvent selectedEvent = timeline.getEvent(id);
if(selectedEvent != null) {
if (selectedEvent instanceof Event) {
eventDialog = new EventDialog(this, (Event)selectedEvent, this, true);
eventDialog.show();
}
else {
moodDialog = new MoodDialog(this, (MoodEvent) selectedEvent);
moodDialog.show();
}
}
}
default:
break;
}
}
private void getBarcodeResults(int requestCode, int resultCode, Intent intent) {
if(resultCode == Activity.RESULT_OK) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
intent.putExtra(Intent.EXTRA_SUBJECT, "Barcode");
intent.putExtra(Intent.EXTRA_TEXT, scanResult.getContents());
Log.i(this.getClass().getSimpleName(), "********* BARCODEINTENT CREATED **************");
Log.i(this.getClass().getSimpleName(), "Title: "+intent.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+intent.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "*************************************");
Toast.makeText(this, R.string.Note_created_toast, Toast.LENGTH_SHORT).show();
addNoteToTimeline(intent);
}
}
else if(resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, R.string.Attach_not_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Attach_not_toast, Toast.LENGTH_SHORT).show();
}
}
/**
* The method that starts the camera.
* The method creates an {@link Intent} of the type {@linkplain MediaStore.ACTION_IMAGE_CAPTURE} which will start the camera,
* and deliver the result back to this activity by starting the intent with the {@link Activity.startActivityForResult()} method.
*
*
*/
public void startCamera() {
//create parameters for Intent
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "TimelineImage");
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
//Put some geolocation information into the image meta tag, if location is known
try {
values.put(MediaStore.Images.Media.LATITUDE, myLocation.getLocation().getLatitude());
values.put(MediaStore.Images.Media.LONGITUDE, myLocation.getLocation().getLongitude());
} catch (NullPointerException e) {
Log.e("startCamera", "Location unknown");
}
//imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
try {
intentFilename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+".jpg";
imageUri = Uri.fromFile(new File(Constants.IMAGE_STORAGE_FILEPATH+intentFilename));
if(!(new File(Constants.IMAGE_STORAGE_FILEPATH)).exists()) {
(new File(Constants.IMAGE_STORAGE_FILEPATH)).mkdirs();
}
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, Constants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
Log.e("StartCamera", "Feil", e);
Toast.makeText(this, R.string.SD_toast, Toast.LENGTH_LONG).show();
}
}
/**
* The method that starts the camera.
* The method creates an {@link Intent} of the type {@linkplain MediaStore.ACTION_VIDEO_CAPTURE} which will start the video camera,
* and deliver the result back to this activity by starting the intent with the {@link Activity.startActivityForResult()} method.
*
*
*/
public void startVideoCamera() {
//TODO: M� muligens legge til mer attributter
ContentValues values = new ContentValues();
values.put(Video.Media.TITLE, "title");
values.put(Video.Media.BUCKET_ID, "test");
values.put(Video.Media.DESCRIPTION, "test Image taken");
try {
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
// intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);//Did not work in Android 2.3
intent.putExtra("output", uri.getPath());
startActivityForResult(intent, Constants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
} catch (Exception e) {
Toast.makeText(this, R.string.SD_toast, Toast.LENGTH_LONG).show();
}
}
/**
* The method that starts the camera.
* The method creates an {@link Intent} of the type {@linkplain MediaStore.Audio.Media.RECORD_SOUND_ACTION} which will start the audio recorder,
* and deliver the result back to this activity by starting the intent with the {@link Activity.startActivityForResult()} method.
*
*/
public void startAudioRecording(){
Intent voiceIntent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
startActivityForResult(voiceIntent, Constants.RECORD_AUDIO_ACTIVITY_REQUEST_CODE);
}
/**
* The method that starts Note creation activity.
* The method creates an {@link Intent} for the {@linkplain NoteActivity} class which will open the Note Activity,
* and deliver the result back to this activity by starting the intent with the {@link Activity.startActivityForResult()} method.
*
*/
public void createNote(){
Intent noteIntent = new Intent(this, NoteActivity.class);
noteIntent.putExtra(Constants.REQUEST_CODE, Constants.CREATE_NOTE_ACTIVITY_REQUEST_CODE);
startActivityForResult(noteIntent, Constants.CREATE_NOTE_ACTIVITY_REQUEST_CODE);
}
/**
* Method that opens the map view activity
*/
public void openMapView() {
if(Utilities.isConnectedToInternet(getApplicationContext())) {
Intent mapViewIntent = new Intent(this, TimelineMapView.class);
mapViewIntent.setAction(Constants.INTENT_ACTION_OPEN_MAP_VIEW_FROM_TIMELINE);
startActivityForResult(mapViewIntent, Constants.MAP_VIEW_ACTIVITY_REQUEST_CODE);
}
else {
Toast.makeText(getApplicationContext(), R.string.Online_functionality_toast, Toast.LENGTH_SHORT).show();
}
}
/**
* The method that starts the Attacment dialog.
*
*/
public void startAttachmentDialog() {
new AttachmentAdder(this, this, timeline);
}
/**
* The method that starts the Reflection creation activity.
*
*/
public void createReflection(){
Intent reflectionIntent = new Intent(this, ReflectionActivity.class);
reflectionIntent.putExtra(Constants.REQUEST_CODE, Constants.CREATE_REFLECTION_ACTIVITY_REQUEST_CODE);
startActivityForResult(reflectionIntent, Constants.CREATE_REFLECTION_ACTIVITY_REQUEST_CODE);
}
/**
* When the Activity is destroyed(ended) the database will be backed up to the SD-card(if availiable),
* and the database closed.
*
*/
@Override
public void onDestroy() {
DatabaseHelper.backupDBToSDcard(DatabaseHelper.getCurrentTimelineDatabase(), databaseName);
DatabaseHelper.getCurrentTimelineDatabase().close();
super.onDestroy();
}
/**
*
* A method that sets all the view components from the layout-xml file.
* The methods also adds listeners and sets up the slide animations for the activity.
*
* @author andekr
*
*/
private void setupViews(){
int duration = 1000;
slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slideLeftIn.setDuration(duration);
slideLeftOut = AnimationUtils
.loadAnimation(this, R.anim.slide_left_out);
slideLeftOut.setDuration(duration);
slideRightIn = AnimationUtils
.loadAnimation(this, R.anim.slide_right_in);
slideRightIn.setDuration(duration);
slideRightOut = AnimationUtils.loadAnimation(this,
R.anim.slide_right_out);
slideRightOut.setDuration(1000);
homeButton = (ImageButton)findViewById(R.id.HomeButton);
homeButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
screenTitle = (TextView)findViewById(R.id.TimelineLabel);
timelineTitleTextView = (TextView) findViewById(R.id.TimelineName);
if(timeline.getTitle().contains(".db")) {
timelineTitleTextView.setText(timeline.getTitle().substring(0, timeline.getTitle().indexOf(".db")));
}else {
timelineTitleTextView.setText(timeline.getTitle());
}
cameraButton = (LinearLayout)findViewById(R.id.MenuCameraButton);
cameraButton.setOnClickListener(startCameraListener);
videoCameraButton = (LinearLayout)findViewById(R.id.MenuVideoCameraButton);
videoCameraButton.setOnClickListener(startVideoCameraListener);
audioRecorderButton = (LinearLayout)findViewById(R.id.MenuAudioButton);
audioRecorderButton.setOnClickListener(startAudioRecorderListener);
createNoteButton = (LinearLayout)findViewById(R.id.MenuNoteButton);
createNoteButton.setOnClickListener(createNoteListener);
attachmentButton = (LinearLayout)findViewById(R.id.MenuAttachmentButton);
attachmentButton.setOnClickListener(addAttachmentListener);
sumDayButton = (LinearLayout)findViewById(R.id.MenuSumDayButton);
sumDayButton.setOnClickListener(startSumDayListener);
scrollview = (HorizontalScrollView) findViewById(R.id.HorizontalScrollView01);
scrollview.setScrollContainer(true);
gridview = (GridView) findViewById(R.id.GridView01);
EventAdapter = new TimelineGridAdapter(this, this);
try {
Date[] dates = timeline.getMinAndMaxDate();
//Sets adapter to zoom to the type most appropriate to the timespan of events, and that the default view includes the last event.
EventAdapter.setZoomType(Utilities.convertTimeScopeInMillisToZoomType(dates), dates[1]);
} catch (NullPointerException e) {
//No experienceevents in TimeLine
// Log.e(e.getStackTrace()[1].getMethodName(), e.getMessage());
EventAdapter.setZoomType(Zoom.MONTH, null);
}
//Sets the adapter that does all the rendering of the activity
gridview.setAdapter(EventAdapter);
scrollRight(0);
zoomControls = (ZoomControls)findViewById(R.id.ZoomControls01);
zoomControls.setOnZoomOutClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EventAdapter.zoomOut();
} catch (MaxZoomedOutException e) {
Toast.makeText(TimelineActivity.this, R.string.Zoomed_out_toast, Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* This method scrolls the view one time unit(month, week, day, hour) forward.
* The delay describes the length of the scroll animation.
*
* @param int delay Delay in ms.
*/
public void scrollRight(int delay) {
// If we don't call fullScroll inside a Runnable, it doesn't scroll to
// the bottom but to the (bottom - 1)
scrollview.postDelayed(new Runnable() {
public void run() {
scrollview.scrollTo(350, 0);
scrollview.setAnimation(AnimationUtils.makeInAnimation(TimelineActivity.this, true));
}
}, delay);
}
/**
* This method scrolls the view one time unit(month, week, day, hour) back.
* The delay describes the length of the scroll animation.
*
* @param int delay Delay in ms.
*/
public void scrollLeftmost(int delay) {
// If we don't call fullScroll inside a Runnable, it doesn't scroll to
// the bottom but to the (bottom - 1)
scrollview.postDelayed(new Runnable() {
public void run() {
scrollview.scrollTo(0, 0);
scrollview.setAnimation(AnimationUtils.makeInAnimation(TimelineActivity.this, true));
}
}, delay);
}
// LISTENERS
private OnClickListener startCameraListener = new OnClickListener() {
public void onClick(View v) {
startCamera();
}
};
private OnClickListener startVideoCameraListener = new OnClickListener() {
public void onClick(View v) {
startVideoCamera();
}
};
private OnClickListener startAudioRecorderListener = new OnClickListener() {
public void onClick(View v) {
startAudioRecording();
}
};
private OnClickListener createNoteListener = new OnClickListener() {
public void onClick(View v) {
createNote();
}
};
private OnClickListener addAttachmentListener = new OnClickListener() {
public void onClick(View v) {
startAttachmentDialog();
}
};
private OnClickListener startSumDayListener = new OnClickListener() {
public void onClick(View v) {
createReflection();
}
};
/**
* Method that adds a picture to the timeline.
* Creates a {@link SimplePicture}.
* Adds it to an {@link Event} if fired from an {@linkplain EventDialog}, else
* the method creates a new {@link Event}.
*
*/
private void addPictureToTimeline(String filename){
SimplePicture picture = new SimplePicture(this);
picture.setPictureUri(imageUri, Constants.MEDIASTORE_URL+filename);
if(selectedEvent!=null){
addItemToExistingEvent(picture);
}else{
createEventAndAddItem(picture);
}
}
/**
* Method that adds a video to the timeline.
* Creates a {@link SimpleVideo}.
* Adds it to an {@link Event} if fired from an {@linkplain EventDialog}, else
* the method creates a new {@link Event}.
*
*/
private void addVideoToTimeline(String filename){
SimpleVideo sVideo = new SimpleVideo(this);
sVideo.setVideoUri(videoUri, Constants.MEDIASTORE_URL+filename);
if(selectedEvent!=null){
addItemToExistingEvent(sVideo);
}else{
createEventAndAddItem(sVideo);
}
}
/**
* Method that adds a audio to the timeline.
* Creates a {@link SimpleRecording}.
* Adds it to an {@link Event} if fired from an {@linkplain EventDialog}, else
* the method creates a new {@link Event}.
*
*/
private void addAudioToTimeline(String filename) {
SimpleRecording sRecordring = new SimpleRecording(this);
sRecordring.setRecordingUri(audioUri, Constants.MEDIASTORE_URL+filename);
if(selectedEvent!=null){
addItemToExistingEvent(sRecordring);
}else{
createEventAndAddItem(sRecordring);
}
}
/**
* Method that adds a note to the timeline.
* Creates a {@link SimpleNote}.
* Adds it to an {@link Event} if fired from an {@linkplain EventDialog}, else
* the method creates a new {@link Event}.
*
*/
private void addNoteToTimeline(Intent data) {
SimpleNote note = new SimpleNote(this);
if(data.getExtras().getString(Intent.EXTRA_SUBJECT) != null)
note.setNoteTitle(data.getExtras().getString(Intent.EXTRA_SUBJECT));
if(data.getExtras().getString(Intent.EXTRA_TEXT) != null)
note.setNoteText(data.getExtras().getString(Intent.EXTRA_TEXT));
if(data.getExtras().getString(Intent.EXTRA_TITLE) != null)
note.setNoteText(data.getExtras().getString(Intent.EXTRA_TITLE));
if(selectedEvent!=null){
addItemToExistingEvent(note);
}else{
createEventAndAddItem(note);
}
}
//Add reflection note to timeline
private void addReflectionToTimeline(Intent data) {
ReflectionNote reflection = new ReflectionNote(this);
if(data.getExtras().getString(Intent.EXTRA_SUBJECT) != null)
reflection.setReflectionTitle(data.getExtras().getString(Intent.EXTRA_SUBJECT));
if(data.getExtras().getString(Intent.EXTRA_TEXT) != null)
reflection.setReflectionText(data.getExtras().getString(Intent.EXTRA_TEXT));
if(data.getExtras().getString(Intent.EXTRA_TITLE) != null)
reflection.setReflectionText(data.getExtras().getString(Intent.EXTRA_TITLE));
if(selectedEvent!=null){
addItemToExistingEvent(reflection);
}else{
createEventAndAddItem(reflection);
}
}
/**
* Creates a new {@link Event} and adds an {@link EventItem}.
*
* @param evIt The {@link EventItem} to be added to the new {@link Event}
*/
private void createEventAndAddItem(EventItem evIt){
final Event ev = new Event(timeline.getId(), myLocation.getLocation(), Utilities.getUserAccount(getApplicationContext()));
timeline.addEvent(ev);
ev.addEventItem(evIt);
EventAdapter.updateAdapter();
contentAdder.addEventToEventContentProvider(ev);
}
private void addMoodEventToTimeline(final MoodEvent moodEvent) {
Runnable SendMoodEventRunnable = new Runnable() {
public void run() {
GoogleAppEngineHandler.persistTimelineObject(moodEvent);
}
};
timeline.addEvent(moodEvent);
EventAdapter.updateAdapter();
contentAdder.addEventToEventContentProvider(moodEvent);
Thread sendMoodThread = new Thread(SendMoodEventRunnable, "shareThread");
sendMoodThread.start();
Toast.makeText(this, R.string.Mood_added_toast, Toast.LENGTH_SHORT).show();
//Adding points
DashboardActivity.addPointsCounter(Constants.MoodPoints);
}
/**
* Adds an {@link EventItem} to an existing {@link Event}.
*
* @param evIt The {@link EventItem} to be added to the existing {@link Event}
*/
private void addItemToExistingEvent(EventItem evIt){
selectedEvent.addEventItem(evIt);
EventAdapter.notifyDataSetChanged();
EventAdapter.updateDialog();
contentAdder.addEventItemToEventContentProviderIfEventAlreadyExists(selectedEvent, evIt);
}
/**
* Updates an existing note.
*
* @param data The {@link Intent} with note data
*/
private void updateNote(Intent data){
Log.i(this.getClass().getSimpleName(), "********* OPPDATERER NOTE **************");
Log.i(this.getClass().getSimpleName(), "Note item plass: "+data.getExtras().getInt("NOTE_ID"));
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "*************************************");
SimpleNote note = (SimpleNote) selectedEvent.getEventItems().get(data.getExtras().getInt("NOTE_ID"));
note.setNoteTitle(data.getExtras().getString(Intent.EXTRA_SUBJECT));
note.setNoteText(data.getExtras().getString(Intent.EXTRA_TEXT));
selectedEvent.getEventItems().set(data.getExtras().getInt("NOTE_ID"), note);
contentUpdater.updateNoteInDB(note);
EventAdapter.updateDialog();
}
private void updateReflection(Intent data){
Log.i(this.getClass().getSimpleName(), "********* OPPDATERER REFLEKSJON **************");
Log.i(this.getClass().getSimpleName(), "Note item plass: "+data.getExtras().getInt("REFLECTION_ID"));
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "*************************************");
ReflectionNote ref = (ReflectionNote) selectedEvent.getEventItems().get(data.getExtras().getInt("REFLECTION_ID"));
ref.setReflectionTitle(data.getExtras().getString(Intent.EXTRA_SUBJECT));
ref.setReflectionText(data.getExtras().getString(Intent.EXTRA_TEXT));
selectedEvent.getEventItems().set(data.getExtras().getInt("REFLECTION_ID"), ref);
contentUpdater.updateReflectionInDB(ref);
EventAdapter.updateDialog();
}
private void updateTags(){
EventAdapter.updateTagDialog();
}
public Event getSelectedEvent() {
return selectedEvent;
}
public void setSelectedEvent(Event selectedEvent) {
this.selectedEvent = selectedEvent;
}
public void addEvent(Event event){
EventAdapter.addEvent(event);
}
public void removeEvent(Event event){
timeline.removeEvent(event);
EventAdapter.removeEvent(event);
contentDeleter.deleteEventFromDB(event);
}
public TimelineGridAdapter getEventAdapter(){
return EventAdapter;
}
public void delete(EventItem exItem) {
contentDeleter.deleteEventItemFromDB(exItem);
}
/**
* Handles click-event in context menu after long click on {@link Event}.
* One element in this context menu: "Delete event".
*
*/
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getGroupId()) {
case R.id.MENU_DELETE_EVENT:
Log.v(this.getClass().getSimpleName()+" LONG-CLICK", "DELETE EVENT: "+ selectedEvent.getId());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.Delete_event_confirmation)
.setPositiveButton(R.string.yes_label, deleteEventListener)
.setNegativeButton(R.string.no_label, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
selectedEvent = null;
dialog.cancel();
}
})
.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
selectedEvent = null;
dialog.cancel() ;
}
});
AlertDialog confirmation = builder.create();
confirmation.show();
return true;
}
return false;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.NEW_MAP_VIEW:
openMapView();
return true;
case R.id.AVERAGE_TIMELINE_MOOD:
double[] moodCoordinates = GoogleAppEngineHandler.getAverageMoodForExperience(timeline);
MoodEvent averageMood = new MoodEvent(timeline.getId(), null, MoodEnum.getType(moodCoordinates[0], moodCoordinates[1]), timeline.getUser());
averageMood.setAverage(true);
new MoodDialog(this, averageMood).show();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Click listener on delete Event yes button
*
*/
public android.content.DialogInterface.OnClickListener deleteEventListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
removeEvent(selectedEvent);
selectedEvent = null;
}
};
public GridView getGridView(){
return gridview;
}
public Experience getTimeline(){
return timeline;
}
@Override
public boolean dispatchTouchEvent(MotionEvent me){
this.detector.onTouchEvent(me);
return super.dispatchTouchEvent(me);
}
public void onDoubleTap() {
}
public void onSwipe(int direction) {
String str = "";
switch (direction) {
case SimpleGestureFilter.SWIPE_RIGHT : str = "Swipe Right";
if(scrollview.getScrollX()==0){
gridview.startAnimation(slideLeftOut);
EventAdapter.minusOne();
str = "M�nednummer:"+Utilities.getMonthNumberOfDate(EventAdapter.getZoomDate());
gridview.startAnimation(slideRightIn);
}
break;
case SimpleGestureFilter.SWIPE_LEFT : str = "Swipe Left";
System.out.println(scrollview.getScrollX());
System.out.println(scrollview.getMeasuredWidth());
//Hack for Galaxy tab
//TODO: THIS HAS TO BE REFACTORED TO ALLOW MULTIPLE SCREEN SIZES
if(scrollview.getMeasuredWidth()==1024){
if(scrollview.getScrollX()==(scrollview.getMeasuredWidth()-548) || scrollview.getScrollX()==0){
gridview.startAnimation(slideRightOut);
EventAdapter.plusOne();
str = "M�nednummer:"+Utilities.getMonthNumberOfDate(EventAdapter.getZoomDate());
str += "Dag:"+EventAdapter.getZoomDate().getDate();
gridview.startAnimation(slideLeftIn);
}
}
if(scrollview.getScrollX()==(scrollview.getMeasuredWidth()-100) || scrollview.getScrollX()==0){
gridview.startAnimation(slideRightOut);
EventAdapter.plusOne();
str = "M�nednummer:"+Utilities.getMonthNumberOfDate(EventAdapter.getZoomDate());
str += "Dag:"+EventAdapter.getZoomDate().getDate();
gridview.startAnimation(slideLeftIn);
}
break;
}
}
public void setTitle(CharSequence title){
screenTitle.setText(title);
}
public ContentAdder getContentAdder() {
return contentAdder;
}
/**
* Overrides the click listener on the device BACK-button.
* The new behavior makes the back button zoom out until max zoomed out.
* When max zoomed out the user needs to click the back button twice to exit the timeline, and enter the menu.
*
*/
@Override
public void onBackPressed() {
try {
EventAdapter.zoomOut();
backCounter=0;
} catch (MaxZoomedOutException e) {
if(backCounter==1){
System.out.println("Resetting backcounter");
backCounter=0;
super.onBackPressed();
}
else{
Toast.makeText(this, R.string.Zoomed_out_back_toast, Toast.LENGTH_SHORT).show();
backCounter++;
}
}
}
/**
* Overrides the long click listener on the device BACK-button.
* A long click on the back button takes you directly to the dashboard.
*
*/
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
System.out.println("Resetting backcounter");
backCounter=0;
super.onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* If another button than the back button is pressed the back counter is reseted, so you have to press BACK twice to return to dashboard.
*
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_MENU) {
return super.onKeyDown(keyCode, event);
}
else if (keyCode != KeyEvent.KEYCODE_BACK) {
System.out.println("Resetting backcounter");
backCounter=0;
return true;
}
return super.onKeyDown(keyCode, event);
}
public MyLocation getMyLocation(){
return myLocation;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mapviewmenu, menu);
return true;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private void setupMoodButtonQuickAction() {
final ActionItem happy = new ActionItem();
final Account user = Utilities.getUserAccount(getApplicationContext());
happy.setIcon(this.getResources().getDrawable(MoodEnum.HAPPY.getIcon()));
happy.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addMoodEventToTimeline(new MoodEvent(timeline.getId(), myLocation.getLocation(), MoodEnum.HAPPY, user));
qa.dismiss();
}
});
final ActionItem nervous = new ActionItem();
nervous.setIcon(this.getResources().getDrawable(MoodEnum.NERVOUS.getIcon()));
nervous.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addMoodEventToTimeline(new MoodEvent(timeline.getId(), myLocation.getLocation(), MoodEnum.NERVOUS, user));
qa.dismiss();
}
});
final ActionItem calm = new ActionItem();
calm.setIcon(this.getResources().getDrawable(MoodEnum.CALM.getIcon()));
calm.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addMoodEventToTimeline(new MoodEvent(timeline.getId(), myLocation.getLocation(), MoodEnum.CALM, user));
qa.dismiss();
}
});
final ActionItem sad = new ActionItem();
sad.setIcon(this.getResources().getDrawable(MoodEnum.SAD.getIcon()));
sad.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
addMoodEventToTimeline(new MoodEvent(timeline.getId(), myLocation.getLocation(), MoodEnum.SAD, user));
qa.dismiss();
}
});
moodButton = (LinearLayout) findViewById(R.id.MenuMoodButton);
moodButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
qa = new QuickAction(v);
qa.addActionItem(happy);
qa.addActionItem(nervous);
qa.addActionItem(calm);
qa.addActionItem(sad);
qa.setAnimStyle(QuickAction.ANIM_AUTO);
qa.show();
}
});
}
public ContentLoader getContentLoader() {
return contentLoader;
}
@Override
public void onResume() {
super.onResume();
Swarm.setActive(this);
Swarm.setAchievementNotificationsEnabled(true);
}
@Override
public void onPause() {
super.onPause();
Swarm.setInactive(this);
}
}
| false | true | protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* PICTURE CREATED **************");
Toast.makeText(this, R.string.Pic_created_toast, Toast.LENGTH_SHORT).show();
//Adding to picture count
DashboardActivity.addPictureCounter();
//Adding points for picture
DashboardActivity.addPointsCounter(Constants.PicturePoints);
//Adding achievement
if (DashboardActivity.getPictureCounter() == 1){
SwarmAchievement.unlock(Constants.PictureAchievement);
Toast.makeText(this, R.string.First_pic_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getPictureCounter() == 10){
SwarmAchievement.unlock(Constants.PictureTenAchievement);
Toast.makeText(this, R.string.Tenth_pic_achi_toast, Toast.LENGTH_LONG).show();
}
addPictureToTimeline(intentFilename);
intentFilename="";
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Pic_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Pic_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* VIDEO RECORDING CREATED **************");
Toast.makeText(this, R.string.Video_created_toast, Toast.LENGTH_SHORT).show();
//Adding to video count
DashboardActivity.addVideoCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.VideoPoints);
//Adding achievement
if (DashboardActivity.getVideoCounter() == 1){
SwarmAchievement.unlock(Constants.VideoAchievement);
Toast.makeText(this, R.string.First_video_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getVideoCounter() == 10){
SwarmAchievement.unlock(Constants.VideoTenAchievement);
Toast.makeText(this, R.string.Tenth_video_achi_toast, Toast.LENGTH_LONG).show();
}
videoUri = data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(videoUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(videoUri, this), Constants.VIDEO_STORAGE_FILEPATH, filename);
addVideoToTimeline(filename);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Video_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Video_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.RECORD_AUDIO_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* AUDIO RECORDING CREATED **************");
Toast.makeText(this, R.string.Audio_created_toast, Toast.LENGTH_SHORT).show();
//Adding to audio count
DashboardActivity.addAudioCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.AudioPoints);
//Adding achievement
if (DashboardActivity.getAudioCounter() == 1){
SwarmAchievement.unlock(Constants.AudioAchievement);
Toast.makeText(this, R.string.First_audio_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getAudioCounter() == 10){
SwarmAchievement.unlock(Constants.AudioTenAchievement);
Toast.makeText(this, R.string.Tenth_audio_achi_toast, Toast.LENGTH_LONG).show();
}
audioUri = data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(audioUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(audioUri, this), Constants.RECORDING_STORAGE_FILEPATH, filename);
addAudioToTimeline(filename);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Audio_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Audio_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.CREATE_NOTE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* NOTE CREATED **************");
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "*************************************");
Toast.makeText(this, R.string.Note_created_toast, Toast.LENGTH_SHORT).show();
//Adding to note count
DashboardActivity.addNoteCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.NotePoints);
//Adding achievement
if (DashboardActivity.getNoteCounter() == 1){
SwarmAchievement.unlock(Constants.NoteAchievement);
Toast.makeText(this, R.string.First_note_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getNoteCounter() == 10){
SwarmAchievement.unlock(Constants.NoteTenAchievement);
Toast.makeText(this, R.string.Tenth_note_achi_toast, Toast.LENGTH_LONG).show();
}
addNoteToTimeline(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Note_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Note_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
//TODO To see REF NOTE place in code...
// REFLECTION NOTE ADDED
case Constants.CREATE_REFLECTION_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* REFLECTION NOTE CREATED **************");
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "************************************************");
//Adding to reflection count
DashboardActivity.addReflectionCounter();
//Adding points
int points = DashboardActivity.checkAndSetRefNotePoints();
Toast.makeText(this, getString(R.string.Reflection_added_toast) + " Points rewarded for Reflection note is: "+points, Toast.LENGTH_SHORT).show();
//Setting date and time for ref note
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
DashboardActivity.setLastRefDate(calendar);
//Canceling former notifications
cancelNotifications();
//Setting alarm for notification
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 12, 1);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 14, 2);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 16, 3);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 18, 4);
//Adding achievement
if (DashboardActivity.getReflectionCounter() == 1){
SwarmAchievement.unlock(Constants.ReflectionNoteAchievement);
Toast.makeText(this, R.string.First_reflection_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getReflectionCounter() == 10){
SwarmAchievement.unlock(Constants.ReflectionNoteTenAchievement);
Toast.makeText(this, R.string.Tenth_reflection_achi_toast, Toast.LENGTH_LONG).show();
}
addReflectionToTimeline(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Reflection_not_added_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Reflection_not_added_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.EDIT_NOTE:
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.Note_edited_toast , Toast.LENGTH_SHORT).show();
updateNote(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Note_not_edited_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Note_not_edited_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.EDIT_REFLECTION:
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.Reflection_edited_toast , Toast.LENGTH_SHORT).show();
updateReflection(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Reflection_not_edited_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Reflection_not_edited_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.NEW_TAG_REQUESTCODE:
if (resultCode == RESULT_OK) {
updateTags();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Tag_not_added_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Tag_not_added_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.SELECT_PICTURE:
if(resultCode == Activity.RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* PICTURE SELECTED **************");
imageUri = (Uri) data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+".jpg";
Utilities.copyFile(Utilities.getRealPathFromURI(imageUri, this), Constants.IMAGE_STORAGE_FILEPATH, filename);
addPictureToTimeline(filename);
}
break;
case Constants.SELECT_VIDEO:
if(resultCode == Activity.RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* VIDEO SELECTED **************");
Toast.makeText(this, R.string.Video_selected_toast, Toast.LENGTH_SHORT).show();
videoUri = (Uri) data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(videoUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(videoUri, this), Constants.VIDEO_STORAGE_FILEPATH, filename);
addVideoToTimeline(filename);
}
case Constants.CAPTURE_BARCODE:
Log.i(this.getClass().getSimpleName(), "********* BARCODE SCANNED **************");
getBarcodeResults(requestCode, resultCode, data);
break;
case Constants.MAP_VIEW_ACTIVITY_REQUEST_CODE:
if(resultCode == RESULT_OK) {
String id = data.getExtras().getString("EVENT_ID");
BaseEvent selectedEvent = timeline.getEvent(id);
if(selectedEvent != null) {
if (selectedEvent instanceof Event) {
eventDialog = new EventDialog(this, (Event)selectedEvent, this, true);
eventDialog.show();
}
else {
moodDialog = new MoodDialog(this, (MoodEvent) selectedEvent);
moodDialog.show();
}
}
}
default:
break;
}
}
| protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case Constants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* PICTURE CREATED **************");
Toast.makeText(this, getString(R.string.Pic_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.PicturePoints, Toast.LENGTH_SHORT).show();
//Adding to picture count
DashboardActivity.addPictureCounter();
//Adding points for picture
DashboardActivity.addPointsCounter(Constants.PicturePoints);
//Adding achievement
if (DashboardActivity.getPictureCounter() == 1){
SwarmAchievement.unlock(Constants.PictureAchievement);
Toast.makeText(this, R.string.First_pic_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getPictureCounter() == 10){
SwarmAchievement.unlock(Constants.PictureTenAchievement);
Toast.makeText(this, R.string.Tenth_pic_achi_toast, Toast.LENGTH_LONG).show();
}
addPictureToTimeline(intentFilename);
intentFilename="";
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Pic_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Pic_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* VIDEO RECORDING CREATED **************");
Toast.makeText(this, getString(R.string.Video_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.VideoPoints, Toast.LENGTH_SHORT).show();
//Adding to video count
DashboardActivity.addVideoCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.VideoPoints);
//Adding achievement
if (DashboardActivity.getVideoCounter() == 1){
SwarmAchievement.unlock(Constants.VideoAchievement);
Toast.makeText(this, R.string.First_video_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getVideoCounter() == 10){
SwarmAchievement.unlock(Constants.VideoTenAchievement);
Toast.makeText(this, R.string.Tenth_video_achi_toast, Toast.LENGTH_LONG).show();
}
videoUri = data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(videoUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(videoUri, this), Constants.VIDEO_STORAGE_FILEPATH, filename);
addVideoToTimeline(filename);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Video_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Video_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.RECORD_AUDIO_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* AUDIO RECORDING CREATED **************");
Toast.makeText(this, getString(R.string.Audio_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.AudioPoints, Toast.LENGTH_SHORT).show();
//Adding to audio count
DashboardActivity.addAudioCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.AudioPoints);
//Adding achievement
if (DashboardActivity.getAudioCounter() == 1){
SwarmAchievement.unlock(Constants.AudioAchievement);
Toast.makeText(this, R.string.First_audio_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getAudioCounter() == 10){
SwarmAchievement.unlock(Constants.AudioTenAchievement);
Toast.makeText(this, R.string.Tenth_audio_achi_toast, Toast.LENGTH_LONG).show();
}
audioUri = data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(audioUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(audioUri, this), Constants.RECORDING_STORAGE_FILEPATH, filename);
addAudioToTimeline(filename);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Audio_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Audio_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.CREATE_NOTE_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* NOTE CREATED **************");
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "*************************************");
Toast.makeText(this, getString(R.string.Note_created_toast) + " " + getString(R.string.Points_rewarded_toast) + Constants.NotePoints, Toast.LENGTH_SHORT).show();
//Adding to note count
DashboardActivity.addNoteCounter();
//Adding points
DashboardActivity.addPointsCounter(Constants.NotePoints);
//Adding achievement
if (DashboardActivity.getNoteCounter() == 1){
SwarmAchievement.unlock(Constants.NoteAchievement);
Toast.makeText(this, R.string.First_note_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getNoteCounter() == 10){
SwarmAchievement.unlock(Constants.NoteTenAchievement);
Toast.makeText(this, R.string.Tenth_note_achi_toast, Toast.LENGTH_LONG).show();
}
addNoteToTimeline(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Note_not_created_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Note_not_created_toast, Toast.LENGTH_SHORT).show();
}
break;
//TODO To see REF NOTE place in code...
// REFLECTION NOTE ADDED
case Constants.CREATE_REFLECTION_ACTIVITY_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* REFLECTION NOTE CREATED **************");
Log.i(this.getClass().getSimpleName(), "Title: "+data.getExtras().getString(Intent.EXTRA_SUBJECT));
Log.i(this.getClass().getSimpleName(), "Text: "+data.getExtras().getString(Intent.EXTRA_TEXT));
Log.i(this.getClass().getSimpleName(), "************************************************");
//Adding to reflection count
DashboardActivity.addReflectionCounter();
//Adding points
int points = DashboardActivity.checkAndSetRefNotePoints();
Toast.makeText(this, getString(R.string.Reflection_added_toast) + " " + getString(R.string.Points_rewarded_toast)+points, Toast.LENGTH_SHORT).show();
//Setting date and time for ref note
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
DashboardActivity.setLastRefDate(calendar);
//Canceling former notifications
cancelNotifications();
//Setting alarm for notification
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 12, 1);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 14, 2);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 16, 3);
createScheduledNotification(DashboardActivity.checkReflectionDate(), "notify", 18, 4);
//Adding achievement
if (DashboardActivity.getReflectionCounter() == 1){
SwarmAchievement.unlock(Constants.ReflectionNoteAchievement);
Toast.makeText(this, R.string.First_reflection_achi_toast, Toast.LENGTH_LONG).show();
}
if (DashboardActivity.getReflectionCounter() == 10){
SwarmAchievement.unlock(Constants.ReflectionNoteTenAchievement);
Toast.makeText(this, R.string.Tenth_reflection_achi_toast, Toast.LENGTH_LONG).show();
}
addReflectionToTimeline(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Reflection_not_added_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Reflection_not_added_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.EDIT_NOTE:
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.Note_edited_toast , Toast.LENGTH_SHORT).show();
updateNote(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Note_not_edited_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Note_not_edited_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.EDIT_REFLECTION:
if (resultCode == RESULT_OK) {
Toast.makeText(this, R.string.Reflection_edited_toast , Toast.LENGTH_SHORT).show();
updateReflection(data);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Reflection_not_edited_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Reflection_not_edited_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.NEW_TAG_REQUESTCODE:
if (resultCode == RESULT_OK) {
updateTags();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, R.string.Tag_not_added_toast, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.Tag_not_added_toast, Toast.LENGTH_SHORT).show();
}
break;
case Constants.SELECT_PICTURE:
if(resultCode == Activity.RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* PICTURE SELECTED **************");
imageUri = (Uri) data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+".jpg";
Utilities.copyFile(Utilities.getRealPathFromURI(imageUri, this), Constants.IMAGE_STORAGE_FILEPATH, filename);
addPictureToTimeline(filename);
}
break;
case Constants.SELECT_VIDEO:
if(resultCode == Activity.RESULT_OK) {
Log.i(this.getClass().getSimpleName(), "********* VIDEO SELECTED **************");
Toast.makeText(this, R.string.Video_selected_toast, Toast.LENGTH_SHORT).show();
videoUri = (Uri) data.getData();
String filename =(Utilities.getUserAccount(this).name+new Date().getTime()).hashCode()+Utilities.getExtension(Utilities.getRealPathFromURI(videoUri, this));
Utilities.copyFile(Utilities.getRealPathFromURI(videoUri, this), Constants.VIDEO_STORAGE_FILEPATH, filename);
addVideoToTimeline(filename);
}
case Constants.CAPTURE_BARCODE:
Log.i(this.getClass().getSimpleName(), "********* BARCODE SCANNED **************");
getBarcodeResults(requestCode, resultCode, data);
break;
case Constants.MAP_VIEW_ACTIVITY_REQUEST_CODE:
if(resultCode == RESULT_OK) {
String id = data.getExtras().getString("EVENT_ID");
BaseEvent selectedEvent = timeline.getEvent(id);
if(selectedEvent != null) {
if (selectedEvent instanceof Event) {
eventDialog = new EventDialog(this, (Event)selectedEvent, this, true);
eventDialog.show();
}
else {
moodDialog = new MoodDialog(this, (MoodEvent) selectedEvent);
moodDialog.show();
}
}
}
default:
break;
}
}
|
diff --git a/src/run/SimPL.java b/src/run/SimPL.java
index 071a3ae..61e1eb6 100644
--- a/src/run/SimPL.java
+++ b/src/run/SimPL.java
@@ -1,297 +1,300 @@
package run;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import parse.Lexer;
import parse.parser;
import semantic.Env;
public class SimPL {
public static final int MAX_BUF_SIZE = 2048;
/**
* the buffer is used to clear a pipe
*/
private static final byte[] dummyBuf = new byte[MAX_BUF_SIZE];
/**
* @param args
*/
public static void main(String[] args) {
try {
Options options = new Options();
// -h parameter
options.addOption("h", "help", false, "print usage");
// -s parameter
options.addOption("s", "shell", false, "interactive shell");
// -f file
options.addOption("f", "file", true, "execute file");
// -o out
options.addOption("o", "out", true, "output file");
CommandLineParser parser = new PosixParser();
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("h")) {
printUsage();
} else if (cmd.hasOption("s")) {
run(null, null, true);
} else if (cmd.hasOption("f")) {
String infile = cmd.getOptionValue("f", "");
String outfile = null;
if (cmd.hasOption("o")) {
outfile = cmd.getOptionValue("o");
} else {
outfile = infile.split("\\.[a-z0-9]+$")[0] + ".rst";
}
run(infile, outfile, false);
} else {
printUsage();
System.exit(-1);
}
} catch (ParseException e) {
printUsage();
System.exit(-1);
}
System.exit(0);
}
public static void printUsage() {
System.err.println("Usage: SimPL [-s | -f file | -h]");
}
/**
* run SimPL, read from console or file, output to file or console
* @param infile input file, if null supplied, then stdin
* @param outfile output file, if null supplied, then stdout
*/
public static void run(String infile, String outfile, boolean printPrompt) {
Scanner in = null;
PrintWriter out = null;
Scanner pipereader = null;
PrintWriter pipeWriter = null;
try {
// create input scanner
if (infile == null || infile.isEmpty()) {
in = new Scanner(System.in);
} else {
in = new Scanner(new FileInputStream(infile));
}
// create output printer
if (outfile == null || outfile.isEmpty()) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(new FileOutputStream(outfile));
}
// construct a pipe
PipedInputStream pipeinstream = new PipedInputStream(MAX_BUF_SIZE);
PipedOutputStream pipeoutstream = new PipedOutputStream(pipeinstream);
pipereader = new Scanner(pipeinstream);
pipereader.useDelimiter("\\$");
pipeWriter = new PrintWriter(pipeoutstream);
int bufsize = 0;
Queue<Position> scriptStarts = new LinkedList<Position>();
scriptStarts.add(Position.ORIGIN_POSITION);
int linenum = 0;
if (printPrompt) {
out.print("SimPL> ");
}
while (in.hasNextLine()) {
// read a line from stdin
String line = in.nextLine();
// if it is only a blank line and nothing in buffer
// then just ingore
if (line.trim().isEmpty() && bufsize == 0) {
if (printPrompt) {
out.print("SimPL> ");
}
continue;
}
// add the total buffer size
bufsize += line.length() + 1;
// should not be more than 2k, if so, then abort
if (bufsize > MAX_BUF_SIZE) {
bufsize = 0;
// clear script positions
if (scriptStarts.size() != 1) {
scriptStarts.clear();
scriptStarts.add(Position.ORIGIN_POSITION);
}
// clear the pipe
pipeWriter.flush();
if (pipeinstream.available() != 0) {
pipeinstream.read(dummyBuf, 0, MAX_BUF_SIZE);
}
// reset linenum
linenum = 0;
// print error message and continue
System.err.println("Error: A script should be less than " + MAX_BUF_SIZE + " characters");
if (printPrompt) {
out.print("SimPL> ");
}
continue;
}
// count occurance of $, the number of expressions
// dollarCount += countDollar(line);
++linenum;
countDollar(line, linenum, scriptStarts);
// store the line into the pipe to read, including a new line
pipeWriter.println(line);
// a script will be executed only
// when the last character of the line is $
// if not, continue to read from stdin
if (line.trim().endsWith("$") == false) {
continue;
}
// now execute the scripts
pipeWriter.flush();
while (scriptStarts.size() > 1) {
String script = pipereader.next();
Position pos = scriptStarts.remove();
// if script is just an empty string, then ingore it
if (script.trim().isEmpty()) {
continue;
}
ErrorMessage.init(pos.line, pos.column);
runScript(script + "$", out);
}
// clear script positions
scriptStarts.clear();
scriptStarts.add(Position.ORIGIN_POSITION);
// clear
bufsize = 0;
// clear the pipe
if (pipeinstream.available() != 0) {
pipeinstream.read(dummyBuf, 0, MAX_BUF_SIZE);
}
// reset linenum
linenum = 0;
// print error message and continue
if (printPrompt) {
out.print("SimPL> ");
}
}
+ if (printPrompt == false && bufsize != 0) {
+ System.err.println("script not ended");
+ }
} catch (FileNotFoundException e) {
System.err.println("cannot open file: " + e.getMessage());
System.exit(-1);
} catch (IOException e) {
System.err.println("Unexpected Error");
e.printStackTrace();
System.exit(-1);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (pipereader != null) {
pipereader.close();
}
if (pipeWriter != null) {
pipeWriter.close();
}
}
}
private static class Position {
public int line;
public int column;
public Position(int line, int column) {
super();
this.line = line;
this.column = column;
}
public static final Position ORIGIN_POSITION = new Position(1, 1);
}
/**
* run a simpl script
* @param script script string, should end with $
* @return 0 if succeeded otherwise 1
*/
public static int runScript(String script, PrintWriter out) {
int retval = 1;
try {
parser p = new parser(new Lexer(new ByteArrayInputStream(script.getBytes())));
p.parse();
Env env = new Env();
out.println(p.result.execute(env));
retval = 0;
} catch (SimplException e) {
System.err.println(e.getMessage());
System.err.println(ErrorMessage.pos());
} catch (Exception e) {
e.printStackTrace();
}
return retval;
}
private static void countDollar(String str, int linenum, Queue<Position> scriptStarts) {
for (int i = 0; i < str.length(); ++i) {
if (str.charAt(i) == '$') {
scriptStarts.add(new Position(linenum, i + 2));
}
}
}
}
| true | true | public static void run(String infile, String outfile, boolean printPrompt) {
Scanner in = null;
PrintWriter out = null;
Scanner pipereader = null;
PrintWriter pipeWriter = null;
try {
// create input scanner
if (infile == null || infile.isEmpty()) {
in = new Scanner(System.in);
} else {
in = new Scanner(new FileInputStream(infile));
}
// create output printer
if (outfile == null || outfile.isEmpty()) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(new FileOutputStream(outfile));
}
// construct a pipe
PipedInputStream pipeinstream = new PipedInputStream(MAX_BUF_SIZE);
PipedOutputStream pipeoutstream = new PipedOutputStream(pipeinstream);
pipereader = new Scanner(pipeinstream);
pipereader.useDelimiter("\\$");
pipeWriter = new PrintWriter(pipeoutstream);
int bufsize = 0;
Queue<Position> scriptStarts = new LinkedList<Position>();
scriptStarts.add(Position.ORIGIN_POSITION);
int linenum = 0;
if (printPrompt) {
out.print("SimPL> ");
}
while (in.hasNextLine()) {
// read a line from stdin
String line = in.nextLine();
// if it is only a blank line and nothing in buffer
// then just ingore
if (line.trim().isEmpty() && bufsize == 0) {
if (printPrompt) {
out.print("SimPL> ");
}
continue;
}
// add the total buffer size
bufsize += line.length() + 1;
// should not be more than 2k, if so, then abort
if (bufsize > MAX_BUF_SIZE) {
bufsize = 0;
// clear script positions
if (scriptStarts.size() != 1) {
scriptStarts.clear();
scriptStarts.add(Position.ORIGIN_POSITION);
}
// clear the pipe
pipeWriter.flush();
if (pipeinstream.available() != 0) {
pipeinstream.read(dummyBuf, 0, MAX_BUF_SIZE);
}
// reset linenum
linenum = 0;
// print error message and continue
System.err.println("Error: A script should be less than " + MAX_BUF_SIZE + " characters");
if (printPrompt) {
out.print("SimPL> ");
}
continue;
}
// count occurance of $, the number of expressions
// dollarCount += countDollar(line);
++linenum;
countDollar(line, linenum, scriptStarts);
// store the line into the pipe to read, including a new line
pipeWriter.println(line);
// a script will be executed only
// when the last character of the line is $
// if not, continue to read from stdin
if (line.trim().endsWith("$") == false) {
continue;
}
// now execute the scripts
pipeWriter.flush();
while (scriptStarts.size() > 1) {
String script = pipereader.next();
Position pos = scriptStarts.remove();
// if script is just an empty string, then ingore it
if (script.trim().isEmpty()) {
continue;
}
ErrorMessage.init(pos.line, pos.column);
runScript(script + "$", out);
}
// clear script positions
scriptStarts.clear();
scriptStarts.add(Position.ORIGIN_POSITION);
// clear
bufsize = 0;
// clear the pipe
if (pipeinstream.available() != 0) {
pipeinstream.read(dummyBuf, 0, MAX_BUF_SIZE);
}
// reset linenum
linenum = 0;
// print error message and continue
if (printPrompt) {
out.print("SimPL> ");
}
}
} catch (FileNotFoundException e) {
System.err.println("cannot open file: " + e.getMessage());
System.exit(-1);
} catch (IOException e) {
System.err.println("Unexpected Error");
e.printStackTrace();
System.exit(-1);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (pipereader != null) {
pipereader.close();
}
if (pipeWriter != null) {
pipeWriter.close();
}
}
}
| public static void run(String infile, String outfile, boolean printPrompt) {
Scanner in = null;
PrintWriter out = null;
Scanner pipereader = null;
PrintWriter pipeWriter = null;
try {
// create input scanner
if (infile == null || infile.isEmpty()) {
in = new Scanner(System.in);
} else {
in = new Scanner(new FileInputStream(infile));
}
// create output printer
if (outfile == null || outfile.isEmpty()) {
out = new PrintWriter(System.out);
} else {
out = new PrintWriter(new FileOutputStream(outfile));
}
// construct a pipe
PipedInputStream pipeinstream = new PipedInputStream(MAX_BUF_SIZE);
PipedOutputStream pipeoutstream = new PipedOutputStream(pipeinstream);
pipereader = new Scanner(pipeinstream);
pipereader.useDelimiter("\\$");
pipeWriter = new PrintWriter(pipeoutstream);
int bufsize = 0;
Queue<Position> scriptStarts = new LinkedList<Position>();
scriptStarts.add(Position.ORIGIN_POSITION);
int linenum = 0;
if (printPrompt) {
out.print("SimPL> ");
}
while (in.hasNextLine()) {
// read a line from stdin
String line = in.nextLine();
// if it is only a blank line and nothing in buffer
// then just ingore
if (line.trim().isEmpty() && bufsize == 0) {
if (printPrompt) {
out.print("SimPL> ");
}
continue;
}
// add the total buffer size
bufsize += line.length() + 1;
// should not be more than 2k, if so, then abort
if (bufsize > MAX_BUF_SIZE) {
bufsize = 0;
// clear script positions
if (scriptStarts.size() != 1) {
scriptStarts.clear();
scriptStarts.add(Position.ORIGIN_POSITION);
}
// clear the pipe
pipeWriter.flush();
if (pipeinstream.available() != 0) {
pipeinstream.read(dummyBuf, 0, MAX_BUF_SIZE);
}
// reset linenum
linenum = 0;
// print error message and continue
System.err.println("Error: A script should be less than " + MAX_BUF_SIZE + " characters");
if (printPrompt) {
out.print("SimPL> ");
}
continue;
}
// count occurance of $, the number of expressions
// dollarCount += countDollar(line);
++linenum;
countDollar(line, linenum, scriptStarts);
// store the line into the pipe to read, including a new line
pipeWriter.println(line);
// a script will be executed only
// when the last character of the line is $
// if not, continue to read from stdin
if (line.trim().endsWith("$") == false) {
continue;
}
// now execute the scripts
pipeWriter.flush();
while (scriptStarts.size() > 1) {
String script = pipereader.next();
Position pos = scriptStarts.remove();
// if script is just an empty string, then ingore it
if (script.trim().isEmpty()) {
continue;
}
ErrorMessage.init(pos.line, pos.column);
runScript(script + "$", out);
}
// clear script positions
scriptStarts.clear();
scriptStarts.add(Position.ORIGIN_POSITION);
// clear
bufsize = 0;
// clear the pipe
if (pipeinstream.available() != 0) {
pipeinstream.read(dummyBuf, 0, MAX_BUF_SIZE);
}
// reset linenum
linenum = 0;
// print error message and continue
if (printPrompt) {
out.print("SimPL> ");
}
}
if (printPrompt == false && bufsize != 0) {
System.err.println("script not ended");
}
} catch (FileNotFoundException e) {
System.err.println("cannot open file: " + e.getMessage());
System.exit(-1);
} catch (IOException e) {
System.err.println("Unexpected Error");
e.printStackTrace();
System.exit(-1);
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
if (pipereader != null) {
pipereader.close();
}
if (pipeWriter != null) {
pipeWriter.close();
}
}
}
|
diff --git a/net.mysocio.default-ui-manager/src/main/java/net/mysocio/ui/executors/basic/likeMessageExecutor.java b/net.mysocio.default-ui-manager/src/main/java/net/mysocio/ui/executors/basic/likeMessageExecutor.java
index de2291a..b240b5e 100644
--- a/net.mysocio.default-ui-manager/src/main/java/net/mysocio/ui/executors/basic/likeMessageExecutor.java
+++ b/net.mysocio.default-ui-manager/src/main/java/net/mysocio/ui/executors/basic/likeMessageExecutor.java
@@ -1,42 +1,45 @@
/**
*
*/
package net.mysocio.ui.executors.basic;
import net.mysocio.data.IConnectionData;
import net.mysocio.data.IDataManager;
import net.mysocio.data.SocioUser;
import net.mysocio.data.accounts.Account;
import net.mysocio.data.management.DataManagerFactory;
import net.mysocio.data.messages.GeneralMessage;
import net.mysocio.ui.management.CommandExecutionException;
import net.mysocio.ui.management.ICommandExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Aladdin
*
*/
public class LikeMessageExecutor implements ICommandExecutor {
private static final Logger logger = LoggerFactory.getLogger(LikeMessageExecutor.class);
@Override
public String execute(IConnectionData connectionData)
throws CommandExecutionException {
IDataManager dataManager = DataManagerFactory.getDataManager();
String accounts = connectionData.getRequestParameter("accounts");
String messageId = connectionData.getRequestParameter("messageId");
SocioUser user = dataManager.getObject(SocioUser.class, connectionData.getUserId());
GeneralMessage message = dataManager.getObject(GeneralMessage.class, messageId);
Account account = user.getMainAccount();
+ if (message == null){
+ throw new CommandExecutionException("dialog.sorry.message.was.already.deleted");
+ }
try {
account.like(message);
} catch (Exception e) {
logger.error("Couldn't post to account with id " + account.getId(),e);
throw new CommandExecutionException(e);
}
return "";
}
}
| true | true | public String execute(IConnectionData connectionData)
throws CommandExecutionException {
IDataManager dataManager = DataManagerFactory.getDataManager();
String accounts = connectionData.getRequestParameter("accounts");
String messageId = connectionData.getRequestParameter("messageId");
SocioUser user = dataManager.getObject(SocioUser.class, connectionData.getUserId());
GeneralMessage message = dataManager.getObject(GeneralMessage.class, messageId);
Account account = user.getMainAccount();
try {
account.like(message);
} catch (Exception e) {
logger.error("Couldn't post to account with id " + account.getId(),e);
throw new CommandExecutionException(e);
}
return "";
}
| public String execute(IConnectionData connectionData)
throws CommandExecutionException {
IDataManager dataManager = DataManagerFactory.getDataManager();
String accounts = connectionData.getRequestParameter("accounts");
String messageId = connectionData.getRequestParameter("messageId");
SocioUser user = dataManager.getObject(SocioUser.class, connectionData.getUserId());
GeneralMessage message = dataManager.getObject(GeneralMessage.class, messageId);
Account account = user.getMainAccount();
if (message == null){
throw new CommandExecutionException("dialog.sorry.message.was.already.deleted");
}
try {
account.like(message);
} catch (Exception e) {
logger.error("Couldn't post to account with id " + account.getId(),e);
throw new CommandExecutionException(e);
}
return "";
}
|
diff --git a/src/com/ichi2/anki/Deck.java b/src/com/ichi2/anki/Deck.java
index 8b9e34b5..0371dfd1 100644
--- a/src/com/ichi2/anki/Deck.java
+++ b/src/com/ichi2/anki/Deck.java
@@ -1,4335 +1,4335 @@
/****************************************************************************************
* Copyright (c) 2009 Daniel Svärd <[email protected]> *
* Copyright (c) 2009 Casey Link <[email protected]> *
* Copyright (c) 2009 Edu Zamora <[email protected]> *
* Copyright (c) 2010 Norbert Nagold <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki;
import android.content.ContentValues;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteStatement;
import android.util.Log;
import com.ichi2.anki.Fact.Field;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* A deck stores all of the cards and scheduling information. It is saved in a file with a name ending in .anki See
* http://ichi2.net/anki/wiki/KeyTermsAndConcepts#Deck
*/
public class Deck {
public static final String TAG_MARKED = "Marked";
public static final int DECK_VERSION = 64;
private static final int NEW_CARDS_DISTRIBUTE = 0;
private static final int NEW_CARDS_LAST = 1;
private static final int NEW_CARDS_FIRST = 2;
private static final int NEW_CARDS_RANDOM = 0;
private static final int NEW_CARDS_OLD_FIRST = 1;
private static final int NEW_CARDS_NEW_FIRST = 2;
private static final int REV_CARDS_OLD_FIRST = 0;
private static final int REV_CARDS_NEW_FIRST = 1;
private static final int REV_CARDS_DUE_FIRST = 2;
private static final int REV_CARDS_RANDOM = 3;
public static final double FACTOR_FOUR = 1.3;
public static final double INITIAL_FACTOR = 2.5;
private static final double MINIMUM_AVERAGE = 1.7;
private static final double MAX_SCHEDULE_TIME = 36500.0;
// Card order strings for building SQL statements
private static final String[] revOrderStrings = { "priority desc, interval desc", "priority desc, interval",
"priority desc, combinedDue", "priority desc, factId, ordinal" };
private static final String[] newOrderStrings = { "priority desc, due", "priority desc, due",
"priority desc, due desc" };
// BEGIN: SQL table columns
private long mId;
private double mCreated;
private double mModified;
private String mDescription;
private int mVersion;
private long mCurrentModelId;
// syncName stores an md5sum of the deck path when syncing is enabled.
// If it doesn't match the current deck path, the deck has been moved,
// and syncing is disabled on load.
private String mSyncName;
private double mLastSync;
private boolean mNeedUnpack = false;
// Scheduling
// Initial intervals
private double mHardIntervalMin;
private double mHardIntervalMax;
private double mMidIntervalMin;
private double mMidIntervalMax;
private double mEasyIntervalMin;
private double mEasyIntervalMax;
// Delays on failure
private long mDelay0;
// Days to delay mature fails
private long mDelay1;
private double mDelay2;
// Collapsing future cards
private double mCollapseTime;
// Priorities and postponing
private String mHighPriority;
private String mMedPriority;
private String mLowPriority;
private String mSuspended; // obsolete in libanki 1.1
// 0 is random, 1 is by input date
private int mNewCardOrder;
// When to show new cards
private int mNewCardSpacing;
// New card spacing global variable
private double mNewSpacing;
private boolean mNewFromCache;
// Limit the number of failed cards in play
private int mFailedCardMax;
// Number of new cards to show per day
private int mNewCardsPerDay;
// Currently unused
private long mSessionRepLimit;
private long mSessionTimeLimit;
// Stats offset
private double mUtcOffset;
// Count cache
private int mCardCount;
private int mFactCount;
private int mFailedNowCount; // obsolete in libanki 1.1
private int mFailedSoonCount;
private int mRevCount;
private int mNewCount;
// Review order
private int mRevCardOrder;
// END: SQL table columns
// BEGIN JOINed variables
// Model currentModel; // Deck.currentModelId = Model.id
// ArrayList<Model> models; // Deck.id = Model.deckId
// END JOINed variables
private double mAverageFactor;
private int mNewCardModulus;
private int mNewCountToday;
private double mLastLoaded;
private boolean mNewEarly;
private boolean mReviewEarly;
public String mMediaPrefix;
private double mDueCutoff;
private double mFailedCutoff;
private String mScheduler;
// Any comments resulting from upgrading the deck should be stored here, both in success and failure
private ArrayList<Integer> upgradeNotes;
// Queues
private LinkedList<QueueItem> mFailedQueue;
private LinkedList<QueueItem> mRevQueue;
private LinkedList<QueueItem> mNewQueue;
private LinkedList<QueueItem> mFailedCramQueue;
private HashMap<Long, Double> mSpacedFacts;
private LinkedList<SpacedCardsItem> mSpacedCards;
private int mQueueLimit;
// Cramming
private String[] mActiveCramTags;
private String mCramOrder;
// Not in Anki Desktop
private String mDeckPath;
private String mDeckName;
private Stats mGlobalStats;
private Stats mDailyStats;
private long mCurrentCardId;
/**
* Undo/Redo variables.
*/
private Stack<UndoRow> mUndoStack;
private Stack<UndoRow> mRedoStack;
private boolean mUndoEnabled = false;
public static synchronized Deck openDeck(String path) throws SQLException {
return openDeck(path, true);
}
public static synchronized Deck openDeck(String path, boolean rebuild) throws SQLException {
Deck deck = null;
Cursor cursor = null;
Log.i(AnkiDroidApp.TAG, "openDeck - Opening database " + path);
AnkiDb ankiDB = AnkiDatabaseManager.getDatabase(path);
try {
// Read in deck table columns
cursor = ankiDB.getDatabase().rawQuery("SELECT * FROM decks LIMIT 1", null);
if (!cursor.moveToFirst()) {
return null;
}
deck = new Deck();
deck.mId = cursor.getLong(0);
deck.mCreated = cursor.getDouble(1);
deck.mModified = cursor.getDouble(2);
deck.mDescription = cursor.getString(3);
deck.mVersion = cursor.getInt(4);
deck.mCurrentModelId = cursor.getLong(5);
deck.mSyncName = cursor.getString(6);
deck.mLastSync = cursor.getDouble(7);
deck.mHardIntervalMin = cursor.getDouble(8);
deck.mHardIntervalMax = cursor.getDouble(9);
deck.mMidIntervalMin = cursor.getDouble(10);
deck.mMidIntervalMax = cursor.getDouble(11);
deck.mEasyIntervalMin = cursor.getDouble(12);
deck.mEasyIntervalMax = cursor.getDouble(13);
deck.mDelay0 = cursor.getLong(14);
deck.mDelay1 = cursor.getLong(15);
deck.mDelay2 = cursor.getDouble(16);
deck.mCollapseTime = cursor.getDouble(17);
deck.mHighPriority = cursor.getString(18);
deck.mMedPriority = cursor.getString(19);
deck.mLowPriority = cursor.getString(20);
deck.mSuspended = cursor.getString(21);
deck.mNewCardOrder = cursor.getInt(22);
deck.mNewCardSpacing = cursor.getInt(23);
deck.mFailedCardMax = cursor.getInt(24);
deck.mNewCardsPerDay = cursor.getInt(25);
deck.mSessionRepLimit = cursor.getInt(26);
deck.mSessionTimeLimit = cursor.getInt(27);
deck.mUtcOffset = cursor.getDouble(28);
deck.mCardCount = cursor.getInt(29);
deck.mFactCount = cursor.getInt(30);
deck.mFailedNowCount = cursor.getInt(31);
deck.mFailedSoonCount = cursor.getInt(32);
deck.mRevCount = cursor.getInt(33);
deck.mNewCount = cursor.getInt(34);
deck.mRevCardOrder = cursor.getInt(35);
Log.i(AnkiDroidApp.TAG, "openDeck - Read " + cursor.getColumnCount() + " columns from decks table.");
} finally {
if (cursor != null) {
cursor.close();
}
}
Log.i(AnkiDroidApp.TAG, String.format(Utils.ENGLISH_LOCALE, "openDeck - modified: %f currentTime: %f", deck.mModified, Utils.now()));
// Initialise queues
deck.mFailedQueue = new LinkedList<QueueItem>();
deck.mRevQueue = new LinkedList<QueueItem>();
deck.mNewQueue = new LinkedList<QueueItem>();
deck.mFailedCramQueue = new LinkedList<QueueItem>();
deck.mSpacedFacts = new HashMap<Long, Double>();
deck.mSpacedCards = new LinkedList<SpacedCardsItem>();
deck.mDeckPath = path;
deck.mDeckName = (new File(path)).getName().replace(".anki", "");
if (deck.mVersion < DECK_VERSION) {
deck.createMetadata();
}
deck.mNeedUnpack = false;
if (Math.abs(deck.getUtcOffset() - 1.0) < 1e-9 || Math.abs(deck.getUtcOffset() - 2.0) < 1e-9) {
// do the rest later
deck.mNeedUnpack = (Math.abs(deck.getUtcOffset() - 1.0) < 1e-9);
// make sure we do this before initVars
deck.setUtcOffset();
deck.mCreated = Utils.now();
}
deck.initVars();
// Upgrade to latest version
deck.upgradeDeck();
if (!rebuild) {
// Minimal startup
deck.mGlobalStats = Stats.globalStats(deck);
deck.mDailyStats = Stats.dailyStats(deck);
return deck;
}
if (deck.mNeedUnpack) {
deck.addIndices();
}
double oldMod = deck.mModified;
// Ensure necessary indices are available
deck.updateDynamicIndices();
// FIXME: Temporary code for upgrade - ensure cards suspended on older clients are recognized
// Ensure cards suspended on older clients are recognized
deck.getDB().getDatabase().execSQL(
"UPDATE cards SET type = type - 3 WHERE type BETWEEN 0 AND 2 AND priority = -3");
// - New delay1 handling
if (deck.mDelay1 > 7l) {
deck.mDelay1 = 0l;
}
ArrayList<Long> ids = new ArrayList<Long>();
// Unsuspend buried/rev early - can remove priorities in the future
ids = deck.getDB().queryColumn(Long.class,
"SELECT id FROM cards WHERE type > 2 OR (priority BETWEEN -2 AND -1)", 0);
if (!ids.isEmpty()) {
deck.updatePriorities(Utils.toPrimitive(ids));
deck.getDB().getDatabase().execSQL("UPDATE cards SET type = relativeDelay WHERE type > 2");
// Save deck to database
deck.commitToDB();
}
// Determine starting factor for new cards
Cursor cur = null;
try {
cur = deck.getDB().getDatabase().rawQuery("SELECT avg(factor) FROM cards WHERE type = 1", null);
if (cur.moveToNext()) {
deck.mAverageFactor = cur.getDouble(0);
} else {
deck.mAverageFactor = INITIAL_FACTOR;
}
if (deck.mAverageFactor == 0.0) {
deck.mAverageFactor = INITIAL_FACTOR;
}
} catch (Exception e) {
deck.mAverageFactor = INITIAL_FACTOR;
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
deck.mAverageFactor = Math.max(deck.mAverageFactor, MINIMUM_AVERAGE);
// Rebuild queue
deck.reset();
// Make sure we haven't accidentally bumped the modification time
double dbMod = 0.0;
try {
cur = deck.getDB().getDatabase().rawQuery("SELECT modified FROM decks", null);
if (cur.moveToNext()) {
dbMod = cur.getDouble(0);
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
assert Math.abs(dbMod - oldMod) < 1.0e-9;
assert deck.mModified == oldMod;
// Create a temporary view for random new cards. Randomizing the cards by themselves
// as is done in desktop Anki in Deck.randomizeNewCards() takes too long.
try {
deck.getDB().getDatabase().execSQL(
"CREATE TEMPORARY VIEW acqCardsRandom AS SELECT * FROM cards " + "WHERE type = " + Card.TYPE_NEW
+ " AND isDue = 1 ORDER BY RANDOM()");
} catch (SQLException e) {
/* Temporary view may still be present if the DB has not been closed */
Log.i(AnkiDroidApp.TAG, "Failed to create temporary view: " + e.getMessage());
}
// Initialize Undo
deck.initUndo();
return deck;
}
public void createMetadata() {
// Just create table deckvars for now
getDB().getDatabase().execSQL(
"CREATE TABLE IF NOT EXISTS deckVars (\"key\" TEXT NOT NULL, value TEXT, " + "PRIMARY KEY (\"key\"))");
}
public synchronized void closeDeck() {
DeckTask.waitToFinish(); // Wait for any thread working on the deck to finish.
if (finishSchedulerMethod != null) {
finishScheduler();
reset();
}
if (modifiedSinceSave()) {
commitToDB();
}
AnkiDatabaseManager.closeDatabase(mDeckPath);
}
public static synchronized int getDeckVersion(String path) throws SQLException {
int version = (int) AnkiDatabaseManager.getDatabase(path).queryScalar("SELECT version FROM decks LIMIT 1");
return version;
}
public Fact newFact(Long modelId) {
Model m = Model.getModel(this, modelId, true);
Fact mFact = new Fact(this, m);
return mFact;
}
public Fact newFact() {
Model m = Model.getModel(this, getCurrentModelId(), true);
Fact mFact = new Fact(this, m);
return mFact;
}
public TreeMap<Long, CardModel> availableCardModels(Fact fact) {
TreeMap<Long, CardModel> cardModels = new TreeMap<Long, CardModel>();
TreeMap<Long, CardModel> availableCardModels = new TreeMap<Long, CardModel>();
CardModel.fromDb(this, fact.getModelId(), cardModels);
for (Map.Entry<Long, CardModel> entry : cardModels.entrySet()) {
CardModel cardmodel = entry.getValue();
if (cardmodel.isActive()) {
// TODO: check for emptiness
availableCardModels.put(cardmodel.getId(), cardmodel);
}
}
return availableCardModels;
}
public TreeMap<Long, CardModel> cardModels(Fact fact) {
TreeMap<Long, CardModel> cardModels = new TreeMap<Long, CardModel>();
CardModel.fromDb(this, fact.getModelId(), cardModels);
return cardModels;
}
/**
* deckVars methods
*/
public boolean hasKey(String key) {
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery("SELECT 1 FROM deckVars WHERE key = '" + key + "'", null);
return cur.moveToNext();
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
public int getInt(String key) throws SQLException {
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery("SELECT value FROM deckVars WHERE key = '" + key + "'", null);
if (cur.moveToFirst()) {
return cur.getInt(0);
} else {
throw new SQLException("DeckVars.getInt: could not retrieve value for " + key);
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
public double getFloat(String key) throws SQLException {
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery("SELECT value FROM deckVars WHERE key = '" + key + "'", null);
if (cur.moveToFirst()) {
return cur.getFloat(0);
} else {
throw new SQLException("DeckVars.getFloat: could not retrieve value for " + key);
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
public boolean getBool(String key) {
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery("SELECT value FROM deckVars WHERE key = '" + key + "'", null);
if (cur.moveToFirst()) {
return (cur.getInt(0) != 0);
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
return false;
}
public String getVar(String key) {
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery("SELECT value FROM deckVars WHERE key = '" + key + "'", null);
if (cur.moveToFirst()) {
return cur.getString(0);
}
} catch (SQLException e) {
Log.e(AnkiDroidApp.TAG, "getVar: " + e.toString());
throw new RuntimeException(e);
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
return null;
}
public void setVar(String key, String value) {
setVar(key, value, true);
}
public void setVar(String key, String value, boolean mod) {
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery("SELECT value FROM deckVars WHERE key = '" + key + "'", null);
if (cur.moveToNext()) {
if (cur.getString(0).equals(value)) {
return;
} else {
getDB().getDatabase()
.execSQL("UPDATE deckVars SET value='" + value + "' WHERE key = '" + key + "'");
}
} else {
getDB().getDatabase().execSQL(
"INSERT INTO deckVars (key, value) VALUES ('" + key + "', '" + value + "')");
}
} catch (SQLException e) {
Log.e(AnkiDroidApp.TAG, "setVar: " + e.toString());
throw new RuntimeException(e);
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
public void setVarDefault(String key, String value) {
if (!hasKey(key)) {
getDB().getDatabase().execSQL("INSERT INTO deckVars (key, value) values ('" + key + "', '" + value + "')");
}
}
private void initVars() {
// tmpMediaDir = null;
mMediaPrefix = null;
// lastTags = "";
mLastLoaded = Utils.now();
// undoEnabled = false;
// sessionStartReps = 0;
// sessionStartTime = 0;
// lastSessionStart = 0;
mQueueLimit = 200;
// If most recent deck var not defined, make sure defaults are set
if (!hasKey("latexPost")) {
setVarDefault("suspendLeeches", "1");
setVarDefault("leechFails", "16");
setVarDefault("perDay", "1");
setVarDefault("newActive", "");
setVarDefault("revActive", "");
setVarDefault("newInactive", mSuspended);
setVarDefault("revInactive", mSuspended);
setVarDefault("newSpacing", "60");
setVarDefault("mediaURL", "");
setVarDefault("latexPre", "\\documentclass[12pt]{article}\n" + "\\special{papersize=3in,5in}\n"
+ "\\usepackage[utf8]{inputenc}\n" + "\\usepackage{amssymb,amsmath}\n" + "\\pagestyle{empty}\n"
+ "\\begin{document}\n");
setVarDefault("latexPost", "\\end{document}");
// FIXME: The next really belongs to the dropbox setup module, it's not supposed to be empty if the user
// wants to use dropbox. ankiqt/ankiqt/ui/main.py : setupMedia
setVarDefault("mediaLocation", "");
}
updateCutoff();
setupStandardScheduler();
}
// Media
// *****
/**
* Return the media directory if exists, none if couldn't be created.
*
* @param create If true it will attempt to create the folder if it doesn't exist
* @param rename This is used to simulate the python with create=None that is only used when renaming the mediaDir
* @return The path of the media directory
*/
public String mediaDir() {
return mediaDir(false, false);
}
public String mediaDir(boolean create) {
return mediaDir(create, false);
}
public String mediaDir(boolean create, boolean rename) {
String dir = null;
if (mDeckPath != null && !mDeckPath.equals("")) {
if (mMediaPrefix != null) {
dir = mMediaPrefix + "/" + mDeckName + ".media";
} else {
dir = mDeckPath.replaceAll("\\.anki$", ".media");
}
if (rename) {
// Don't create, but return dir
return dir;
} else {
File mediaDir = new File(dir);
if (!mediaDir.exists() && create) {
try {
if (!mediaDir.mkdir()) {
Log.e(AnkiDroidApp.TAG, "Couldn't create media directory " + dir);
return null;
}
} catch (SecurityException e) {
Log.e(AnkiDroidApp.TAG, "Security restriction: Couldn't create media directory " + dir);
return null;
}
}
}
}
if (dir == null) {
return null;
} else {
// TODO: Inefficient, should use prior File
File mediaDir = new File(dir);
if (!mediaDir.exists() || !mediaDir.isDirectory()) {
return null;
}
}
return dir;
}
/**
* Upgrade deck to latest version. Any comments resulting from the upgrade, should be stored in upgradeNotes, as
* R.string.id, successful or not. The idea is to have Deck.java generate the notes from upgrading and not the UI.
* Still we need access to a Resources object and it's messy to pass that in openDeck. Instead we store the ids for
* the messages and make a separate call from the UI to static upgradeNotesToMessages in order to properly translate
* the IDs to messages for viewing. We shouldn't do this directly from the UI, as the messages contain %s variables
* that need to be populated from deck values, and it's better to contain the libanki logic to the relevant classes.
*
* @return True if the upgrade is supported, false if the upgrade needs to be performed by Anki Desktop
*/
private boolean upgradeDeck() {
// Oldest versions in existence are 31 as of 11/07/2010
// We support upgrading from 39 and up.
// Unsupported are about 135 decks, missing about 6% as of 11/07/2010
//
double oldmod = mModified;
upgradeNotes = new ArrayList<Integer>();
if (mVersion < 39) {
// Unsupported version
upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_too_old_version);
return false;
}
if (mVersion < 40) {
// Now stores media url
getDB().getDatabase().execSQL("UPDATE models SET features = ''");
mVersion = 40;
commitToDB();
}
if (mVersion < 43) {
getDB().getDatabase().execSQL("UPDATE fieldModels SET features = ''");
mVersion = 43;
commitToDB();
}
if (mVersion < 44) {
// Leaner indices
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_factId");
mVersion = 44;
commitToDB();
}
if (mVersion < 48) {
updateFieldCache(Utils.toPrimitive(getDB().queryColumn(Long.class, "SELECT id FROM facts", 0)));
mVersion = 48;
commitToDB();
}
if (mVersion < 50) {
// more new type handling
rebuildTypes();
mVersion = 50;
commitToDB();
}
if (mVersion < 52) {
// The commented code below follows libanki by setting the syncName to the MD5 hash of the path.
// The problem with that is that it breaks syncing with already uploaded decks.
// if ((mSyncName != null) && !mSyncName.equals("")) {
// if (!mDeckName.equals(mSyncName)) {
// upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_52_note);
// disableSyncing(false);
// } else {
// enableSyncing(false);
// }
// }
mVersion = 52;
commitToDB();
}
if (mVersion < 53) {
if (getBool("perDay")) {
if (Math.abs(mHardIntervalMin - 0.333) < 0.001) {
mHardIntervalMin = Math.max(1.0, mHardIntervalMin);
mHardIntervalMax = Math.max(1.1, mHardIntervalMax);
}
}
mVersion = 53;
commitToDB();
}
if (mVersion < 54) {
// editFontFamily now used as a boolean, but in integer type, so set to 1 == true
getDB().getDatabase().execSQL("UPDATE fieldModels SET editFontFamily = 1");
mVersion = 54;
commitToDB();
}
if (mVersion < 57) {
// Add an index for priority & modified
mVersion = 57;
commitToDB();
}
if (mVersion < 61) {
// First check if the deck has LaTeX, if so it should be upgraded in Anki
if (hasLaTeX()) {
upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_version_61_has_latex);
return false;
}
// Do our best to upgrade templates to the new style
String txt =
"<span style=\"font-family: %s; font-size: %spx; color: %s; white-space: pre-wrap;\">%s</span>";
Map<Long, Model> models = Model.getModels(this);
Set<String> unstyled = new HashSet<String>();
boolean changed = false;
for (Model m : models.values()) {
TreeMap<Long, FieldModel> fieldModels = m.getFieldModels();
for (FieldModel fm : fieldModels.values()) {
changed = false;
Log.i(AnkiDroidApp.TAG, "family: '" + fm.getQuizFontFamily() + "'");
Log.i(AnkiDroidApp.TAG, "family: " + fm.getQuizFontSize());
Log.i(AnkiDroidApp.TAG, "family: '" + fm.getQuizFontColour() + "'");
if ((fm.getQuizFontFamily() != null && !fm.getQuizFontFamily().equals("")) ||
fm.getQuizFontSize() != 0 ||
(fm.getQuizFontColour() != null && fm.getQuizFontColour().equals(""))) {
} else {
unstyled.add(fm.getName());
}
// Fill out missing info
if (fm.getQuizFontFamily() == null || fm.getQuizFontFamily().equals("")) {
fm.setQuizFontFamily("Arial");
changed = true;
}
if (fm.getQuizFontSize() == 0) {
fm.setQuizFontSize(20);
changed = true;
}
if (fm.getQuizFontColour() == null || fm.getQuizFontColour().equals("")) {
fm.setQuizFontColour("#000000");
changed = true;
}
if (fm.getEditFontSize() == 0) {
fm.setEditFontSize(20);
changed = true;
}
if (changed) {
fm.toDB(this);
}
}
for (CardModel cm : m.getCardModels()) {
// Embed the old font information into card templates
String format = cm.getQFormat();
cm.setQFormat(String.format(txt, cm.getQuestionFontFamily(), cm.getQuestionFontSize(),
cm.getQuestionFontColour(), format));
format = cm.getAFormat();
cm.setAFormat(String.format(txt, cm.getAnswerFontFamily(), cm.getAnswerFontSize(),
cm.getAnswerFontColour(), format));
// Escape fields that had no previous styling
for (String un : unstyled) {
String oldStyle = "%(" + un + ")s";
String newStyle = "{{{" + un + "}}}";
cm.setQFormat(cm.getQFormat().replace(oldStyle, newStyle));
cm.setAFormat(cm.getAFormat().replace(oldStyle, newStyle));
}
cm.toDB(this);
}
}
// Rebuild q/a for the above & because latex has changed
// We should be doing updateAllCards(), but it takes too long (really)
// updateAllCards();
// Rebuild the media db based on new format
Media.rebuildMediaDir(this, false);
mVersion = 61;
commitToDB();
}
if (mVersion < 62) {
// Updated Indices
String[] indices = { "intervalDesc", "intervalAsc", "randomOrder", "dueAsc", "dueDesc" };
for (String d : indices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_" + d + "2");
}
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_typeCombined");
addIndices();
updateDynamicIndices();
getDB().getDatabase().execSQL("VACUUM");
mVersion = 62;
commitToDB();
}
if (mVersion < 64) {
// Remove old static indices, as all clients should be libanki1.2+
String[] oldStaticIndices = { "ix_cards_duePriority", "ix_cards_priorityDue" };
for (String d : oldStaticIndices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS " + d);
}
// Remove old dynamic indices
String[] oldDynamicIndices = { "intervalDesc", "intervalAsc", "randomOrder", "dueAsc", "dueDesc" };
for (String d : oldDynamicIndices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_" + d);
}
getDB().getDatabase().execSQL("ANALYZE");
mVersion = 64;
commitToDB();
// Note: we keep the priority index for now
}
if (mVersion < 65) {
// We weren't correctly setting relativeDelay when answering cards in previous versions, so ensure
// everything is set correctly
rebuildTypes();
mVersion = 65;
commitToDB();
}
// Executing a pragma here is very slow on large decks, so we store our own record
- if (getInt("pageSize") != 4096) {
+ if ((!hasKey("pageSize")) || (getInt("pageSize") != 4096)) {
commitToDB();
getDB().getDatabase().execSQL("PRAGMA page_size = 4096");
getDB().getDatabase().execSQL("PRAGMA legacy_file_format = 0");
getDB().getDatabase().execSQL("VACUUM");
setVar("pageSize", "4096", false);
commitToDB();
}
assert (mModified == oldmod);
return true;
}
public static String upgradeNotesToMessages(Deck deck, Resources res) {
String notes = "";
for (Integer note : deck.upgradeNotes) {
notes = notes.concat(res.getString(note.intValue()) + "\n");
}
return notes;
}
private boolean hasLaTeX() {
Cursor cursor = null;
try {
cursor = getDB().getDatabase().rawQuery(
"SELECT Id FROM fields WHERE " +
"(value like '%[latex]%[/latex]%') OR " +
"(value like '%[$]%[/$]%') OR " +
"(value like '%[$$]%[/$$]%') LIMIT 1 ", null);
if (cursor.moveToFirst()) {
return true;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return false;
}
/**
* Add indices to the DB.
*/
private void addIndices() {
// Counts, failed cards
getDB().getDatabase().execSQL(
"CREATE INDEX IF NOT EXISTS ix_cards_typeCombined ON cards (type, " + "combinedDue, factId)");
// Scheduler-agnostic type
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cards_relativeDelay ON cards (relativeDelay)");
// Index on modified, to speed up sync summaries
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cards_modified ON cards (modified)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_facts_modified ON facts (modified)");
// Priority - temporary index to make compat code faster. This can be removed when all clients are on 1.2,
// as can the ones below
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cards_priority ON cards (priority)");
// Average factor
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cards_factor ON cards (type, factor)");
// Card spacing
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cards_factId ON cards (factId)");
// Stats
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_stats_typeDay ON stats (type, day)");
// Fields
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_fields_factId ON fields (factId)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_fields_fieldModelId ON fields (fieldModelId)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_fields_value ON fields (value)");
// Media
getDB().getDatabase().execSQL("CREATE UNIQUE INDEX IF NOT EXISTS ix_media_filename ON media (filename)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_media_originalPath ON media (originalPath)");
// Deletion tracking
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cardsDeleted_cardId ON cardsDeleted (cardId)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_modelsDeleted_modelId ON modelsDeleted (modelId)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_factsDeleted_factId ON factsDeleted (factId)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_mediaDeleted_factId ON mediaDeleted (mediaId)");
// Tags
String txt = "CREATE UNIQUE INDEX IF NOT EXISTS ix_tags_tag on tags (tag)";
try {
getDB().getDatabase().execSQL(txt);
} catch (SQLException e) {
getDB().getDatabase().execSQL("DELETE FROM tags WHERE EXISTS (SELECT 1 FROM tags t2 " +
"WHERE tags.tag = t2.tag AND tags.rowid > t2.rowid)");
getDB().getDatabase().execSQL(txt);
}
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cardTags_tagCard ON cardTags (tagId, cardId)");
getDB().getDatabase().execSQL("CREATE INDEX IF NOT EXISTS ix_cardTags_cardId ON cardTags (cardId)");
}
/*
* Add stripped HTML cache for sorting/searching. Currently needed as part of the upgradeDeck, the cache is not
* really used, yet.
*/
private void updateFieldCache(long[] fids) {
HashMap<Long, String> r = new HashMap<Long, String>();
Cursor cur = null;
Log.i(AnkiDroidApp.TAG, "updatefieldCache fids: " + Utils.ids2str(fids));
try {
cur = getDB().getDatabase().rawQuery(
"SELECT factId, group_concat(value, ' ') FROM fields " + "WHERE factId IN " + Utils.ids2str(fids)
+ " GROUP BY factId", null);
while (cur.moveToNext()) {
String values = cur.getString(1);
// if (values.charAt(0) == ' ') {
// Fix for a slight difference between how Android SQLite and python sqlite work.
// Inconsequential difference in this context, but messes up any effort for automated testing.
values = values.replaceFirst("^ *", "");
// }
r.put(cur.getLong(0), Utils.stripHTMLMedia(values));
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
if (r.size() > 0) {
getDB().getDatabase().beginTransaction();
SQLiteStatement st = getDB().getDatabase().compileStatement("UPDATE facts SET spaceUntil=? WHERE id=?");
for (Long fid : r.keySet()) {
st.bindString(1, r.get(fid));
st.bindLong(2, fid.longValue());
st.execute();
}
getDB().getDatabase().setTransactionSuccessful();
getDB().getDatabase().endTransaction();
}
}
private boolean modifiedSinceSave() {
return mModified > mLastLoaded;
}
/*
* Queue Management*****************************
*/
private class QueueItem {
private long cardID;
private long factID;
private double due;
QueueItem(long cardID, long factID) {
this.cardID = cardID;
this.factID = factID;
this.due = 0.0;
}
QueueItem(long cardID, long factID, double due) {
this.cardID = cardID;
this.factID = factID;
this.due = due;
}
long getCardID() {
return cardID;
}
long getFactID() {
return factID;
}
double getDue() {
return due;
}
}
private class SpacedCardsItem {
private double space;
private ArrayList<Long> cards;
SpacedCardsItem(double space, ArrayList<Long> cards) {
this.space = space;
this.cards = cards;
}
double getSpace() {
return space;
}
ArrayList<Long> getCards() {
return cards;
}
}
/*
* Tomorrow's due cards ******************************
*/
public int getNextDueCards() {
String sql = String.format(Utils.ENGLISH_LOCALE,
"SELECT count(*) FROM cards c WHERE type = 0 OR type = 1 AND combinedDue < %f", mDueCutoff + 86400);
return (int) getDB().queryScalar(cardLimit("revActive", "revInactive", sql));
}
public int getNextNewCards() {
String sql = String.format(Utils.ENGLISH_LOCALE,
"SELECT count(*) FROM cards c WHERE type = 2 AND combinedDue < %f", mDueCutoff + 86400);
return Math.min((int) getDB().queryScalar(cardLimit("newActive", "newInactive", sql)), mNewCardsPerDay);
}
/*
* Scheduler related overridable methods******************************
*/
private Method getCardIdMethod;
private Method fillFailedQueueMethod;
private Method fillRevQueueMethod;
private Method fillNewQueueMethod;
private Method rebuildFailedCountMethod;
private Method rebuildRevCountMethod;
private Method rebuildNewCountMethod;
private Method requeueCardMethod;
private Method timeForNewCardMethod;
private Method updateNewCountTodayMethod;
private Method cardQueueMethod;
private Method finishSchedulerMethod;
private Method answerCardMethod;
private Method cardLimitMethod;
private Method answerPreSaveMethod;
private Method spaceCardsMethod;
private long getCardId() {
try {
return ((Long) getCardIdMethod.invoke(Deck.this, true)).longValue();
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private long getCardId(boolean check) {
try {
return ((Long) getCardIdMethod.invoke(Deck.this, check)).longValue();
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void fillFailedQueue() {
try {
fillFailedQueueMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void fillRevQueue() {
try {
fillRevQueueMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void fillNewQueue() {
try {
fillNewQueueMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void rebuildFailedCount() {
try {
rebuildFailedCountMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void rebuildRevCount() {
try {
rebuildRevCountMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void rebuildNewCount() {
try {
rebuildNewCountMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void requeueCard(Card card, boolean oldIsRev) {
try {
requeueCardMethod.invoke(Deck.this, card, oldIsRev);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private boolean timeForNewCard() {
try {
return ((Boolean) timeForNewCardMethod.invoke(Deck.this)).booleanValue();
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void updateNewCountToday() {
try {
updateNewCountTodayMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private int cardQueue(Card card) {
try {
return ((Integer) cardQueueMethod.invoke(Deck.this, card)).intValue();
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public void finishScheduler() {
try {
finishSchedulerMethod.invoke(Deck.this);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public void answerCard(Card card, int ease) {
try {
answerCardMethod.invoke(Deck.this, card, ease);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private String cardLimit(String active, String inactive, String sql) {
try {
return ((String) cardLimitMethod.invoke(Deck.this, active, inactive, sql));
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private String cardLimit(String[] active, String[] inactive, String sql) {
try {
return ((String) cardLimitMethod.invoke(Deck.this, active, inactive, sql));
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void answerPreSave(Card card, int ease) {
try {
answerPreSaveMethod.invoke(Deck.this, card, ease);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private void spaceCards(Card card) {
try {
spaceCardsMethod.invoke(Deck.this, card);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public boolean hasFinishScheduler() {
return !(finishSchedulerMethod == null);
}
public String name() {
return mScheduler;
}
/*
* Standard Scheduling*****************************
*/
public void setupStandardScheduler() {
try {
getCardIdMethod = Deck.class.getDeclaredMethod("_getCardId", boolean.class);
fillFailedQueueMethod = Deck.class.getDeclaredMethod("_fillFailedQueue");
fillRevQueueMethod = Deck.class.getDeclaredMethod("_fillRevQueue");
fillNewQueueMethod = Deck.class.getDeclaredMethod("_fillNewQueue");
rebuildFailedCountMethod = Deck.class.getDeclaredMethod("_rebuildFailedCount");
rebuildRevCountMethod = Deck.class.getDeclaredMethod("_rebuildRevCount");
rebuildNewCountMethod = Deck.class.getDeclaredMethod("_rebuildNewCount");
requeueCardMethod = Deck.class.getDeclaredMethod("_requeueCard", Card.class, boolean.class);
timeForNewCardMethod = Deck.class.getDeclaredMethod("_timeForNewCard");
updateNewCountTodayMethod = Deck.class.getDeclaredMethod("_updateNewCountToday");
cardQueueMethod = Deck.class.getDeclaredMethod("_cardQueue", Card.class);
finishSchedulerMethod = null;
answerCardMethod = Deck.class.getDeclaredMethod("_answerCard", Card.class, int.class);
cardLimitMethod = Deck.class.getDeclaredMethod("_cardLimit", String.class, String.class, String.class);
answerPreSaveMethod = null;
spaceCardsMethod = Deck.class.getDeclaredMethod("_spaceCards", Card.class);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
mScheduler = "standard";
// Restore any cards temporarily suspended by alternate schedulers
if (mVersion == DECK_VERSION) {
resetAfterReviewEarly();
}
}
private void fillQueues() {
fillFailedQueue();
fillRevQueue();
fillNewQueue();
for (QueueItem i : mFailedQueue) {
Log.i(AnkiDroidApp.TAG, "failed queue: cid: " + i.getCardID() + " fid: " + i.getFactID() + " cd: " + i.getDue());
}
for (QueueItem i : mRevQueue) {
Log.i(AnkiDroidApp.TAG, "rev queue: cid: " + i.getCardID() + " fid: " + i.getFactID());
}
for (QueueItem i : mNewQueue) {
Log.i(AnkiDroidApp.TAG, "new queue: cid: " + i.getCardID() + " fid: " + i.getFactID());
}
}
public long retrieveCardCount() {
return getDB().queryScalar("SELECT count(*) from cards");
}
private void rebuildCounts() {
// global counts
try {
mCardCount = (int) getDB().queryScalar("SELECT count(*) from cards");
mFactCount = (int) getDB().queryScalar("SELECT count(*) from facts");
} catch (SQLException e) {
Log.e(AnkiDroidApp.TAG, "rebuildCounts: Error while getting global counts: " + e.toString());
mCardCount = 0;
mFactCount = 0;
}
// due counts
rebuildFailedCount();
rebuildRevCount();
rebuildNewCount();
}
@SuppressWarnings("unused")
private String _cardLimit(String active, String inactive, String sql) {
String[] yes = Utils.parseTags(getVar(active));
String[] no = Utils.parseTags(getVar(inactive));
if (yes.length > 0) {
long yids[] = Utils.toPrimitive(tagIds(yes).values());
long nids[] = Utils.toPrimitive(tagIds(no).values());
return sql.replace("WHERE", "WHERE +c.id IN (SELECT cardId FROM cardTags WHERE " + "tagId IN "
+ Utils.ids2str(yids) + ") AND +c.id NOT IN (SELECT cardId FROM " + "cardTags WHERE tagId in "
+ Utils.ids2str(nids) + ") AND");
} else if (no.length > 0) {
long nids[] = Utils.toPrimitive(tagIds(no).values());
return sql.replace("WHERE", "WHERE +c.id NOT IN (SELECT cardId FROM cardTags WHERE tagId IN "
+ Utils.ids2str(nids) + ") AND");
} else {
return sql;
}
}
/**
* This is a count of all failed cards within the current day cutoff. The cards may not be ready for review yet, but
* can still be displayed if failedCardsMax is reached.
*/
@SuppressWarnings("unused")
private void _rebuildFailedCount() {
String sql = String.format(Utils.ENGLISH_LOCALE,
"SELECT count(*) FROM cards c WHERE type = 0 AND combinedDue < %f", mFailedCutoff);
mFailedSoonCount = (int) getDB().queryScalar(cardLimit("revActive", "revInactive", sql));
}
@SuppressWarnings("unused")
private void _rebuildRevCount() {
String sql = String.format(Utils.ENGLISH_LOCALE,
"SELECT count(*) FROM cards c WHERE type = 1 AND combinedDue < %f", mDueCutoff);
mRevCount = (int) getDB().queryScalar(cardLimit("revActive", "revInactive", sql));
}
@SuppressWarnings("unused")
private void _rebuildNewCount() {
String sql = String.format(Utils.ENGLISH_LOCALE,
"SELECT count(*) FROM cards c WHERE type = 2 AND combinedDue < %f", mDueCutoff);
mNewCount = (int) getDB().queryScalar(cardLimit("newActive", "newInactive", sql));
updateNewCountToday();
mSpacedCards.clear();
}
@SuppressWarnings("unused")
private void _updateNewCountToday() {
mNewCountToday = Math.max(Math.min(mNewCount, mNewCardsPerDay - newCardsDoneToday()), 0);
}
@SuppressWarnings("unused")
private void _fillFailedQueue() {
if ((mFailedSoonCount != 0) && mFailedQueue.isEmpty()) {
Cursor cur = null;
try {
String sql = "SELECT c.id, factId, combinedDue FROM cards c WHERE type = 0 AND combinedDue < "
+ mFailedCutoff + " ORDER BY combinedDue LIMIT " + mQueueLimit;
cur = getDB().getDatabase().rawQuery(cardLimit("revActive", "revInactive", sql), null);
while (cur.moveToNext()) {
QueueItem qi = new QueueItem(cur.getLong(0), cur.getLong(1), cur.getDouble(2));
mFailedQueue.add(0, qi); // Add to front, so list is reversed as it is built
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
}
@SuppressWarnings("unused")
private void _fillRevQueue() {
if ((mRevCount != 0) && mRevQueue.isEmpty()) {
Cursor cur = null;
try {
String sql = "SELECT c.id, factId, combinedDue FROM cards c WHERE type = 1 AND combinedDue < "
+ mDueCutoff + " ORDER BY " + revOrder() + " LIMIT " + mQueueLimit;
cur = getDB().getDatabase().rawQuery(cardLimit("revActive", "revInactive", sql), null);
while (cur.moveToNext()) {
QueueItem qi = new QueueItem(cur.getLong(0), cur.getLong(1), cur.getDouble(2));
mRevQueue.add(0, qi); // Add to front, so list is reversed as it is built
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
}
@SuppressWarnings("unused")
private void _fillNewQueue() {
if ((mNewCountToday != 0) && mNewQueue.isEmpty() && mSpacedCards.isEmpty()) {
Cursor cur = null;
try {
String sql = "SELECT c.id, factId, combinedDue FROM cards c WHERE type = 2 AND combinedDue < "
+ mDueCutoff + " ORDER BY " + newOrder() + " LIMIT " + mQueueLimit;
cur = getDB().getDatabase().rawQuery(cardLimit("newActive", "newInactive", sql), null);
while (cur.moveToNext()) {
QueueItem qi = new QueueItem(cur.getLong(0), cur.getLong(1), cur.getDouble(2));
mNewQueue.addFirst(qi); // Add to front, so list is reversed as it is built
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
}
private boolean queueNotEmpty(LinkedList<QueueItem> queue, Method fillFunc) {
return queueNotEmpty(queue, fillFunc, false);
}
private boolean queueNotEmpty(LinkedList<QueueItem> queue, Method fillFunc, boolean _new) {
while (true) {
removeSpaced(queue, _new);
if (!queue.isEmpty()) {
return true;
}
try {
fillFunc.invoke(Deck.this);
mSpacedFacts.clear(); // workaround for freezing cards problem. remove this when the code is up to date
// with libanki
} catch (Exception e) {
Log.e(AnkiDroidApp.TAG, "queueNotEmpty: Error while invoking overridable fill method:" + e.toString());
return false;
}
if (queue.isEmpty()) {
return false;
}
}
}
private void removeSpaced(LinkedList<QueueItem> queue) {
removeSpaced(queue, false);
}
private void removeSpaced(LinkedList<QueueItem> queue, boolean _new) {
ArrayList<Long> popped = new ArrayList<Long>();
double delay = 0.0;
while (!queue.isEmpty()) {
long fid = ((QueueItem) queue.getLast()).getFactID();
if (mSpacedFacts.containsKey(fid)) {
// Still spaced
long id = queue.removeLast().getCardID();
// Assuming 10 cards/minute, track id if likely to expire before queue refilled
if (_new && (mNewSpacing < (double) mQueueLimit * 6.0)) {
popped.add(id);
delay = mSpacedFacts.get(fid);
}
} else {
if (!popped.isEmpty()) {
mSpacedCards.add(new SpacedCardsItem(delay, popped));
}
break;
}
}
}
private boolean revNoSpaced() {
return queueNotEmpty(mRevQueue, fillRevQueueMethod);
}
private boolean newNoSpaced() {
return queueNotEmpty(mNewQueue, fillNewQueueMethod, true);
}
@SuppressWarnings("unused")
private void _requeueCard(Card card, boolean oldIsRev) {
int newType = 0;
// try {
if (card.getReps() == 1) {
if (mNewFromCache) {
// Fetched from spaced cache
newType = 2;
ArrayList<Long> cards = mSpacedCards.remove().getCards();
// Reschedule the siblings
if (cards.size() > 1) {
cards.remove(0);
mSpacedCards.addLast(new SpacedCardsItem(Utils.now() + mNewSpacing, cards));
}
} else {
// Fetched from normal queue
newType = 1;
mNewQueue.removeLast();
}
} else if (!oldIsRev) {
mFailedQueue.removeLast();
} else {
mRevQueue.removeLast();
}
// } catch (Exception e) {
// throw new RuntimeException("requeueCard() failed. Counts: " +
// mFailedSoonCount + " " + mRevCount + " " + mNewCountToday + ", Queue: " +
// mFailedQueue.size() + " " + mRevQueue.size() + " " + mNewQueue.size() + ", Card info: " +
// card.getReps() + " " + card.isRev() + " " + oldIsRev);
// }
}
private String revOrder() {
return revOrderStrings[mRevCardOrder];
}
private String newOrder() {
return newOrderStrings[mNewCardOrder];
}
// Rebuild the type cache. Only necessary on upgrade.
private void rebuildTypes() {
getDB().getDatabase().execSQL(
"UPDATE cards SET " + "type = (CASE " + "WHEN successive THEN 1 WHEN reps THEN 0 ELSE 2 END), "
+ "relativeDelay = (CASE " + "WHEN successive THEN 1 WHEN reps THEN 0 ELSE 2 END) "
+ "WHERE type >= 0");
// old-style suspended cards
getDB().getDatabase().execSQL("UPDATE cards SET type = type - 3 WHERE priority = -3 AND type >= 0");
}
@SuppressWarnings("unused")
private int _cardQueue(Card card) {
return cardType(card);
}
// Return the type of the current card (what queue it's in)
private int cardType(Card card) {
if (card.isRev()) {
return 1;
} else if (!card.isNew()) {
return 0;
} else {
return 2;
}
}
public void updateCutoff() {
Calendar cal = Calendar.getInstance();
int newday = (int) mUtcOffset + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000;
cal.add(Calendar.MILLISECOND, -cal.get(Calendar.ZONE_OFFSET) - cal.get(Calendar.DST_OFFSET));
cal.add(Calendar.SECOND, (int) -mUtcOffset + 86400);
cal.set(Calendar.AM_PM, Calendar.AM);
cal.set(Calendar.HOUR, 0); // Yes, verbose but crystal clear
cal.set(Calendar.MINUTE, 0); // Apologies for that, here was my rant
cal.set(Calendar.SECOND, 0); // But if you can improve this bit and
cal.set(Calendar.MILLISECOND, 0); // collapse it to one statement please do
cal.getTimeInMillis();
Log.d(AnkiDroidApp.TAG, "New day happening at " + newday + " sec after 00:00 UTC");
cal.add(Calendar.SECOND, newday);
long cutoff = cal.getTimeInMillis() / 1000;
// Cutoff must not be in the past
while (cutoff < System.currentTimeMillis() / 1000) {
cutoff += 86400.0;
}
// Cutoff must not be more than 24 hours in the future
cutoff = Math.min(System.currentTimeMillis() / 1000 + 86400, cutoff);
mFailedCutoff = cutoff;
if (getBool("perDay")) {
mDueCutoff = (double) cutoff;
} else {
mDueCutoff = (double) Utils.now();
}
}
public void reset() {
// Setup global/daily stats
mGlobalStats = Stats.globalStats(this);
mDailyStats = Stats.dailyStats(this);
// Recheck counts
rebuildCounts();
// Empty queues; will be refilled by getCard()
mFailedQueue.clear();
mRevQueue.clear();
mNewQueue.clear();
mSpacedFacts.clear();
// Determine new card distribution
if (mNewCardSpacing == NEW_CARDS_DISTRIBUTE) {
if (mNewCountToday != 0) {
mNewCardModulus = (mNewCountToday + mRevCount) / mNewCountToday;
// If there are cards to review, ensure modulo >= 2
if (mRevCount != 0) {
mNewCardModulus = Math.max(2, mNewCardModulus);
}
} else {
mNewCardModulus = 0;
}
} else {
mNewCardModulus = 0;
}
// Recache css
rebuildCSS();
// Spacing for delayed cards - not to be confused with newCardSpacing above
mNewSpacing = getFloat("newSpacing");
}
// Checks if the day has rolled over.
private void checkDailyStats() {
if (!Utils.genToday(mUtcOffset).toString().equals(mDailyStats.getDay().toString())) {
mDailyStats = Stats.dailyStats(this);
}
}
/*
* Review early*****************************
*/
public void setupReviewEarlyScheduler() {
try {
fillRevQueueMethod = Deck.class.getDeclaredMethod("_fillRevEarlyQueue");
rebuildRevCountMethod = Deck.class.getDeclaredMethod("_rebuildRevEarlyCount");
finishSchedulerMethod = Deck.class.getDeclaredMethod("_onReviewEarlyFinished");
answerPreSaveMethod = Deck.class.getDeclaredMethod("_reviewEarlyPreSave", Card.class, int.class);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
mScheduler = "reviewEarly";
}
@SuppressWarnings("unused")
private void _reviewEarlyPreSave(Card card, int ease) {
if (ease > 1) {
// Prevent it from appearing in next queue fill
card.setType(card.getType() + 6);
}
}
private void resetAfterReviewEarly() {
// Put temporarily suspended cards back into play. Caller must .reset()
// FIXME: Can ignore priorities in the future (following libanki)
ArrayList<Long> ids = getDB().queryColumn(Long.class,
"SELECT id FROM cards WHERE type BETWEEN 6 AND 8 OR priority = -1", 0);
if (!ids.isEmpty()) {
updatePriorities(Utils.toPrimitive(ids));
getDB().getDatabase().execSQL("UPDATE cards SET type = type -6 WHERE type BETWEEN 6 AND 8");
flushMod();
}
}
@SuppressWarnings("unused")
private void _onReviewEarlyFinished() {
// Clean up buried cards
resetAfterReviewEarly();
// And go back to regular scheduler
setupStandardScheduler();
}
@SuppressWarnings("unused")
private void _rebuildRevEarlyCount() {
// In the future it would be nice to skip the first x days of due cards
mRevCount = (int) getDB().queryScalar(cardLimit("revActive", "revInactive", String.format(Utils.ENGLISH_LOCALE,
"SELECT count() FROM cards c WHERE type = 1 AND combinedDue > %f", mDueCutoff)));
}
@SuppressWarnings("unused")
private void _fillRevEarlyQueue() {
if ((mRevCount != 0) && mRevQueue.isEmpty()) {
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery(cardLimit("revActive", "revInactive", String.format(
Utils.ENGLISH_LOCALE,
"SELECT id, factId, combinedDue FROM cards c WHERE type = 1 AND combinedDue > %f " +
"ORDER BY combinedDue LIMIT %d", mDueCutoff, mQueueLimit)), null);
while (cur.moveToNext()) {
QueueItem qi = new QueueItem(cur.getLong(0), cur.getLong(1));
mRevQueue.add(0, qi); // Add to front, so list is reversed as it is built
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
}
/*
* Learn more*****************************
*/
public void setupLearnMoreScheduler() {
try {
rebuildNewCountMethod = Deck.class.getDeclaredMethod("_rebuildLearnMoreCount");
updateNewCountTodayMethod = Deck.class.getDeclaredMethod("_updateLearnMoreCountToday");
finishSchedulerMethod = Deck.class.getDeclaredMethod("setupStandardScheduler");
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
mScheduler = "learnMore";
}
@SuppressWarnings("unused")
private void _rebuildLearnMoreCount() {
mNewCount = (int) getDB().queryScalar(
cardLimit("newActive", "newInactive", String.format(Utils.ENGLISH_LOCALE,
"SELECT count(*) FROM cards c WHERE type = 2 AND combinedDue < %f", mDueCutoff)));
mSpacedCards.clear();
}
@SuppressWarnings("unused")
private void _updateLearnMoreCountToday() {
mNewCountToday = mNewCount;
}
/*
* Cramming*****************************
*/
public void setupCramScheduler(String[] active, String order) {
try {
getCardIdMethod = Deck.class.getDeclaredMethod("_getCramCardId", boolean.class);
mActiveCramTags = active;
mCramOrder = order;
rebuildFailedCountMethod = Deck.class.getDeclaredMethod("_rebuildFailedCramCount");
rebuildRevCountMethod = Deck.class.getDeclaredMethod("_rebuildCramCount");
rebuildNewCountMethod = Deck.class.getDeclaredMethod("_rebuildNewCramCount");
fillFailedQueueMethod = Deck.class.getDeclaredMethod("_fillFailedCramQueue");
fillRevQueueMethod = Deck.class.getDeclaredMethod("_fillCramQueue");
finishSchedulerMethod = Deck.class.getDeclaredMethod("setupStandardScheduler");
mFailedCramQueue.clear();
requeueCardMethod = Deck.class.getDeclaredMethod("_requeueCramCard", Card.class, boolean.class);
cardQueueMethod = Deck.class.getDeclaredMethod("_cramCardQueue", Card.class);
answerCardMethod = Deck.class.getDeclaredMethod("_answerCramCard", Card.class, int.class);
spaceCardsMethod = Deck.class.getDeclaredMethod("_spaceCramCards", Card.class);
// Reuse review early's code
answerPreSaveMethod = Deck.class.getDeclaredMethod("_cramPreSave", Card.class, int.class);
cardLimitMethod = Deck.class.getDeclaredMethod("_cramCardLimit", String[].class, String[].class,
String.class);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
mScheduler = "cram";
}
@SuppressWarnings("unused")
private void _answerCramCard(Card card, int ease) {
_answerCard(card, ease);
if (ease == 1) {
mFailedCramQueue.addFirst(new QueueItem(card.getId(), card.getFactId()));
}
}
@SuppressWarnings("unused")
private long _getCramCardId(boolean check) {
checkDailyStats();
fillQueues();
if ((mFailedCardMax != 0) && (mFailedSoonCount >= mFailedCardMax)) {
return ((QueueItem) mFailedQueue.getLast()).getCardID();
}
// Card due for review?
if (revNoSpaced()) {
return ((QueueItem) mRevQueue.getLast()).getCardID();
}
if (!mFailedQueue.isEmpty()) {
return ((QueueItem) mFailedQueue.getLast()).getCardID();
}
if (check) {
// Collapse spaced cards before reverting back to old scheduler
reset();
return getCardId(false);
}
// If we're in a custom scheduler, we may need to switch back
if (finishSchedulerMethod != null) {
finishScheduler();
reset();
return getCardId();
}
return 0l;
}
@SuppressWarnings("unused")
private int _cramCardQueue(Card card) {
if ((!mRevQueue.isEmpty()) && (((QueueItem) mRevQueue.getLast()).getCardID() == card.getId())) {
return 1;
} else {
return 0;
}
}
@SuppressWarnings("unused")
private void _requeueCramCard(Card card, boolean oldIsRev) {
if (cardQueue(card) == 1) {
mRevQueue.removeLast();
} else {
mFailedCramQueue.removeLast();
}
}
@SuppressWarnings("unused")
private void _rebuildNewCramCount() {
mNewCount = 0;
mNewCountToday = 0;
}
@SuppressWarnings("unused")
private String _cramCardLimit(String active[], String inactive[], String sql) {
// inactive is (currently) ignored
if (active.length > 0) {
long yids[] = Utils.toPrimitive(tagIds(active).values());
return sql.replace("WHERE ", "WHERE +c.id IN (SELECT cardId FROM cardTags WHERE " + "tagId IN "
+ Utils.ids2str(yids) + ") AND ");
} else {
return sql;
}
}
@SuppressWarnings("unused")
private void _fillCramQueue() {
if ((mRevCount != 0) && mRevQueue.isEmpty()) {
Cursor cur = null;
try {
Log.i(AnkiDroidApp.TAG, "fill cram queue: " + mActiveCramTags + " " + mCramOrder + " " + mQueueLimit);
String sql = "SELECT id, factId FROM cards c WHERE type BETWEEN 0 AND 2 ORDER BY " + mCramOrder
+ " LIMIT " + mQueueLimit;
sql = cardLimit(mActiveCramTags, null, sql);
Log.i(AnkiDroidApp.TAG, "SQL: " + sql);
cur = getDB().getDatabase().rawQuery(sql, null);
while (cur.moveToNext()) {
QueueItem qi = new QueueItem(cur.getLong(0), cur.getLong(1));
mRevQueue.add(0, qi); // Add to front, so list is reversed as it is built
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
}
@SuppressWarnings("unused")
private void _rebuildCramCount() {
mRevCount = (int) getDB().queryScalar(
cardLimit(mActiveCramTags, null, "SELECT count(*) FROM cards c WHERE type BETWEEN 0 AND 2"));
}
@SuppressWarnings("unused")
private void _rebuildFailedCramCount() {
mFailedSoonCount = mFailedCramQueue.size();
}
@SuppressWarnings("unused")
private void _fillFailedCramQueue() {
mFailedQueue = mFailedCramQueue;
}
@SuppressWarnings("unused")
private void _spaceCramCards(Card card) {
mSpacedFacts.put(card.getFactId(), Utils.now() + mNewSpacing);
}
@SuppressWarnings("unused")
private void _cramPreSave(Card card, int ease) {
// prevent it from appearing in next queue fill
card.setType(card.getType() + 6);
}
private void setModified() {
mModified = Utils.now();
}
public void setModified(double mod) {
mModified = mod;
}
public void flushMod() {
setModified();
commitToDB();
}
public void commitToDB() {
Log.i(AnkiDroidApp.TAG, "commitToDB - Saving deck to DB...");
ContentValues values = new ContentValues();
values.put("created", mCreated);
values.put("modified", mModified);
values.put("description", mDescription);
values.put("version", mVersion);
values.put("currentModelId", mCurrentModelId);
values.put("syncName", mSyncName);
values.put("lastSync", mLastSync);
values.put("hardIntervalMin", mHardIntervalMin);
values.put("hardIntervalMax", mHardIntervalMax);
values.put("midIntervalMin", mMidIntervalMin);
values.put("midIntervalMax", mMidIntervalMax);
values.put("easyIntervalMin", mEasyIntervalMin);
values.put("easyIntervalMax", mEasyIntervalMax);
values.put("delay0", mDelay0);
values.put("delay1", mDelay1);
values.put("delay2", mDelay2);
values.put("collapseTime", mCollapseTime);
values.put("highPriority", mHighPriority);
values.put("medPriority", mMedPriority);
values.put("lowPriority", mLowPriority);
values.put("suspended", mSuspended);
values.put("newCardOrder", mNewCardOrder);
values.put("newCardSpacing", mNewCardSpacing);
values.put("failedCardMax", mFailedCardMax);
values.put("newCardsPerDay", mNewCardsPerDay);
values.put("sessionRepLimit", mSessionRepLimit);
values.put("sessionTimeLimit", mSessionTimeLimit);
values.put("utcOffset", mUtcOffset);
values.put("cardCount", mCardCount);
values.put("factCount", mFactCount);
values.put("failedNowCount", mFailedNowCount);
values.put("failedSoonCount", mFailedSoonCount);
values.put("revCount", mRevCount);
values.put("newCount", mNewCount);
values.put("revCardOrder", mRevCardOrder);
getDB().getDatabase().update("decks", values, "id = " + mId, null);
}
public static double getLastModified(String deckPath) {
double value;
Cursor cursor = null;
// Log.i(AnkiDroidApp.TAG, "Deck - getLastModified from deck = " + deckPath);
boolean dbAlreadyOpened = AnkiDatabaseManager.isDatabaseOpen(deckPath);
try {
cursor = AnkiDatabaseManager.getDatabase(deckPath).getDatabase().rawQuery(
"SELECT modified" + " FROM decks" + " LIMIT 1", null);
if (!cursor.moveToFirst()) {
value = -1;
} else {
value = cursor.getDouble(0);
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
if (!dbAlreadyOpened) {
AnkiDatabaseManager.closeDatabase(deckPath);
}
return value;
}
/*
* Getters and Setters for deck properties NOTE: The setters flushMod()
* *********************************************************
*/
public AnkiDb getDB() {
// TODO: Make this a reference to a member variable
return AnkiDatabaseManager.getDatabase(mDeckPath);
}
public String getDeckPath() {
return mDeckPath;
}
public void setDeckPath(String path) {
mDeckPath = path;
}
// public String getSyncName() {
// return mSyncName;
// }
// public void setSyncName(String name) {
// mSyncName = name;
// flushMod();
// }
public int getRevCardOrder() {
return mRevCardOrder;
}
public void setRevCardOrder(int num) {
if (num >= 0) {
mRevCardOrder = num;
flushMod();
}
}
public int getNewCardSpacing() {
return mNewCardSpacing;
}
public void setNewCardSpacing(int num) {
if (num >= 0) {
mNewCardSpacing = num;
flushMod();
}
}
public int getNewCardOrder() {
return mNewCardOrder;
}
public void setNewCardOrder(int num) {
if (num >= 0) {
mNewCardOrder = num;
flushMod();
}
}
public boolean getPerDay() {
return getBool("perDay");
}
public void setPerDay(boolean perDay) {
if (perDay) {
setVar("perDay", "1");
} else {
setVar("perDay", "0");
}
}
public boolean getSuspendLeeches() {
return getBool("suspendLeeches");
}
public void setSuspendLeeches(boolean suspendLeeches) {
if (suspendLeeches) {
setVar("suspendLeeches", "1");
} else {
setVar("suspendLeeches", "0");
}
}
public int getNewCardsPerDay() {
return mNewCardsPerDay;
}
public void setNewCardsPerDay(int num) {
if (num >= 0) {
mNewCardsPerDay = num;
flushMod();
reset();
}
}
public long getSessionRepLimit() {
return mSessionRepLimit;
}
public void setSessionRepLimit(long num) {
if (num >= 0) {
mSessionRepLimit = num;
flushMod();
}
}
public long getSessionTimeLimit() {
return mSessionTimeLimit;
}
public void setSessionTimeLimit(long num) {
if (num >= 0) {
mSessionTimeLimit = num;
flushMod();
}
}
/**
* @return the failedSoonCount
*/
public int getFailedSoonCount() {
return mFailedSoonCount;
}
/**
* @return the revCount
*/
public int getRevCount() {
return mRevCount;
}
/**
* @return the newCountToday
*/
public int getNewCountToday() {
return mNewCountToday;
}
/**
* @return the number of due cards in the deck
*/
public int getDueCount() {
return mFailedSoonCount + mRevCount;
}
/**
* @param cardCount the cardCount to set
*/
public void setCardCount(int cardCount) {
mCardCount = cardCount;
// XXX: Need to flushmod() ?
}
/**
* Get the cached total number of cards of the deck.
*
* @return The number of cards contained in the deck
*/
public int getCardCount() {
return mCardCount;
}
/**
* Get the number of mature cards of the deck.
*
* @return The number of cards contained in the deck
*/
public int getMatureCardCount() {
return (int) (getDB().queryScalar("SELECT count(*) from cards WHERE interval >= " + Card.MATURE_THRESHOLD));
}
/**
* @return the currentModelId
*/
public long getCurrentModelId() {
return mCurrentModelId;
}
/**
* @return the deckName
*/
public String getDeckName() {
return mDeckName;
}
/**
* @return the deck UTC offset in number seconds
*/
public double getUtcOffset() {
return mUtcOffset;
}
public void setUtcOffset() {
// 4am
Calendar cal = Calendar.getInstance();
mUtcOffset = 4 * 60 * 60 - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / 1000;
}
/**
* @return the newCount
*/
public int getNewCount() {
return mNewCount;
}
/**
* @return the modified
*/
public double getModified() {
return mModified;
}
/**
* @param lastSync the lastSync to set
*/
public void setLastSync(double lastSync) {
mLastSync = lastSync;
}
/**
* @return the lastSync
*/
public double getLastSync() {
return mLastSync;
}
/**
* @param factCount the factCount to set
*/
public void setFactCount(int factCount) {
mFactCount = factCount;
// XXX: Need to flushmod() ?
}
/**
* @return the factCount
*/
public int getFactCount() {
return mFactCount;
}
/**
* @param lastLoaded the lastLoaded to set
*/
public double getLastLoaded() {
return mLastLoaded;
}
/**
* @param lastLoaded the lastLoaded to set
*/
public void setLastLoaded(double lastLoaded) {
mLastLoaded = lastLoaded;
}
public int getVersion() {
return mVersion;
}
public boolean isUnpackNeeded() {
return mNeedUnpack;
}
/*
* Getting the next card*****************************
*/
/**
* Return the next card object.
*
* @return The next due card or null if nothing is due.
*/
public Card getCard() {
mCurrentCardId = getCardId();
if (mCurrentCardId != 0l) {
return cardFromId(mCurrentCardId);
} else {
return null;
}
}
// Refreshes the current card and returns it (used when editing cards)
public Card getCurrentCard() {
return cardFromId(mCurrentCardId);
}
/**
* Return the next due card Id, or 0
*
* @param check Check for expired, or new day rollover
* @return The Id of the next card, or 0 in case of error
*/
@SuppressWarnings("unused")
private long _getCardId(boolean check) {
checkDailyStats();
fillQueues();
updateNewCountToday();
if (!mFailedQueue.isEmpty()) {
// Failed card due?
if (mDelay0 != 0l) {
if ((long) ((QueueItem) mFailedQueue.getLast()).getDue() + mDelay0 < System.currentTimeMillis() / 1000) {
return mFailedQueue.getLast().getCardID();
}
}
// Failed card queue too big?
if ((mFailedCardMax != 0) && (mFailedSoonCount >= mFailedCardMax)) {
return mFailedQueue.getLast().getCardID();
}
}
// Distribute new cards?
if (newNoSpaced() && timeForNewCard()) {
long id = getNewCard();
if (id != 0L) {
return id;
}
}
// Card due for review?
if (revNoSpaced()) {
return mRevQueue.getLast().getCardID();
}
// New cards left?
if (mNewCountToday != 0) {
return getNewCard();
}
if (check) {
// Check for expired cards, or new day rollover
updateCutoff();
reset();
return getCardId(false);
}
// Display failed cards early/last
if ((!check) && showFailedLast() && (!mFailedQueue.isEmpty())) {
return mFailedQueue.getLast().getCardID();
}
// If we're in a custom scheduler, we may need to switch back
if (finishSchedulerMethod != null) {
finishScheduler();
reset();
return getCardId();
}
return 0l;
}
/*
* Get card: helper functions*****************************
*/
@SuppressWarnings("unused")
private boolean _timeForNewCard() {
// True if it's time to display a new card when distributing.
if (mNewCountToday == 0) {
return false;
}
if (mNewCardSpacing == NEW_CARDS_LAST) {
return false;
}
if (mNewCardSpacing == NEW_CARDS_FIRST) {
return true;
}
// Force review if there are very high priority cards
try {
if (!mRevQueue.isEmpty()) {
if (getDB().queryScalar(
"SELECT 1 FROM cards WHERE id = " + mRevQueue.getLast().getCardID() + " AND priority = 4") == 1) {
return false;
}
}
} catch (Exception e) {
// No result from query.
}
if (mNewCardModulus != 0) {
return (mDailyStats.getReps() % mNewCardModulus == 0);
} else {
return false;
}
}
private long getNewCard() {
int src = 0;
if ((!mSpacedCards.isEmpty()) && (mSpacedCards.get(0).getSpace() < Utils.now())) {
// Spaced card has expired
src = 0;
} else if (!mNewQueue.isEmpty()) {
// Card left in new queue
src = 1;
} else if (!mSpacedCards.isEmpty()) {
// Card left in spaced queue
src = 0;
} else {
// Only cards spaced to another day left
return 0L;
}
if (src == 0) {
mNewFromCache = true;
return mSpacedCards.get(0).getCards().get(0);
} else {
mNewFromCache = false;
return mNewQueue.getLast().getCardID();
}
}
private boolean showFailedLast() {
return ((mCollapseTime != 0.0) || (mDelay0 == 0));
}
/**
* Given a card ID, return a card and start the card timer.
*
* @param id The ID of the card to be returned
*/
public Card cardFromId(long id) {
if (id == 0) {
return null;
}
Card card = new Card(this);
boolean result = card.fromDB(id);
if (!result) {
return null;
}
card.mDeck = this;
card.genFuzz();
card.startTimer();
return card;
}
// TODO: The real methods to update cards on Anki should be implemented instead of this
public void updateAllCards() {
updateAllCardsFromPosition(0, Long.MAX_VALUE);
}
public long updateAllCardsFromPosition(long numUpdatedCards, long limitCards) {
// TODO: Cache this query, order by FactId, Id
Cursor cursor = null;
try {
cursor = getDB().getDatabase().rawQuery(
"SELECT id, factId " + "FROM cards " + "ORDER BY factId, id " + "LIMIT " + limitCards + " OFFSET "
+ numUpdatedCards, null);
getDB().getDatabase().beginTransaction();
while (cursor.moveToNext()) {
// Get card
Card card = new Card(this);
card.fromDB(cursor.getLong(0));
Log.i(AnkiDroidApp.TAG, "Card id = " + card.getId() + ", numUpdatedCards = " + numUpdatedCards);
// Load tags
card.loadTags();
// Get the related fact
Fact fact = card.getFact();
// Log.i(AnkiDroidApp.TAG, "Fact id = " + fact.id);
// Generate the question and answer for this card and update it
HashMap<String, String> newQA = CardModel.formatQA(fact, card.getCardModel(), card.splitTags());
card.setQuestion(newQA.get("question"));
Log.i(AnkiDroidApp.TAG, "Question = " + card.getQuestion());
card.setAnswer(newQA.get("answer"));
Log.i(AnkiDroidApp.TAG, "Answer = " + card.getAnswer());
card.updateQAfields();
numUpdatedCards++;
}
getDB().getDatabase().setTransactionSuccessful();
} finally {
getDB().getDatabase().endTransaction();
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
return numUpdatedCards;
}
/*
* Answering a card*****************************
*/
public void _answerCard(Card card, int ease) {
Log.i(AnkiDroidApp.TAG, "answerCard");
String undoName = "Answer Card";
setUndoStart(undoName, card.getId());
double now = Utils.now();
// Old state
String oldState = card.getState();
int oldQueue = cardQueue(card);
double lastDelaySecs = Utils.now() - card.getCombinedDue();
double lastDelay = lastDelaySecs / 86400.0;
boolean oldIsRev = card.isRev();
// update card details
double last = card.getInterval();
card.setInterval(nextInterval(card, ease));
if (lastDelay >= 0) {
card.setLastInterval(last); // keep last interval if reviewing early
}
if (!card.isNew()) {
card.setLastDue(card.getDue()); // only update if card was not new
}
card.setDue(nextDue(card, ease, oldState));
card.setIsDue(0);
card.setLastFactor(card.getFactor());
card.setSpaceUntil(0);
if (lastDelay >= 0) {
card.updateFactor(ease, mAverageFactor); // don't update factor if learning ahead
}
// Spacing
spaceCards(card);
// Adjust counts for current card
if (ease == 1) {
if (card.getDue() < mFailedCutoff) {
mFailedSoonCount += 1;
}
}
if (oldQueue == 0) {
mFailedSoonCount -= 1;
} else if (oldQueue == 1) {
mRevCount -= 1;
} else {
mNewCount -= 1;
}
// card stats
card.updateStats(ease, oldState);
// Update type & ensure past cutoff
card.setType(cardType(card));
card.setRelativeDelay(card.getType());
if (ease != 1) {
card.setDue(Math.max(card.getDue(), mDueCutoff + 1));
}
// Allow custom schedulers to munge the card
if (answerPreSaveMethod != null) {
answerPreSave(card, ease);
}
// Save
card.setCombinedDue(card.getDue());
card.toDB();
// global/daily stats
Stats.updateAllStats(mGlobalStats, mDailyStats, card, ease, oldState);
// review history
CardHistoryEntry entry = new CardHistoryEntry(this, card, ease, lastDelay);
entry.writeSQL();
mModified = now;
setUndoEnd(undoName);
// Remove form queue
requeueCard(card, oldIsRev);
// Leech handling - we need to do this after the queue, as it may cause a reset
if (isLeech(card)) {
Log.i(AnkiDroidApp.TAG, "card is leech!");
handleLeech(card);
}
}
@SuppressWarnings("unused")
private void _spaceCards(Card card) {
// Update new counts
double _new = Utils.now() + mNewSpacing;
// Space reviews too if integer minute
String lim = "= 2";
if (mNewSpacing % 60 == 0) {
lim = "BETWEEN 1 AND 2";
}
getDB().getDatabase().execSQL(
String.format(Utils.ENGLISH_LOCALE, "UPDATE cards SET combinedDue = (CASE WHEN type = 1 THEN %f "
+ "WHEN type = 2 THEN %f END), modified = %f, isDue = 0 WHERE id != %d AND factId = %d "
+ "AND combinedDue < %f AND type %s",
mDueCutoff, _new, Utils.now(), card.getId(), card.getFactId(), mDueCutoff, lim));
// Update local cache of seen facts
mSpacedFacts.put(card.getFactId(), _new);
}
private boolean isLeech(Card card) {
int no = card.getNoCount();
int fmax = 0;
try {
fmax = getInt("leechFails");
} catch (SQLException e) {
// No leech threshold found in DeckVars
return false;
}
Log.i(AnkiDroidApp.TAG, "leech handling: " + card.getSuccessive() + " successive fails and " + no + " total fails, threshold at " + fmax);
// Return true if:
// - The card failed AND
// - The number of failures exceeds the leech threshold AND
// - There were at least threshold/2 reps since last time
if (!card.isRev() && (no >= fmax) && ((fmax - no) % Math.max(fmax / 2, 1) == 0)) {
return true;
} else {
return false;
}
}
private void handleLeech(Card card) {
Card scard = cardFromId(card.getId());
String tags = scard.getFact().getTags();
tags = Utils.addTags("Leech", tags);
scard.getFact().setTags(Utils.canonifyTags(tags));
// FIXME: Inefficient, we need to save the fact so that the modified tags can be used in setModified,
// then after setModified we need to save again! Just make setModified to use the tags from the fact,
// not reload them from the DB.
scard.getFact().toDb();
scard.getFact().setModified(true, this);
scard.getFact().toDb();
updateFactTags(new long[] { scard.getFact().getId() });
card.setLeechFlag(true);
if (getBool("suspendLeeches")) {
suspendCards(new long[] { card.getId() });
card.setSuspendedFlag(true);
}
reset();
}
/*
* Interval management*********************************************************
*/
public double nextInterval(Card card, int ease) {
double delay = card.adjustedDelay(ease);
return nextInterval(card, delay, ease);
}
private double nextInterval(Card card, double delay, int ease) {
double interval = card.getInterval();
double factor = card.getFactor();
// if shown early and not failed
if ((delay < 0) && card.isRev()) {
// FIXME: From libanki: This should recreate lastInterval from interval /
// lastFactor, or we lose delay information when reviewing early
interval = Math.max(card.getLastInterval(), card.getInterval() + delay);
if (interval < mMidIntervalMin) {
interval = 0;
}
delay = 0;
}
// if interval is less than mid interval, use presets
if (ease == Card.EASE_FAILED) {
interval *= mDelay2;
if (interval < mHardIntervalMin) {
interval = 0;
}
} else if (interval == 0) {
if (ease == Card.EASE_HARD) {
interval = mHardIntervalMin + card.getFuzz() * (mHardIntervalMax - mHardIntervalMin);
} else if (ease == Card.EASE_MID) {
interval = mMidIntervalMin + card.getFuzz() * (mMidIntervalMax - mMidIntervalMin);
} else if (ease == Card.EASE_EASY) {
interval = mEasyIntervalMin + card.getFuzz() * (mEasyIntervalMax - mEasyIntervalMin);
}
} else {
// if not cramming, boost initial 2
if ((interval < mHardIntervalMax) && (interval > 0.166)) {
double mid = (mMidIntervalMin + mMidIntervalMax) / 2.0;
interval = mid / factor;
}
// multiply last interval by factor
if (ease == Card.EASE_HARD) {
interval = (interval + delay / 4.0) * 1.2;
} else if (ease == Card.EASE_MID) {
interval = (interval + delay / 2.0) * factor;
} else if (ease == Card.EASE_EASY) {
interval = (interval + delay) * factor * FACTOR_FOUR;
}
interval *= 0.95 + card.getFuzz() * (1.05 - 0.95);
}
interval = Math.min(interval, MAX_SCHEDULE_TIME);
return interval;
}
private double nextDue(Card card, int ease, String oldState) {
double due;
if (ease == Card.EASE_FAILED) {
// 600 is a magic value which means no bonus, and is used to ease upgrades
if (oldState.equals(Card.STATE_MATURE) && mDelay1 != 0 && mDelay1 != 600) {
// user wants a bonus of 1+ days. put the failed cards at the
// start of the future day, so that failures that day will come
// after the waiting cards
return mFailedCutoff + (mDelay1 - 1) * 86400;
} else {
due = 0.0;
}
} else {
due = card.getInterval() * 86400.0;
}
return (due + Utils.now());
}
/*
* Tags: Querying*****************************
*/
/**
* Get a map of card IDs to their associated tags (fact, model and template)
*
* @param where SQL restriction on the query. If empty, then returns tags for all the cards
* @return The map of card IDs to an array of strings with 3 elements representing the triad {card tags, model tags,
* template tags}
*/
private HashMap<Long, List<String>> splitTagsList() {
return splitTagsList("");
}
private HashMap<Long, List<String>> splitTagsList(String where) {
Cursor cur = null;
HashMap<Long, List<String>> results = new HashMap<Long, List<String>>();
try {
cur = getDB().getDatabase().rawQuery(
"SELECT cards.id, facts.tags, models.tags, cardModels.name "
+ "FROM cards, facts, models, cardModels "
+ "WHERE cards.factId == facts.id AND facts.modelId == models.id "
+ "AND cards.cardModelId = cardModels.id " + where, null);
while (cur.moveToNext()) {
ArrayList<String> tags = new ArrayList<String>();
tags.add(cur.getString(1));
tags.add(cur.getString(2));
tags.add(cur.getString(3));
results.put(cur.getLong(0), tags);
}
} catch (SQLException e) {
Log.e(AnkiDroidApp.TAG, "splitTagsList: Error while retrieving tags from DB: " + e.toString());
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
return results;
}
/**
* Returns all model tags, all template tags and a filtered set of fact tags
*
* @param where Optional, SQL filter for fact tags. If skipped, returns all fact tags
* @return All the distinct individual tags, sorted, as an array of string
*/
public String[] allTags_() {
return allTags_("");
}
private String[] allTags_(String where) {
ArrayList<String> t = new ArrayList<String>();
t.addAll(getDB().queryColumn(String.class, "SELECT tags FROM facts " + where, 0));
t.addAll(getDB().queryColumn(String.class, "SELECT tags FROM models", 0));
t.addAll(getDB().queryColumn(String.class, "SELECT name FROM cardModels", 0));
String joined = Utils.joinTags(t);
String[] parsed = Utils.parseTags(joined);
List<String> joinedList = Arrays.asList(parsed);
TreeSet<String> joinedSet = new TreeSet<String>(joinedList);
return joinedSet.toArray(new String[joinedSet.size()]);
}
/*
* Tags: Caching*****************************
*/
public void updateFactTags(long[] factIds) {
updateCardTags(Utils.toPrimitive(getDB().queryColumn(Long.class,
"SELECT id FROM cards WHERE factId IN " + Utils.ids2str(factIds), 0)));
}
public void updateCardTags() {
updateCardTags(null);
}
public void updateCardTags(long[] cardIds) {
HashMap<String, Long> tids = new HashMap<String, Long>();
HashMap<Long, List<String>> rows = new HashMap<Long, List<String>>();
if (cardIds == null) {
getDB().getDatabase().execSQL("DELETE FROM cardTags");
getDB().getDatabase().execSQL("DELETE FROM tags");
tids = tagIds(allTags_());
rows = splitTagsList();
} else {
Log.i(AnkiDroidApp.TAG, "updateCardTags cardIds: " + Arrays.toString(cardIds));
getDB().getDatabase().execSQL("DELETE FROM cardTags WHERE cardId IN " + Utils.ids2str(cardIds));
String fids = Utils.ids2str(Utils.toPrimitive(getDB().queryColumn(Long.class,
"SELECT factId FROM cards WHERE id IN " + Utils.ids2str(cardIds), 0)));
Log.i(AnkiDroidApp.TAG, "updateCardTags fids: " + fids);
tids = tagIds(allTags_("WHERE id IN " + fids));
Log.i(AnkiDroidApp.TAG, "updateCardTags tids keys: " + Arrays.toString(tids.keySet().toArray(new String[tids.size()])));
Log.i(AnkiDroidApp.TAG, "updateCardTags tids values: " + Arrays.toString(tids.values().toArray(new Long[tids.size()])));
rows = splitTagsList("AND facts.id IN " + fids);
Log.i(AnkiDroidApp.TAG, "updateCardTags rows keys: " + Arrays.toString(rows.keySet().toArray(new Long[rows.size()])));
for (List<String> l : rows.values()) {
Log.i(AnkiDroidApp.TAG, "updateCardTags rows values: ");
for (String v : l) {
Log.i(AnkiDroidApp.TAG, "updateCardTags row item: " + v);
}
}
}
ArrayList<HashMap<String, Long>> d = new ArrayList<HashMap<String, Long>>();
for (Long id : rows.keySet()) {
for (int src = 0; src < 3; src++) { // src represents the tag type, fact: 0, model: 1, template: 2
for (String tag : Utils.parseTags(rows.get(id).get(src))) {
HashMap<String, Long> ditem = new HashMap<String, Long>();
ditem.put("cardId", id);
ditem.put("tagId", tids.get(tag.toLowerCase()));
ditem.put("src", new Long(src));
Log.i(AnkiDroidApp.TAG, "populating ditem " + src + " " + tag);
d.add(ditem);
}
}
}
for (HashMap<String, Long> ditem : d) {
getDB().getDatabase().execSQL(
"INSERT INTO cardTags (cardId, tagId, src) VALUES " + "(" + ditem.get("cardId") + ", "
+ ditem.get("tagId") + ", " + ditem.get("src") + ")");
}
getDB().getDatabase().execSQL(
"DELETE FROM tags WHERE priority = 2 AND id NOT IN " + "(SELECT DISTINCT tagId FROM cardTags)");
}
/*
* Tags: adding/removing in bulk*********************************************************
*/
public ArrayList<String> factTags(long[] factIds) {
return getDB().queryColumn(String.class, "SELECT tags FROM facts WHERE id IN " + Utils.ids2str(factIds), 0);
}
public void addTag(long factId, String tag) {
long[] ids = new long[1];
ids[0] = factId;
addTag(ids, tag);
}
public void addTag(long[] factIds, String tag) {
ArrayList<String> factTagsList = factTags(factIds);
String undoName = "Add Tag";
setUndoStart(undoName);
// Create tag if necessary
long tagId = tagId(tag, true);
int nbFactTags = factTagsList.size();
for (int i = 0; i < nbFactTags; i++) {
String newTags = factTagsList.get(i);
if (newTags.indexOf(tag) == -1) {
if (newTags.length() == 0) {
newTags += tag;
} else {
newTags += "," + tag;
}
}
Log.i(AnkiDroidApp.TAG, "old tags = " + factTagsList.get(i));
Log.i(AnkiDroidApp.TAG, "new tags = " + newTags);
if (newTags.length() > factTagsList.get(i).length()) {
getDB().getDatabase().execSQL(
"update facts set " + "tags = \"" + newTags + "\", " + "modified = "
+ String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now()) + " where id = " + factIds[i]);
}
}
ArrayList<String> cardIdList = getDB().queryColumn(String.class,
"select id from cards where factId in " + Utils.ids2str(factIds), 0);
ContentValues values = new ContentValues();
for (String cardId : cardIdList) {
try {
// Check if the tag already exists
getDB().queryScalar(
"SELECT id FROM cardTags WHERE cardId = " + cardId + " and tagId = " + tagId + " and src = "
+ Card.TAGS_FACT);
} catch (SQLException e) {
values.put("cardId", cardId);
values.put("tagId", tagId);
values.put("src", String.valueOf(Card.TAGS_FACT));
getDB().getDatabase().insert("cardTags", null, values);
}
}
flushMod();
setUndoEnd(undoName);
}
public void deleteTag(long factId, String tag) {
String undoName = "Delete Tag";
setUndoStart(undoName);
long[] ids = new long[1];
ids[0] = factId;
deleteTag(ids, tag);
setUndoEnd(undoName);
}
public void deleteTag(long[] factIds, String tag) {
ArrayList<String> factTagsList = factTags(factIds);
long tagId = tagId(tag, false);
int nbFactTags = factTagsList.size();
for (int i = 0; i < nbFactTags; i++) {
String factTags = factTagsList.get(i);
String newTags = factTags;
int tagIdx = factTags.indexOf(tag);
if ((tagIdx == 0) && (factTags.length() > tag.length())) {
// tag is the first element of many, remove "tag,"
newTags = factTags.substring(tag.length() + 1, factTags.length());
} else if ((tagIdx > 0) && (tagIdx + tag.length() == factTags.length())) {
// tag is the last of many elements, remove ",tag"
newTags = factTags.substring(0, tagIdx - 1);
} else if (tagIdx > 0) {
// tag is enclosed between other elements, remove ",tag"
newTags = factTags.substring(0, tagIdx - 1) + factTags.substring(tag.length(), factTags.length());
} else if (tagIdx == 0) {
// tag is the only element
newTags = "";
}
Log.i(AnkiDroidApp.TAG, "old tags = " + factTags);
Log.i(AnkiDroidApp.TAG, "new tags = " + newTags);
if (newTags.length() < factTags.length()) {
getDB().getDatabase().execSQL(
"update facts set " + "tags = \"" + newTags + "\", " + "modified = "
+ String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now()) + " where id = " + factIds[i]);
}
}
ArrayList<String> cardIdList = getDB().queryColumn(String.class,
"select id from cards where factId in " + Utils.ids2str(factIds), 0);
for (String cardId : cardIdList) {
getDB().getDatabase().execSQL(
"DELETE FROM cardTags WHERE cardId = " + cardId + " and tagId = " + tagId + " and src = "
+ Card.TAGS_FACT);
}
// delete unused tags from tags table
try {
getDB().queryScalar("select id from cardTags where tagId = " + tagId + " limit 1");
} catch (SQLException e) {
getDB().getDatabase().execSQL("delete from tags" + " where id = " + tagId);
}
flushMod();
}
/*
* Suspending*****************************
*/
/**
* Suspend cards in bulk. Caller must .reset()
*
* @param ids List of card IDs of the cards that are to be suspended.
*/
public void suspendCards(long[] ids) {
String undoName = "Suspend Card";
if (ids.length == 1) {
setUndoStart(undoName, ids[0]);
} else {
setUndoStart(undoName);
}
getDB().getDatabase().execSQL(
"UPDATE cards SET type = relativeDelay -3, priority = -3, modified = "
+ String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now())
+ ", isDue = 0 WHERE type >= 0 AND id IN " + Utils.ids2str(ids));
setUndoEnd(undoName);
flushMod();
}
/**
* Unsuspend cards in bulk. Caller must .reset()
*
* @param ids List of card IDs of the cards that are to be unsuspended.
*/
public void unsuspendCards(long[] ids) {
getDB().getDatabase().execSQL(
"UPDATE cards SET type = relativeDelay, priority = 0, " + "modified = "
+ String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now()) + " WHERE type < 0 AND id IN "
+ Utils.ids2str(ids));
updatePriorities(ids);
flushMod();
}
/**
* Bury all cards for fact until next session. Caller must .reset()
*
* @param Fact .
*/
public void buryFact(long factId, long cardId) {
// TODO: Unbury fact after return to StudyOptions
String undoName = "Bury Fact";
setUndoStart(undoName, cardId);
getDB().getDatabase().execSQL(
"UPDATE cards SET type = priority = -2, isDue = 0, type = type + 3 WHERE type >= 0 AND type <= 3 AND factId = " + factId);
setUndoEnd(undoName);
flushMod();
}
/**
* Priorities
*******************************/
/**
* Update all card priorities if changed. If partial is true, only updates cards with tags defined as priority low,
* med or high in the deck, or with tags whose priority is set to 2 and they are not found in the priority tags of
* the deck. If false, it updates all card priorities Caller must .reset()
*
* @param partial Partial update (true) or not (false)
* @param dirty Passed to updatePriorities(), if true it updates the modified field of the cards
*/
public void updateAllPriorities() {
updateAllPriorities(false, true);
}
public void updateAllPriorities(boolean partial) {
updateAllPriorities(partial, true);
}
public void updateAllPriorities(boolean partial, boolean dirty) {
HashMap<Long, Integer> newPriorities = updateTagPriorities();
if (!partial) {
newPriorities.clear();
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery("SELECT id, priority AS pri FROM tags", null);
while (cur.moveToNext()) {
newPriorities.put(cur.getLong(0), cur.getInt(1));
}
} catch (SQLException e) {
Log.e(AnkiDroidApp.TAG, "updateAllPriorities: Error while getting all tags: " + e.toString());
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
ArrayList<Long> cids = getDB().queryColumn(
Long.class,
"SELECT DISTINCT cardId FROM cardTags WHERE tagId in "
+ Utils.ids2str(Utils.toPrimitive(newPriorities.keySet())), 0);
updatePriorities(Utils.toPrimitive(cids), null, dirty);
}
}
/**
* Update priority setting on tags table
*/
private HashMap<Long, Integer> updateTagPriorities() {
// Make sure all priority tags exist
for (String s : new String[] { mLowPriority, mMedPriority, mHighPriority }) {
tagIds(Utils.parseTags(s));
}
HashMap<Long, Integer> newPriorities = new HashMap<Long, Integer>();
Cursor cur = null;
ArrayList<String> tagNames = null;
ArrayList<Long> tagIdList = null;
ArrayList<Integer> tagPriorities = null;
try {
tagNames = new ArrayList<String>();
tagIdList = new ArrayList<Long>();
tagPriorities = new ArrayList<Integer>();
cur = getDB().getDatabase().rawQuery("SELECT tag, id, priority FROM tags", null);
while (cur.moveToNext()) {
tagNames.add(cur.getString(0).toLowerCase());
tagIdList.add(cur.getLong(1));
tagPriorities.add(cur.getInt(2));
}
} catch (SQLException e) {
Log.e(AnkiDroidApp.TAG, "updateTagPriorities: Error while tag priorities: " + e.toString());
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
HashMap<String, Integer> typeAndPriorities = new HashMap<String, Integer>();
typeAndPriorities.put(mLowPriority, 1);
typeAndPriorities.put(mMedPriority, 3);
typeAndPriorities.put(mHighPriority, 4);
HashMap<String, Integer> up = new HashMap<String, Integer>();
for (String type : typeAndPriorities.keySet()) {
for (String tag : Utils.parseTags(type.toLowerCase())) {
up.put(tag, typeAndPriorities.get(type));
}
}
String tag = null;
long tagId = 0l;
for (int i = 0; i < tagNames.size(); i++) {
tag = tagNames.get(i);
tagId = tagIdList.get(i).longValue();
if (up.containsKey(tag) && (up.get(tag).compareTo(tagPriorities.get(i)) == 0)) {
newPriorities.put(tagId, up.get(tag));
} else if ((!up.containsKey(tag)) && (tagPriorities.get(i).intValue() != 2)) {
newPriorities.put(tagId, 2);
} else {
continue;
}
try {
getDB().getDatabase().execSQL(
"UPDATE tags SET priority = " + newPriorities.get(tagId) + " WHERE id = " + tagId);
} catch (SQLException e) {
Log.e(AnkiDroidApp.TAG, "updatePriorities: Error while updating tag priorities for tag " + tag + ": "
+ e.toString());
continue;
}
}
return newPriorities;
}
/**
* Update priorities for cardIds in bulk. Caller must .reset().
*
* @param cardIds List of card IDs identifying whose cards' priorities to update.
* @param suspend List of tags. The cards from the above list that have those tags will be suspended.
* @param dirty If true will update the modified value of each card handled.
*/
private void updatePriorities(long[] cardIds) {
updatePriorities(cardIds, null, true);
}
private void updatePriorities(long[] cardIds, String[] suspend) {
updatePriorities(cardIds, suspend, true);
}
void updatePriorities(long[] cardIds, String[] suspend, boolean dirty) {
Cursor cursor = null;
Log.i(AnkiDroidApp.TAG, "updatePriorities - Updating priorities...");
// Any tags to suspend
if (suspend != null && suspend.length > 0) {
long ids[] = Utils.toPrimitive(tagIds(suspend, false).values());
getDB().getDatabase().execSQL("UPDATE tags SET priority = 0 WHERE id in " + Utils.ids2str(ids));
}
String limit = "";
if (cardIds.length <= 1000) {
limit = "and cardTags.cardId in " + Utils.ids2str(cardIds);
}
String query = "SELECT cardTags.cardId, CASE WHEN max(tags.priority) > 2 THEN max(tags.priority) "
+ "WHEN min(tags.priority) = 1 THEN 1 ELSE 2 END FROM cardTags,tags "
+ "WHERE cardTags.tagId = tags.id " + limit + " GROUP BY cardTags.cardId";
try {
cursor = getDB().getDatabase().rawQuery(query, null);
if (cursor.moveToFirst()) {
int len = cursor.getCount();
long[][] cards = new long[len][2];
for (int i = 0; i < len; i++) {
cards[i][0] = cursor.getLong(0);
cards[i][1] = cursor.getInt(1);
}
String extra = "";
if (dirty) {
extra = ", modified = " + String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now());
}
for (int pri = Card.PRIORITY_NONE; pri <= Card.PRIORITY_HIGH; pri++) {
int count = 0;
for (int i = 0; i < len; i++) {
if (cards[i][1] == pri) {
count++;
}
}
long[] cs = new long[count];
int j = 0;
for (int i = 0; i < len; i++) {
if (cards[i][1] == pri) {
cs[j] = cards[i][0];
j++;
}
}
// Catch review early & buried but not suspended cards
getDB().getDatabase().execSQL(
"UPDATE cards " + "SET priority = " + pri + extra + " WHERE id in " + Utils.ids2str(cs)
+ " and " + "priority != " + pri + " and " + "priority >= -2");
}
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
/*
* Counts related to due cards *********************************************************
*/
private int newCardsDoneToday() {
return mDailyStats.getNewCardsCount();
}
/*
* Cards CRUD*********************************************************
*/
/**
* Bulk delete cards by ID. Caller must .reset()
*
* @param ids List of card IDs of the cards to be deleted.
*/
public void deleteCards(List<String> ids) {
Log.i(AnkiDroidApp.TAG, "deleteCards = " + ids.toString());
// Bulk delete cards by ID
if (ids != null && ids.size() > 0) {
commitToDB();
double now = Utils.now();
Log.i(AnkiDroidApp.TAG, "Now = " + now);
String idsString = Utils.ids2str(ids);
// Grab fact ids
// ArrayList<String> factIds = ankiDB.queryColumn(String.class,
// "SELECT factId FROM cards WHERE id in " + idsString,
// 0);
// Delete cards
getDB().getDatabase().execSQL("DELETE FROM cards WHERE id in " + idsString);
// Note deleted cards
String sqlInsert = "INSERT INTO cardsDeleted values (?," + String.format(Utils.ENGLISH_LOCALE, "%f", now)
+ ")";
SQLiteStatement statement = getDB().getDatabase().compileStatement(sqlInsert);
for (String id : ids) {
statement.bindString(1, id);
statement.executeInsert();
}
statement.close();
// Gather affected tags (before we delete the corresponding cardTags)
ArrayList<String> tags = getDB().queryColumn(String.class,
"SELECT tagId FROM cardTags WHERE cardId in " + idsString, 0);
// Delete cardTags
getDB().getDatabase().execSQL("DELETE FROM cardTags WHERE cardId in " + idsString);
// Find out if this tags are used by anything else
ArrayList<String> unusedTags = new ArrayList<String>();
for (String tagId : tags) {
Cursor cursor = null;
try {
cursor = getDB().getDatabase().rawQuery(
"SELECT * FROM cardTags WHERE tagId = " + tagId + " LIMIT 1", null);
if (!cursor.moveToFirst()) {
unusedTags.add(tagId);
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
// Delete unused tags
getDB().getDatabase().execSQL(
"DELETE FROM tags WHERE id in " + Utils.ids2str(unusedTags) + " and priority = "
+ Card.PRIORITY_NORMAL);
// Remove any dangling fact
deleteDanglingFacts();
flushMod();
}
}
/*
* Facts CRUD*********************************************************
*/
/**
* Add a fact to the deck. Return list of new cards
*/
public Fact addFact(Fact fact, TreeMap<Long, CardModel> cardModels) {
return addFact(fact, cardModels, true);
}
public Fact addFact(Fact fact, TreeMap<Long, CardModel> cardModels, boolean reset) {
// TODO: assert fact is Valid
// TODO: assert fact is Unique
double now = Utils.now();
// add fact to fact table
ContentValues values = new ContentValues();
values.put("id", fact.getId());
values.put("modelId", fact.getModelId());
values.put("created", now);
values.put("modified", now);
values.put("tags", "");
values.put("spaceUntil", 0);
getDB().getDatabase().insert("facts", null, values);
// get cardmodels for the new fact
// TreeMap<Long, CardModel> availableCardModels = availableCardModels(fact);
if (cardModels.isEmpty()) {
Log.e(AnkiDroidApp.TAG, "Error while adding fact: No cardmodels for the new fact");
return null;
}
// update counts
mFactCount++;
// add fields to fields table
for (Field f : fact.getFields()) {
// Re-use the content value
values.clear();
values.put("value", f.getValue());
values.put("id", f.getId());
values.put("factId", f.getFactId());
values.put("fieldModelId", f.getFieldModelId());
values.put("ordinal", f.getOrdinal());
AnkiDatabaseManager.getDatabase(mDeckPath).getDatabase().insert("fields", null, values);
}
ArrayList<Long> newCardIds = new ArrayList<Long>();
for (Map.Entry<Long, CardModel> entry : cardModels.entrySet()) {
CardModel cardModel = entry.getValue();
Card newCard = new Card(this, fact, cardModel, Utils.now());
newCard.addToDb();
newCardIds.add(newCard.getId());
mCardCount++;
mNewCount++;
Log.i(AnkiDroidApp.TAG, entry.getKey().toString());
}
commitToDB();
// TODO: code related to random in newCardOrder
// Update card q/a
fact.setModified(true, this);
updateFactTags(new long[] { fact.getId() });
// This will call reset() which will update counts
updatePriorities(Utils.toPrimitive(newCardIds));
flushMod();
if (reset) {
reset();
}
return fact;
}
/**
* Bulk delete facts by ID. Don't touch cards, assume any cards have already been removed. Caller must .reset().
*
* @param ids List of fact IDs of the facts to be removed.
*/
public void deleteFacts(List<String> ids) {
Log.i(AnkiDroidApp.TAG, "deleteFacts = " + ids.toString());
int len = ids.size();
if (len > 0) {
commitToDB();
double now = Utils.now();
String idsString = Utils.ids2str(ids);
Log.i(AnkiDroidApp.TAG, "DELETE FROM facts WHERE id in " + idsString);
getDB().getDatabase().execSQL("DELETE FROM facts WHERE id in " + idsString);
Log.i(AnkiDroidApp.TAG, "DELETE FROM fields WHERE factId in " + idsString);
getDB().getDatabase().execSQL("DELETE FROM fields WHERE factId in " + idsString);
String sqlInsert = "INSERT INTO factsDeleted VALUES(?," + String.format(Utils.ENGLISH_LOCALE, "%f", now)
+ ")";
SQLiteStatement statement = getDB().getDatabase().compileStatement(sqlInsert);
for (String id : ids) {
Log.i(AnkiDroidApp.TAG, "inserting into factsDeleted");
statement.bindString(1, id);
statement.executeInsert();
}
statement.close();
setModified();
}
}
/**
* Delete any fact without cards.
*
* @return ArrayList<String> list with the id of the deleted facts
*/
private ArrayList<String> deleteDanglingFacts() {
Log.i(AnkiDroidApp.TAG, "deleteDanglingFacts");
ArrayList<String> danglingFacts = getDB().queryColumn(String.class,
"SELECT facts.id FROM facts WHERE facts.id NOT IN (SELECT DISTINCT factId from cards)", 0);
if (danglingFacts.size() > 0) {
deleteFacts(danglingFacts);
}
return danglingFacts;
}
/*
* Models CRUD*********************************************************
*/
/**
* Delete MODEL, and all its cards/facts. Caller must .reset() TODO: Handling of the list of models and currentModel
*
* @param id The ID of the model to be deleted.
*/
public void deleteModel(String id) {
Log.i(AnkiDroidApp.TAG, "deleteModel = " + id);
Cursor cursor = null;
boolean modelExists = false;
try {
cursor = getDB().getDatabase().rawQuery("SELECT * FROM models WHERE id = " + id, null);
// Does the model exist?
if (cursor.moveToFirst()) {
modelExists = true;
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
if (modelExists) {
// Delete the cards that use the model id, through fact
ArrayList<String> cardsToDelete = getDB()
.queryColumn(
String.class,
"SELECT cards.id FROM cards, facts WHERE facts.modelId = " + id
+ " AND facts.id = cards.factId", 0);
deleteCards(cardsToDelete);
// Delete model
getDB().getDatabase().execSQL("DELETE FROM models WHERE id = " + id);
// Note deleted model
ContentValues values = new ContentValues();
values.put("modelId", id);
values.put("deletedTime", Utils.now());
getDB().getDatabase().insert("modelsDeleted", null, values);
flushMod();
}
}
public void deleteFieldModel(String modelId, String fieldModelId) {
Log.i(AnkiDroidApp.TAG, "deleteFieldModel, modelId = " + modelId + ", fieldModelId = " + fieldModelId);
// Delete field model
getDB().getDatabase().execSQL("DELETE FROM fields WHERE fieldModel = " + fieldModelId);
// Note like modified the facts that use this model
getDB().getDatabase().execSQL(
"UPDATE facts SET modified = " + String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now())
+ " WHERE modelId = " + modelId);
// TODO: remove field model from list
// Update Question/Answer formats
// TODO: All these should be done with the field object
String fieldName = "";
Cursor cursor = null;
try {
cursor = getDB().getDatabase().rawQuery("SELECT name FROM fieldModels WHERE id = " + fieldModelId, null);
if (cursor.moveToNext()) {
fieldName = cursor.getString(0);
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
SQLiteStatement statement = null;
try {
cursor = getDB().getDatabase().rawQuery(
"SELECT id, qformat, aformat FROM cardModels WHERE modelId = " + modelId, null);
String sql = "UPDATE cardModels SET qformat = ?, aformat = ? WHERE id = ?";
statement = getDB().getDatabase().compileStatement(sql);
while (cursor.moveToNext()) {
String id = cursor.getString(0);
String newQFormat = cursor.getString(1);
String newAFormat = cursor.getString(2);
newQFormat = newQFormat.replace("%%(" + fieldName + ")s", "");
newQFormat = newQFormat.replace("%%(text:" + fieldName + ")s", "");
newAFormat = newAFormat.replace("%%(" + fieldName + ")s", "");
newAFormat = newAFormat.replace("%%(text:" + fieldName + ")s", "");
statement.bindString(1, newQFormat);
statement.bindString(2, newAFormat);
statement.bindString(3, id);
statement.execute();
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
statement.close();
// TODO: updateCardsFromModel();
// Note the model like modified (TODO: We should use the object model instead handling the DB directly)
getDB().getDatabase().execSQL(
"UPDATE models SET modified = " + String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now())
+ " WHERE id = " + modelId);
flushMod();
}
public void deleteCardModel(String modelId, String cardModelId) {
Log.i(AnkiDroidApp.TAG, "deleteCardModel, modelId = " + modelId + ", fieldModelId = " + cardModelId);
// Delete all cards that use card model from the deck
ArrayList<String> cardIds = getDB().queryColumn(String.class,
"SELECT id FROM cards WHERE cardModelId = " + cardModelId, 0);
deleteCards(cardIds);
// I assume that the line "model.cardModels.remove(cardModel)" actually deletes cardModel from DB (I might be
// wrong)
getDB().getDatabase().execSQL("DELETE FROM cardModels WHERE id = " + cardModelId);
// Note the model like modified (TODO: We should use the object model instead handling the DB directly)
getDB().getDatabase().execSQL(
"UPDATE models SET modified = " + String.format(Utils.ENGLISH_LOCALE, "%f", Utils.now())
+ " WHERE id = " + modelId);
flushMod();
}
// CSS for all the fields
private String rebuildCSS() {
StringBuilder css = new StringBuilder(512);
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery(
"SELECT id, quizFontFamily, quizFontSize, quizFontColour, -1, "
+ "features, editFontFamily FROM fieldModels", null);
while (cur.moveToNext()) {
css.append(_genCSS(".fm", cur));
}
cur.close();
cur = getDB().getDatabase().rawQuery("SELECT id, null, null, null, questionAlign, 0, 0 FROM cardModels",
null);
StringBuilder cssAnswer = new StringBuilder(512);
while (cur.moveToNext()) {
css.append(_genCSS("#cmq", cur));
cssAnswer.append(_genCSS("#cma", cur));
}
css.append(cssAnswer.toString());
cur.close();
cur = getDB().getDatabase().rawQuery("SELECT id, lastFontColour FROM cardModels", null);
while (cur.moveToNext()) {
css.append(".cmb").append(Utils.hexifyID(cur.getLong(0))).append(" {background:").append(
cur.getString(1)).append(";}\n");
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
setVar("cssCache", css.toString(), false);
addHexCache();
return css.toString();
}
private String _genCSS(String prefix, Cursor row) {
StringBuilder t = new StringBuilder(256);
long id = row.getLong(0);
String fam = row.getString(1);
int siz = row.getInt(2);
String col = row.getString(3);
int align = row.getInt(4);
String rtl = row.getString(5);
int pre = row.getInt(6);
if (fam != null) {
t.append("font-family:\"").append(fam).append("\";");
}
if (siz != 0) {
t.append("font-size:").append(siz).append("px;");
}
if (col != null) {
t.append("color:").append(col).append(";");
}
if (rtl != null && rtl.compareTo("rtl") == 0) {
t.append("direction:rtl;unicode-bidi:embed;");
}
if (pre != 0) {
t.append("white-space:pre-wrap;");
}
if (align != -1) {
if (align == 0) {
t.append("text-align:center;");
} else if (align == 1) {
t.append("text-align:left;");
} else {
t.append("text-align:right;");
}
}
if (t.length() > 0) {
t.insert(0, prefix + Utils.hexifyID(id) + " {").append("}\n");
}
return t.toString();
}
private void addHexCache() {
ArrayList<Long> ids = getDB().queryColumn(Long.class,
"SELECT id FROM fieldModels UNION SELECT id FROM cardModels UNION SELECT id FROM models", 0);
JSONObject jsonObject = new JSONObject();
for (Long id : ids) {
try {
jsonObject.put(id.toString(), Utils.hexifyID(id.longValue()));
} catch (JSONException e) {
Log.e(AnkiDroidApp.TAG, "addHexCache: Error while generating JSONObject: " + e.toString());
throw new RuntimeException(e);
}
}
setVar("hexCache", jsonObject.toString(), false);
}
//
// Syncing
// *************************
// Toggling does not bump deck mod time, since it may happen on upgrade and the variable is not synced
// public void enableSyncing() {
// enableSyncing(true);
// }
// public void enableSyncing(boolean ls) {
// mSyncName = Utils.checksum(mDeckPath);
// if (ls) {
// mLastSync = 0;
// }
// commitToDB();
// }
// private void disableSyncing() {
// disableSyncing(true);
// }
// private void disableSyncing(boolean ls) {
// mSyncName = "";
// if (ls) {
// mLastSync = 0;
// }
// commitToDB();
// }
// public boolean syncingEnabled() {
// return (mSyncName != null) && !(mSyncName.equals(""));
// }
// private void checkSyncHash() {
// if ((mSyncName != null) && !mSyncName.equals(Utils.checksum(mDeckPath))) {
// disableSyncing();
// }
// }
/*
* Undo/Redo*********************************************************
*/
private class UndoRow {
private String mName;
private Long mStart;
private Long mEnd;
private Long mCardId;
UndoRow(String name, Long cardId, Long start, Long end) {
mName = name;
mCardId = cardId;
mStart = start;
mEnd = end;
}
}
private void initUndo() {
mUndoStack = new Stack<UndoRow>();
mRedoStack = new Stack<UndoRow>();
mUndoEnabled = true;
try {
getDB().getDatabase()
.execSQL("CREATE TEMPORARY TABLE undoLog (seq INTEGER PRIMARY KEY NOT NULL, sql TEXT)");
} catch (SQLException e) {
/* Temporary table may still be present if the DB has not been closed */
Log.i(AnkiDroidApp.TAG, "Failed to create temporary table: " + e.getMessage());
}
ArrayList<String> tables = getDB().queryColumn(String.class,
"SELECT name FROM sqlite_master WHERE type = 'table'", 0);
Iterator<String> iter = tables.iterator();
while (iter.hasNext()) {
String table = iter.next();
if (table.equals("undoLog") || table.equals("sqlite_stat1")) {
continue;
}
ArrayList<String> columns = getDB().queryColumn(String.class, "PRAGMA TABLE_INFO(" + table + ")", 1);
// Insert trigger
StringBuilder sql = new StringBuilder(512);
sql.append("CREATE TEMP TRIGGER _undo_%s_it AFTER INSERT ON %s BEGIN INSERT INTO undoLog VALUES ").append(
"(null, 'DELETE FROM %s WHERE rowid = ' || new.rowid); END");
getDB().getDatabase().execSQL(String.format(Utils.ENGLISH_LOCALE, sql.toString(), table, table, table));
// Update trigger
sql = new StringBuilder(512);
sql.append(String.format(Utils.ENGLISH_LOCALE, "CREATE TEMP TRIGGER _undo_%s_ut AFTER UPDATE ON %s BEGIN "
+ "INSERT INTO undoLog VALUES (null, 'UPDATE %s ", table, table, table));
String sep = "SET ";
for (String column : columns) {
if (column.equals("unique")) {
continue;
}
sql.append(String.format(Utils.ENGLISH_LOCALE, "%s%s=' || quote(old.%s) || '", sep, column, column));
sep = ",";
}
sql.append(" WHERE rowid = ' || old.rowid); END");
getDB().getDatabase().execSQL(sql.toString());
// Delete trigger
sql = new StringBuilder(512);
sql.append(String.format(Utils.ENGLISH_LOCALE, "CREATE TEMP TRIGGER _undo_%s_dt BEFORE DELETE ON %s BEGIN "
+ "INSERT INTO undoLog VALUES (null, 'INSERT INTO %s (rowid", table, table, table));
for (String column : columns) {
sql.append(String.format(Utils.ENGLISH_LOCALE, ",\"%s\"", column));
}
sql.append(") VALUES (' || old.rowid ||'");
for (String column : columns) {
if (column.equals("unique")) {
sql.append(",1");
continue;
}
sql.append(String.format(Utils.ENGLISH_LOCALE, ", ' || quote(old.%s) ||'", column));
}
sql.append(")'); END");
getDB().getDatabase().execSQL(sql.toString());
}
}
public String undoName() {
return mUndoStack.peek().mName;
}
public String redoName() {
return mRedoStack.peek().mName;
}
public boolean undoAvailable() {
return (mUndoEnabled && !mUndoStack.isEmpty());
}
public boolean redoAvailable() {
return (mUndoEnabled && !mRedoStack.isEmpty());
}
public void resetUndo() {
try {
getDB().getDatabase().execSQL("delete from undoLog");
} catch (SQLException e) {
}
mUndoStack.clear();
mRedoStack.clear();
}
private void setUndoBarrier() {
if (mUndoStack.isEmpty() || mUndoStack.peek() != null) {
mUndoStack.push(null);
}
}
public void setUndoStart(String name) {
setUndoStart(name, 0, false);
}
public void setUndoStart(String name, long cardId) {
setUndoStart(name, cardId, false);
}
/**
* @param reviewEarly set to true for early review
*/
public void setReviewEarly(boolean reviewEarly) {
mReviewEarly = reviewEarly;
}
private void setUndoStart(String name, long cardId, boolean merge) {
if (!mUndoEnabled) {
return;
}
commitToDB();
if (merge && !mUndoStack.isEmpty()) {
if ((mUndoStack.peek() != null) && (mUndoStack.peek().mName.equals(name))) {
// libanki: merge with last entry?
return;
}
}
mUndoStack.push(new UndoRow(name, cardId, latestUndoRow(), null));
}
public void setUndoEnd(String name) {
if (!mUndoEnabled) {
return;
}
commitToDB();
long end = latestUndoRow();
while (mUndoStack.peek() == null) {
mUndoStack.pop(); // Strip off barrier
}
UndoRow row = mUndoStack.peek();
row.mEnd = end;
if (row.mStart == row.mEnd) {
mUndoStack.pop();
} else {
mRedoStack.clear();
}
}
private long latestUndoRow() {
long result = 0;
try {
result = getDB().queryScalar("SELECT MAX(rowid) FROM undoLog");
} catch (SQLException e) {
Log.i(AnkiDroidApp.TAG, e.getMessage());
}
return result;
}
private long undoredo(Stack<UndoRow> src, Stack<UndoRow> dst, long oldCardId) {
UndoRow row;
commitToDB();
while (true) {
row = src.pop();
if (row != null) {
break;
}
}
Long start = row.mStart;
Long end = row.mEnd;
if (end == null) {
end = latestUndoRow();
}
ArrayList<String> sql = getDB().queryColumn(
String.class,
String.format(Utils.ENGLISH_LOCALE, "SELECT sql FROM undoLog " + "WHERE seq > %d and seq <= %d "
+ "ORDER BY seq DESC", start, end), 0);
Long newstart = latestUndoRow();
for (String s : sql) {
getDB().getDatabase().execSQL(s);
}
Long newend = latestUndoRow();
dst.push(new UndoRow(row.mName, oldCardId, newstart, newend));
return row.mCardId;
}
/**
* Undo the last action(s). Caller must .reset()
*/
public long undo(long oldCardId) {
long cardId = 0;
if (!mUndoStack.isEmpty()) {
cardId = undoredo(mUndoStack, mRedoStack, oldCardId);
commitToDB();
reset();
}
return cardId;
}
/**
* Redo the last action(s). Caller must .reset()
*/
public long redo(long oldCardId) {
long cardId = 0;
if (!mRedoStack.isEmpty()) {
cardId = undoredo(mRedoStack, mUndoStack, oldCardId);
commitToDB();
reset();
}
return cardId;
}
/*
* Dynamic indices*********************************************************
*/
private void updateDynamicIndices() {
Log.i(AnkiDroidApp.TAG, "updateDynamicIndices - Updating indices...");
HashMap<String, String> indices = new HashMap<String, String>();
indices.put("intervalDesc", "(type, priority desc, interval desc, factId, combinedDue)");
indices.put("intervalAsc", "(type, priority desc, interval, factId, combinedDue)");
indices.put("randomOrder", "(type, priority desc, factId, ordinal, combinedDue)");
indices.put("dueAsc", "(type, priority desc, due, factId, combinedDue)");
indices.put("dueDesc", "(type, priority desc, due desc, factId, combinedDue)");
ArrayList<String> required = new ArrayList<String>();
if (mRevCardOrder == REV_CARDS_OLD_FIRST) {
required.add("intervalDesc");
}
if (mRevCardOrder == REV_CARDS_NEW_FIRST) {
required.add("intervalAsc");
}
if (mRevCardOrder == REV_CARDS_RANDOM) {
required.add("randomOrder");
}
if (mRevCardOrder == REV_CARDS_DUE_FIRST || mNewCardOrder == NEW_CARDS_OLD_FIRST
|| mNewCardOrder == NEW_CARDS_RANDOM) {
required.add("dueAsc");
}
if (mNewCardOrder == NEW_CARDS_NEW_FIRST) {
required.add("dueDesc");
}
// Add/delete
boolean analyze = false;
Set<Entry<String, String>> entries = indices.entrySet();
Iterator<Entry<String, String>> iter = entries.iterator();
String indexName = null;
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
indexName = "ix_cards_" + entry.getKey() + "2";
if (required.contains(entry.getKey())) {
Cursor cursor = null;
try {
cursor = getDB().getDatabase().rawQuery(
"SELECT 1 FROM sqlite_master WHERE name = '" + indexName + "'", null);
if ((!cursor.moveToNext()) || (cursor.getInt(0) != 1)) {
getDB().getDatabase().execSQL("CREATE INDEX " + indexName + " ON cards " + entry.getValue());
analyze = true;
}
} finally {
if (cursor != null) {
cursor.close();
}
}
} else {
// Leave old indices for older clients
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS " + indexName);
}
}
if (analyze) {
getDB().getDatabase().execSQL("ANALYZE");
}
}
/*
* JSON
*/
public JSONObject bundleJson(JSONObject bundledDeck) {
try {
bundledDeck.put("averageFactor", mAverageFactor);
bundledDeck.put("cardCount", mCardCount);
bundledDeck.put("collapseTime", mCollapseTime);
bundledDeck.put("created", mCreated);
// bundledDeck.put("currentModelId", currentModelId);
bundledDeck.put("delay0", mDelay0);
bundledDeck.put("delay1", mDelay1);
bundledDeck.put("delay2", mDelay2);
bundledDeck.put("description", mDescription);
bundledDeck.put("easyIntervalMax", mEasyIntervalMax);
bundledDeck.put("easyIntervalMin", mEasyIntervalMin);
bundledDeck.put("factCount", mFactCount);
bundledDeck.put("failedCardMax", mFailedCardMax);
bundledDeck.put("failedNowCount", mFailedNowCount);
bundledDeck.put("failedSoonCount", mFailedSoonCount);
bundledDeck.put("hardIntervalMax", mHardIntervalMax);
bundledDeck.put("hardIntervalMin", mHardIntervalMin);
bundledDeck.put("highPriority", mHighPriority);
bundledDeck.put("id", mId);
bundledDeck.put("lastLoaded", mLastLoaded);
bundledDeck.put("lastSync", mLastSync);
bundledDeck.put("lowPriority", mLowPriority);
bundledDeck.put("medPriority", mMedPriority);
bundledDeck.put("midIntervalMax", mMidIntervalMax);
bundledDeck.put("midIntervalMin", mMidIntervalMin);
bundledDeck.put("modified", mModified);
bundledDeck.put("newCardModulus", mNewCardModulus);
bundledDeck.put("newCount", mNewCount);
bundledDeck.put("newCountToday", mNewCountToday);
bundledDeck.put("newEarly", mNewEarly);
bundledDeck.put("revCount", mRevCount);
bundledDeck.put("reviewEarly", mReviewEarly);
bundledDeck.put("suspended", mSuspended);
bundledDeck.put("undoEnabled", mUndoEnabled);
bundledDeck.put("utcOffset", mUtcOffset);
} catch (JSONException e) {
Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
return bundledDeck;
}
public void updateFromJson(JSONObject deckPayload) {
try {
// Update deck
mCardCount = deckPayload.getInt("cardCount");
mCollapseTime = deckPayload.getDouble("collapseTime");
mCreated = deckPayload.getDouble("created");
// css
mCurrentModelId = deckPayload.getLong("currentModelId");
mDelay0 = deckPayload.getLong("delay0");
mDelay1 = deckPayload.getLong("delay1");
mDelay2 = deckPayload.getDouble("delay2");
mDescription = deckPayload.getString("description");
mDueCutoff = deckPayload.getDouble("dueCutoff");
mEasyIntervalMax = deckPayload.getDouble("easyIntervalMax");
mEasyIntervalMin = deckPayload.getDouble("easyIntervalMin");
mFactCount = deckPayload.getInt("factCount");
mFailedCardMax = deckPayload.getInt("failedCardMax");
mFailedNowCount = deckPayload.getInt("failedNowCount");
mFailedSoonCount = deckPayload.getInt("failedSoonCount");
// forceMediaDir
mHardIntervalMax = deckPayload.getDouble("hardIntervalMax");
mHardIntervalMin = deckPayload.getDouble("hardIntervalMin");
mHighPriority = deckPayload.getString("highPriority");
mId = deckPayload.getLong("id");
// key
mLastLoaded = deckPayload.getDouble("lastLoaded");
// lastSessionStart
mLastSync = deckPayload.getDouble("lastSync");
// lastTags
mLowPriority = deckPayload.getString("lowPriority");
mMedPriority = deckPayload.getString("medPriority");
mMediaPrefix = deckPayload.getString("mediaPrefix");
mMidIntervalMax = deckPayload.getDouble("midIntervalMax");
mMidIntervalMin = deckPayload.getDouble("midIntervalMin");
mModified = deckPayload.getDouble("modified");
// needLock
mNewCardOrder = deckPayload.getInt("newCardOrder");
mNewCardSpacing = deckPayload.getInt("newCardSpacing");
mNewCardsPerDay = deckPayload.getInt("newCardsPerDay");
mNewCount = deckPayload.getInt("newCount");
// progressHandlerCalled
// progressHandlerEnabled
mQueueLimit = deckPayload.getInt("queueLimit");
mRevCardOrder = deckPayload.getInt("revCardOrder");
mRevCount = deckPayload.getInt("revCount");
mScheduler = deckPayload.getString("scheduler");
mSessionRepLimit = deckPayload.getInt("sessionRepLimit");
// sessionStartReps
// sessionStartTime
mSessionTimeLimit = deckPayload.getInt("sessionTimeLimit");
mSuspended = deckPayload.getString("suspended");
// tmpMediaDir
mUndoEnabled = deckPayload.getBoolean("undoEnabled");
mUtcOffset = deckPayload.getDouble("utcOffset");
commitToDB();
} catch (JSONException e) {
Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
}
}
/*
* Utility functions (might be better in a separate class) *********************************************************
*/
/**
* Return ID for tag, creating if necessary.
*
* @param tag the tag we are looking for
* @param create whether to create the tag if it doesn't exist in the database
* @return ID of the specified tag, 0 if it doesn't exist, and -1 in the case of error
*/
private long tagId(String tag, Boolean create) {
long id = 0;
try {
id = getDB().queryScalar("select id from tags where tag = \"" + tag + "\"");
} catch (SQLException e) {
if (create) {
ContentValues value = new ContentValues();
value.put("tag", tag);
id = getDB().getDatabase().insert("tags", null, value);
} else {
id = 0;
}
}
return id;
}
/**
* Gets the IDs of the specified tags.
*
* @param tags An array of the tags to get IDs for.
* @param create Whether to create the tag if it doesn't exist in the database. Default = true
* @return An array of IDs of the tags.
*/
private HashMap<String, Long> tagIds(String[] tags) {
return tagIds(tags, true);
}
private HashMap<String, Long> tagIds(String[] tags, boolean create) {
HashMap<String, Long> results = new HashMap<String, Long>();
if (create) {
for (String tag : tags) {
getDB().getDatabase().execSQL("INSERT OR IGNORE INTO tags (tag) VALUES ('" + tag + "')");
}
}
if (tags.length != 0) {
StringBuilder tagList = new StringBuilder(128);
for (int i = 0; i < tags.length; i++) {
tagList.append("'").append(tags[i]).append("'");
if (i < tags.length - 1) {
tagList.append(", ");
}
}
Cursor cur = null;
try {
cur = getDB().getDatabase().rawQuery(
"SELECT tag, id FROM tags WHERE tag in (" + tagList.toString() + ")", null);
while (cur.moveToNext()) {
results.put(cur.getString(0).toLowerCase(), cur.getLong(1));
}
} finally {
if (cur != null && !cur.isClosed()) {
cur.close();
}
}
}
return results;
}
}
| true | true | private boolean upgradeDeck() {
// Oldest versions in existence are 31 as of 11/07/2010
// We support upgrading from 39 and up.
// Unsupported are about 135 decks, missing about 6% as of 11/07/2010
//
double oldmod = mModified;
upgradeNotes = new ArrayList<Integer>();
if (mVersion < 39) {
// Unsupported version
upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_too_old_version);
return false;
}
if (mVersion < 40) {
// Now stores media url
getDB().getDatabase().execSQL("UPDATE models SET features = ''");
mVersion = 40;
commitToDB();
}
if (mVersion < 43) {
getDB().getDatabase().execSQL("UPDATE fieldModels SET features = ''");
mVersion = 43;
commitToDB();
}
if (mVersion < 44) {
// Leaner indices
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_factId");
mVersion = 44;
commitToDB();
}
if (mVersion < 48) {
updateFieldCache(Utils.toPrimitive(getDB().queryColumn(Long.class, "SELECT id FROM facts", 0)));
mVersion = 48;
commitToDB();
}
if (mVersion < 50) {
// more new type handling
rebuildTypes();
mVersion = 50;
commitToDB();
}
if (mVersion < 52) {
// The commented code below follows libanki by setting the syncName to the MD5 hash of the path.
// The problem with that is that it breaks syncing with already uploaded decks.
// if ((mSyncName != null) && !mSyncName.equals("")) {
// if (!mDeckName.equals(mSyncName)) {
// upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_52_note);
// disableSyncing(false);
// } else {
// enableSyncing(false);
// }
// }
mVersion = 52;
commitToDB();
}
if (mVersion < 53) {
if (getBool("perDay")) {
if (Math.abs(mHardIntervalMin - 0.333) < 0.001) {
mHardIntervalMin = Math.max(1.0, mHardIntervalMin);
mHardIntervalMax = Math.max(1.1, mHardIntervalMax);
}
}
mVersion = 53;
commitToDB();
}
if (mVersion < 54) {
// editFontFamily now used as a boolean, but in integer type, so set to 1 == true
getDB().getDatabase().execSQL("UPDATE fieldModels SET editFontFamily = 1");
mVersion = 54;
commitToDB();
}
if (mVersion < 57) {
// Add an index for priority & modified
mVersion = 57;
commitToDB();
}
if (mVersion < 61) {
// First check if the deck has LaTeX, if so it should be upgraded in Anki
if (hasLaTeX()) {
upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_version_61_has_latex);
return false;
}
// Do our best to upgrade templates to the new style
String txt =
"<span style=\"font-family: %s; font-size: %spx; color: %s; white-space: pre-wrap;\">%s</span>";
Map<Long, Model> models = Model.getModels(this);
Set<String> unstyled = new HashSet<String>();
boolean changed = false;
for (Model m : models.values()) {
TreeMap<Long, FieldModel> fieldModels = m.getFieldModels();
for (FieldModel fm : fieldModels.values()) {
changed = false;
Log.i(AnkiDroidApp.TAG, "family: '" + fm.getQuizFontFamily() + "'");
Log.i(AnkiDroidApp.TAG, "family: " + fm.getQuizFontSize());
Log.i(AnkiDroidApp.TAG, "family: '" + fm.getQuizFontColour() + "'");
if ((fm.getQuizFontFamily() != null && !fm.getQuizFontFamily().equals("")) ||
fm.getQuizFontSize() != 0 ||
(fm.getQuizFontColour() != null && fm.getQuizFontColour().equals(""))) {
} else {
unstyled.add(fm.getName());
}
// Fill out missing info
if (fm.getQuizFontFamily() == null || fm.getQuizFontFamily().equals("")) {
fm.setQuizFontFamily("Arial");
changed = true;
}
if (fm.getQuizFontSize() == 0) {
fm.setQuizFontSize(20);
changed = true;
}
if (fm.getQuizFontColour() == null || fm.getQuizFontColour().equals("")) {
fm.setQuizFontColour("#000000");
changed = true;
}
if (fm.getEditFontSize() == 0) {
fm.setEditFontSize(20);
changed = true;
}
if (changed) {
fm.toDB(this);
}
}
for (CardModel cm : m.getCardModels()) {
// Embed the old font information into card templates
String format = cm.getQFormat();
cm.setQFormat(String.format(txt, cm.getQuestionFontFamily(), cm.getQuestionFontSize(),
cm.getQuestionFontColour(), format));
format = cm.getAFormat();
cm.setAFormat(String.format(txt, cm.getAnswerFontFamily(), cm.getAnswerFontSize(),
cm.getAnswerFontColour(), format));
// Escape fields that had no previous styling
for (String un : unstyled) {
String oldStyle = "%(" + un + ")s";
String newStyle = "{{{" + un + "}}}";
cm.setQFormat(cm.getQFormat().replace(oldStyle, newStyle));
cm.setAFormat(cm.getAFormat().replace(oldStyle, newStyle));
}
cm.toDB(this);
}
}
// Rebuild q/a for the above & because latex has changed
// We should be doing updateAllCards(), but it takes too long (really)
// updateAllCards();
// Rebuild the media db based on new format
Media.rebuildMediaDir(this, false);
mVersion = 61;
commitToDB();
}
if (mVersion < 62) {
// Updated Indices
String[] indices = { "intervalDesc", "intervalAsc", "randomOrder", "dueAsc", "dueDesc" };
for (String d : indices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_" + d + "2");
}
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_typeCombined");
addIndices();
updateDynamicIndices();
getDB().getDatabase().execSQL("VACUUM");
mVersion = 62;
commitToDB();
}
if (mVersion < 64) {
// Remove old static indices, as all clients should be libanki1.2+
String[] oldStaticIndices = { "ix_cards_duePriority", "ix_cards_priorityDue" };
for (String d : oldStaticIndices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS " + d);
}
// Remove old dynamic indices
String[] oldDynamicIndices = { "intervalDesc", "intervalAsc", "randomOrder", "dueAsc", "dueDesc" };
for (String d : oldDynamicIndices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_" + d);
}
getDB().getDatabase().execSQL("ANALYZE");
mVersion = 64;
commitToDB();
// Note: we keep the priority index for now
}
if (mVersion < 65) {
// We weren't correctly setting relativeDelay when answering cards in previous versions, so ensure
// everything is set correctly
rebuildTypes();
mVersion = 65;
commitToDB();
}
// Executing a pragma here is very slow on large decks, so we store our own record
if (getInt("pageSize") != 4096) {
commitToDB();
getDB().getDatabase().execSQL("PRAGMA page_size = 4096");
getDB().getDatabase().execSQL("PRAGMA legacy_file_format = 0");
getDB().getDatabase().execSQL("VACUUM");
setVar("pageSize", "4096", false);
commitToDB();
}
assert (mModified == oldmod);
return true;
}
| private boolean upgradeDeck() {
// Oldest versions in existence are 31 as of 11/07/2010
// We support upgrading from 39 and up.
// Unsupported are about 135 decks, missing about 6% as of 11/07/2010
//
double oldmod = mModified;
upgradeNotes = new ArrayList<Integer>();
if (mVersion < 39) {
// Unsupported version
upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_too_old_version);
return false;
}
if (mVersion < 40) {
// Now stores media url
getDB().getDatabase().execSQL("UPDATE models SET features = ''");
mVersion = 40;
commitToDB();
}
if (mVersion < 43) {
getDB().getDatabase().execSQL("UPDATE fieldModels SET features = ''");
mVersion = 43;
commitToDB();
}
if (mVersion < 44) {
// Leaner indices
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_factId");
mVersion = 44;
commitToDB();
}
if (mVersion < 48) {
updateFieldCache(Utils.toPrimitive(getDB().queryColumn(Long.class, "SELECT id FROM facts", 0)));
mVersion = 48;
commitToDB();
}
if (mVersion < 50) {
// more new type handling
rebuildTypes();
mVersion = 50;
commitToDB();
}
if (mVersion < 52) {
// The commented code below follows libanki by setting the syncName to the MD5 hash of the path.
// The problem with that is that it breaks syncing with already uploaded decks.
// if ((mSyncName != null) && !mSyncName.equals("")) {
// if (!mDeckName.equals(mSyncName)) {
// upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_52_note);
// disableSyncing(false);
// } else {
// enableSyncing(false);
// }
// }
mVersion = 52;
commitToDB();
}
if (mVersion < 53) {
if (getBool("perDay")) {
if (Math.abs(mHardIntervalMin - 0.333) < 0.001) {
mHardIntervalMin = Math.max(1.0, mHardIntervalMin);
mHardIntervalMax = Math.max(1.1, mHardIntervalMax);
}
}
mVersion = 53;
commitToDB();
}
if (mVersion < 54) {
// editFontFamily now used as a boolean, but in integer type, so set to 1 == true
getDB().getDatabase().execSQL("UPDATE fieldModels SET editFontFamily = 1");
mVersion = 54;
commitToDB();
}
if (mVersion < 57) {
// Add an index for priority & modified
mVersion = 57;
commitToDB();
}
if (mVersion < 61) {
// First check if the deck has LaTeX, if so it should be upgraded in Anki
if (hasLaTeX()) {
upgradeNotes.add(com.ichi2.anki.R.string.deck_upgrade_version_61_has_latex);
return false;
}
// Do our best to upgrade templates to the new style
String txt =
"<span style=\"font-family: %s; font-size: %spx; color: %s; white-space: pre-wrap;\">%s</span>";
Map<Long, Model> models = Model.getModels(this);
Set<String> unstyled = new HashSet<String>();
boolean changed = false;
for (Model m : models.values()) {
TreeMap<Long, FieldModel> fieldModels = m.getFieldModels();
for (FieldModel fm : fieldModels.values()) {
changed = false;
Log.i(AnkiDroidApp.TAG, "family: '" + fm.getQuizFontFamily() + "'");
Log.i(AnkiDroidApp.TAG, "family: " + fm.getQuizFontSize());
Log.i(AnkiDroidApp.TAG, "family: '" + fm.getQuizFontColour() + "'");
if ((fm.getQuizFontFamily() != null && !fm.getQuizFontFamily().equals("")) ||
fm.getQuizFontSize() != 0 ||
(fm.getQuizFontColour() != null && fm.getQuizFontColour().equals(""))) {
} else {
unstyled.add(fm.getName());
}
// Fill out missing info
if (fm.getQuizFontFamily() == null || fm.getQuizFontFamily().equals("")) {
fm.setQuizFontFamily("Arial");
changed = true;
}
if (fm.getQuizFontSize() == 0) {
fm.setQuizFontSize(20);
changed = true;
}
if (fm.getQuizFontColour() == null || fm.getQuizFontColour().equals("")) {
fm.setQuizFontColour("#000000");
changed = true;
}
if (fm.getEditFontSize() == 0) {
fm.setEditFontSize(20);
changed = true;
}
if (changed) {
fm.toDB(this);
}
}
for (CardModel cm : m.getCardModels()) {
// Embed the old font information into card templates
String format = cm.getQFormat();
cm.setQFormat(String.format(txt, cm.getQuestionFontFamily(), cm.getQuestionFontSize(),
cm.getQuestionFontColour(), format));
format = cm.getAFormat();
cm.setAFormat(String.format(txt, cm.getAnswerFontFamily(), cm.getAnswerFontSize(),
cm.getAnswerFontColour(), format));
// Escape fields that had no previous styling
for (String un : unstyled) {
String oldStyle = "%(" + un + ")s";
String newStyle = "{{{" + un + "}}}";
cm.setQFormat(cm.getQFormat().replace(oldStyle, newStyle));
cm.setAFormat(cm.getAFormat().replace(oldStyle, newStyle));
}
cm.toDB(this);
}
}
// Rebuild q/a for the above & because latex has changed
// We should be doing updateAllCards(), but it takes too long (really)
// updateAllCards();
// Rebuild the media db based on new format
Media.rebuildMediaDir(this, false);
mVersion = 61;
commitToDB();
}
if (mVersion < 62) {
// Updated Indices
String[] indices = { "intervalDesc", "intervalAsc", "randomOrder", "dueAsc", "dueDesc" };
for (String d : indices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_" + d + "2");
}
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_typeCombined");
addIndices();
updateDynamicIndices();
getDB().getDatabase().execSQL("VACUUM");
mVersion = 62;
commitToDB();
}
if (mVersion < 64) {
// Remove old static indices, as all clients should be libanki1.2+
String[] oldStaticIndices = { "ix_cards_duePriority", "ix_cards_priorityDue" };
for (String d : oldStaticIndices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS " + d);
}
// Remove old dynamic indices
String[] oldDynamicIndices = { "intervalDesc", "intervalAsc", "randomOrder", "dueAsc", "dueDesc" };
for (String d : oldDynamicIndices) {
getDB().getDatabase().execSQL("DROP INDEX IF EXISTS ix_cards_" + d);
}
getDB().getDatabase().execSQL("ANALYZE");
mVersion = 64;
commitToDB();
// Note: we keep the priority index for now
}
if (mVersion < 65) {
// We weren't correctly setting relativeDelay when answering cards in previous versions, so ensure
// everything is set correctly
rebuildTypes();
mVersion = 65;
commitToDB();
}
// Executing a pragma here is very slow on large decks, so we store our own record
if ((!hasKey("pageSize")) || (getInt("pageSize") != 4096)) {
commitToDB();
getDB().getDatabase().execSQL("PRAGMA page_size = 4096");
getDB().getDatabase().execSQL("PRAGMA legacy_file_format = 0");
getDB().getDatabase().execSQL("VACUUM");
setVar("pageSize", "4096", false);
commitToDB();
}
assert (mModified == oldmod);
return true;
}
|
diff --git a/src/main/java/com/saplo/api/client/HTTPSessionApache.java b/src/main/java/com/saplo/api/client/HTTPSessionApache.java
index 8388399..c47d22a 100644
--- a/src/main/java/com/saplo/api/client/HTTPSessionApache.java
+++ b/src/main/java/com/saplo/api/client/HTTPSessionApache.java
@@ -1,196 +1,196 @@
/**
*
*/
package com.saplo.api.client;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.HashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NoHttpResponseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import com.saplo.api.client.TransportRegistry.SessionFactory;
import com.saplo.api.client.entity.JSONRPCRequestObject;
import com.saplo.api.client.entity.JSONRPCResponseObject;
/**
* @author progre55
*
*/
public class HTTPSessionApache implements Session {
private static Log logger = LogFactory.getLog(HTTPSessionApache.class);
protected URI uri;
protected volatile String params;
// protected int clientsCount;
// protected Stack<DefaultHttpClient> clientPool;
protected HttpHost proxy = new HttpHost("localhost");
protected boolean proxified = false;
public HTTPSessionApache(URI uri, String params, int count) {
this.uri = uri;
this.params = params;
// this.clientsCount = count;
// clientPool = new Stack<DefaultHttpClient>();
// fillPool();
}
public JSONRPCResponseObject sendAndReceive(JSONRPCRequestObject message)
throws JSONException, SaploClientException {
HttpPost httpost = new HttpPost(uri+"?"+params);
- ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes());
+ ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes(Charset.forName("UTF-8")));
ent.setContentEncoding(HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded");
httpost.setEntity(ent);
// DefaultHttpClient httpClient = getClient();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
if(proxified)
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse response = httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
// probably the API is down..
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, statusCode);
String got = "";
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
got = new String(bytes, Charset.forName("UTF-8"));
}
JSONTokener tokener = new JSONTokener(got);
Object rawResponseMessage = tokener.nextValue();
JSONObject responseMessage = (JSONObject) rawResponseMessage;
if (responseMessage == null)
throw new ClientError("Invalid response type - " + rawResponseMessage);
return new JSONRPCResponseObject(responseMessage);
} catch (ClientProtocolException e) {
throw new ClientError(e);
} catch (NoHttpResponseException nr) {
// TODO what code to send here? 404? for now, just send 777
// cause 404 is thrown when response.getStatusLine().getStatusCode() == 404 above
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, 777);
} catch (IOException e) {
throw new ClientError(e);
} finally {
// releaseClient(httpClient);
httpClient.getConnectionManager().shutdown();
}
}
public void setParams(String params) {
this.params = params;
}
public void setProxy(String address, int port) {
this.proxified = true;
this.proxy = new HttpHost(address, port, "http");
}
// /**
// * Get a client from the pool.
// *
// * @return - HttpClient
// */
// protected synchronized DefaultHttpClient getClient() {
// DefaultHttpClient cl = null;
// try {
// while (clientPool.empty())
// this.wait();
// logger.debug("Remaining clients: " + clientPool.size());
// cl = clientPool.pop();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
//
// return cl;
// }
//
// /**
// * Put the client back into the pool.
// *
// * @param client - the client to return into the pool
// */
// public synchronized void releaseClient(DefaultHttpClient client) {
// clientPool.push(client);
// this.notify();
// }
//
// private void fillPool() {
// for (int i = 0; i < clientsCount; i++) {
// DefaultHttpClient cl = new DefaultHttpClient();
// clientPool.push(cl);
// }
// }
/**
* Close all the clients and clear the pool.
*/
public synchronized void close() {
// for (int i = 0; i < clientsCount; i++) {
// DefaultHttpClient cl = clientPool.pop();
// cl.getConnectionManager().shutdown();
// }
// clientPool.clear();
}
static class SessionFactoryImpl implements SessionFactory {
volatile HashMap<URI, Session> sessionMap = new HashMap<URI, Session>();
public Session newSession(URI uri, String params, int count) {
Session session = sessionMap.get(uri);
if (session == null) {
synchronized (sessionMap) {
session = sessionMap.get(uri);
if(session == null) {
session = new HTTPSessionApache(uri, params, count);
sessionMap.put(uri, session);
}
}
}
return session;
}
}
/**
* Register this transport in 'registry'
*/
public static void register(TransportRegistry registry) {
registry.registerTransport("http", new SessionFactoryImpl());
}
/**
* De-register this transport from the 'registry'
*/
public static void deregister(TransportRegistry registry) {
registry.deregisterTransport("http");
}
}
| true | true | public JSONRPCResponseObject sendAndReceive(JSONRPCRequestObject message)
throws JSONException, SaploClientException {
HttpPost httpost = new HttpPost(uri+"?"+params);
ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes());
ent.setContentEncoding(HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded");
httpost.setEntity(ent);
// DefaultHttpClient httpClient = getClient();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
if(proxified)
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse response = httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
// probably the API is down..
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, statusCode);
String got = "";
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
got = new String(bytes, Charset.forName("UTF-8"));
}
JSONTokener tokener = new JSONTokener(got);
Object rawResponseMessage = tokener.nextValue();
JSONObject responseMessage = (JSONObject) rawResponseMessage;
if (responseMessage == null)
throw new ClientError("Invalid response type - " + rawResponseMessage);
return new JSONRPCResponseObject(responseMessage);
} catch (ClientProtocolException e) {
throw new ClientError(e);
} catch (NoHttpResponseException nr) {
// TODO what code to send here? 404? for now, just send 777
// cause 404 is thrown when response.getStatusLine().getStatusCode() == 404 above
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, 777);
} catch (IOException e) {
throw new ClientError(e);
} finally {
// releaseClient(httpClient);
httpClient.getConnectionManager().shutdown();
}
}
| public JSONRPCResponseObject sendAndReceive(JSONRPCRequestObject message)
throws JSONException, SaploClientException {
HttpPost httpost = new HttpPost(uri+"?"+params);
ByteArrayEntity ent = new ByteArrayEntity(message.toString().getBytes(Charset.forName("UTF-8")));
ent.setContentEncoding(HTTP.UTF_8);
ent.setContentType("application/x-www-form-urlencoded");
httpost.setEntity(ent);
// DefaultHttpClient httpClient = getClient();
DefaultHttpClient httpClient = new DefaultHttpClient();
try {
if(proxified)
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse response = httpClient.execute(httpost);
HttpEntity entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK)
// probably the API is down..
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, statusCode);
String got = "";
if (entity != null) {
byte[] bytes = EntityUtils.toByteArray(entity);
got = new String(bytes, Charset.forName("UTF-8"));
}
JSONTokener tokener = new JSONTokener(got);
Object rawResponseMessage = tokener.nextValue();
JSONObject responseMessage = (JSONObject) rawResponseMessage;
if (responseMessage == null)
throw new ClientError("Invalid response type - " + rawResponseMessage);
return new JSONRPCResponseObject(responseMessage);
} catch (ClientProtocolException e) {
throw new ClientError(e);
} catch (NoHttpResponseException nr) {
// TODO what code to send here? 404? for now, just send 777
// cause 404 is thrown when response.getStatusLine().getStatusCode() == 404 above
throw new SaploClientException(ResponseCodes.MSG_API_DOWN_EXCEPTION, ResponseCodes.CODE_API_DOWN_EXCEPTION, 777);
} catch (IOException e) {
throw new ClientError(e);
} finally {
// releaseClient(httpClient);
httpClient.getConnectionManager().shutdown();
}
}
|
diff --git a/src/com/sas/comp/server/EmbeddedServer.java b/src/com/sas/comp/server/EmbeddedServer.java
index 8599b61..2353a48 100644
--- a/src/com/sas/comp/server/EmbeddedServer.java
+++ b/src/com/sas/comp/server/EmbeddedServer.java
@@ -1,35 +1,35 @@
package com.sas.comp.server;
import org.apache.catalina.core.AprLifecycleListener;
import org.apache.catalina.core.StandardServer;
import org.apache.catalina.startup.Tomcat;
public class EmbeddedServer {
public static void main(final String[] args) throws Exception {
final EmbeddedServer server = new EmbeddedServer();
server.start();
}
private void start() throws Exception {
final String appBase = "";
- final Integer port = 80;
+ final Integer port = 8080;
final Tomcat tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.setBaseDir("./web");
tomcat.getHost().setAppBase(appBase);
final String contextPath = "/";
// Add AprLifecycleListener
StandardServer server = (StandardServer) tomcat.getServer();
AprLifecycleListener listener = new AprLifecycleListener();
server.addLifecycleListener(listener);
tomcat.addWebapp(contextPath, appBase);
tomcat.start();
tomcat.getServer().await();
}
}
| true | true | private void start() throws Exception {
final String appBase = "";
final Integer port = 80;
final Tomcat tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.setBaseDir("./web");
tomcat.getHost().setAppBase(appBase);
final String contextPath = "/";
// Add AprLifecycleListener
StandardServer server = (StandardServer) tomcat.getServer();
AprLifecycleListener listener = new AprLifecycleListener();
server.addLifecycleListener(listener);
tomcat.addWebapp(contextPath, appBase);
tomcat.start();
tomcat.getServer().await();
}
| private void start() throws Exception {
final String appBase = "";
final Integer port = 8080;
final Tomcat tomcat = new Tomcat();
tomcat.setPort(port);
tomcat.setBaseDir("./web");
tomcat.getHost().setAppBase(appBase);
final String contextPath = "/";
// Add AprLifecycleListener
StandardServer server = (StandardServer) tomcat.getServer();
AprLifecycleListener listener = new AprLifecycleListener();
server.addLifecycleListener(listener);
tomcat.addWebapp(contextPath, appBase);
tomcat.start();
tomcat.getServer().await();
}
|
diff --git a/src/com/cyanogenmod/filemanager/ui/widgets/DirectoryInlineAutocompleteTextView.java b/src/com/cyanogenmod/filemanager/ui/widgets/DirectoryInlineAutocompleteTextView.java
index b674d98..6ab3017 100644
--- a/src/com/cyanogenmod/filemanager/ui/widgets/DirectoryInlineAutocompleteTextView.java
+++ b/src/com/cyanogenmod/filemanager/ui/widgets/DirectoryInlineAutocompleteTextView.java
@@ -1,183 +1,186 @@
/*
* Copyright (C) 2012 The CyanogenMod Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.cyanogenmod.filemanager.ui.widgets;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import com.cyanogenmod.filemanager.util.CommandHelper;
import com.cyanogenmod.filemanager.util.FileHelper;
import java.io.File;
import java.util.List;
/**
* A widget based on {@link InlineAutocompleteTextView} for autocomplete
* directories like a bash console do (with tab key).
*/
public class DirectoryInlineAutocompleteTextView
extends InlineAutocompleteTextView
implements InlineAutocompleteTextView.OnTextChangedListener {
/**
* An interface to communicate validation events.
*/
public interface OnValidationListener {
/**
* Method invoked when the value is void.
*/
void onVoidValue();
/**
* Method invoked when the value is a valid value.
*/
void onValidValue();
/**
* Method invoked when the value is a invalid value.
*/
void onInvalidValue();
}
private static final String TAG = "DirectoryInlineAutocompleteTextView"; //$NON-NLS-1$
private OnValidationListener mOnValidationListener;
private String mLastParent;
/**
* Constructor of <code>DirectoryInlineAutocompleteTextView</code>.
*
* @param context The current context
*/
public DirectoryInlineAutocompleteTextView(Context context) {
super(context);
init();
}
/**
* Constructor of <code>DirectoryInlineAutocompleteTextView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
*/
public DirectoryInlineAutocompleteTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
/**
* Constructor of <code>DirectoryInlineAutocompleteTextView</code>.
*
* @param context The current context
* @param attrs The attributes of the XML tag that is inflating the view.
* @param defStyle The default style to apply to this view. If 0, no style
* will be applied (beyond what is included in the theme). This may
* either be an attribute resource, whose value will be retrieved
* from the current theme, or an explicit style resource.
*/
public DirectoryInlineAutocompleteTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
/**
* Method that initializes the view. This method loads all the necessary
* information and create an appropriate layout for the view
*/
private void init() {
//Sets last parent
this.mLastParent = ""; //$NON-NLS-1$
//Set the listener
setOnTextChangedListener(this);
setCompletionString(File.separator);
}
/**
* Method that set the listener for retrieve validation events.
*
* @param onValidationListener The listener for retrieve validation events
*/
public void setOnValidationListener(OnValidationListener onValidationListener) {
this.mOnValidationListener = onValidationListener;
}
/**
* {@inheritDoc}
*/
@Override
public void onTextChanged(String newValue, List<String> currentFilterData) {
String value = newValue;
//Check if directory is valid
if (value.length() == 0) {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onVoidValue();
}
} else {
boolean relative = FileHelper.isRelativePath(value);
if (relative) {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onInvalidValue();
}
} else {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onValidValue();
}
}
}
//Ensure data
if (!value.startsWith(File.separator)) {
currentFilterData.clear();
this.mLastParent = ""; //$NON-NLS-1$
return;
}
//Get the new parent
String newParent = FileHelper.getParentDir(new File(value));
+ if (newParent == null) {
+ newParent = FileHelper.ROOT_DIRECTORY;
+ }
if (!newParent.endsWith(File.separator)) {
newParent += File.separator;
}
if (value.compareTo(File.separator) == 0) {
newParent = File.separator;
currentFilterData.clear();
} else if (value.endsWith(File.separator)) {
//Force the change of parent
newParent = new File(value, "a").getParent(); //$NON-NLS-1$
if (!newParent.endsWith(File.separator)) {
newParent += File.separator;
}
currentFilterData.clear();
} else {
value = newParent;
}
//If a new path is detected, then load the new data
if (newParent.compareTo(this.mLastParent) != 0 || currentFilterData.isEmpty()) {
this.mLastParent = newParent;
currentFilterData.clear();
try {
List<String> newData =
CommandHelper.quickFolderSearch(getContext(), value, null);
currentFilterData.addAll(newData);
} catch (Throwable ex) {
Log.e(TAG, "Quick folder search failed", ex); //$NON-NLS-1$
currentFilterData.clear();
}
}
}
}
| true | true | public void onTextChanged(String newValue, List<String> currentFilterData) {
String value = newValue;
//Check if directory is valid
if (value.length() == 0) {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onVoidValue();
}
} else {
boolean relative = FileHelper.isRelativePath(value);
if (relative) {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onInvalidValue();
}
} else {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onValidValue();
}
}
}
//Ensure data
if (!value.startsWith(File.separator)) {
currentFilterData.clear();
this.mLastParent = ""; //$NON-NLS-1$
return;
}
//Get the new parent
String newParent = FileHelper.getParentDir(new File(value));
if (!newParent.endsWith(File.separator)) {
newParent += File.separator;
}
if (value.compareTo(File.separator) == 0) {
newParent = File.separator;
currentFilterData.clear();
} else if (value.endsWith(File.separator)) {
//Force the change of parent
newParent = new File(value, "a").getParent(); //$NON-NLS-1$
if (!newParent.endsWith(File.separator)) {
newParent += File.separator;
}
currentFilterData.clear();
} else {
value = newParent;
}
//If a new path is detected, then load the new data
if (newParent.compareTo(this.mLastParent) != 0 || currentFilterData.isEmpty()) {
this.mLastParent = newParent;
currentFilterData.clear();
try {
List<String> newData =
CommandHelper.quickFolderSearch(getContext(), value, null);
currentFilterData.addAll(newData);
} catch (Throwable ex) {
Log.e(TAG, "Quick folder search failed", ex); //$NON-NLS-1$
currentFilterData.clear();
}
}
}
| public void onTextChanged(String newValue, List<String> currentFilterData) {
String value = newValue;
//Check if directory is valid
if (value.length() == 0) {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onVoidValue();
}
} else {
boolean relative = FileHelper.isRelativePath(value);
if (relative) {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onInvalidValue();
}
} else {
if (this.mOnValidationListener != null) {
this.mOnValidationListener.onValidValue();
}
}
}
//Ensure data
if (!value.startsWith(File.separator)) {
currentFilterData.clear();
this.mLastParent = ""; //$NON-NLS-1$
return;
}
//Get the new parent
String newParent = FileHelper.getParentDir(new File(value));
if (newParent == null) {
newParent = FileHelper.ROOT_DIRECTORY;
}
if (!newParent.endsWith(File.separator)) {
newParent += File.separator;
}
if (value.compareTo(File.separator) == 0) {
newParent = File.separator;
currentFilterData.clear();
} else if (value.endsWith(File.separator)) {
//Force the change of parent
newParent = new File(value, "a").getParent(); //$NON-NLS-1$
if (!newParent.endsWith(File.separator)) {
newParent += File.separator;
}
currentFilterData.clear();
} else {
value = newParent;
}
//If a new path is detected, then load the new data
if (newParent.compareTo(this.mLastParent) != 0 || currentFilterData.isEmpty()) {
this.mLastParent = newParent;
currentFilterData.clear();
try {
List<String> newData =
CommandHelper.quickFolderSearch(getContext(), value, null);
currentFilterData.addAll(newData);
} catch (Throwable ex) {
Log.e(TAG, "Quick folder search failed", ex); //$NON-NLS-1$
currentFilterData.clear();
}
}
}
|
diff --git a/src/main/java/com/authdb/util/Util.java b/src/main/java/com/authdb/util/Util.java
index e504670..8a8bd98 100644
--- a/src/main/java/com/authdb/util/Util.java
+++ b/src/main/java/com/authdb/util/Util.java
@@ -1,1538 +1,1539 @@
/**
(C) Copyright 2011 CraftFire <[email protected]>
Contex <[email protected]>, Wulfspider <[email protected]>
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
**/
package com.authdb.util;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import com.mysql.jdbc.Blob;
import org.bukkit.Location;
import org.bukkit.entity.Player;
import com.authdb.AuthDB;
import com.authdb.scripts.Custom;
import com.authdb.scripts.cms.DLE;
import com.authdb.scripts.cms.Drupal;
import com.authdb.scripts.cms.Joomla;
import com.authdb.scripts.cms.WordPress;
import com.authdb.scripts.forum.BBPress;
import com.authdb.scripts.forum.IPB;
import com.authdb.scripts.forum.MyBB;
import com.authdb.scripts.forum.PhpBB;
import com.authdb.scripts.forum.PunBB;
import com.authdb.scripts.forum.SMF;
import com.authdb.scripts.forum.VBulletin;
import com.authdb.scripts.forum.Vanilla;
import com.authdb.scripts.forum.XenForo;
import com.authdb.util.Messages.Message;
import com.authdb.util.databases.EBean;
import com.authdb.util.databases.MySQL;
import com.authdb.util.encryption.Encryption;
import com.craftfire.util.general.GeneralUtil;
import com.craftfire.util.managers.CraftFireManager;
import com.craftfire.util.managers.DatabaseManager;
import com.craftfire.util.managers.LoggingManager;
import com.craftfire.util.managers.ServerManager;
public class Util {
public static LoggingManager logging = new LoggingManager();
public static CraftFireManager craftFire = new CraftFireManager();
public static DatabaseManager databaseManager = new DatabaseManager();
public static GeneralUtil gUtil = new GeneralUtil();
public static com.authdb.util.managers.PlayerManager authDBplayer = new com.authdb.util.managers.PlayerManager();
public static com.craftfire.util.managers.PlayerManager craftFirePlayer = new com.craftfire.util.managers.PlayerManager();
public static ServerManager server = new ServerManager();
static int schedule = 1;
public static boolean checkScript(String type, String script, String player, String password,
String email, String ipAddress) throws SQLException {
boolean caseSensitive = false;
if (Util.databaseManager.getDatabaseType().equalsIgnoreCase("ebean")) {
EBean eBeanClass = EBean.checkPlayer(player, true);
if (type.equalsIgnoreCase("checkuser")) {
if (eBeanClass.getRegistered().equalsIgnoreCase("true")) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("checkpassword")) {
String storedPassword = eBeanClass.getPassword();
if (Encryption.SHA512(password).equals(storedPassword)) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("adduser")) {
Custom.adduser(player, email, password, ipAddress);
eBeanClass.setEmail(email);
eBeanClass.setPassword(Encryption.SHA512(password));
eBeanClass.setRegistered("true");
eBeanClass.setIp(ipAddress);
} else if (type.equalsIgnoreCase("numusers")) {
int amount = EBean.getUsers();
logging.Info(amount + " user registrations in database");
}
} else if (Config.database_ison) {
String usertable = null, usernamefield = null, passwordfield = null, saltfield = "";
boolean bans = false;
PreparedStatement ps = null;
int number = 0;
if (Config.custom_enabled) {
if (type.equalsIgnoreCase("checkuser")) {
String check = MySQL.getfromtable(Config.custom_table, "*", Config.custom_userfield, player);
if (check != "fail") {
Config.hasForumBoard = true;
return true;
}
return false;
} else if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (Custom.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player);
EBean.checkPassword(player, hash);
if (Custom.check_hash(password, hash)) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("syncpassword")) {
String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player);
EBean.checkPassword(player, hash);
return true;
} else if (type.equalsIgnoreCase("adduser")) {
Custom.adduser(player, email, password, ipAddress);
EBean.sync(player);
return true;
} else if (type.equalsIgnoreCase("numusers")) {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.custom_table + "`");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
logging.Info(rs.getInt("countit") + " user registrations in database");
}
}
} else if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) {
usertable = "users";
//bantable = "banlist";
if (checkVersionInRange(PhpBB.VersionRange)) {
usernamefield = "username_clean";
passwordfield = "user_password";
/*useridfield = "user_id";
banipfield = "ban_ip";
bannamefield = "ban_userid";
banreasonfield = "";*/
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (PhpBB.check_hash(password, hash)) {
return true;
}
}
/*else if (type.equalsIgnoreCase("checkban")) {
String check = "fail";
if (ipAddress != null) {
String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", player);
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid);
} else {
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + banipfield + "", ipAddress);
}
if (check != "fail") {
return true;
} else {
return false;
}
} */
} else if (checkVersionInRange(PhpBB.VersionRange2)) {
usernamefield = "username_clean"; // TODO: use equalsIgnoreCase to allow for all variations?
passwordfield = "user_password";
Config.hasForumBoard = true;
bans = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (PhpBB.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
PhpBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) {
usertable = "members";
if (checkVersionInRange(SMF.VersionRange)) {
usernamefield = "memberName";
passwordfield = "passwd";
saltfield = "passwordSalt";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && SMF.check_hash(SMF.hash(1, player, password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (SMF.check_hash(SMF.hash(1, player, password), hash)) {
return true;
}
}
} else if (checkVersionInRange(SMF.VersionRange2) || checkVersionInRange("2.0-2.0")
|| checkVersionInRange("2.0.0-2.0.0")) {
usernamefield = "member_name";
passwordfield = "passwd";
+ saltfield = "password_salt";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && SMF.check_hash(SMF.hash(2, player, password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (SMF.check_hash(SMF.hash(2, player, password), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
SMF.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) {
usertable = "users";
if (checkVersionInRange(MyBB.VersionRange)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
bans = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && MyBB.check_hash(MyBB.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (MyBB.check_hash(MyBB.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
MyBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) {
usertable = "user";
if (checkVersionInRange(VBulletin.VersionRange)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) {
return true;
}
}
} else if (checkVersionInRange(VBulletin.VersionRange2)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
bans = true;
number = 2;
caseSensitive = true;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
VBulletin.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) {
usertable = "users";
if (checkVersionInRange(Drupal.VersionRange)) {
usernamefield = "name";
passwordfield = "pass";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Encryption.md5(password).equals(storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Encryption.md5(password).equals(hash)) {
return true;
}
}
} else if (checkVersionInRange(Drupal.VersionRange2)) {
usernamefield = "name";
passwordfield = "pass";
Config.hasForumBoard = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && storedPassword.equals(Drupal.user_check_password(password, storedPassword))) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (hash.equals(Drupal.user_check_password(password, hash))) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
Drupal.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) {
usertable = "users";
if (checkVersionInRange(Joomla.VersionRange)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Joomla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Joomla.check_hash(password, hash)) {
return true;
}
}
} else if (checkVersionInRange(Joomla.VersionRange2)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Joomla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Joomla.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
Joomla.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) {
if (checkVersionInRange(Vanilla.VersionRange)) {
usertable = "User";
usernamefield = "Name";
passwordfield = "Password";
caseSensitive = true;
if (Vanilla.check() == 2) {
usertable = usertable.toLowerCase();
}
Config.hasForumBoard = true;
number = Vanilla.check();
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Vanilla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Vanilla.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
String emailcheck = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + usernamefield + "`", "Email", email);
if (emailcheck.equalsIgnoreCase("fail")) {
Vanilla.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
return false;
}
} else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) {
usertable = "users";
//bantable = "bans";
if (checkVersionInRange(PunBB.VersionRange)) {
//bannamefield = "username";
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PunBB.check_hash(PunBB.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (PunBB.check_hash(PunBB.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
PunBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) {
usertable = "user";
if (checkVersionInRange(XenForo.VersionRange)) {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
usernamefield = "username";
passwordfield = "password";
caseSensitive = true;
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
if (hash != null) {
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
// TODO: Auto-generated catch block
logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thehash = forumCacheValue(cache, "hash");
String thesalt = forumCacheValue(cache, "salt");
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
String storedSalt = eBeanClass.getSalt();
if (storedPassword != null && storedSalt != null && XenForo.check_hash(XenForo.hash(1, storedSalt, password), storedPassword)) {
return true;
}
EBean.checkSalt(player, thesalt);
EBean.checkPassword(player, thehash);
if (XenForo.check_hash(XenForo.hash(1, thesalt, password), thehash)) {
return true;
}
} else {
return false;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
XenForo.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thehash = forumCacheValue(cache, "hash");
EBean.checkPassword(player, thehash);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
// TODO: Auto-generated catch block
logging.StackTrace(e.getStackTrace(),
Thread.currentThread().getStackTrace()[1].getMethodName(),
Thread.currentThread().getStackTrace()[1].getLineNumber(),
Thread.currentThread().getStackTrace()[1].getClassName(),
Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thesalt = forumCacheValue(cache, "salt");
EBean.checkSalt(player, thesalt);
return true;
}
} else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) {
usertable = "users";
if (checkVersionInRange(BBPress.VersionRange)) {
usernamefield = "user_login";
passwordfield = "user_pass";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && BBPress.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (BBPress.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
BBPress.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) {
usertable = "users";
if (checkVersionInRange(DLE.VersionRange)) {
usernamefield = "name";
passwordfield = "password";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && DLE.check_hash(DLE.hash(password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (DLE.check_hash(DLE.hash(password), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
DLE.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) {
usertable = "members";
if (checkVersionInRange(IPB.VersionRange)) {
- saltfield = "members_pass_salt";
usernamefield = "members_l_username";
passwordfield = "members_pass_hash";
+ saltfield = "members_pass_salt";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password.toLowerCase(), null), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (IPB.check_hash(IPB.hash("find", player.toLowerCase(), password, null), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
IPB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) {
usertable = "users";
if (checkVersionInRange(WordPress.VersionRange)) {
usernamefield = "user_login";
passwordfield = "user_pass";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && WordPress.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (WordPress.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
WordPress.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} /* else if (script.equalsIgnoreCase(Config.Script11_name) || script.equalsIgnoreCase(Config.Script11_shortname)) {
usertable = "users";
if (checkVersionInRange(Config.Script11_versionrange)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
if (XE.check_hash(password, hash)) { return true; }
}
}
if (type.equalsIgnoreCase("adduser")) {
XE.adduser(number, player, email, password, ipAddress);
return true;
}
} */
if (!Config.hasForumBoard) {
if (!Config.custom_enabled) {
String tempVers = Config.script_version;
Config.script_version = scriptVersion();
logging.Info(System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|" + System.getProperty("line.separator")
+ "|--------------------------------AUTHDB WARNING-------------------------------|" + System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|" + System.getProperty("line.separator")
+ "| COULD NOT FIND A COMPATIBLE SCRIPT VERSION! |" + System.getProperty("line.separator")
+ "| PLEASE CHECK YOUR SCRIPT VERSION AND TRY AGAIN. PLUGIN MAY OR MAY NOT WORK. |" + System.getProperty("line.separator")
+ "| YOUR SCRIPT VERSION FOR " + Config.script_name + " HAS BEEN SET FROM " + tempVers + " TO " + Config.script_version + " |" + System.getProperty("line.separator")
+ "| FOR A LIST OF SCRIPT VERSIONS, |" + System.getProperty("line.separator")
+ "| CHECK: http://wiki.bukkit.org/AuthDB#Scripts_Supported |" + System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|");
}
}
if (!caseSensitive && player != null) {
player = player.toLowerCase();
}
if (Config.hasForumBoard && type.equalsIgnoreCase("checkuser") && !Config.custom_enabled) {
//EBean eBeanClass = EBean.find(player, Column.registered, "true");
//if (eBeanClass != null) { return true; }
String check = MySQL.getfromtable(Config.script_tableprefix + usertable, "*", usernamefield, player);
if (check != "fail") { return true; }
return false;
} /*else if (Config.hasForumBoard && type.equalsIgnoreCase("checkban") && !Config.custom_enabled && bantable != null) {
String check = MySQL.getfromtable(Config.script_tableprefix + bantable, "*", bannamefield, player);
if (check != "fail") { return true; }
}*/ else if (Config.hasForumBoard && type.equalsIgnoreCase("numusers") && !Config.custom_enabled) {
if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `"
+ Config.script_tableprefix + usertable + "` WHERE `group_id` !=6");
} else {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `"
+ Config.script_tableprefix + usertable + "`");
}
ResultSet rs = ps.executeQuery();
if (rs.next()) { logging.Info(rs.getInt("countit") + " user registrations in database"); }
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) {
String hash = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + passwordfield + "`", usernamefield, player);
EBean.checkPassword(player, hash);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") {
String salt = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + saltfield + "`", usernamefield, player);
EBean.checkSalt(player, salt);
return true;
}
}
return false;
}
static String scriptVersion() {
String script = Config.script_name;
if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) {
return split(PhpBB.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) {
return split(SMF.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) {
return split(MyBB.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) {
return split(VBulletin.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) {
return split(Drupal.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) {
return split(Joomla.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) {
return split(Vanilla.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) {
return split(PunBB.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) {
return split(XenForo.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) {
return split(BBPress.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) {
return split(DLE.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) {
return split(IPB.LatestVersionRange, "-")[1];
} else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) {
return split(WordPress.LatestVersionRange, "-")[1];
}
return null;
}
public static String[] split(String string, String delimiter) {
String[] split = string.split(delimiter);
return split;
}
static void fillChatField(Player player, String text) {
for (int i = 0; i < 20; i++) {
player.sendMessage("");
}
player.sendMessage(text);
}
static void spamText(final Player player, final String text, final int delay, final int show) {
//if (Config.login_delay > 0 && !AuthDB.AuthDB_SpamMessage.containsKey(player.getName())) {
if (Config.login_delay > 0) {
schedule = AuthDB.server.getScheduler().scheduleSyncDelayedTask(AuthDB.plugin, new Runnable() {
@Override
public void run() {
/*
if (AuthDB.isAuthorized(player) && AuthDB.AuthDB_SpamMessage.containsKey(player.getName())) {
AuthDB.server.getScheduler().cancelTask(AuthDB.AuthDB_SpamMessage.get(player.getName()));
AuthDB.AuthDB_SpamMessage.remove(player.getName());
AuthDB.AuthDB_SpamMessageTime.remove(player.getName());
} else {
if (!AuthDB.AuthDB_SpamMessage.containsKey(player.getName())) { AuthDB.AuthDB_SpamMessage.put(player.getName(), schedule); }
if (!AuthDB.AuthDB_SpamMessageTime.containsKey(player.getName())) { AuthDB.AuthDB_SpamMessageTime.put(player.getName(), timeStamp()); }
if ((AuthDB.AuthDB_SpamMessageTime.get(player.getName()) + show) <= timeStamp()) {
AuthDB.server.getScheduler().cancelTask(AuthDB.AuthDB_SpamMessage.get(player.getName()));
AuthDB.AuthDB_SpamMessage.remove(player.getName());
AuthDB.AuthDB_SpamMessageTime.remove(player.getName());
}
String message = replaceStrings(text, player, null);
if (Config.link_rename && !checkOtherName(player.getName()).equals(player.getName())) {
message = message.replaceAll(player.getName(), player.getDisplayName());
player.sendMessage(message);
}
else {
player.sendMessage(message);
}
fillChatField(player, message);
}
*/
String message = replaceStrings(text, player, null);
if (Config.link_rename && !checkOtherName(player.getName()).equals(player.getName())) {
message = message.replaceAll(player.getName(), player.getDisplayName());
player.sendMessage(message);
} else {
player.sendMessage(message);
}
} }, delay);
}
}
public static long timeStamp() {
return System.currentTimeMillis()/1000;
}
public static long timeMS() {
return System.currentTimeMillis();
}
boolean checkingBan(String usertable, String useridfield, String usernamefield, String username, String bantable, String banipfield, String bannamefield, String ipAddress) throws SQLException {
String check = "fail";
if (ipAddress == null) {
String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", username);
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid);
} else {
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", ipAddress);
}
if (check != "fail") {
return true;
} else {
return false;
}
}
public static String forumCache(String cache, String player, int userid, String nummember, String activemembers, String newusername, String newuserid, String extrausername, String lastvalue) {
StringTokenizer st = new StringTokenizer(cache, ":");
int i = 0;
List<String> array = new ArrayList<String>();
while (st.hasMoreTokens()) { array.add(st.nextToken() + ":"); }
StringBuffer newcache = new StringBuffer();
while (array.size() > i) {
if (array.get(i).equals("\"" + nummember + "\";i:") && nummember != null) {
String temp = array.get(i + 1);
temp = removeChar(temp, '"');
temp = removeChar(temp, ':');
temp = removeChar(temp, 's');
temp = removeChar(temp, ';');
temp = temp.trim();
int tempnum = Integer.parseInt(temp) + 1;
if (lastvalue.equalsIgnoreCase(nummember)) {
temp = tempnum + ";}";
} else {
temp = tempnum + ";s:";
}
array.set(i + 1, temp);
} else if (array.get(i).equals("\"" + newusername + "\";s:") && newusername != null) {
array.set(i + 1, player.length() + ":");
if (lastvalue.equalsIgnoreCase(newusername)) {
array.set(i + 2, "\"" + player + "\"" + ";}");
} else {
array.set(i + 2, "\"" + player + "\"" + ";s" + ":");
}
} else if (array.get(i).equals("\"" + extrausername + "\";s:") && extrausername != null) {
array.set(i + 1, player.length() + ":");
if (lastvalue.equalsIgnoreCase(extrausername)) {
array.set(i + 2, "\"" + player + "\"" + ";}");
} else {
array.set(i + 2, "\"" + player + "\"" + ";s" + ":");
}
} else if (array.get(i).equals("\"" + activemembers + "\";s:") && activemembers != null) {
String temp = array.get(i + 2);
temp = removeChar(temp, '"');
temp = removeChar(temp, ':');
temp = removeChar(temp, 's');
temp = removeChar(temp, ';');
temp = temp.trim();
int tempnum = Integer.parseInt(temp) + 1;
String templength = "" + tempnum;
if (lastvalue.equalsIgnoreCase(activemembers)) {
temp = "\"" + tempnum + "\"" + ";}";
} else {
temp = "\"" + tempnum + "\"" + ";s:";
}
array.set(i + 1, templength.length() + ":");
array.set(i + 2, temp);
} else if (array.get(i).equals("\"" + newuserid + "\";s:") && newuserid != null) {
String dupe = "" + userid;
array.set(i + 1, dupe.length() + ":");
if (lastvalue.equalsIgnoreCase(newuserid)) {
array.set(i + 2, "\"" + userid + "\"" + ";}");
} else {
array.set(i + 2, "\"" + userid + "\"" + ";s:");
}
}
newcache.append(array.get(i));
i++;
}
return newcache.toString();
}
public static String forumCacheValue(String cache, String value) {
StringTokenizer st = new StringTokenizer(cache, ":");
int i = 0;
List<String> array = new ArrayList<String>();
while (st.hasMoreTokens()) { array.add(st.nextToken() + ":"); }
while (array.size() > i) {
if (array.get(i).equals("\"" + value + "\";s:") && value != null) {
String temp = array.get(i + 2);
temp = removeChar(temp, '"');
temp = removeChar(temp, ':');
temp = removeChar(temp, 's');
temp = removeChar(temp, ';');
temp = temp.trim();
return temp;
}
i++;
}
return "no";
}
public static boolean checkVersionInRange(String versionrange) {
String version = Config.script_version;
String[] versions = version.split("\\.");
String[] versionss = versionrange.split("\\-");
String[] versionrange1= versionss[0].split("\\.");
String[] versionrange2= versionss[1].split("\\.");
Util.logging.Debug("Config version: " + version);
Util.logging.Debug("Version range: " + versionrange);
Util.logging.Debug("Version range 1: " + versionss[0]);
Util.logging.Debug("Version range 2: " + versionss[1]);
if (version.equals(versionss[0]) || version.equals(versionss[1])) {
Util.logging.Debug("Version checking PASSED at first check.");
return true;
}
if (versionrange1.length == versions.length) {
int a = Integer.parseInt(versionrange1[0]);
int b = Integer.parseInt(versionrange2[0]);
int c = Integer.parseInt(versions[0]);
Util.logging.Debug("Version checking: a = " + a + ", b = " + b + ", c = " + c);
if (a <= c && b >= c) {
int d = b - c;
Util.logging.Debug("Version checking: d = " + d);
if (d > 0) {
Util.logging.Debug("Version checking PASSED at second check.");
return true;
} else if (d == 0) {
int a2 = Integer.parseInt(versionrange1[1]);
int b2 = Integer.parseInt(versionrange2[1]);
int c2 = Integer.parseInt(versions[1]);
Util.logging.Debug("Version checking: a2 = " + a2 + ", b2 = " + b2 + ", c2 = " + c2);
if (a2 <= c2 && b2 >= c2) {
if (versionrange1.length == 2) {
Util.logging.Debug("Version checking PASSED at third check.");
return true;
} else if (versionrange1.length > 2) {
int d2 = b2 - c2;
Util.logging.Debug("Version checking: d2 = " + d2);
if (d2 > 0) {
Util.logging.Debug("Version checking PASSED at fourth check.");
return true;
} else if (d2 == 0) {
int a3 = Integer.parseInt(versionrange1[2]);
int b3 = Integer.parseInt(versionrange2[2]);
int c3 = Integer.parseInt(versions[2]);
Util.logging.Debug("Version checking: a3 = " + a3 + ", b3 = " + b3 + ", c3 = " + c3);
if ((a3 <= c3 && b3 >= c3) || (b3 >= c3 && versionrange1.length != 4)) {
if (versionrange1.length != 4) {
Util.logging.Debug("Version checking PASSED at fifth check.");
return true;
} else if (versionrange1.length == 4) {
int d3 = b3 - c3;
Util.logging.Debug("Version checking: d3 = " + d3);
if (d3 > 0) {
Util.logging.Debug("Version checking PASSED at sixth check.");
return true;
} else if (d3 == 0) {
int a4 = Integer.parseInt(versionrange1[3]);
int b4 = Integer.parseInt(versionrange2[3]);
int c4 = Integer.parseInt(versions[3]);
Util.logging.Debug("Version checking: a4 = " + a4 + ", b4 = " + b4 + ", c4 = " + c4);
if (a4 <= c4 && b4 >= c4) {
Util.logging.Debug("Version checking PASSED at seventh check.");
return true;
}
}
}
}
}
}
}
}
}
}
Util.logging.Debug("Version checking DID NOT PASS.");
return false;
}
public static int toTicks(String time, String length) {
logging.Debug("Launching function: toTicks(String time, String length) - " + time + ":" + length);
time = time.toLowerCase();
int lengthint = Integer.parseInt(length);
if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) {
return lengthint * 1728000;
} else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) {
return lengthint * 72000;
} else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) {
return lengthint * 1200;
} else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) {
return lengthint * 20;
}
return 0;
}
public static int toSeconds(String time, String length) {
logging.Debug("Launching function: toSeconds(String time, String length) - " + time + ":" + length);
time = time.toLowerCase();
int lengthint = Integer.parseInt(length);
if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) {
return lengthint * 86400;
} else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) {
return lengthint * 3600;
} else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) {
return lengthint * 60;
} else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) {
return lengthint;
}
return 0;
}
public static int stringToTicks(String string) {
String[] split = string.split(" ");
String length = split[0];
String time = split[1].toLowerCase();
int lengthint = Integer.parseInt(length);
logging.Debug("Launching function: FullStringToSeconds(String time, String length) - " + time + ":" + length);
if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) {
return lengthint * 1728000;
} else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) {
return lengthint * 72000;
} else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) {
return lengthint * 1200;
} else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) {
return lengthint * 20;
}
return 0;
}
public static int stringToSeconds(String string) {
String[] split = string.split(" ");
String length = split[0];
String time = split[1].toLowerCase();
int lengthint = Integer.parseInt(length);
logging.Debug("Launching function: StringToSeconds(String time, String length) - " + time + ":" + length);
if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) {
return lengthint * 86400;
} else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) {
return lengthint * 3600;
} else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) {
return lengthint * 60;
} else if (time.equalsIgnoreCase("second") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) {
return lengthint;
}
return 0;
}
public static String toLoginMethod(String method) {
method = method.toLowerCase();
if (method.equalsIgnoreCase("prompt")) {
return method;
} else {
return "normal";
}
}
public static boolean checkWhitelist(String whitelist, Player player) {
String username = player.getName().toLowerCase();
logging.Debug("Launching function: checkWhitelist(String whitelist, String username) - " + username);
StringTokenizer st = null;
if (whitelist.equalsIgnoreCase("username")) {
st = new StringTokenizer(Config.filter_whitelist, ", ");
}
while (st != null && st.hasMoreTokens()) {
String whitelistname = st.nextToken().toLowerCase();
logging.Debug("Whitelist: " + whitelistname);
if (whitelistname.equals(username)) {
logging.Debug("Found user in whitelist: " + whitelistname);
if (whitelist.equalsIgnoreCase("username")) {
Messages.sendMessage(Message.filter_whitelist, player, null);
}
return true;
}
}
return false;
}
public static void checkIdle(Player player) {
logging.Debug("Launching function: CheckIdle(Player player)");
if (!AuthDB.isAuthorized(player)) {
Messages.sendMessage(Message.kickPlayerIdleLoginMessage, player, null);
}
}
public static long ip2Long(String ip) {
logging.Debug("Launching function: IP2Long(String IP)");
long f1, f2, f3, f4;
String tokens[] = ip.split("\\.");
if (tokens.length != 4) {
return -1;
}
try {
f1 = Long.parseLong(tokens[0]) << 24;
f2 = Long.parseLong(tokens[1]) << 16;
f3 = Long.parseLong(tokens[2]) << 8;
f4 = Long.parseLong(tokens[3]);
return f1 + f2 + f3 + f4;
} catch (Exception e) {
return -1;
}
}
public static boolean checkFilter(String what, String string) {
if (what.equalsIgnoreCase("username")) {
logging.Debug("Launching function: checkFilter(String what, String string) - " + Config.filter_username);
int lengtha = string.length();
int lengthb = Config.filter_username.length();
int i = 0;
char thechar1, thechar2;
while (i < lengtha) {
thechar1 = string.charAt(i);
int a = 0;
while (a < lengthb) {
thechar2 = Config.filter_username.charAt(a);
if (thechar1 == thechar2 || thechar1 == '\'' || thechar1 == '\"') {
Util.logging.Info(string + " has bad characters in his/her name: " + thechar2);
Config.has_badcharacters = true;
return false;
}
a++;
}
i++;
}
Config.has_badcharacters = false;
Util.logging.Debug(string + " does not have bad characters in his/her name.");
return true;
} else if (what.equalsIgnoreCase("password")) {
logging.Debug("Launching function: checkFilter(String what, String string) - " + Config.filter_password);
int lengtha = string.length();
int lengthb = Config.filter_password.length();
int i = 0;
char thechar1, thechar2;
while (i < lengtha) {
thechar1 = string.charAt(i);
int a = 0;
while (a < lengthb) {
thechar2 = Config.filter_password.charAt(a);
//logging.Debug(i + "-" + thechar1 + ":" + a + "-" + thechar2);
if (thechar1 == thechar2 || thechar1 == '\'' || thechar1 == '\"') {
logging.Debug("FOUND BAD CHARACTER!!: " + thechar2);
return false;
}
a++;
}
i++;
}
return true;
}
return true;
}
public static String fixCharacters(String string) {
int lengtha = string.length();
int lengthb = "`~!@#$%^&*()-= + {[]}|\\:;\"<, >.?/".length();
int i = 0;
char thechar1, thechar2;
StringBuffer tempstring = new StringBuffer();
while (i < lengtha) {
thechar1 = string.charAt(i);
int a = 0;
while (a < lengthb) {
thechar2 = "`~!@#$%^&*()-= + {[]}|\\:;\"<, >.?/".charAt(a);
if (thechar1 == thechar2 || thechar1 == '\'' || thechar1 == '\"') {
thechar1 = thechar2;
}
a++;
}
tempstring.append(thechar1);
i++;
}
return tempstring.toString();
}
public static String replaceStrings(String string, Player player, String additional) {
long start = Util.timeMS();
logging.Debug(("Launching function: replaceStrings(String string, Player player, String additional)"));
String extra = "";
if (additional != null) {
extra = additional;
}
if (!Config.has_badcharacters && Config.database_ison && player != null && player.getName().length() > Integer.parseInt(Config.username_minimum) && player.getName().length() < Integer.parseInt(Config.username_maximum) && extra.equalsIgnoreCase("login") == false) {
string = string.replaceAll("\\{IP\\}", craftFirePlayer.getIP(player));
string = string.replaceAll("\\{PLAYER\\}", player.getName());
string = string.replaceAll("\\{NEWPLAYER\\}", "");
string = string.replaceAll("\\{PLAYERNEW\\}", "");
string = string.replaceAll("&", "§");
if (!Util.checkOtherName(player.getName()).equals(player.getName())) {
string = string.replaceAll("\\{DISPLAYNAME\\}", checkOtherName(player.getName()));
}
} else {
string = string.replaceAll("&", Matcher.quoteReplacement("�"));
}
String email = "";
if (Config.custom_emailrequired) {
email = "email";
}
// Replacement variables
string = string.replaceAll("\\{USERMIN\\}", Config.username_minimum);
string = string.replaceAll("\\{USERMAX\\}", Config.username_maximum);
string = string.replaceAll("\\{PASSMIN\\}", Config.password_minimum);
string = string.replaceAll("\\{PASSMAX\\}", Config.password_maximum);
string = string.replaceAll("\\{PLUGIN\\}", AuthDB.pluginName);
string = string.replaceAll("\\{VERSION\\}", AuthDB.pluginVersion);
string = string.replaceAll("\\{LOGINTIMEOUT\\}", Config.login_timeout_length + " " + replaceTime(Config.login_timeout_length, Config.login_timeout_time));
string = string.replaceAll("\\{REGISTERTIMEOUT\\}", "" + Config.register_timeout_length + " " + replaceTime(Config.register_timeout_length, Config.register_timeout_time));
string = string.replaceAll("\\{USERBADCHARACTERS\\}", Matcher.quoteReplacement(Config.filter_username));
string = string.replaceAll("\\{PASSBADCHARACTERS\\}", Matcher.quoteReplacement(Config.filter_password));
string = string.replaceAll("\\{EMAILREQUIRED\\}", email);
string = string.replaceAll("\\{NEWLINE\\}", System.getProperty("line.separator"));
string = string.replaceAll("\\{newline\\}", System.getProperty("line.separator"));
string = string.replaceAll("\\{N\\}", System.getProperty("line.separator"));
string = string.replaceAll("\\{n\\}", System.getProperty("line.separator"));
string = string.replaceAll("\\{NL\\}", System.getProperty("line.separator"));
string = string.replaceAll("\\{nl\\}", System.getProperty("line.separator"));
// Commands
string = string.replaceAll("\\{REGISTERCMD\\}", Config.commands_user_register + " (" + Config.aliases_user_register + ")");
string = string.replaceAll("\\{LINKCMD\\}", Config.commands_user_link + " (" + Config.aliases_user_link + ")");
string = string.replaceAll("\\{UNLINKCMD\\}", Config.commands_user_unlink + " (" + Config.aliases_user_unlink + ")");
string = string.replaceAll("\\{LOGINCMD\\}", Config.commands_user_login + " (" + Config.aliases_user_login + ")");
// Uppercase colors
string = string.replaceAll("\\{BLACK\\}", "§0");
string = string.replaceAll("\\{DARKBLUE\\}", "§1");
string = string.replaceAll("\\{DARKGREEN\\}", "§2");
string = string.replaceAll("\\{DARKTEAL\\}", "§3");
string = string.replaceAll("\\{DARKRED\\}", "§4");
string = string.replaceAll("\\{PURPLE\\}", "§5");
string = string.replaceAll("\\{GOLD\\}", "§6");
string = string.replaceAll("\\{GRAY\\}", "§7");
string = string.replaceAll("\\{DARKGRAY\\}", "§8");
string = string.replaceAll("\\{BLUE\\}", "§9");
string = string.replaceAll("\\{BRIGHTGREEN\\}", "§a");
string = string.replaceAll("\\{TEAL\\}", "§b");
string = string.replaceAll("\\{RED\\}", "§c");
string = string.replaceAll("\\{PINK\\}", "§d");
string = string.replaceAll("\\{YELLOW\\}", "§e");
string = string.replaceAll("\\{WHITE\\}", "§f");
string = string.replaceAll("\\{BLACK\\}", "§0");
string = string.replaceAll("\\{NAVY\\}", "§1");
string = string.replaceAll("\\{GREEN\\}", "§2");
string = string.replaceAll("\\{BLUE\\}", "§3");
string = string.replaceAll("\\{RED\\}", "§4");
string = string.replaceAll("\\{PURPLE\\}", "§5");
string = string.replaceAll("\\{GOLD\\}", "§6");
string = string.replaceAll("\\{LIGHTGRAY\\}", "§7");
string = string.replaceAll("\\{GRAY\\}", "§8");
string = string.replaceAll("\\{DARKPURPLE\\}", "§9");
string = string.replaceAll("\\{LIGHTGREEN\\}", "§a");
string = string.replaceAll("\\{LIGHTBLUE\\}", "§b");
string = string.replaceAll("\\{ROSE\\}", "§c");
string = string.replaceAll("\\{LIGHTPURPLE\\}", "§d");
string = string.replaceAll("\\{YELLOW\\}", "§e");
string = string.replaceAll("\\{WHITE\\}", "§f");
// Lowercase colors
string = string.replaceAll("\\{black\\}", "§0");
string = string.replaceAll("\\{darkblue\\}", "§1");
string = string.replaceAll("\\{darkgreen\\}", "§2");
string = string.replaceAll("\\{darkteal\\}", "§3");
string = string.replaceAll("\\{darkred\\}", "§4");
string = string.replaceAll("\\{purple\\}", "§5");
string = string.replaceAll("\\{gold\\}", "§6");
string = string.replaceAll("\\{gray\\}", "§7");
string = string.replaceAll("\\{darkgray\\}", "§8");
string = string.replaceAll("\\{blue\\}", "§9");
string = string.replaceAll("\\{brightgreen\\}", "§a");
string = string.replaceAll("\\{teal\\}", "§b");
string = string.replaceAll("\\{red\\}", "§c");
string = string.replaceAll("\\{pink\\}", "§d");
string = string.replaceAll("\\{yellow\\}", "§e");
string = string.replaceAll("\\{white\\}", "§f");
string = string.replaceAll("\\{black\\}", "§0");
string = string.replaceAll("\\{navy\\}", "§1");
string = string.replaceAll("\\{green\\}", "§2");
string = string.replaceAll("\\{blue\\}", "§3");
string = string.replaceAll("\\{red\\}", "§4");
string = string.replaceAll("\\{purple\\}", "§5");
string = string.replaceAll("\\{gold\\}", "§6");
string = string.replaceAll("\\{lightgray\\}", "§7");
string = string.replaceAll("\\{gray\\}", "§8");
string = string.replaceAll("\\{darkpurple\\}", "§9");
string = string.replaceAll("\\{lightgreen\\}", "§a");
string = string.replaceAll("\\{lightblue\\}", "§b");
string = string.replaceAll("\\{rose\\}", "§c");
string = string.replaceAll("\\{lightpurple\\}", "§d");
string = string.replaceAll("\\{yellow\\}", "§e");
string = string.replaceAll("\\{white\\}", "§f");
long stop = Util.timeMS();
Util.logging.Debug("Took " + ((stop - start) / 1000) + " seconds (" + (stop - start) + "ms) to replace tags.");
return string;
}
public static String replaceTime(String length, String time) {
int lengthint = Integer.parseInt(length);
if (time.equalsIgnoreCase("days") || time.equalsIgnoreCase("day") || time.equalsIgnoreCase("d")) {
if (lengthint > 1) {
return Messages.time_days;
} else {
return Messages.time_day;
}
} else if (time.equalsIgnoreCase("hours") || time.equalsIgnoreCase("hour") || time.equalsIgnoreCase("hr") || time.equalsIgnoreCase("hrs") || time.equalsIgnoreCase("h")) {
if (lengthint > 1) {
return Messages.time_hours;
} else {
return Messages.time_hour;
}
} else if (time.equalsIgnoreCase("minute") || time.equalsIgnoreCase("minutes") || time.equalsIgnoreCase("min") || time.equalsIgnoreCase("mins") || time.equalsIgnoreCase("m")) {
if (lengthint > 1) {
return Messages.time_minutes;
} else {
return Messages.time_minute;
}
} else if (time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("seconds") || time.equalsIgnoreCase("sec") || time.equalsIgnoreCase("s")) {
if (lengthint > 1) {
return Messages.time_seconds;
} else {
return Messages.time_second;
}
} else if (time.equalsIgnoreCase("milliseconds") || time.equalsIgnoreCase("millisecond") || time.equalsIgnoreCase("milli") || time.equalsIgnoreCase("ms")) {
if (lengthint > 1) {
return Messages.time_milliseconds;
} else {
return Messages.time_millisecond;
}
}
return time;
}
public static String removeColors(String toremove) {
long start = Util.timeMS();
logging.Debug("Launching function: removeColors");
toremove = toremove.replace("?0", "");
toremove = toremove.replace("?2", "");
toremove = toremove.replace("?3", "");
toremove = toremove.replace("?4", "");
toremove = toremove.replace("?5", "");
toremove = toremove.replace("?6", "");
toremove = toremove.replace("?7", "");
toremove = toremove.replace("?8", "");
toremove = toremove.replace("?9", "");
toremove = toremove.replace("?a", "");
toremove = toremove.replace("?b", "");
toremove = toremove.replace("?c", "");
toremove = toremove.replace("?d", "");
toremove = toremove.replace("?e", "");
toremove = toremove.replace("?f", "");
long stop = Util.timeMS();
Util.logging.Debug("Took " + ((stop - start) / 1000) + " seconds (" + (stop - start) + "ms) to replace colors.");
return toremove;
}
public static String removeChar(String s, char c) {
logging.Debug("Launching function: removeChar(String s, char c)");
StringBuffer r = new StringBuffer(s.length());
r.setLength(s.length());
int current = 0;
for (int i = 0; i < s.length(); i++) {
char cur = s.charAt(i);
if (cur != c) r.setCharAt(current++, cur);
}
return r.toString();
}
public static String getRandomString(int length) {
String charset = "0123456789abcdefghijklmnopqrstuvwxyz";
Random rand = new Random(System.currentTimeMillis());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int pos = rand.nextInt(charset.length());
sb.append(charset.charAt(pos));
}
return sb.toString();
}
public static String getRandomString2(int length, String charset) {
Random rand = new Random(System.currentTimeMillis());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int pos = rand.nextInt(charset.length());
sb.append(charset.charAt(pos));
}
return sb.toString();
}
public static int randomNumber(int min, int max) {
return (int) (Math.random() * (max - min + 1)) + min;
}
public static Location landLocation(Location location) {
while (location.getBlock().getType().getId() == 0) {
location.setY(location.getY() - 1);
}
location.setY(location.getY() + 2);
return location;
}
public static String checkOtherName(String player) {
if (AuthDB.AuthDB_LinkedNames.containsKey(player)) {
return AuthDB.AuthDB_LinkedNames.get(player);
} else if (!AuthDB.AuthDB_LinkedNameCheck.containsKey(player)) {
AuthDB.AuthDB_LinkedNameCheck.put(player, "yes");
EBean eBeanClass = EBean.checkPlayer(player, true);
String linkedName = eBeanClass.getLinkedname();
if (linkedName != null && linkedName.equals("") == false) {
AuthDB.AuthDB_LinkedNames.put(player, linkedName);
return linkedName;
}
}
return player;
}
public static boolean checkIfLoggedIn(Player player) {
for (Player p : player.getServer().getOnlinePlayers()) {
if (p.getName().equalsIgnoreCase(player.getName()) && AuthDB.isAuthorized(p)) {
return true;
}
}
return false;
}
public static String getAction(String action) {
if (action.toLowerCase().equalsIgnoreCase("kick")) {
return "kick";
} else if (action.toLowerCase().equalsIgnoreCase("ban")) {
return "ban";
} else if (action.toLowerCase().equalsIgnoreCase("rename")) {
return "rename";
}
return "kick";
}
public static int hexToInt(char ch) {
if (ch >= '0' && ch <= '9') {
return ch - '0';
}
ch = Character.toUpperCase(ch);
if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 0xA;
}
throw new IllegalArgumentException("Not a hex character: " + ch);
}
public static String hexToString(String str) {
char[] chars = str.toCharArray();
StringBuffer hex = new StringBuffer();
for (int i = 0; i < chars.length; i++) {
hex.append(Integer.toHexString((int) chars[i]));
}
return hex.toString();
}
public static String checkSessionStart (String string) {
if (string.equalsIgnoreCase("login")) {
return "login";
} else if (string.equalsIgnoreCase("logoff")) {
return "logoff";
} else {
return "login";
}
}
public static String convertToHex(byte[] data) {
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int twoHalfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9)) {
buf.append((char) ('0' + halfbyte));
} else {
buf.append((char) ('a' + (halfbyte - 10)));
}
halfbyte = data[i] & 0x0F;
}
while (twoHalfs++< 1);
}
return buf.toString();
}
public static String bytes2hex(byte[] bytes) {
StringBuffer r = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
String x = Integer.toHexString(bytes[i] & 0xff);
if (x.length() < 2) {
r.append("0");
}
r.append(x);
}
return r.toString();
}
}
| false | true | public static boolean checkScript(String type, String script, String player, String password,
String email, String ipAddress) throws SQLException {
boolean caseSensitive = false;
if (Util.databaseManager.getDatabaseType().equalsIgnoreCase("ebean")) {
EBean eBeanClass = EBean.checkPlayer(player, true);
if (type.equalsIgnoreCase("checkuser")) {
if (eBeanClass.getRegistered().equalsIgnoreCase("true")) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("checkpassword")) {
String storedPassword = eBeanClass.getPassword();
if (Encryption.SHA512(password).equals(storedPassword)) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("adduser")) {
Custom.adduser(player, email, password, ipAddress);
eBeanClass.setEmail(email);
eBeanClass.setPassword(Encryption.SHA512(password));
eBeanClass.setRegistered("true");
eBeanClass.setIp(ipAddress);
} else if (type.equalsIgnoreCase("numusers")) {
int amount = EBean.getUsers();
logging.Info(amount + " user registrations in database");
}
} else if (Config.database_ison) {
String usertable = null, usernamefield = null, passwordfield = null, saltfield = "";
boolean bans = false;
PreparedStatement ps = null;
int number = 0;
if (Config.custom_enabled) {
if (type.equalsIgnoreCase("checkuser")) {
String check = MySQL.getfromtable(Config.custom_table, "*", Config.custom_userfield, player);
if (check != "fail") {
Config.hasForumBoard = true;
return true;
}
return false;
} else if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (Custom.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player);
EBean.checkPassword(player, hash);
if (Custom.check_hash(password, hash)) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("syncpassword")) {
String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player);
EBean.checkPassword(player, hash);
return true;
} else if (type.equalsIgnoreCase("adduser")) {
Custom.adduser(player, email, password, ipAddress);
EBean.sync(player);
return true;
} else if (type.equalsIgnoreCase("numusers")) {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.custom_table + "`");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
logging.Info(rs.getInt("countit") + " user registrations in database");
}
}
} else if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) {
usertable = "users";
//bantable = "banlist";
if (checkVersionInRange(PhpBB.VersionRange)) {
usernamefield = "username_clean";
passwordfield = "user_password";
/*useridfield = "user_id";
banipfield = "ban_ip";
bannamefield = "ban_userid";
banreasonfield = "";*/
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (PhpBB.check_hash(password, hash)) {
return true;
}
}
/*else if (type.equalsIgnoreCase("checkban")) {
String check = "fail";
if (ipAddress != null) {
String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", player);
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid);
} else {
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + banipfield + "", ipAddress);
}
if (check != "fail") {
return true;
} else {
return false;
}
} */
} else if (checkVersionInRange(PhpBB.VersionRange2)) {
usernamefield = "username_clean"; // TODO: use equalsIgnoreCase to allow for all variations?
passwordfield = "user_password";
Config.hasForumBoard = true;
bans = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (PhpBB.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
PhpBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) {
usertable = "members";
if (checkVersionInRange(SMF.VersionRange)) {
usernamefield = "memberName";
passwordfield = "passwd";
saltfield = "passwordSalt";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && SMF.check_hash(SMF.hash(1, player, password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (SMF.check_hash(SMF.hash(1, player, password), hash)) {
return true;
}
}
} else if (checkVersionInRange(SMF.VersionRange2) || checkVersionInRange("2.0-2.0")
|| checkVersionInRange("2.0.0-2.0.0")) {
usernamefield = "member_name";
passwordfield = "passwd";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && SMF.check_hash(SMF.hash(2, player, password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (SMF.check_hash(SMF.hash(2, player, password), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
SMF.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) {
usertable = "users";
if (checkVersionInRange(MyBB.VersionRange)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
bans = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && MyBB.check_hash(MyBB.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (MyBB.check_hash(MyBB.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
MyBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) {
usertable = "user";
if (checkVersionInRange(VBulletin.VersionRange)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) {
return true;
}
}
} else if (checkVersionInRange(VBulletin.VersionRange2)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
bans = true;
number = 2;
caseSensitive = true;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
VBulletin.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) {
usertable = "users";
if (checkVersionInRange(Drupal.VersionRange)) {
usernamefield = "name";
passwordfield = "pass";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Encryption.md5(password).equals(storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Encryption.md5(password).equals(hash)) {
return true;
}
}
} else if (checkVersionInRange(Drupal.VersionRange2)) {
usernamefield = "name";
passwordfield = "pass";
Config.hasForumBoard = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && storedPassword.equals(Drupal.user_check_password(password, storedPassword))) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (hash.equals(Drupal.user_check_password(password, hash))) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
Drupal.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) {
usertable = "users";
if (checkVersionInRange(Joomla.VersionRange)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Joomla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Joomla.check_hash(password, hash)) {
return true;
}
}
} else if (checkVersionInRange(Joomla.VersionRange2)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Joomla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Joomla.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
Joomla.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) {
if (checkVersionInRange(Vanilla.VersionRange)) {
usertable = "User";
usernamefield = "Name";
passwordfield = "Password";
caseSensitive = true;
if (Vanilla.check() == 2) {
usertable = usertable.toLowerCase();
}
Config.hasForumBoard = true;
number = Vanilla.check();
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Vanilla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Vanilla.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
String emailcheck = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + usernamefield + "`", "Email", email);
if (emailcheck.equalsIgnoreCase("fail")) {
Vanilla.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
return false;
}
} else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) {
usertable = "users";
//bantable = "bans";
if (checkVersionInRange(PunBB.VersionRange)) {
//bannamefield = "username";
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PunBB.check_hash(PunBB.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (PunBB.check_hash(PunBB.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
PunBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) {
usertable = "user";
if (checkVersionInRange(XenForo.VersionRange)) {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
usernamefield = "username";
passwordfield = "password";
caseSensitive = true;
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
if (hash != null) {
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
// TODO: Auto-generated catch block
logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thehash = forumCacheValue(cache, "hash");
String thesalt = forumCacheValue(cache, "salt");
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
String storedSalt = eBeanClass.getSalt();
if (storedPassword != null && storedSalt != null && XenForo.check_hash(XenForo.hash(1, storedSalt, password), storedPassword)) {
return true;
}
EBean.checkSalt(player, thesalt);
EBean.checkPassword(player, thehash);
if (XenForo.check_hash(XenForo.hash(1, thesalt, password), thehash)) {
return true;
}
} else {
return false;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
XenForo.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thehash = forumCacheValue(cache, "hash");
EBean.checkPassword(player, thehash);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
// TODO: Auto-generated catch block
logging.StackTrace(e.getStackTrace(),
Thread.currentThread().getStackTrace()[1].getMethodName(),
Thread.currentThread().getStackTrace()[1].getLineNumber(),
Thread.currentThread().getStackTrace()[1].getClassName(),
Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thesalt = forumCacheValue(cache, "salt");
EBean.checkSalt(player, thesalt);
return true;
}
} else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) {
usertable = "users";
if (checkVersionInRange(BBPress.VersionRange)) {
usernamefield = "user_login";
passwordfield = "user_pass";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && BBPress.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (BBPress.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
BBPress.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) {
usertable = "users";
if (checkVersionInRange(DLE.VersionRange)) {
usernamefield = "name";
passwordfield = "password";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && DLE.check_hash(DLE.hash(password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (DLE.check_hash(DLE.hash(password), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
DLE.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) {
usertable = "members";
if (checkVersionInRange(IPB.VersionRange)) {
saltfield = "members_pass_salt";
usernamefield = "members_l_username";
passwordfield = "members_pass_hash";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password.toLowerCase(), null), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (IPB.check_hash(IPB.hash("find", player.toLowerCase(), password, null), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
IPB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) {
usertable = "users";
if (checkVersionInRange(WordPress.VersionRange)) {
usernamefield = "user_login";
passwordfield = "user_pass";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && WordPress.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (WordPress.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
WordPress.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} /* else if (script.equalsIgnoreCase(Config.Script11_name) || script.equalsIgnoreCase(Config.Script11_shortname)) {
usertable = "users";
if (checkVersionInRange(Config.Script11_versionrange)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
if (XE.check_hash(password, hash)) { return true; }
}
}
if (type.equalsIgnoreCase("adduser")) {
XE.adduser(number, player, email, password, ipAddress);
return true;
}
} */
if (!Config.hasForumBoard) {
if (!Config.custom_enabled) {
String tempVers = Config.script_version;
Config.script_version = scriptVersion();
logging.Info(System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|" + System.getProperty("line.separator")
+ "|--------------------------------AUTHDB WARNING-------------------------------|" + System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|" + System.getProperty("line.separator")
+ "| COULD NOT FIND A COMPATIBLE SCRIPT VERSION! |" + System.getProperty("line.separator")
+ "| PLEASE CHECK YOUR SCRIPT VERSION AND TRY AGAIN. PLUGIN MAY OR MAY NOT WORK. |" + System.getProperty("line.separator")
+ "| YOUR SCRIPT VERSION FOR " + Config.script_name + " HAS BEEN SET FROM " + tempVers + " TO " + Config.script_version + " |" + System.getProperty("line.separator")
+ "| FOR A LIST OF SCRIPT VERSIONS, |" + System.getProperty("line.separator")
+ "| CHECK: http://wiki.bukkit.org/AuthDB#Scripts_Supported |" + System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|");
}
}
if (!caseSensitive && player != null) {
player = player.toLowerCase();
}
if (Config.hasForumBoard && type.equalsIgnoreCase("checkuser") && !Config.custom_enabled) {
//EBean eBeanClass = EBean.find(player, Column.registered, "true");
//if (eBeanClass != null) { return true; }
String check = MySQL.getfromtable(Config.script_tableprefix + usertable, "*", usernamefield, player);
if (check != "fail") { return true; }
return false;
} /*else if (Config.hasForumBoard && type.equalsIgnoreCase("checkban") && !Config.custom_enabled && bantable != null) {
String check = MySQL.getfromtable(Config.script_tableprefix + bantable, "*", bannamefield, player);
if (check != "fail") { return true; }
}*/ else if (Config.hasForumBoard && type.equalsIgnoreCase("numusers") && !Config.custom_enabled) {
if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `"
+ Config.script_tableprefix + usertable + "` WHERE `group_id` !=6");
} else {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `"
+ Config.script_tableprefix + usertable + "`");
}
ResultSet rs = ps.executeQuery();
if (rs.next()) { logging.Info(rs.getInt("countit") + " user registrations in database"); }
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) {
String hash = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + passwordfield + "`", usernamefield, player);
EBean.checkPassword(player, hash);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") {
String salt = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + saltfield + "`", usernamefield, player);
EBean.checkSalt(player, salt);
return true;
}
}
| public static boolean checkScript(String type, String script, String player, String password,
String email, String ipAddress) throws SQLException {
boolean caseSensitive = false;
if (Util.databaseManager.getDatabaseType().equalsIgnoreCase("ebean")) {
EBean eBeanClass = EBean.checkPlayer(player, true);
if (type.equalsIgnoreCase("checkuser")) {
if (eBeanClass.getRegistered().equalsIgnoreCase("true")) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("checkpassword")) {
String storedPassword = eBeanClass.getPassword();
if (Encryption.SHA512(password).equals(storedPassword)) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("adduser")) {
Custom.adduser(player, email, password, ipAddress);
eBeanClass.setEmail(email);
eBeanClass.setPassword(Encryption.SHA512(password));
eBeanClass.setRegistered("true");
eBeanClass.setIp(ipAddress);
} else if (type.equalsIgnoreCase("numusers")) {
int amount = EBean.getUsers();
logging.Info(amount + " user registrations in database");
}
} else if (Config.database_ison) {
String usertable = null, usernamefield = null, passwordfield = null, saltfield = "";
boolean bans = false;
PreparedStatement ps = null;
int number = 0;
if (Config.custom_enabled) {
if (type.equalsIgnoreCase("checkuser")) {
String check = MySQL.getfromtable(Config.custom_table, "*", Config.custom_userfield, player);
if (check != "fail") {
Config.hasForumBoard = true;
return true;
}
return false;
} else if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (Custom.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player);
EBean.checkPassword(player, hash);
if (Custom.check_hash(password, hash)) {
return true;
}
return false;
} else if (type.equalsIgnoreCase("syncpassword")) {
String hash = MySQL.getfromtable(Config.custom_table, "`" + Config.custom_passfield + "`", "" + Config.custom_userfield + "", player);
EBean.checkPassword(player, hash);
return true;
} else if (type.equalsIgnoreCase("adduser")) {
Custom.adduser(player, email, password, ipAddress);
EBean.sync(player);
return true;
} else if (type.equalsIgnoreCase("numusers")) {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `" + Config.custom_table + "`");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
logging.Info(rs.getInt("countit") + " user registrations in database");
}
}
} else if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) {
usertable = "users";
//bantable = "banlist";
if (checkVersionInRange(PhpBB.VersionRange)) {
usernamefield = "username_clean";
passwordfield = "user_password";
/*useridfield = "user_id";
banipfield = "ban_ip";
bannamefield = "ban_userid";
banreasonfield = "";*/
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (PhpBB.check_hash(password, hash)) {
return true;
}
}
/*else if (type.equalsIgnoreCase("checkban")) {
String check = "fail";
if (ipAddress != null) {
String userid = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + useridfield + "`", "" + usernamefield + "", player);
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + bannamefield + "", userid);
} else {
check = MySQL.getfromtable(Config.script_tableprefix + "" + bantable + "", "`" + banipfield + "`", "" + banipfield + "", ipAddress);
}
if (check != "fail") {
return true;
} else {
return false;
}
} */
} else if (checkVersionInRange(PhpBB.VersionRange2)) {
usernamefield = "username_clean"; // TODO: use equalsIgnoreCase to allow for all variations?
passwordfield = "user_password";
Config.hasForumBoard = true;
bans = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PhpBB.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (PhpBB.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
PhpBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(SMF.Name) || script.equalsIgnoreCase(SMF.ShortName)) {
usertable = "members";
if (checkVersionInRange(SMF.VersionRange)) {
usernamefield = "memberName";
passwordfield = "passwd";
saltfield = "passwordSalt";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && SMF.check_hash(SMF.hash(1, player, password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (SMF.check_hash(SMF.hash(1, player, password), hash)) {
return true;
}
}
} else if (checkVersionInRange(SMF.VersionRange2) || checkVersionInRange("2.0-2.0")
|| checkVersionInRange("2.0.0-2.0.0")) {
usernamefield = "member_name";
passwordfield = "passwd";
saltfield = "password_salt";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && SMF.check_hash(SMF.hash(2, player, password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (SMF.check_hash(SMF.hash(2, player, password), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
SMF.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(MyBB.Name) || script.equalsIgnoreCase(MyBB.ShortName)) {
usertable = "users";
if (checkVersionInRange(MyBB.VersionRange)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
bans = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && MyBB.check_hash(MyBB.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (MyBB.check_hash(MyBB.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
MyBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(VBulletin.Name) || script.equalsIgnoreCase(VBulletin.ShortName)) {
usertable = "user";
if (checkVersionInRange(VBulletin.VersionRange)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
bans = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) {
return true;
}
}
} else if (checkVersionInRange(VBulletin.VersionRange2)) {
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
bans = true;
number = 2;
caseSensitive = true;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && VBulletin.check_hash(VBulletin.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (VBulletin.check_hash(VBulletin.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
VBulletin.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Drupal.Name) || script.equalsIgnoreCase(Drupal.ShortName)) {
usertable = "users";
if (checkVersionInRange(Drupal.VersionRange)) {
usernamefield = "name";
passwordfield = "pass";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Encryption.md5(password).equals(storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Encryption.md5(password).equals(hash)) {
return true;
}
}
} else if (checkVersionInRange(Drupal.VersionRange2)) {
usernamefield = "name";
passwordfield = "pass";
Config.hasForumBoard = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && storedPassword.equals(Drupal.user_check_password(password, storedPassword))) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (hash.equals(Drupal.user_check_password(password, hash))) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
Drupal.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Joomla.Name) || script.equalsIgnoreCase(Joomla.ShortName)) {
usertable = "users";
if (checkVersionInRange(Joomla.VersionRange)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Joomla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Joomla.check_hash(password, hash)) {
return true;
}
}
} else if (checkVersionInRange(Joomla.VersionRange2)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 2;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Joomla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Joomla.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
Joomla.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(Vanilla.Name) || script.equalsIgnoreCase(Vanilla.ShortName)) {
if (checkVersionInRange(Vanilla.VersionRange)) {
usertable = "User";
usernamefield = "Name";
passwordfield = "Password";
caseSensitive = true;
if (Vanilla.check() == 2) {
usertable = usertable.toLowerCase();
}
Config.hasForumBoard = true;
number = Vanilla.check();
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && Vanilla.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (Vanilla.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
String emailcheck = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + usernamefield + "`", "Email", email);
if (emailcheck.equalsIgnoreCase("fail")) {
Vanilla.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
return false;
}
} else if (script.equalsIgnoreCase(PunBB.Name) || script.equalsIgnoreCase(PunBB.ShortName)) {
usertable = "users";
//bantable = "bans";
if (checkVersionInRange(PunBB.VersionRange)) {
//bannamefield = "username";
saltfield = "salt";
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && PunBB.check_hash(PunBB.hash("find", player, password, ""), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (PunBB.check_hash(PunBB.hash("find", player, password, ""), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
PunBB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(XenForo.Name) || script.equalsIgnoreCase(XenForo.ShortName)) {
usertable = "user";
if (checkVersionInRange(XenForo.VersionRange)) {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
usernamefield = "username";
passwordfield = "password";
caseSensitive = true;
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
if (hash != null) {
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
// TODO: Auto-generated catch block
logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thehash = forumCacheValue(cache, "hash");
String thesalt = forumCacheValue(cache, "salt");
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
String storedSalt = eBeanClass.getSalt();
if (storedPassword != null && storedSalt != null && XenForo.check_hash(XenForo.hash(1, storedSalt, password), storedPassword)) {
return true;
}
EBean.checkSalt(player, thesalt);
EBean.checkPassword(player, thehash);
if (XenForo.check_hash(XenForo.hash(1, thesalt, password), thehash)) {
return true;
}
} else {
return false;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
XenForo.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
logging.StackTrace(e.getStackTrace(), Thread.currentThread().getStackTrace()[1].getMethodName(), Thread.currentThread().getStackTrace()[1].getLineNumber(), Thread.currentThread().getStackTrace()[1].getClassName(), Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thehash = forumCacheValue(cache, "hash");
EBean.checkPassword(player, thehash);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") {
String userid = MySQL.getfromtable(Config.script_tableprefix + usertable, "`user_id`", "username", player);
Blob hash = MySQL.getfromtableBlob(Config.script_tableprefix + "user_authenticate", "`data`", "user_id", userid);
int offset = -1;
int chunkSize = 1024;
long blobLength = hash.length();
if (chunkSize > blobLength) {
chunkSize = (int) blobLength;
}
char buffer[] = new char[chunkSize];
StringBuilder stringBuffer = new StringBuilder();
Reader reader = new InputStreamReader(hash.getBinaryStream());
try {
while ((offset = reader.read(buffer)) != -1) {
stringBuffer.append(buffer, 0, offset);
}
} catch (IOException e) {
// TODO: Auto-generated catch block
logging.StackTrace(e.getStackTrace(),
Thread.currentThread().getStackTrace()[1].getMethodName(),
Thread.currentThread().getStackTrace()[1].getLineNumber(),
Thread.currentThread().getStackTrace()[1].getClassName(),
Thread.currentThread().getStackTrace()[1].getFileName());
}
String cache = stringBuffer.toString();
String thesalt = forumCacheValue(cache, "salt");
EBean.checkSalt(player, thesalt);
return true;
}
} else if (script.equalsIgnoreCase(BBPress.Name) || script.equalsIgnoreCase(BBPress.ShortName)) {
usertable = "users";
if (checkVersionInRange(BBPress.VersionRange)) {
usernamefield = "user_login";
passwordfield = "user_pass";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && BBPress.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (BBPress.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
BBPress.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(DLE.Name) || script.equalsIgnoreCase(DLE.ShortName)) {
usertable = "users";
if (checkVersionInRange(DLE.VersionRange)) {
usernamefield = "name";
passwordfield = "password";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && DLE.check_hash(DLE.hash(password), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "",
"`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (DLE.check_hash(DLE.hash(password), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
DLE.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(IPB.Name) || script.equalsIgnoreCase(IPB.ShortName)) {
usertable = "members";
if (checkVersionInRange(IPB.VersionRange)) {
usernamefield = "members_l_username";
passwordfield = "members_pass_hash";
saltfield = "members_pass_salt";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && IPB.check_hash(IPB.hash("find", player, password.toLowerCase(), null), storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player.toLowerCase());
EBean.checkPassword(player, hash);
if (IPB.check_hash(IPB.hash("find", player.toLowerCase(), password, null), hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
IPB.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} else if (script.equalsIgnoreCase(WordPress.Name) || script.equalsIgnoreCase(WordPress.ShortName)) {
usertable = "users";
if (checkVersionInRange(WordPress.VersionRange)) {
usernamefield = "user_login";
passwordfield = "user_pass";
Config.hasForumBoard = true;
caseSensitive = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
EBean eBeanClass = EBean.find(player);
String storedPassword = eBeanClass.getPassword();
if (storedPassword != null && WordPress.check_hash(password, storedPassword)) {
return true;
}
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
EBean.checkPassword(player, hash);
if (WordPress.check_hash(password, hash)) {
return true;
}
}
}
if (type.equalsIgnoreCase("adduser")) {
WordPress.adduser(number, player, email, password, ipAddress);
EBean.sync(player);
return true;
}
} /* else if (script.equalsIgnoreCase(Config.Script11_name) || script.equalsIgnoreCase(Config.Script11_shortname)) {
usertable = "users";
if (checkVersionInRange(Config.Script11_versionrange)) {
usernamefield = "username";
passwordfield = "password";
Config.hasForumBoard = true;
number = 1;
if (type.equalsIgnoreCase("checkpassword")) {
String hash = MySQL.getfromtable(Config.script_tableprefix + "" + usertable + "", "`" + passwordfield + "`", "" + usernamefield + "", player);
if (XE.check_hash(password, hash)) { return true; }
}
}
if (type.equalsIgnoreCase("adduser")) {
XE.adduser(number, player, email, password, ipAddress);
return true;
}
} */
if (!Config.hasForumBoard) {
if (!Config.custom_enabled) {
String tempVers = Config.script_version;
Config.script_version = scriptVersion();
logging.Info(System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|" + System.getProperty("line.separator")
+ "|--------------------------------AUTHDB WARNING-------------------------------|" + System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|" + System.getProperty("line.separator")
+ "| COULD NOT FIND A COMPATIBLE SCRIPT VERSION! |" + System.getProperty("line.separator")
+ "| PLEASE CHECK YOUR SCRIPT VERSION AND TRY AGAIN. PLUGIN MAY OR MAY NOT WORK. |" + System.getProperty("line.separator")
+ "| YOUR SCRIPT VERSION FOR " + Config.script_name + " HAS BEEN SET FROM " + tempVers + " TO " + Config.script_version + " |" + System.getProperty("line.separator")
+ "| FOR A LIST OF SCRIPT VERSIONS, |" + System.getProperty("line.separator")
+ "| CHECK: http://wiki.bukkit.org/AuthDB#Scripts_Supported |" + System.getProperty("line.separator")
+ "|-----------------------------------------------------------------------------|");
}
}
if (!caseSensitive && player != null) {
player = player.toLowerCase();
}
if (Config.hasForumBoard && type.equalsIgnoreCase("checkuser") && !Config.custom_enabled) {
//EBean eBeanClass = EBean.find(player, Column.registered, "true");
//if (eBeanClass != null) { return true; }
String check = MySQL.getfromtable(Config.script_tableprefix + usertable, "*", usernamefield, player);
if (check != "fail") { return true; }
return false;
} /*else if (Config.hasForumBoard && type.equalsIgnoreCase("checkban") && !Config.custom_enabled && bantable != null) {
String check = MySQL.getfromtable(Config.script_tableprefix + bantable, "*", bannamefield, player);
if (check != "fail") { return true; }
}*/ else if (Config.hasForumBoard && type.equalsIgnoreCase("numusers") && !Config.custom_enabled) {
if (script.equalsIgnoreCase(PhpBB.Name) || script.equalsIgnoreCase(PhpBB.ShortName)) {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `"
+ Config.script_tableprefix + usertable + "` WHERE `group_id` !=6");
} else {
ps = (PreparedStatement) MySQL.mysql.prepareStatement("SELECT COUNT(*) as `countit` FROM `"
+ Config.script_tableprefix + usertable + "`");
}
ResultSet rs = ps.executeQuery();
if (rs.next()) { logging.Info(rs.getInt("countit") + " user registrations in database"); }
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncpassword") && !Config.custom_enabled) {
String hash = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + passwordfield + "`", usernamefield, player);
EBean.checkPassword(player, hash);
return true;
} else if (Config.hasForumBoard && type.equalsIgnoreCase("syncsalt") && !Config.custom_enabled && saltfield != null && saltfield != "") {
String salt = MySQL.getfromtable(Config.script_tableprefix + usertable, "`" + saltfield + "`", usernamefield, player);
EBean.checkSalt(player, salt);
return true;
}
}
|
diff --git a/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java b/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java
index e3ead79..5595557 100644
--- a/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java
+++ b/src/main/java/com/lebelw/Tickets/commands/TemplateCmd.java
@@ -1,337 +1,341 @@
package com.lebelw.Tickets.commands;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.lebelw.Tickets.TDatabase;
import com.lebelw.Tickets.TLogger;
import com.lebelw.Tickets.TPermissions;
import com.lebelw.Tickets.TTools;
import com.lebelw.Tickets.Tickets;
import com.lebelw.Tickets.extras.DataManager;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandException;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* @description Handles a command.
* @author Tagette
*/
public class TemplateCmd implements CommandExecutor {
private final Tickets plugin;
DataManager dbm = TDatabase.dbm;
Player target;
int currentticket, ticketarg, amount;
public TemplateCmd(Tickets instance) {
plugin = instance;
}
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean handled = false;
if (is(label, "ticket")) {
if (args == null || args.length == 0) {
handled = true;
if (isPlayer(sender)){
String name = getName(sender);
try{
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'");
if (result != null && result.next()){
sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN));
}
else
sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED));
} catch (SQLException se) {
TLogger.error(se.getMessage());
}
}
}
else {
//Is the first argument give?
if (is(args[0],"help")){
handled = true;
sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN)
+ " version " + colorizeText(Tickets.version, ChatColor.GREEN) + ".");
sendMessage(sender, "Commands:");
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone");
}
}
else if (is(args[0],"send")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
if (args.length == 1 || args.length == 2){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
return handled;
}
if (!TTools.isInt(args[1])){
if (TTools.isInt(args[2])){
String sendername = ((Player)sender).getName();
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
+ if (sendername == name){
+ sendMessage(sender,colorizeText("You can't send ticket(s) to yourself!",ChatColor.RED));
+ return handled;
+ }
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(sendername)){
currentticket = getPlayerTicket(sendername);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
if (givePlayerTicket(name,ticketarg)){
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}
}else{
sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else {
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
else if(is(args[0],"give")){
handled = true;
//We check the guy permission
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (givePlayerTicket(name,ticketarg)){
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
//Is the first argument take?
else if(is(args[0],"take")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
}else{
sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
}
}
return handled;
}
// Simplifies and shortens the if statements for commands.
private boolean is(String entered, String label) {
return entered.equalsIgnoreCase(label);
}
// Checks if the current user is actually a player.
private boolean isPlayer(CommandSender sender) {
return sender != null && sender instanceof Player;
}
// Checks if the current user is actually a player and sends a message to that player.
private boolean sendMessage(CommandSender sender, String message) {
boolean sent = false;
if (isPlayer(sender)) {
Player player = (Player) sender;
player.sendMessage(message);
sent = true;
}
return sent;
}
private boolean sendLog(CommandSender sender, String message) {
boolean sent = false;
if (!isPlayer(sender)) {
TLogger.info(message);
sent = true;
}
return sent;
}
// Checks if the current user is actually a player and returns the name of that player.
private String getName(CommandSender sender) {
String name = "";
if (isPlayer(sender)) {
Player player = (Player) sender;
name = player.getName();
}
return name;
}
// Gets the player if the current user is actually a player.
private Player getPlayer(CommandSender sender) {
Player player = null;
if (isPlayer(sender)) {
player = (Player) sender;
}
return player;
}
private String colorizeText(String text, ChatColor color) {
return color + text + ChatColor.WHITE;
}
/*
* Checks if a player account exists
*
* @param name The full name of the player.
*/
private boolean checkIfPlayerExists(String name)
{
ResultSet result = dbm.query("SELECT id FROM players WHERE name = '" + name + "'");
try {
if (result != null && result.next()){
return true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
TLogger.warning(e.getMessage());
return false;
}
return false;
}
/*
* Get the amount of tickets a player have
*
* @param name The full name of the player.
*/
private int getPlayerTicket(String name){
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name = '" + name + "'");
try {
if (result != null && result.next()){
return result.getInt("Ticket");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
TLogger.warning(e.getMessage());
return 0;
}
return 0;
}
/*
* Create a player ticket account
*
* @param name The full name of the player.
*/
private boolean createPlayerTicketAccount(String name){
if (!checkIfPlayerExists(name)){
if(dbm.insert("INSERT INTO players(name) VALUES('" + name + "')")){
return true;
}else{
return false;
}
}else{
return false;
}
}
private boolean givePlayerTicket(String name, Integer amount){
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket + amount;
return dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
}else{
if (createPlayerTicketAccount(name)){
return dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
}else{
return false;
}
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean handled = false;
if (is(label, "ticket")) {
if (args == null || args.length == 0) {
handled = true;
if (isPlayer(sender)){
String name = getName(sender);
try{
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'");
if (result != null && result.next()){
sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN));
}
else
sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED));
} catch (SQLException se) {
TLogger.error(se.getMessage());
}
}
}
else {
//Is the first argument give?
if (is(args[0],"help")){
handled = true;
sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN)
+ " version " + colorizeText(Tickets.version, ChatColor.GREEN) + ".");
sendMessage(sender, "Commands:");
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone");
}
}
else if (is(args[0],"send")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
if (args.length == 1 || args.length == 2){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
return handled;
}
if (!TTools.isInt(args[1])){
if (TTools.isInt(args[2])){
String sendername = ((Player)sender).getName();
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(sendername)){
currentticket = getPlayerTicket(sendername);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
if (givePlayerTicket(name,ticketarg)){
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}
}else{
sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else {
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
else if(is(args[0],"give")){
handled = true;
//We check the guy permission
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (givePlayerTicket(name,ticketarg)){
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
//Is the first argument take?
else if(is(args[0],"take")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
}else{
sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
}
}
return handled;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
boolean handled = false;
if (is(label, "ticket")) {
if (args == null || args.length == 0) {
handled = true;
if (isPlayer(sender)){
String name = getName(sender);
try{
ResultSet result = dbm.query("SELECT ticket FROM players WHERE name='" + name + "'");
if (result != null && result.next()){
sendMessage(sender,colorizeText("You have ",ChatColor.GREEN) + result.getInt("ticket") + colorizeText(" ticket(s).",ChatColor.GREEN));
}
else
sendMessage(sender,colorizeText("You have 0 ticket",ChatColor.RED));
} catch (SQLException se) {
TLogger.error(se.getMessage());
}
}
}
else {
//Is the first argument give?
if (is(args[0],"help")){
handled = true;
sendMessage(sender, "You are using " + colorizeText(Tickets.name, ChatColor.GREEN)
+ " version " + colorizeText(Tickets.version, ChatColor.GREEN) + ".");
sendMessage(sender, "Commands:");
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket give <Name> <Amount>",ChatColor.YELLOW) +" - Give ticket to semeone");
}
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
sendMessage(sender,colorizeText("/ticket take <Name> <Amount>",ChatColor.YELLOW) +" - Take ticket to semeone");
}
}
else if (is(args[0],"send")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.send", getPlayer(sender).isOp())){
if (args.length == 1 || args.length == 2){
sendMessage(sender,colorizeText("/ticket send <Name> <Amount>",ChatColor.YELLOW) +" - Send ticket to semeone");
return handled;
}
if (!TTools.isInt(args[1])){
if (TTools.isInt(args[2])){
String sendername = ((Player)sender).getName();
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
if (sendername == name){
sendMessage(sender,colorizeText("You can't send ticket(s) to yourself!",ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(sendername)){
currentticket = getPlayerTicket(sendername);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You online have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)! You can't send ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
if (givePlayerTicket(name,ticketarg)){
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}
}else{
sendMessage(sender,colorizeText("You can't send ticket(s) because you don't have any!",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}else {
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
else if(is(args[0],"give")){
handled = true;
//We check the guy permission
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.give", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (givePlayerTicket(name,ticketarg)){
sendMessage(sender,colorizeText(args[2] +" ticket(s) has been given to "+ name,ChatColor.GREEN));
if (target.getName() != null){
sendMessage(target,colorizeText("You received "+ ticketarg +" ticket(s) from "+ ((Player)sender).getName() + ".",ChatColor.GREEN));
}
}else{
sendMessage(sender,colorizeText("A error occured",ChatColor.GREEN));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
//Is the first argument take?
else if(is(args[0],"take")){
handled = true;
if (isPlayer(sender) && TPermissions.permission(getPlayer(sender), "ticket.take", getPlayer(sender).isOp())){
//We check if we received a string for the first parameter (Player)
if (args[1] != null && !TTools.isInt(args[1])){
//We check if we received a int for the second parameter (Amount)
if (args[2] != null && TTools.isInt(args[2])){
String name = args[1];
try {
target = plugin.matchSinglePlayer(sender, name);
if (target.getName() != null){
name = target.getName();
}
}catch (CommandException error){
sendMessage(sender,colorizeText(error.getMessage(),ChatColor.RED));
return handled;
}
ticketarg = Integer.parseInt(args[2]);
if (checkIfPlayerExists(name)){
currentticket = getPlayerTicket(name);
amount = currentticket - ticketarg;
if (amount < 0){
sendMessage(sender,colorizeText("You can't remove ",ChatColor.RED) + ticketarg + colorizeText(" ticket(s)! This player only have ",ChatColor.RED) + currentticket + colorizeText(" ticket(s)!",ChatColor.RED));
return handled;
}
dbm.update("UPDATE players SET ticket=" + amount + " WHERE name = '" + name + "'");
}else{
sendMessage(sender,colorizeText("You can't remove tickets to " + name + " because he doesn't have any!",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("String received for the second parameter. Expecting integer.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Integer received for the first parameter. Expecting string.",ChatColor.RED));
}
}
else{
sendMessage(sender,colorizeText("Permission denied.",ChatColor.RED));
}
}
}
}
return handled;
}
|
diff --git a/src/gwt/src/org/rstudio/studio/client/common/FilePathUtils.java b/src/gwt/src/org/rstudio/studio/client/common/FilePathUtils.java
index b480c31d00..0006f1b5f9 100644
--- a/src/gwt/src/org/rstudio/studio/client/common/FilePathUtils.java
+++ b/src/gwt/src/org/rstudio/studio/client/common/FilePathUtils.java
@@ -1,56 +1,56 @@
/*
* FilePathUtils.java
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.common;
import org.rstudio.core.client.files.FileSystemItem;
public class FilePathUtils
{
public static String friendlyFileName(String unfriendlyFileName)
{
int idx = unfriendlyFileName.lastIndexOf("/");
if (idx < 0)
{
idx = unfriendlyFileName.lastIndexOf("\\");
}
return unfriendlyFileName.substring(
idx + 1, unfriendlyFileName.length()).trim();
}
public static String normalizePath (String path, String workingDirectory)
{
// Examine the path to see if it appears to be absolute. An absolute path
- // - begins with ~ , or
- // - begins with / (Unix-like systems), or
- // - begins with F:/ (Windows systems), where F is an alphabetic drive
- // letter.
+ // - begins with ~ , or
+ // - begins with / (Unix-like systems), or
+ // - begins with F:/ (Windows systems), where F is an alphabetic drive
+ // letter.
if (path.startsWith(FileSystemItem.HOME_PREFIX) ||
path.startsWith("/") ||
path.matches("^[a-zA-Z]:\\/.*"))
{
return path;
}
// if the path appears to be relative, prepend the working directory
// (consider: should we try to handle ..-style relative notation here?)
String prefix = new String(workingDirectory +
(workingDirectory.endsWith("/") ? "" : "/"));
String relative = new String(path.startsWith("./") ?
path.substring(2, path.length()) : path);
return prefix + relative;
}
}
| true | true | public static String normalizePath (String path, String workingDirectory)
{
// Examine the path to see if it appears to be absolute. An absolute path
// - begins with ~ , or
// - begins with / (Unix-like systems), or
// - begins with F:/ (Windows systems), where F is an alphabetic drive
// letter.
if (path.startsWith(FileSystemItem.HOME_PREFIX) ||
path.startsWith("/") ||
path.matches("^[a-zA-Z]:\\/.*"))
{
return path;
}
// if the path appears to be relative, prepend the working directory
// (consider: should we try to handle ..-style relative notation here?)
String prefix = new String(workingDirectory +
(workingDirectory.endsWith("/") ? "" : "/"));
String relative = new String(path.startsWith("./") ?
path.substring(2, path.length()) : path);
return prefix + relative;
}
| public static String normalizePath (String path, String workingDirectory)
{
// Examine the path to see if it appears to be absolute. An absolute path
// - begins with ~ , or
// - begins with / (Unix-like systems), or
// - begins with F:/ (Windows systems), where F is an alphabetic drive
// letter.
if (path.startsWith(FileSystemItem.HOME_PREFIX) ||
path.startsWith("/") ||
path.matches("^[a-zA-Z]:\\/.*"))
{
return path;
}
// if the path appears to be relative, prepend the working directory
// (consider: should we try to handle ..-style relative notation here?)
String prefix = new String(workingDirectory +
(workingDirectory.endsWith("/") ? "" : "/"));
String relative = new String(path.startsWith("./") ?
path.substring(2, path.length()) : path);
return prefix + relative;
}
|
diff --git a/kerberos-codec/src/test/java/org/apache/directory/shared/kerberos/codec/HostAddressDecoderTest.java b/kerberos-codec/src/test/java/org/apache/directory/shared/kerberos/codec/HostAddressDecoderTest.java
index f4ebe5a67a..6a4cc2d76e 100644
--- a/kerberos-codec/src/test/java/org/apache/directory/shared/kerberos/codec/HostAddressDecoderTest.java
+++ b/kerberos-codec/src/test/java/org/apache/directory/shared/kerberos/codec/HostAddressDecoderTest.java
@@ -1,246 +1,246 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.shared.kerberos.codec;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.apache.directory.junit.tools.Concurrent;
import org.apache.directory.junit.tools.ConcurrentJunitRunner;
import org.apache.directory.shared.asn1.ber.Asn1Container;
import org.apache.directory.shared.asn1.ber.Asn1Decoder;
import org.apache.directory.shared.asn1.codec.DecoderException;
import org.apache.directory.shared.asn1.codec.EncoderException;
import org.apache.directory.shared.kerberos.codec.hostAddress.HostAddressContainer;
import org.apache.directory.shared.kerberos.codec.types.HostAddrType;
import org.apache.directory.shared.kerberos.components.HostAddress;
import org.apache.directory.shared.ldap.util.StringTools;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Test the HostAddress decoder.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
@RunWith(ConcurrentJunitRunner.class)
@Concurrent()
public class HostAddressDecoderTest
{
/**
* Test the decoding of a HostAddress
*/
@Test
public void testHostAddress()
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x16 );
stream.put( new byte[]
{ 0x30, 0x14,
(byte)0xA0, 0x03, // addr-type
0x02, 0x01, 0x02, // IPV4
(byte)0xA1, 0x0D, // address : 192.168.0.1
0x04, 0x0B, '1', '9', '2', '.', '1', '6', '8', '.', '0', '.', '1'
} );
String decodedPdu = StringTools.dumpBytes( stream.array() );
stream.flip();
- // Allocate a EncryptedHostAddressData Container
+ // Allocate a HostAddress Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
try
{
kerberosDecoder.decode( stream, hostAddressContainer );
}
catch ( DecoderException de )
{
fail( de.getMessage() );
}
// Check the decoded HostAddress
HostAddress hostAddress = ( ( HostAddressContainer ) hostAddressContainer ).getHostAddress();
assertEquals( HostAddrType.ADDRTYPE_INET, hostAddress.getAddrType() );
assertTrue( Arrays.equals( StringTools.getBytesUtf8( "192.168.0.1" ), hostAddress.getAddress() ) );
// Check the encoding
ByteBuffer bb = ByteBuffer.allocate( hostAddress.computeLength() );
try
{
bb = hostAddress.encode( bb );
// Check the length
assertEquals( 0x16, bb.limit() );
String encodedPdu = StringTools.dumpBytes( bb.array() );
assertEquals( encodedPdu, decodedPdu );
}
catch ( EncoderException ee )
{
fail();
}
}
/**
* Test the decoding of a HostAddress with nothing in it
*/
@Test( expected = DecoderException.class)
public void testHostAddressEmpty() throws DecoderException
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x02 );
stream.put( new byte[]
{ 0x30, 0x00 } );
stream.flip();
// Allocate a HostAddress Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
kerberosDecoder.decode( stream, hostAddressContainer );
fail();
}
/**
* Test the decoding of a HostAddress with no addr-type
*/
@Test( expected = DecoderException.class)
public void testHostAddressNoAddrType() throws DecoderException
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x04 );
stream.put( new byte[]
{ 0x30, 0x02,
(byte)0xA0, 0x00 // addr-type
} );
stream.flip();
// Allocate a HostAddress Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
kerberosDecoder.decode( stream, hostAddressContainer );
fail();
}
/**
* Test the decoding of a HostAddress with an empty addr-type
*/
@Test( expected = DecoderException.class)
public void testHostAddressEmptyAddrType() throws DecoderException
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x0B );
stream.put( new byte[]
{ 0x30, 0x04,
(byte)0xA0, 0x03, // addr-type
0x02, 0x00 //
} );
stream.flip();
// Allocate a HostAddress Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
kerberosDecoder.decode( stream, hostAddressContainer );
fail();
}
/**
* Test the decoding of a HostAddress with no address
*/
@Test( expected = DecoderException.class)
public void testHostAddressNoAddress() throws DecoderException
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x09 );
stream.put( new byte[]
{ 0x30, 0x07,
(byte)0xA0, 0x03, // addr-type
0x02, 0x01, 0x02, //
(byte)0xA1, 0x00 // address
} );
stream.flip();
// Allocate a HostAddress Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
kerberosDecoder.decode( stream, hostAddressContainer );
fail();
}
/**
* Test the decoding of a HostAddress empty address
*/
@Test( expected = DecoderException.class )
public void testHostAddressEmptyAddress() throws DecoderException
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x0E );
stream.put( new byte[]
{ 0x30, 0x14,
(byte)0xA0, 0x03, // addr-type
0x02, 0x01, 0x02, // IPV4
(byte)0xA1, 0x02, // address
0x04, 0x00
} );
stream.flip();
// Allocate a HostAddress Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
kerberosDecoder.decode( stream, hostAddressContainer );
fail();
}
}
| true | true | public void testHostAddress()
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x16 );
stream.put( new byte[]
{ 0x30, 0x14,
(byte)0xA0, 0x03, // addr-type
0x02, 0x01, 0x02, // IPV4
(byte)0xA1, 0x0D, // address : 192.168.0.1
0x04, 0x0B, '1', '9', '2', '.', '1', '6', '8', '.', '0', '.', '1'
} );
String decodedPdu = StringTools.dumpBytes( stream.array() );
stream.flip();
// Allocate a EncryptedHostAddressData Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
try
{
kerberosDecoder.decode( stream, hostAddressContainer );
}
catch ( DecoderException de )
{
fail( de.getMessage() );
}
// Check the decoded HostAddress
HostAddress hostAddress = ( ( HostAddressContainer ) hostAddressContainer ).getHostAddress();
assertEquals( HostAddrType.ADDRTYPE_INET, hostAddress.getAddrType() );
assertTrue( Arrays.equals( StringTools.getBytesUtf8( "192.168.0.1" ), hostAddress.getAddress() ) );
// Check the encoding
ByteBuffer bb = ByteBuffer.allocate( hostAddress.computeLength() );
try
{
bb = hostAddress.encode( bb );
// Check the length
assertEquals( 0x16, bb.limit() );
String encodedPdu = StringTools.dumpBytes( bb.array() );
assertEquals( encodedPdu, decodedPdu );
}
catch ( EncoderException ee )
{
fail();
}
}
| public void testHostAddress()
{
Asn1Decoder kerberosDecoder = new Asn1Decoder();
ByteBuffer stream = ByteBuffer.allocate( 0x16 );
stream.put( new byte[]
{ 0x30, 0x14,
(byte)0xA0, 0x03, // addr-type
0x02, 0x01, 0x02, // IPV4
(byte)0xA1, 0x0D, // address : 192.168.0.1
0x04, 0x0B, '1', '9', '2', '.', '1', '6', '8', '.', '0', '.', '1'
} );
String decodedPdu = StringTools.dumpBytes( stream.array() );
stream.flip();
// Allocate a HostAddress Container
Asn1Container hostAddressContainer = new HostAddressContainer();
// Decode the HostAddress PDU
try
{
kerberosDecoder.decode( stream, hostAddressContainer );
}
catch ( DecoderException de )
{
fail( de.getMessage() );
}
// Check the decoded HostAddress
HostAddress hostAddress = ( ( HostAddressContainer ) hostAddressContainer ).getHostAddress();
assertEquals( HostAddrType.ADDRTYPE_INET, hostAddress.getAddrType() );
assertTrue( Arrays.equals( StringTools.getBytesUtf8( "192.168.0.1" ), hostAddress.getAddress() ) );
// Check the encoding
ByteBuffer bb = ByteBuffer.allocate( hostAddress.computeLength() );
try
{
bb = hostAddress.encode( bb );
// Check the length
assertEquals( 0x16, bb.limit() );
String encodedPdu = StringTools.dumpBytes( bb.array() );
assertEquals( encodedPdu, decodedPdu );
}
catch ( EncoderException ee )
{
fail();
}
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java b/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
index 967fac51b..0fdd433fd 100644
--- a/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
+++ b/src/web/org/codehaus/groovy/grails/web/metaclass/RenderDynamicMethod.java
@@ -1,285 +1,288 @@
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.web.metaclass;
import grails.util.JSonBuilder;
import grails.util.OpenRicoBuilder;
import groovy.lang.*;
import groovy.text.Template;
import groovy.xml.StreamingMarkupBuilder;
import org.apache.commons.collections.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.web.pages.GroovyPagesTemplateEngine;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.GrailsHttpServletResponse;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
/**
* Allows rendering of text, views, and templates to the response
*
* @author Graeme Rocher
* @since Oct 27, 2005
*/
public class RenderDynamicMethod extends AbstractDynamicControllerMethod {
public static final String METHOD_SIGNATURE = "render";
public static final Pattern METHOD_PATTERN = Pattern.compile('^'+METHOD_SIGNATURE+'$');
public static final String ARGUMENT_TEXT = "text";
public static final String ARGUMENT_CONTENT_TYPE = "contentType";
public static final String ARGUMENT_ENCODING = "encoding";
public static final String ARGUMENT_VIEW = "view";
public static final String ARGUMENT_MODEL = "model";
public static final String ARGUMENT_TEMPLATE = "template";
public static final String ARGUMENT_BEAN = "bean";
public static final String ARGUMENT_COLLECTION = "collection";
public static final String ARGUMENT_BUILDER = "builder";
public static final String ARGUMENT_VAR = "var";
private static final String DEFAULT_ARGUMENT = "it";
private static final String BUILDER_TYPE_RICO = "rico";
private static final String BUILDER_TYPE_JSON = "json";
private GrailsControllerHelper helper;
protected GrailsHttpServletResponse response;
private static final String ARGUMENT_TO = "to";
public RenderDynamicMethod(GrailsControllerHelper helper, HttpServletRequest request, HttpServletResponse response) {
super(METHOD_PATTERN, request, response);
this.helper = helper;
if(response instanceof GrailsHttpServletResponse)
this.response = (GrailsHttpServletResponse)response;
else
this.response = new GrailsHttpServletResponse(response);
}
public Object invoke(Object target, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
try {
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString(),
argMap.get(ARGUMENT_ENCODING).toString());
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
}
else {
out = response.getWriter();
}
}
catch(IOException ioe) {
throw new ControllerExecutionException("I/O creating write in method [render] on class ["+target.getClass()+"]: " + ioe.getMessage(),ioe);
}
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = helper.getControllerClassByName(target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri,attrs.getServletContext(),request,response);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
+ catch(GroovyRuntimeException gre) {
+ throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
+ }
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
} catch (ServletException e) {
throw new ControllerExecutionException("Servlet exception executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
if(controller!=null)
controller.setProperty(ControllerDynamicMethods.RENDER_VIEW_PROPERTY,Boolean.valueOf(renderView));
return null;
}
}
| true | true | public Object invoke(Object target, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
try {
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString(),
argMap.get(ARGUMENT_ENCODING).toString());
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
}
else {
out = response.getWriter();
}
}
catch(IOException ioe) {
throw new ControllerExecutionException("I/O creating write in method [render] on class ["+target.getClass()+"]: " + ioe.getMessage(),ioe);
}
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = helper.getControllerClassByName(target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri,attrs.getServletContext(),request,response);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
} catch (ServletException e) {
throw new ControllerExecutionException("Servlet exception executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
if(controller!=null)
controller.setProperty(ControllerDynamicMethods.RENDER_VIEW_PROPERTY,Boolean.valueOf(renderView));
return null;
}
| public Object invoke(Object target, Object[] arguments) {
if(arguments.length == 0)
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
boolean renderView = true;
GroovyObject controller = (GroovyObject)target;
if((arguments[0] instanceof String)||(arguments[0] instanceof GString)) {
try {
response.getWriter().write(arguments[0].toString());
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException(e.getMessage(),e);
}
}
else if(arguments[0] instanceof Closure) {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(response.getWriter());
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[0]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(arguments[0] instanceof Map) {
Map argMap = (Map)arguments[0];
Writer out;
try {
if(argMap.containsKey(ARGUMENT_TO)) {
out = (Writer)argMap.get(ARGUMENT_TO);
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE) && argMap.containsKey(ARGUMENT_ENCODING)) {
out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString(),
argMap.get(ARGUMENT_ENCODING).toString());
}
else if(argMap.containsKey(ARGUMENT_CONTENT_TYPE)) {
out = response.getWriter(argMap.get(ARGUMENT_CONTENT_TYPE).toString());
}
else {
out = response.getWriter();
}
}
catch(IOException ioe) {
throw new ControllerExecutionException("I/O creating write in method [render] on class ["+target.getClass()+"]: " + ioe.getMessage(),ioe);
}
if(arguments[arguments.length - 1] instanceof Closure) {
if(BUILDER_TYPE_RICO.equals(argMap.get(ARGUMENT_BUILDER))) {
OpenRicoBuilder orb;
try {
orb = new OpenRicoBuilder(response);
renderView = false;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
orb.invokeMethod("ajax", new Object[]{ arguments[arguments.length - 1] });
}
else if(BUILDER_TYPE_JSON.equals(argMap.get(ARGUMENT_BUILDER))){
JSonBuilder jsonBuilder;
try{
jsonBuilder = new JSonBuilder(response);
renderView = false;
}catch(IOException e){
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
jsonBuilder.invokeMethod("json", new Object[]{ arguments[arguments.length - 1] });
}
else {
StreamingMarkupBuilder b = new StreamingMarkupBuilder();
Writable markup = (Writable)b.bind(arguments[arguments.length - 1]);
try {
markup.writeTo(out);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
}
else if(arguments[arguments.length - 1] instanceof String) {
try {
out.write((String)arguments[arguments.length - 1]);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+arguments[arguments.length - 1]+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_TEXT)) {
String text = argMap.get(ARGUMENT_TEXT).toString();
try {
out.write(text);
} catch (IOException e) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
renderView = false;
}
else if(argMap.containsKey(ARGUMENT_VIEW)) {
String viewName = argMap.get(ARGUMENT_VIEW).toString();
String viewUri;
if(viewName.indexOf('/') > -1) {
if(!viewName.startsWith("/"))
viewName = '/' + viewName;
viewUri = viewName;
}
else {
GrailsControllerClass controllerClass = helper.getControllerClassByName(target.getClass().getName());
viewUri = controllerClass.getViewByName(viewName);
}
Map model;
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
model = (Map)modelObject;
}
else {
model = new BeanMap(target);
}
controller.setProperty( ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY, new ModelAndView(viewUri,model) );
}
else if(argMap.containsKey(ARGUMENT_TEMPLATE)) {
String templateName = argMap.get(ARGUMENT_TEMPLATE).toString();
String var = (String)argMap.get(ARGUMENT_VAR);
// get the template uri
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)controller.getProperty(ControllerDynamicMethods.GRAILS_ATTRIBUTES);
String templateUri = attrs.getTemplateUri(templateName,request);
// retrieve gsp engine
GroovyPagesTemplateEngine engine = attrs.getPagesTemplateEngine();
try {
Template t = engine.createTemplate(templateUri,attrs.getServletContext(),request,response);
if(t == null) {
throw new ControllerExecutionException("Unable to load template for uri ["+templateUri+"]. Template not found.");
}
Map binding = new HashMap();
if(argMap.containsKey(ARGUMENT_BEAN)) {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, argMap.get(ARGUMENT_BEAN));
Writable w = t.make(binding);
w.writeTo(out);
}
else if(argMap.containsKey(ARGUMENT_COLLECTION)) {
Object colObject = argMap.get(ARGUMENT_COLLECTION);
if(colObject instanceof Collection) {
Collection c = (Collection) colObject;
for (Iterator i = c.iterator(); i.hasNext();) {
Object o = i.next();
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, o);
else
binding.put(var, o);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else {
if(StringUtils.isBlank(var))
binding.put(DEFAULT_ARGUMENT, argMap.get(ARGUMENT_BEAN));
else
binding.put(var, colObject);
Writable w = t.make(binding);
w.writeTo(out);
}
}
else if(argMap.containsKey(ARGUMENT_MODEL)) {
Object modelObject = argMap.get(ARGUMENT_MODEL);
if(modelObject instanceof Map) {
Writable w = t.make((Map)argMap.get(ARGUMENT_MODEL));
w.writeTo(out);
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
}
else {
Writable w = t.make(new BeanMap(target));
w.writeTo(out);
}
renderView = false;
}
catch(GroovyRuntimeException gre) {
throw new ControllerExecutionException("Error rendering template ["+templateName+"]: " + gre.getMessage(),gre);
}
catch(IOException ioex) {
throw new ControllerExecutionException("I/O error executing render method for arguments ["+argMap+"]: " + ioex.getMessage(),ioex);
} catch (ServletException e) {
throw new ControllerExecutionException("Servlet exception executing render method for arguments ["+argMap+"]: " + e.getMessage(),e);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
}
else {
throw new MissingMethodException(METHOD_SIGNATURE,target.getClass(),arguments);
}
if(controller!=null)
controller.setProperty(ControllerDynamicMethods.RENDER_VIEW_PROPERTY,Boolean.valueOf(renderView));
return null;
}
|
diff --git a/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java b/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java
index dd098a3..4884166 100644
--- a/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java
+++ b/EnrichmentAnalysisUI/src/org/mongkie/ui/enrichment/EnrichmentChooserTopComponent.java
@@ -1,479 +1,479 @@
/*
* This file is part of MONGKIE. Visit <http://www.mongkie.org/> for details.
* Copyright (C) 2011 Korean Bioinformation Center(KOBIC)
*
* MONGKIE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MONGKIE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mongkie.ui.enrichment;
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingUtilities;
import static kobic.prefuse.Constants.NODES;
import kobic.prefuse.display.DisplayListener;
import org.mongkie.enrichment.EnrichmentController;
import org.mongkie.enrichment.EnrichmentModel;
import org.mongkie.enrichment.EnrichmentModelListener;
import org.mongkie.enrichment.spi.Enrichment;
import org.mongkie.enrichment.spi.EnrichmentBuilder;
import static org.mongkie.visualization.Config.MODE_ACTION;
import static org.mongkie.visualization.Config.ROLE_NETWORK;
import org.mongkie.visualization.MongkieDisplay;
import org.mongkie.visualization.workspace.ModelChangeListener;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import prefuse.Visualization;
import prefuse.data.Graph;
import prefuse.data.Table;
import prefuse.data.Tuple;
import static prefuse.data.event.EventConstants.*;
import prefuse.data.event.TableListener;
/**
*
* @author Yeongjun Jang <[email protected]>
*/
@ConvertAsProperties(dtd = "-//org.mongkie.ui.enrichment//EnrichmentChooser//EN",
autostore = false)
@TopComponent.Description(preferredID = "EnrichmentChooserTopComponent",
iconBase = "org/mongkie/ui/enrichment/resources/enrichment.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS)
@TopComponent.Registration(mode = MODE_ACTION, openAtStartup = false, roles = ROLE_NETWORK, position = 400)
@ActionID(category = "Window", id = "org.mongkie.ui.enrichment.EnrichmentChooserTopComponent")
@ActionReference(path = "Menu/Window", position = 70)
@TopComponent.OpenActionRegistration(displayName = "#CTL_EnrichmentChooserAction",
preferredID = "EnrichmentChooserTopComponent")
public final class EnrichmentChooserTopComponent extends TopComponent
implements EnrichmentModelListener, DisplayListener<MongkieDisplay>, TableListener {
private static final String NO_SELECTION =
NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.choose.displayText");
private EnrichmentModel model;
public EnrichmentChooserTopComponent() {
initComponents();
settingsSeparator.setVisible(false);
setName(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "CTL_EnrichmentChooserTopComponent"));
setToolTipText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "HINT_EnrichmentChooserTopComponent"));
putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
initializeChooser();
addEventListeners();
Lookup.getDefault().lookup(EnrichmentController.class).fireModelChangeEvent();
}
private void initializeChooser() {
DefaultComboBoxModel enrichmentComboBoxModel = new DefaultComboBoxModel();
enrichmentComboBoxModel.addElement(NO_SELECTION);
enrichmentComboBoxModel.setSelectedItem(NO_SELECTION);
for (EnrichmentBuilder builder : Lookup.getDefault().lookupAll(EnrichmentBuilder.class)) {
enrichmentComboBoxModel.addElement(builder);
}
enrichmentComboBox.setModel(enrichmentComboBoxModel);
}
private void addEventListeners() {
Lookup.getDefault().lookup(EnrichmentController.class).addModelChangeListener(new ModelChangeListener<EnrichmentModel>() {
@Override
public void modelChanged(EnrichmentModel o, EnrichmentModel n) {
if (o != null) {
o.removeModelListener(EnrichmentChooserTopComponent.this);
o.getDisplay().removeDisplayListener(EnrichmentChooserTopComponent.this);
}
model = n;
if (model != null) {
model.addModelListener(EnrichmentChooserTopComponent.this);
model.getDisplay().addDisplayListener(EnrichmentChooserTopComponent.this);
}
refreshModel();
}
});
enrichmentComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (enrichmentComboBox.getSelectedItem().equals(NO_SELECTION)) {
if (model != null) {
setSelectedEnrichment(null);
}
settingsSeparator.setVisible(false);
settingsPanel.removeAll();
settingsPanel.revalidate();
settingsPanel.repaint();
} else if (enrichmentComboBox.getSelectedItem() instanceof EnrichmentBuilder) {
EnrichmentBuilder builder = (EnrichmentBuilder) enrichmentComboBox.getSelectedItem();
setSelectedEnrichment(builder);
settingsPanel.removeAll();
EnrichmentBuilder.SettingUI settings = builder.getSettingUI();
if (settings != null) {
settingsSeparator.setVisible(true);
settings.load(builder.getEnrichment());
settingsPanel.add(settings.getPanel(), BorderLayout.CENTER);
} else {
settingsSeparator.setVisible(false);
}
settingsPanel.revalidate();
settingsPanel.repaint();
}
}
});
geneIdColumnComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (model != null) {
Lookup.getDefault().lookup(EnrichmentController.class).setGeneIDColumn((String) e.getItem());
}
}
});
}
private void setSelectedEnrichment(EnrichmentBuilder builder) {
if (model.get() != null && model.get().getBuilder() == builder) {
return;
}
Lookup.getDefault().lookup(EnrichmentController.class).setEnrichment(builder != null ? builder.getEnrichment() : null);
}
private void refreshModel() {
refreshChooser();
refreshGeneIdColumnComboBox();
refreshEnabled();
refreshResult();
}
@Override
public void graphDisposing(MongkieDisplay d, Graph g) {
g.getNodeTable().removeTableListener(this);
}
@Override
public void graphChanged(MongkieDisplay d, Graph g) {
if (g != null) {
g.getNodeTable().addTableListener(this);
}
refreshGeneIdColumnComboBox();
}
@Override
public void tableChanged(Table t, int start, int end, int col, int type) {
if (col != ALL_COLUMNS && (type == INSERT || type == DELETE)) {
refreshGeneIdColumnComboBox();
}
}
private void refreshGeneIdColumnComboBox() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
geneIdColumnComboBox.removeAllItems();
if (model != null) {
Table nodeTable = model.getDisplay().getGraph().getNodeTable();
String geneIdCol = model.getGeneIDColumn();
for (int i = 0; i < nodeTable.getColumnCount(); i++) {
if (nodeTable.getColumn(i).canGetString()) {
geneIdColumnComboBox.addItem(nodeTable.getColumnName(i));
}
}
geneIdColumnComboBox.setSelectedItem(
model.get() == null || nodeTable.getColumnNumber(geneIdCol) < 0 ? null : geneIdCol);
}
}
});
}
private void refreshChooser() {
Enrichment en = model != null ? model.get() : null;
enrichmentComboBox.getModel().setSelectedItem(en != null ? en.getBuilder() : NO_SELECTION);
}
private void refreshEnabled() {
if (model == null || !model.isRunning()) {
runButton.setText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text"));
runButton.setIcon(ImageUtilities.loadImageIcon("org/mongkie/ui/enrichment/resources/run.gif", false));
runButton.setToolTipText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.toolTipText"));
} else if (model.isRunning()) {
runButton.setText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.cancelButton.text"));
runButton.setIcon(ImageUtilities.loadImageIcon("org/mongkie/ui/enrichment/resources/stop.png", false));
runButton.setToolTipText(NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.cancelButton.toolTipText"));
}
boolean enabled = model != null && model.get() != null && model.getDisplay().isFired();
runButton.setEnabled(enabled);
infoLabel.setEnabled(enabled);
wholeNetworkButton.setEnabled(enabled && !model.isRunning());
fromSelectionButton.setEnabled(enabled && !model.isRunning());
geneIdColumnComboBox.setEnabled(enabled && !model.isRunning());
EnrichmentBuilder.SettingUI settings = enabled ? model.get().getBuilder().getSettingUI() : null;
if (settings != null) {
settings.setEnabled(!model.isRunning());
}
enrichmentComboBox.setEnabled(model != null && !model.isRunning() && model.getDisplay().isFired());
}
private void refreshResult() {
EnrichmentResultTopComponent resultDisplayer = EnrichmentResultTopComponent.getInstance();
if (model == null || model.getDisplay().getGraph().getNodeCount() < 1) {
resultDisplayer.setResult(null);
} else if (model.isRunning()) {
resultDisplayer.setBusy(true);
} else {
resultDisplayer.setResult(model.getResult());
}
}
private void run() {
Enrichment en = model.get();
EnrichmentBuilder.SettingUI settings = en.getBuilder().getSettingUI();
if (settings != null) {
settings.apply(en);
}
Object geneIdCol = model.getGeneIDColumn();
if (geneIdCol == null) {
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message("Select a ID column of query genes.", NotifyDescriptor.ERROR_MESSAGE));
return;
}
Lookup.getDefault().lookup(EnrichmentController.class).analyze(getGeneIdsFromSelectedColumn());
}
private String[] getGeneIdsFromSelectedColumn() {
Set<String> genes = new HashSet<String>();
// for (Iterator<Tuple> nodeIter = model.getDisplay().getGraph().getNodeTable().tuples(); nodeIter.hasNext();) {
for (Iterator<Tuple> nodeIter = fromSelectionButton.isSelected()
? model.getDisplay().getVisualization().getFocusGroup(Visualization.FOCUS_ITEMS).tuples()
: model.getDisplay().getVisualization().items(NODES);
nodeIter.hasNext();) {
String gene = nodeIter.next().getString(model.getGeneIDColumn());
if (gene == null || (gene = gene.trim()).isEmpty()) {
continue;
}
genes.add(gene);
}
return genes.toArray(new String[genes.size()]);
}
private void cancel() {
Lookup.getDefault().lookup(EnrichmentController.class).cancelAnalyzing();
}
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
selectionButtonGroup = new javax.swing.ButtonGroup();
enrichmentComboBox = new javax.swing.JComboBox();
infoLabel = new javax.swing.JLabel();
selectionSeparator = new org.jdesktop.swingx.JXTitledSeparator();
wholeNetworkButton = new javax.swing.JRadioButton();
fromSelectionButton = new javax.swing.JRadioButton();
settingsSeparator = new org.jdesktop.swingx.JXTitledSeparator();
runButton = new javax.swing.JButton();
settingsPanel = new javax.swing.JPanel();
geneIdColumnLabel = new javax.swing.JLabel();
geneIdColumnComboBox = new javax.swing.JComboBox();
selectionButtonGroup.add(wholeNetworkButton);
selectionButtonGroup.add(fromSelectionButton);
setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 3, 2, 4));
enrichmentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene Ontology", "Pathway (KoPath)" }));
infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/information.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(infoLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.infoLabel.text")); // NOI18N
selectionSeparator.setEnabled(false);
selectionSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/light-bulb.png"))); // NOI18N
selectionSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.selectionSeparator.title")); // NOI18N
wholeNetworkButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(wholeNetworkButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.wholeNetworkButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(fromSelectionButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.fromSelectionButton.text")); // NOI18N
settingsSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/settings.png"))); // NOI18N
settingsSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.settingsSeparator.title")); // NOI18N
runButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/run.gif"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(runButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text")); // NOI18N
runButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runButtonActionPerformed(evt);
}
});
settingsPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 16, 2, 4));
settingsPanel.setLayout(new java.awt.BorderLayout());
org.openide.awt.Mnemonics.setLocalizedText(geneIdColumnLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.geneIdColumnLabel.text")); // NOI18N
geneIdColumnComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene ID" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(settingsSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(selectionSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(enrichmentComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(8, 8, 8)
.addComponent(infoLabel)
- .addGap(6, 6, 6))
+ .addGap(2, 2, 2))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(runButton, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(geneIdColumnLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(geneIdColumnComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(wholeNetworkButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fromSelectionButton)))
.addContainerGap(20, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(infoLabel)
.addComponent(enrichmentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(selectionSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(wholeNetworkButton)
.addComponent(fromSelectionButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(geneIdColumnLabel)
.addComponent(geneIdColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(settingsSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(runButton))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {selectionSeparator, settingsSeparator});
}// </editor-fold>//GEN-END:initComponents
private void runButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runButtonActionPerformed
if (model.isRunning()) {
cancel();
} else {
run();
}
}//GEN-LAST:event_runButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JComboBox enrichmentComboBox;
private javax.swing.JRadioButton fromSelectionButton;
private javax.swing.JComboBox geneIdColumnComboBox;
private javax.swing.JLabel geneIdColumnLabel;
private javax.swing.JLabel infoLabel;
private javax.swing.JButton runButton;
private javax.swing.ButtonGroup selectionButtonGroup;
private org.jdesktop.swingx.JXTitledSeparator selectionSeparator;
private javax.swing.JPanel settingsPanel;
private org.jdesktop.swingx.JXTitledSeparator settingsSeparator;
private javax.swing.JRadioButton wholeNetworkButton;
// End of variables declaration//GEN-END:variables
@Override
public void componentOpened() {
// TODO add custom code on component opening
}
@Override
public void componentClosed() {
// TODO add custom code on component closing
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// TODO store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// TODO read your settings according to their version
}
@Override
public void analyzingStarted(Enrichment en) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
EnrichmentResultTopComponent resultDisplayer = EnrichmentResultTopComponent.getInstance();
Lookup.getDefault().lookup(EnrichmentController.class).clearResult();
resultDisplayer.setLookupContents();
resultDisplayer.setBusy(true);
resultDisplayer.open();
resultDisplayer.requestActive();
refreshEnabled();
}
});
}
@Override
public void analyzingFinished(final Enrichment en) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
EnrichmentResultTopComponent resultDisplayer = EnrichmentResultTopComponent.getInstance();
resultDisplayer.setResult(model.getResult(en));
resultDisplayer.open();
resultDisplayer.requestActive();
refreshEnabled();
}
});
}
@Override
public void enrichmentChanged(Enrichment oe, Enrichment ne) {
refreshModel();
}
}
| true | true | private void initComponents() {
selectionButtonGroup = new javax.swing.ButtonGroup();
enrichmentComboBox = new javax.swing.JComboBox();
infoLabel = new javax.swing.JLabel();
selectionSeparator = new org.jdesktop.swingx.JXTitledSeparator();
wholeNetworkButton = new javax.swing.JRadioButton();
fromSelectionButton = new javax.swing.JRadioButton();
settingsSeparator = new org.jdesktop.swingx.JXTitledSeparator();
runButton = new javax.swing.JButton();
settingsPanel = new javax.swing.JPanel();
geneIdColumnLabel = new javax.swing.JLabel();
geneIdColumnComboBox = new javax.swing.JComboBox();
selectionButtonGroup.add(wholeNetworkButton);
selectionButtonGroup.add(fromSelectionButton);
setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 3, 2, 4));
enrichmentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene Ontology", "Pathway (KoPath)" }));
infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/information.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(infoLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.infoLabel.text")); // NOI18N
selectionSeparator.setEnabled(false);
selectionSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/light-bulb.png"))); // NOI18N
selectionSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.selectionSeparator.title")); // NOI18N
wholeNetworkButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(wholeNetworkButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.wholeNetworkButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(fromSelectionButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.fromSelectionButton.text")); // NOI18N
settingsSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/settings.png"))); // NOI18N
settingsSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.settingsSeparator.title")); // NOI18N
runButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/run.gif"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(runButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text")); // NOI18N
runButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runButtonActionPerformed(evt);
}
});
settingsPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 16, 2, 4));
settingsPanel.setLayout(new java.awt.BorderLayout());
org.openide.awt.Mnemonics.setLocalizedText(geneIdColumnLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.geneIdColumnLabel.text")); // NOI18N
geneIdColumnComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene ID" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(settingsSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(selectionSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(enrichmentComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(8, 8, 8)
.addComponent(infoLabel)
.addGap(6, 6, 6))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(runButton, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(geneIdColumnLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(geneIdColumnComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(wholeNetworkButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fromSelectionButton)))
.addContainerGap(20, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(infoLabel)
.addComponent(enrichmentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(selectionSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(wholeNetworkButton)
.addComponent(fromSelectionButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(geneIdColumnLabel)
.addComponent(geneIdColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(settingsSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(runButton))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {selectionSeparator, settingsSeparator});
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
selectionButtonGroup = new javax.swing.ButtonGroup();
enrichmentComboBox = new javax.swing.JComboBox();
infoLabel = new javax.swing.JLabel();
selectionSeparator = new org.jdesktop.swingx.JXTitledSeparator();
wholeNetworkButton = new javax.swing.JRadioButton();
fromSelectionButton = new javax.swing.JRadioButton();
settingsSeparator = new org.jdesktop.swingx.JXTitledSeparator();
runButton = new javax.swing.JButton();
settingsPanel = new javax.swing.JPanel();
geneIdColumnLabel = new javax.swing.JLabel();
geneIdColumnComboBox = new javax.swing.JComboBox();
selectionButtonGroup.add(wholeNetworkButton);
selectionButtonGroup.add(fromSelectionButton);
setBorder(javax.swing.BorderFactory.createEmptyBorder(6, 3, 2, 4));
enrichmentComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene Ontology", "Pathway (KoPath)" }));
infoLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/information.png"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(infoLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.infoLabel.text")); // NOI18N
selectionSeparator.setEnabled(false);
selectionSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/light-bulb.png"))); // NOI18N
selectionSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.selectionSeparator.title")); // NOI18N
wholeNetworkButton.setSelected(true);
org.openide.awt.Mnemonics.setLocalizedText(wholeNetworkButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.wholeNetworkButton.text")); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(fromSelectionButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.fromSelectionButton.text")); // NOI18N
settingsSeparator.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/settings.png"))); // NOI18N
settingsSeparator.setTitle(org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.settingsSeparator.title")); // NOI18N
runButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/mongkie/ui/enrichment/resources/run.gif"))); // NOI18N
org.openide.awt.Mnemonics.setLocalizedText(runButton, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.runButton.text")); // NOI18N
runButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
runButtonActionPerformed(evt);
}
});
settingsPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 16, 2, 4));
settingsPanel.setLayout(new java.awt.BorderLayout());
org.openide.awt.Mnemonics.setLocalizedText(geneIdColumnLabel, org.openide.util.NbBundle.getMessage(EnrichmentChooserTopComponent.class, "EnrichmentChooserTopComponent.geneIdColumnLabel.text")); // NOI18N
geneIdColumnComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Gene ID" }));
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(settingsPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(settingsSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(selectionSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(enrichmentComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(8, 8, 8)
.addComponent(infoLabel)
.addGap(2, 2, 2))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(runButton, javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(geneIdColumnLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(geneIdColumnComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addComponent(wholeNetworkButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(fromSelectionButton)))
.addContainerGap(20, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
.addComponent(infoLabel)
.addComponent(enrichmentComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(selectionSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(wholeNetworkButton)
.addComponent(fromSelectionButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(geneIdColumnLabel)
.addComponent(geneIdColumnComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(settingsSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(settingsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(runButton))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {selectionSeparator, settingsSeparator});
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/vehicleShepard/VehicleDB.java b/src/vehicleShepard/VehicleDB.java
index a492336..bd51b93 100644
--- a/src/vehicleShepard/VehicleDB.java
+++ b/src/vehicleShepard/VehicleDB.java
@@ -1,336 +1,336 @@
package vehicleShepard;
/*
* This class is controlling the methods containing
* methods using our database
* This implies:
* making a new vehicle
* getting a vehicle by its ID
* getting a list of vehicles
* getting a list of vehicles (after search)
*/
import java.sql.*;
public class VehicleDB
{
////////////
//VEHICLES//
////////////
/**
* This method creates a new vehicle in our database
* This happens by the help of an array
* @param info
*/
public void newVehicle(Object[] info)
{
int vehicleID = getNumberOfVehicles() + 1;
//We connect to our database
Connection conn = ConnectDB.initConn();
Statement s;
//We insert the needed data into our database
try
{
s = conn.createStatement();
try
{
s.executeUpdate("INSERT INTO Vehicle (`vehicleID`, `make`, `model`, `odometer`, `fuel`, `automatic`, `statusID`, `typeID`) VALUES ('" + vehicleID + "', '" + info[0] + "', '" + info[1] + "', '" + info[2] + "', '" + info[3] + "', '" + info[4] + "', '" + info[5] + "', '" + info[6] + "')");
s.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (SQLException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
finally
{
//Close the connection
ConnectDB.closeConn(conn);
}
}
/**
* This method finds a vehicle, from the given name
* @param vehicleID
* @return vehicle
*/
public Object[] getVehicleByID(int vehicleID) //TODO We should see, if this method should return String[], String[][] or an object of type User(something something).
{
Object[] vehicle = new Object[8];
//We connect to our database
Connection conn = ConnectDB.initConn();
Statement s;
try
{
s = conn.createStatement();
s.executeQuery("SELECT vehicleID FROM Vehicle WHERE vehicleID = " + vehicleID + "");
ResultSet rs = s.getResultSet();
while(rs.next())
{
vehicle[0] = rs.getString("vehicleID");
vehicle[1] = rs.getString("make");
vehicle[2] = rs.getString("model");
vehicle[3] = rs.getInt("odumeter");
vehicle[4] = rs.getInt("fuel");
vehicle[5] = rs.getInt("automatic");
vehicle[6] = rs.getInt("statusID");
vehicle[7] = rs.getInt("typeID");
}
s.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//Close the connection
ConnectDB.closeConn(conn);
}
return vehicle;
}
/**
*
* @return
*/
private int getNumberOfVehicles()
{
int count = 0;
//We connect to our database
Connection conn = ConnectDB.initConn();
try
{
Statement s = conn.createStatement();
s.executeQuery("SELECT vehicleID FROM Vehicle");
ResultSet rs = s.getResultSet();
while(rs.next())
{
count++;
}
s.close();
System.out.println("count: " + count);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//Close the connection
ConnectDB.closeConn(conn);
}
return count;
}
/**
*
* @return
*/
public Object[][] getList()
{
int number = getNumberOfVehicles();
int count = 0;
//We want a list of customers in a 2D Array
Object[][] vehicleList = new Object[number][8];
//We connect to our database
Connection conn = ConnectDB.initConn();
try
{
Statement s = conn.createStatement();
- s.executeQuery("SELECT * FROM Customer");
+ s.executeQuery("SELECT * FROM Vehicle");
ResultSet rs = s.getResultSet();
while(rs.next())
{
vehicleList[count][0] = rs.getString("vehicleID");
vehicleList[count][1] = rs.getString("make");
vehicleList[count][2] = rs.getString("model");
vehicleList[count][3] = rs.getInt("odumeter");
vehicleList[count][4] = rs.getInt("fuel");
vehicleList[count][5] = rs.getInt("automatic");
vehicleList[count][6] = rs.getInt("statusID");
vehicleList[count][7] = rs.getInt("typeID");
count++;
}
s.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//Close the connection
ConnectDB.closeConn(conn);
}
return vehicleList;
}
/**
*
* @param searchString
* @return vehicles
*/
public Object[][] getVehicles(String searchString)
{
String searchTerm = searchString.toLowerCase().trim();
Object[][] vehicleList = getList();
int number = getNumberOfVehicles();
Object[][] vehicles = Search.stringSearch(searchTerm, vehicleList, number, 8); //TODO No variable called users created... This should be created at the start of this method
//stringSearch(searchTerm, getList(), number, 7);
return vehicles;
}
////////////////
//VEHICLETYPES//
////////////////
private int getNumberOfVehicleTypes()
{
int count = 0;
Connection conn = ConnectDB.initConn();
try
{
Statement s = conn.createStatement();
s.executeQuery("SELECT vehicleTypeID FROM VehicleType");
ResultSet rs = s.getResultSet();
while(rs.next())
{
count++;
}
s.close();
System.out.println("count: " + count);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
ConnectDB.closeConn(conn);
}
return count;
}
/**
* Returns the names of all vehicle types in an array of strings
* @return vehTypeNames The names of all vehicle types in an array of strings
*/
public String[] getVehicleTypeNames()
{
int count = 0;
int number = getNumberOfVehicleTypes();
String[] vehTypeNames = new String[number];
Connection conn = ConnectDB.initConn();
try
{
Statement s = conn.createStatement();
s.executeQuery("SELECT name FROM VehicleType ORDER BY vehicleTypeID");
ResultSet rs = s.getResultSet();
while(rs.next())
{
vehTypeNames[count] = rs.getString("name");
count++;
}
s.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
ConnectDB.closeConn(conn);
}
return vehTypeNames;
}
/**
* Returns the price rates of all vehicle types in an array of ints
* @return vehTypePrices The price rates of all vehicle types in an array of ints
*/
public int[] getVehicleTypePrices()
{
int count = 0;
int number = getNumberOfVehicleTypes();
int[] vehTypePrices = new int[number];
Connection conn = ConnectDB.initConn();
try
{
Statement s = conn.createStatement();
s.executeQuery("SELECT priceRate FROM VehicleType ORDER BY vehicleTypeID");
ResultSet rs = s.getResultSet();
while(rs.next())
{
vehTypePrices[count] = rs.getInt("priceRate");
count++;
}
s.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
finally
{
ConnectDB.closeConn(conn);
}
return vehTypePrices;
}
}
| true | true | public Object[][] getList()
{
int number = getNumberOfVehicles();
int count = 0;
//We want a list of customers in a 2D Array
Object[][] vehicleList = new Object[number][8];
//We connect to our database
Connection conn = ConnectDB.initConn();
try
{
Statement s = conn.createStatement();
s.executeQuery("SELECT * FROM Customer");
ResultSet rs = s.getResultSet();
while(rs.next())
{
vehicleList[count][0] = rs.getString("vehicleID");
vehicleList[count][1] = rs.getString("make");
vehicleList[count][2] = rs.getString("model");
vehicleList[count][3] = rs.getInt("odumeter");
vehicleList[count][4] = rs.getInt("fuel");
vehicleList[count][5] = rs.getInt("automatic");
vehicleList[count][6] = rs.getInt("statusID");
vehicleList[count][7] = rs.getInt("typeID");
count++;
}
s.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//Close the connection
ConnectDB.closeConn(conn);
}
return vehicleList;
}
| public Object[][] getList()
{
int number = getNumberOfVehicles();
int count = 0;
//We want a list of customers in a 2D Array
Object[][] vehicleList = new Object[number][8];
//We connect to our database
Connection conn = ConnectDB.initConn();
try
{
Statement s = conn.createStatement();
s.executeQuery("SELECT * FROM Vehicle");
ResultSet rs = s.getResultSet();
while(rs.next())
{
vehicleList[count][0] = rs.getString("vehicleID");
vehicleList[count][1] = rs.getString("make");
vehicleList[count][2] = rs.getString("model");
vehicleList[count][3] = rs.getInt("odumeter");
vehicleList[count][4] = rs.getInt("fuel");
vehicleList[count][5] = rs.getInt("automatic");
vehicleList[count][6] = rs.getInt("statusID");
vehicleList[count][7] = rs.getInt("typeID");
count++;
}
s.close();
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
//Close the connection
ConnectDB.closeConn(conn);
}
return vehicleList;
}
|
diff --git a/user/test/com/google/gwt/i18n/client/I18N_nb_Test.java b/user/test/com/google/gwt/i18n/client/I18N_nb_Test.java
index ede08e82f..88da5d9de 100644
--- a/user/test/com/google/gwt/i18n/client/I18N_nb_Test.java
+++ b/user/test/com/google/gwt/i18n/client/I18N_nb_Test.java
@@ -1,69 +1,69 @@
/*
* Copyright 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.i18n.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.junit.client.GWTTestCase;
/**
* Tests the Norwegian Bokmal locale.
*/
public class I18N_nb_Test extends GWTTestCase {
/**
* Test deprecated locale aliases with Messages.
*/
public interface MyMessages extends Messages {
@DefaultMessage("default")
String nbLocale();
@DefaultMessage("default")
String noBokmalLocale();
@DefaultMessage("default")
String noLocale();
}
@Override
public String getModuleName() {
return "com.google.gwt.i18n.I18NTest_nb";
}
/**
* Test alias resolution.
*/
public void testAliases() {
MyMessages msg = GWT.create(MyMessages.class);
assertEquals("nb", msg.nbLocale());
assertEquals("no_BOKMAL", msg.noBokmalLocale());
assertEquals("no", msg.noLocale());
}
/**
* Test currency codes.
*/
public void testCurrency() {
CurrencyList currencyList = CurrencyList.get();
CurrencyData currencyData = currencyList.getDefault();
assertNotNull(currencyData);
assertEquals("NOK", currencyData.getCurrencyCode());
assertEquals("kr", currencyData.getCurrencySymbol());
currencyData = currencyList.lookup("RUB");
assertNotNull(currencyData);
assertEquals("RUB", currencyData.getCurrencyCode());
- assertEquals("руб", currencyData.getCurrencySymbol());
+ assertEquals("руб.", currencyData.getCurrencySymbol());
}
}
| true | true | public void testCurrency() {
CurrencyList currencyList = CurrencyList.get();
CurrencyData currencyData = currencyList.getDefault();
assertNotNull(currencyData);
assertEquals("NOK", currencyData.getCurrencyCode());
assertEquals("kr", currencyData.getCurrencySymbol());
currencyData = currencyList.lookup("RUB");
assertNotNull(currencyData);
assertEquals("RUB", currencyData.getCurrencyCode());
assertEquals("руб", currencyData.getCurrencySymbol());
}
| public void testCurrency() {
CurrencyList currencyList = CurrencyList.get();
CurrencyData currencyData = currencyList.getDefault();
assertNotNull(currencyData);
assertEquals("NOK", currencyData.getCurrencyCode());
assertEquals("kr", currencyData.getCurrencySymbol());
currencyData = currencyList.lookup("RUB");
assertNotNull(currencyData);
assertEquals("RUB", currencyData.getCurrencyCode());
assertEquals("руб.", currencyData.getCurrencySymbol());
}
|
diff --git a/tests/src/com/fsck/k9/mail/internet/ViewablesTest.java b/tests/src/com/fsck/k9/mail/internet/ViewablesTest.java
index 5ba6fa8c..c6af4639 100644
--- a/tests/src/com/fsck/k9/mail/internet/ViewablesTest.java
+++ b/tests/src/com/fsck/k9/mail/internet/ViewablesTest.java
@@ -1,188 +1,188 @@
package com.fsck.k9.mail.internet;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import android.test.AndroidTestCase;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.Message.RecipientType;
import com.fsck.k9.mail.internet.MimeUtility.ViewableContainer;
public class ViewablesTest extends AndroidTestCase {
public void testSimplePlainTextMessage() throws MessagingException {
String bodyText = "K-9 Mail rocks :>";
// Create text/plain body
TextBody body = new TextBody(bodyText);
// Create message
MimeMessage message = new MimeMessage();
message.setBody(body);
// Extract text
ViewableContainer container = MimeUtility.extractTextAndAttachments(getContext(), message);
String expectedText = bodyText;
String expectedHtml =
"<html><head/><body>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
"K-9 Mail rocks :>" +
"</pre>" +
"</body></html>";
assertEquals(expectedText, container.text);
assertEquals(expectedHtml, container.html);
}
public void testSimpleHtmlMessage() throws MessagingException {
String bodyText = "<strong>K-9 Mail</strong> rocks :>";
// Create text/plain body
TextBody body = new TextBody(bodyText);
// Create message
MimeMessage message = new MimeMessage();
message.setHeader("Content-Type", "text/html");
message.setBody(body);
// Extract text
ViewableContainer container = MimeUtility.extractTextAndAttachments(getContext(), message);
String expectedText = "K-9 Mail rocks :>";
String expectedHtml =
"<html><head/><body>" +
bodyText +
"</body></html>";
assertEquals(expectedText, container.text);
assertEquals(expectedHtml, container.html);
}
public void testMultipartPlainTextMessage() throws MessagingException {
String bodyText1 = "text body 1";
String bodyText2 = "text body 2";
// Create text/plain bodies
TextBody body1 = new TextBody(bodyText1);
TextBody body2 = new TextBody(bodyText2);
// Create multipart/mixed part
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart bodyPart1 = new MimeBodyPart(body1, "text/plain");
MimeBodyPart bodyPart2 = new MimeBodyPart(body2, "text/plain");
multipart.addBodyPart(bodyPart1);
multipart.addBodyPart(bodyPart2);
// Create message
MimeMessage message = new MimeMessage();
message.setBody(multipart);
// Extract text
ViewableContainer container = MimeUtility.extractTextAndAttachments(getContext(), message);
String expectedText =
bodyText1 + "\n\n" +
"------------------------------------------------------------------------\n\n" +
bodyText2;
String expectedHtml =
"<html><head/><body>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
bodyText1 +
"</pre>" +
"<p style=\"margin-top: 2.5em; margin-bottom: 1em; " +
"border-bottom: 1px solid #000\"></p>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
bodyText2 +
"</pre>" +
"</body></html>";
assertEquals(expectedText, container.text);
assertEquals(expectedHtml, container.html);
}
public void testTextPlusRfc822Message() throws MessagingException {
Locale.setDefault(Locale.US);
- TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
String bodyText = "Some text here";
String innerBodyText = "Hey there. I'm inside a message/rfc822 (inline) attachment.";
// Create text/plain body
TextBody textBody = new TextBody(bodyText);
// Create inner text/plain body
TextBody innerBody = new TextBody(innerBodyText);
// Create message/rfc822 body
MimeMessage innerMessage = new MimeMessage();
innerMessage.addSentDate(new Date(112, 02, 17));
innerMessage.setRecipients(RecipientType.TO, new Address[] { new Address("[email protected]") });
innerMessage.setSubject("Subject");
innerMessage.setFrom(new Address("[email protected]"));
innerMessage.setBody(innerBody);
// Create multipart/mixed part
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart bodyPart1 = new MimeBodyPart(textBody, "text/plain");
MimeBodyPart bodyPart2 = new MimeBodyPart(innerMessage, "message/rfc822");
bodyPart2.setHeader("Content-Disposition", "inline; filename=\"message.eml\"");
multipart.addBodyPart(bodyPart1);
multipart.addBodyPart(bodyPart2);
// Create message
MimeMessage message = new MimeMessage();
message.setBody(multipart);
// Extract text
ViewableContainer container = MimeUtility.extractTextAndAttachments(getContext(), message);
String expectedText =
bodyText +
"\n\n" +
"----- message.eml ------------------------------------------------------" +
"\n\n" +
"From: [email protected]" + "\n" +
"To: [email protected]" + "\n" +
"Sent: Sat Mar 17 00:00:00 GMT+00:00 2012" + "\n" +
"Subject: Subject" + "\n" +
"\n" +
innerBodyText;
String expectedHtml =
"<html><head/><body>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
bodyText +
"</pre>" +
"<p style=\"margin-top: 2.5em; margin-bottom: 1em; border-bottom: " +
"1px solid #000\">message.eml</p>" +
"<table style=\"border: 0\">" +
"<tr>" +
"<th style=\"text-align: left; vertical-align: top;\">From:</th>" +
"<td>[email protected]</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">To:</th>" +
"<td>[email protected]</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">Sent:</th>" +
"<td>Sat Mar 17 00:00:00 GMT+00:00 2012</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">Subject:</th>" +
"<td>Subject</td>" +
"</tr>" +
"</table>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
innerBodyText +
"</pre>" +
"</body></html>";
assertEquals(expectedText, container.text);
assertEquals(expectedHtml, container.html);
}
}
| true | true | public void testTextPlusRfc822Message() throws MessagingException {
Locale.setDefault(Locale.US);
TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
String bodyText = "Some text here";
String innerBodyText = "Hey there. I'm inside a message/rfc822 (inline) attachment.";
// Create text/plain body
TextBody textBody = new TextBody(bodyText);
// Create inner text/plain body
TextBody innerBody = new TextBody(innerBodyText);
// Create message/rfc822 body
MimeMessage innerMessage = new MimeMessage();
innerMessage.addSentDate(new Date(112, 02, 17));
innerMessage.setRecipients(RecipientType.TO, new Address[] { new Address("[email protected]") });
innerMessage.setSubject("Subject");
innerMessage.setFrom(new Address("[email protected]"));
innerMessage.setBody(innerBody);
// Create multipart/mixed part
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart bodyPart1 = new MimeBodyPart(textBody, "text/plain");
MimeBodyPart bodyPart2 = new MimeBodyPart(innerMessage, "message/rfc822");
bodyPart2.setHeader("Content-Disposition", "inline; filename=\"message.eml\"");
multipart.addBodyPart(bodyPart1);
multipart.addBodyPart(bodyPart2);
// Create message
MimeMessage message = new MimeMessage();
message.setBody(multipart);
// Extract text
ViewableContainer container = MimeUtility.extractTextAndAttachments(getContext(), message);
String expectedText =
bodyText +
"\n\n" +
"----- message.eml ------------------------------------------------------" +
"\n\n" +
"From: [email protected]" + "\n" +
"To: [email protected]" + "\n" +
"Sent: Sat Mar 17 00:00:00 GMT+00:00 2012" + "\n" +
"Subject: Subject" + "\n" +
"\n" +
innerBodyText;
String expectedHtml =
"<html><head/><body>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
bodyText +
"</pre>" +
"<p style=\"margin-top: 2.5em; margin-bottom: 1em; border-bottom: " +
"1px solid #000\">message.eml</p>" +
"<table style=\"border: 0\">" +
"<tr>" +
"<th style=\"text-align: left; vertical-align: top;\">From:</th>" +
"<td>[email protected]</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">To:</th>" +
"<td>[email protected]</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">Sent:</th>" +
"<td>Sat Mar 17 00:00:00 GMT+00:00 2012</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">Subject:</th>" +
"<td>Subject</td>" +
"</tr>" +
"</table>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
innerBodyText +
"</pre>" +
"</body></html>";
assertEquals(expectedText, container.text);
assertEquals(expectedHtml, container.html);
}
| public void testTextPlusRfc822Message() throws MessagingException {
Locale.setDefault(Locale.US);
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
String bodyText = "Some text here";
String innerBodyText = "Hey there. I'm inside a message/rfc822 (inline) attachment.";
// Create text/plain body
TextBody textBody = new TextBody(bodyText);
// Create inner text/plain body
TextBody innerBody = new TextBody(innerBodyText);
// Create message/rfc822 body
MimeMessage innerMessage = new MimeMessage();
innerMessage.addSentDate(new Date(112, 02, 17));
innerMessage.setRecipients(RecipientType.TO, new Address[] { new Address("[email protected]") });
innerMessage.setSubject("Subject");
innerMessage.setFrom(new Address("[email protected]"));
innerMessage.setBody(innerBody);
// Create multipart/mixed part
MimeMultipart multipart = new MimeMultipart();
MimeBodyPart bodyPart1 = new MimeBodyPart(textBody, "text/plain");
MimeBodyPart bodyPart2 = new MimeBodyPart(innerMessage, "message/rfc822");
bodyPart2.setHeader("Content-Disposition", "inline; filename=\"message.eml\"");
multipart.addBodyPart(bodyPart1);
multipart.addBodyPart(bodyPart2);
// Create message
MimeMessage message = new MimeMessage();
message.setBody(multipart);
// Extract text
ViewableContainer container = MimeUtility.extractTextAndAttachments(getContext(), message);
String expectedText =
bodyText +
"\n\n" +
"----- message.eml ------------------------------------------------------" +
"\n\n" +
"From: [email protected]" + "\n" +
"To: [email protected]" + "\n" +
"Sent: Sat Mar 17 00:00:00 GMT+00:00 2012" + "\n" +
"Subject: Subject" + "\n" +
"\n" +
innerBodyText;
String expectedHtml =
"<html><head/><body>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
bodyText +
"</pre>" +
"<p style=\"margin-top: 2.5em; margin-bottom: 1em; border-bottom: " +
"1px solid #000\">message.eml</p>" +
"<table style=\"border: 0\">" +
"<tr>" +
"<th style=\"text-align: left; vertical-align: top;\">From:</th>" +
"<td>[email protected]</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">To:</th>" +
"<td>[email protected]</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">Sent:</th>" +
"<td>Sat Mar 17 00:00:00 GMT+00:00 2012</td>" +
"</tr><tr>" +
"<th style=\"text-align: left; vertical-align: top;\">Subject:</th>" +
"<td>Subject</td>" +
"</tr>" +
"</table>" +
"<pre style=\"white-space: pre-wrap; word-wrap:break-word; " +
"font-family: sans-serif; margin-top: 0px\">" +
innerBodyText +
"</pre>" +
"</body></html>";
assertEquals(expectedText, container.text);
assertEquals(expectedHtml, container.html);
}
|
diff --git a/sahi/src/com/redhat/qe/jon/sahi/tests/PluginsTest.java b/sahi/src/com/redhat/qe/jon/sahi/tests/PluginsTest.java
index 381f3801..eefeca99 100644
--- a/sahi/src/com/redhat/qe/jon/sahi/tests/PluginsTest.java
+++ b/sahi/src/com/redhat/qe/jon/sahi/tests/PluginsTest.java
@@ -1,110 +1,111 @@
package com.redhat.qe.jon.sahi.tests;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.redhat.qe.auto.testng.Assert;
import com.redhat.qe.auto.testng.TestNGUtils;
import com.redhat.qe.jon.sahi.base.SahiTestScript;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class PluginsTest extends SahiTestScript {
//exact list of req'd plugins being provided by development
//*************************************
//* Agent Plugins validation
//*************************************
@Test (groups="PluginsTest", dataProvider="agentPluginsData")
public void validateAgentPlugins(String agentPluginsName, boolean pageRedirection){
Assert.assertTrue(sahiTasks.getAgentServerPluginsStaus(agentPluginsName, pageRedirection, true), "Agent Plugins '"+agentPluginsName+"' status");
}
//*************************************
//* Server Plugins validation
//*************************************
@Test (groups="PluginsTest", dataProvider="serverPluginsData")
public void validateServerPlugins(String serverPluginsName, boolean pageRedirection){
Assert.assertTrue(sahiTasks.getAgentServerPluginsStaus(serverPluginsName, pageRedirection, false), "Server Plugins '"+serverPluginsName+"' status");
}
@DataProvider(name="agentPluginsData")
public Object[][] getAgentPluginsData() {
ArrayList<List<Object>> agentPluginsdata = new ArrayList<List<Object>>();
agentPluginsdata.add(Arrays.asList(new Object[]{"Abstract Augeas Plugin", true}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Abstract Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Aliases", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Ant Bundle Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Apache HTTP Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Cobbler", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Cron", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"File Template Bundle Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Generic JMX", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"GRUB Boot Loader", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hibernate Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hosts", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hudson", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"IIS", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server", false}));
- agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 5.x", false}));
+// agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 5.x", false}));
+ agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 5.x/6.x", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 7.x", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBossCache 2.x Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBossCache 3.x Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"mod_cluster", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"MySql Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Network Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"OpenSSH", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Operating System Platforms", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Oracle Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Performance Test Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Postfix", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"PostgreSQL Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Receiver for SNMP Traps", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"RHQ Agent", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"RHQ Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Samba", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Script", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Sudo Access", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Tomcat Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Twitter Plugin", false}));
return TestNGUtils.convertListOfListsTo2dArray(agentPluginsdata);
}
@DataProvider(name="serverPluginsData")
public Object[][] getServerPluginsData() {
ArrayList<List<Object>> serverPluginsdata = new ArrayList<List<Object>>();
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:CLI", true}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:Email", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:IRC", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:Microblog", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:Mobicents", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:Operations", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:Roles", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:SNMP", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Alert:Subject", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Ant Bundle Processor", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Disk Content", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Drift:JPA (RHQ default)", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"File Template Bundle Processor", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"PackageType:CLI", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Perspective:Core", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"URL Content", false}));
serverPluginsdata.add(Arrays.asList(new Object[]{"Yum Content", false}));
return TestNGUtils.convertListOfListsTo2dArray(serverPluginsdata);
}
}
| true | true | public Object[][] getAgentPluginsData() {
ArrayList<List<Object>> agentPluginsdata = new ArrayList<List<Object>>();
agentPluginsdata.add(Arrays.asList(new Object[]{"Abstract Augeas Plugin", true}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Abstract Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Aliases", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Ant Bundle Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Apache HTTP Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Cobbler", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Cron", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"File Template Bundle Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Generic JMX", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"GRUB Boot Loader", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hibernate Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hosts", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hudson", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"IIS", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 5.x", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 7.x", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBossCache 2.x Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBossCache 3.x Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"mod_cluster", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"MySql Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Network Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"OpenSSH", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Operating System Platforms", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Oracle Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Performance Test Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Postfix", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"PostgreSQL Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Receiver for SNMP Traps", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"RHQ Agent", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"RHQ Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Samba", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Script", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Sudo Access", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Tomcat Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Twitter Plugin", false}));
return TestNGUtils.convertListOfListsTo2dArray(agentPluginsdata);
}
| public Object[][] getAgentPluginsData() {
ArrayList<List<Object>> agentPluginsdata = new ArrayList<List<Object>>();
agentPluginsdata.add(Arrays.asList(new Object[]{"Abstract Augeas Plugin", true}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Abstract Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Aliases", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Ant Bundle Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Apache HTTP Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Cobbler", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Cron", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"File Template Bundle Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Generic JMX", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"GRUB Boot Loader", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hibernate Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hosts", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Hudson", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"IIS", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server", false}));
// agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 5.x", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 5.x/6.x", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBoss Application Server 7.x", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBossCache 2.x Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"JBossCache 3.x Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"mod_cluster", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"MySql Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Network Services", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"OpenSSH", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Operating System Platforms", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Oracle Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Performance Test Plugin", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Postfix", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"PostgreSQL Database", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Receiver for SNMP Traps", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"RHQ Agent", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"RHQ Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Samba", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Script", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Sudo Access", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Tomcat Server", false}));
agentPluginsdata.add(Arrays.asList(new Object[]{"Twitter Plugin", false}));
return TestNGUtils.convertListOfListsTo2dArray(agentPluginsdata);
}
|
diff --git a/src/main/java/org/candlepin/policy/js/compliance/ComplianceRules.java b/src/main/java/org/candlepin/policy/js/compliance/ComplianceRules.java
index 09e289ecb..b90f02603 100644
--- a/src/main/java/org/candlepin/policy/js/compliance/ComplianceRules.java
+++ b/src/main/java/org/candlepin/policy/js/compliance/ComplianceRules.java
@@ -1,131 +1,131 @@
/**
* Copyright (c) 2009 - 2012 Red Hat, Inc.
*
* This software is licensed to you under the GNU General Public License,
* version 2 (GPLv2). There is NO WARRANTY for this software, express or
* implied, including the implied warranties of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
* along with this software; if not, see
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
*
* Red Hat trademarks are not licensed under GPLv2. No permission is
* granted to use or replicate Red Hat trademarks that are incorporated
* in this software or its documentation.
*/
package org.candlepin.policy.js.compliance;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.candlepin.jackson.ExportBeanPropertyFilter;
import org.candlepin.model.Consumer;
import org.candlepin.model.Entitlement;
import org.candlepin.model.EntitlementCurator;
import org.candlepin.policy.js.JsRunner;
import org.candlepin.policy.js.JsonJsContext;
import org.candlepin.policy.js.JsContext;
import org.candlepin.policy.js.RuleExecutionException;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.introspect.JacksonAnnotationIntrospector;
import org.codehaus.jackson.map.ser.impl.SimpleFilterProvider;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import org.mozilla.javascript.RhinoException;
import com.google.inject.Inject;
/**
* Compliance
*
* A class used to check consumer compliance status.
*/
public class ComplianceRules {
private EntitlementCurator entCurator;
private JsRunner jsRules;
private ObjectMapper mapper;
private static Logger log = Logger.getLogger(ComplianceRules.class);
@Inject
public ComplianceRules(JsRunner jsRules, EntitlementCurator entCurator) {
this.entCurator = entCurator;
this.jsRules = jsRules;
mapper = new ObjectMapper();
SimpleFilterProvider filterProvider = new SimpleFilterProvider();
filterProvider.setDefaultFilter(new ExportBeanPropertyFilter());
mapper.setFilters(filterProvider);
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
jsRules.init("compliance_name_space");
}
/**
* Check compliance status for a consumer on a specific date.
*
* @param c Consumer to check.
* @param date Date to check compliance status for.
* @return Compliance status.
*/
public ComplianceStatus getStatus(Consumer c, Date date) {
List<Entitlement> ents = entCurator.listByConsumer(c);
JsonJsContext args = new JsonJsContext();
args.put("consumer", c);
args.put("entitlements", ents);
args.put("ondate", date);
args.put("helper", new ComplianceRulesHelper(entCurator), false);
args.put("log", log, false);
// Convert the JSON returned into a ComplianceStatus object:
String json = runJsFunction(String.class, "get_status", args);
- log.warn(json);
+ log.debug("Output: " + json);
try {
ComplianceStatus status = mapper.readValue(json, ComplianceStatus.class);
return status;
}
catch (Exception e) {
throw new RuleExecutionException(e);
}
}
public boolean isStackCompliant(Consumer consumer, String stackId,
List<Entitlement> entsToConsider) {
JsonJsContext args = new JsonJsContext();
args.put("stack_id", stackId);
args.put("consumer", consumer);
args.put("entitlements", entsToConsider);
args.put("log", log, false);
return runJsFunction(Boolean.class, "is_stack_compliant", args);
}
public boolean isEntitlementCompliant(Consumer consumer, Entitlement ent) {
JsonJsContext args = new JsonJsContext();
args.put("consumer", consumer);
args.put("ent", ent);
args.put("log", log, false);
return runJsFunction(Boolean.class, "is_ent_compliant", args);
}
private <T extends Object> T runJsFunction(Class<T> clazz, String function,
JsContext context) {
T returner = null;
try {
returner = jsRules.invokeMethod(function, context);
}
catch (NoSuchMethodException e) {
log.warn("No compliance javascript method found: " + function);
}
catch (RhinoException e) {
throw new RuleExecutionException(e);
}
return returner;
}
}
| true | true | public ComplianceStatus getStatus(Consumer c, Date date) {
List<Entitlement> ents = entCurator.listByConsumer(c);
JsonJsContext args = new JsonJsContext();
args.put("consumer", c);
args.put("entitlements", ents);
args.put("ondate", date);
args.put("helper", new ComplianceRulesHelper(entCurator), false);
args.put("log", log, false);
// Convert the JSON returned into a ComplianceStatus object:
String json = runJsFunction(String.class, "get_status", args);
log.warn(json);
try {
ComplianceStatus status = mapper.readValue(json, ComplianceStatus.class);
return status;
}
catch (Exception e) {
throw new RuleExecutionException(e);
}
}
| public ComplianceStatus getStatus(Consumer c, Date date) {
List<Entitlement> ents = entCurator.listByConsumer(c);
JsonJsContext args = new JsonJsContext();
args.put("consumer", c);
args.put("entitlements", ents);
args.put("ondate", date);
args.put("helper", new ComplianceRulesHelper(entCurator), false);
args.put("log", log, false);
// Convert the JSON returned into a ComplianceStatus object:
String json = runJsFunction(String.class, "get_status", args);
log.debug("Output: " + json);
try {
ComplianceStatus status = mapper.readValue(json, ComplianceStatus.class);
return status;
}
catch (Exception e) {
throw new RuleExecutionException(e);
}
}
|
diff --git a/src/com/sonyericsson/chkbugreport/Context.java b/src/com/sonyericsson/chkbugreport/Context.java
index 8d55d11..8bc0768 100644
--- a/src/com/sonyericsson/chkbugreport/Context.java
+++ b/src/com/sonyericsson/chkbugreport/Context.java
@@ -1,34 +1,34 @@
package com.sonyericsson.chkbugreport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Context {
// Time window markers
private TimeWindowMarker mTimeWindowStart = new TimeWindowMarker();
private TimeWindowMarker mTimeWindowEnd = new TimeWindowMarker();
public void parseTimeWindow(String timeWindow) {
try {
Matcher m = Pattern.compile("(.*)\\.\\.(.*)").matcher(timeWindow);
if (!m.matches()) {
throw new IllegalArgumentException("Incorrect time window range");
}
mTimeWindowStart = new TimeWindowMarker(m.group(1));
mTimeWindowEnd = new TimeWindowMarker(m.group(2));
} catch (Exception e) {
- System.err.println("Error parsing timewindow: `" + timeWindow + "�: " + e);
+ System.err.println("Error parsing timewindow: `" + timeWindow + "': " + e);
System.exit(1);
}
}
public TimeWindowMarker getTimeWindowStart() {
return mTimeWindowStart;
}
public TimeWindowMarker getTimeWindowEnd() {
return mTimeWindowEnd;
}
}
| true | true | public void parseTimeWindow(String timeWindow) {
try {
Matcher m = Pattern.compile("(.*)\\.\\.(.*)").matcher(timeWindow);
if (!m.matches()) {
throw new IllegalArgumentException("Incorrect time window range");
}
mTimeWindowStart = new TimeWindowMarker(m.group(1));
mTimeWindowEnd = new TimeWindowMarker(m.group(2));
} catch (Exception e) {
System.err.println("Error parsing timewindow: `" + timeWindow + "�: " + e);
System.exit(1);
}
}
| public void parseTimeWindow(String timeWindow) {
try {
Matcher m = Pattern.compile("(.*)\\.\\.(.*)").matcher(timeWindow);
if (!m.matches()) {
throw new IllegalArgumentException("Incorrect time window range");
}
mTimeWindowStart = new TimeWindowMarker(m.group(1));
mTimeWindowEnd = new TimeWindowMarker(m.group(2));
} catch (Exception e) {
System.err.println("Error parsing timewindow: `" + timeWindow + "': " + e);
System.exit(1);
}
}
|
diff --git a/src/de/echox/hacklace/pix0lat0r/data/MatrixSerializer.java b/src/de/echox/hacklace/pix0lat0r/data/MatrixSerializer.java
index bb97529..91c3b01 100644
--- a/src/de/echox/hacklace/pix0lat0r/data/MatrixSerializer.java
+++ b/src/de/echox/hacklace/pix0lat0r/data/MatrixSerializer.java
@@ -1,60 +1,60 @@
package de.echox.hacklace.pix0lat0r.data;
import java.util.Iterator;
import java.util.List;
// TODO class works only for byte size displays
public class MatrixSerializer {
public static byte[] serialize(List<Matrix> matrixes) {
int width = matrixes.get(0).getWidth();
int size = (matrixes.size() * width);
byte[] result = new byte[size];
int position = 0;
for (Iterator<Matrix> it = matrixes.iterator(); it.hasNext();) {
Matrix matrix = it.next();
byte[] serialized = serialize(matrix);
System.arraycopy(serialized, 0, result, position, serialized.length);
position += serialized.length;
}
return result;
}
public static byte[] serialize(Matrix matrix) {
int width = matrix.getWidth();
byte[] result = new byte[matrix.getWidth()];
for(int x=0; x < width; x++) {
result[x] = serialize(matrix.getColumn(x));
}
return result;
}
public static byte serialize(boolean[] row) {
byte result = 0;
if(row[0]) {
result += 0x01;
- } else if (row[1]) {
+ } if (row[1]) {
result += 0x02;
- } else if (row[2]) {
+ } if (row[2]) {
result += 0x04;
- } else if (row[3]) {
+ } if (row[3]) {
result += 0x08;
- } else if (row[4]) {
+ } if (row[4]) {
result += 0x10;
- } else if (row[5]) {
+ } if (row[5]) {
result += 0x20;
- } else if (row[6]) {
+ } if (row[6]) {
result += 0x40;
}
return result;
}
}
| false | true | public static byte serialize(boolean[] row) {
byte result = 0;
if(row[0]) {
result += 0x01;
} else if (row[1]) {
result += 0x02;
} else if (row[2]) {
result += 0x04;
} else if (row[3]) {
result += 0x08;
} else if (row[4]) {
result += 0x10;
} else if (row[5]) {
result += 0x20;
} else if (row[6]) {
result += 0x40;
}
return result;
}
| public static byte serialize(boolean[] row) {
byte result = 0;
if(row[0]) {
result += 0x01;
} if (row[1]) {
result += 0x02;
} if (row[2]) {
result += 0x04;
} if (row[3]) {
result += 0x08;
} if (row[4]) {
result += 0x10;
} if (row[5]) {
result += 0x20;
} if (row[6]) {
result += 0x40;
}
return result;
}
|
diff --git a/automaatnehindaja/src/automaatnehindaja/TaskstableServlet.java b/automaatnehindaja/src/automaatnehindaja/TaskstableServlet.java
index b8ad20b..9ca867b 100644
--- a/automaatnehindaja/src/automaatnehindaja/TaskstableServlet.java
+++ b/automaatnehindaja/src/automaatnehindaja/TaskstableServlet.java
@@ -1,124 +1,126 @@
package automaatnehindaja;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
@WebServlet("/Taskstable")
public class TaskstableServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(TaskstableServlet.class);
public TaskstableServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
+ response.setCharacterEncoding("UTF-8");
+ request.setCharacterEncoding("UTF-8");
Connection c = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String statement;
String course = request.getParameter("course");
System.out.println(course);
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/automaatnehindaja", "ahindaja",
"k1rven2gu");
if (request.isUserInRole("tudeng")) {
statement = "SELECT "
+ "tasks.id, tasks.name, tasks.deadline, attempt.result "
+ "FROM tasks "
+ "LEFT OUTER JOIN "
+ "attempt on tasks.id = attempt.task " + "AND "
+ "attempt.username = ? "
+ "WHERE tasks.coursename = ?;";
stmt = c.prepareStatement(statement);
stmt.setString(2, course);
stmt.setString(1, request.getUserPrincipal().getName());
} else if (request.isUserInRole("admin") || request.isUserInRole("responsible")) {
statement = "SELECT tasks.id, tasks.name, tasks.deadline, count(attempt.task) AS attempts, "
+ "(SELECT count(*) FROM attempt where attempt.task = tasks.id AND "
+ "attempt.result = 'OK') AS successful "
+ "FROM tasks " + "LEFT JOIN attempt "
+ "ON tasks.id = attempt.task "
+ "WHERE tasks.coursename = ? "
+ "GROUP BY tasks.id;";
stmt = c.prepareStatement(statement);
stmt.setString(1, course);
} else {
return;
}
rs = stmt.executeQuery();
response.setContentType("application/json");
JSONObject json = new JSONObject();
if (request.isUserInRole("tudeng")) {
try {
json.put("role", "tudeng");
while (rs.next()) {
json.append("id", rs.getString(1));
json.append("name", rs.getString(2));
json.append("deadline", rs.getDate(3).toString());
String tulemus = rs.getString(4);
if (tulemus == null) {
tulemus = "Esitamata";
}
json.append("result", tulemus);
}
} catch (JSONException e) {
logger.debug("JSONEXCEPTION", e);
}
}
else if (request.isUserInRole("admin") || request.isUserInRole("responsible")) {
try {
json.put("role", "admin");
while (rs.next()) {
json.append("id", rs.getString(1));
json.append("name", rs.getString(2));
json.append("deadline", rs.getDate(3).toString());
json.append("resultCount", rs.getInt(4));
json.append("successCount", rs.getInt(5));
}
} catch (JSONException e) {
logger.debug("JSONEXCEPTION", e);
}
} else {
response.sendRedirect("/automaatnehindaja/error.html");
return;
}
c.close();
response.getWriter().write(json.toString());
} catch (SQLException e) {
logger.debug("SQLEXCEPTION", e);
} catch (ClassNotFoundException f) {
logger.debug("CLASSNOTFOUNDEXCEPTION", f);
}
}
}
| true | true | protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Connection c = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String statement;
String course = request.getParameter("course");
System.out.println(course);
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/automaatnehindaja", "ahindaja",
"k1rven2gu");
if (request.isUserInRole("tudeng")) {
statement = "SELECT "
+ "tasks.id, tasks.name, tasks.deadline, attempt.result "
+ "FROM tasks "
+ "LEFT OUTER JOIN "
+ "attempt on tasks.id = attempt.task " + "AND "
+ "attempt.username = ? "
+ "WHERE tasks.coursename = ?;";
stmt = c.prepareStatement(statement);
stmt.setString(2, course);
stmt.setString(1, request.getUserPrincipal().getName());
} else if (request.isUserInRole("admin") || request.isUserInRole("responsible")) {
statement = "SELECT tasks.id, tasks.name, tasks.deadline, count(attempt.task) AS attempts, "
+ "(SELECT count(*) FROM attempt where attempt.task = tasks.id AND "
+ "attempt.result = 'OK') AS successful "
+ "FROM tasks " + "LEFT JOIN attempt "
+ "ON tasks.id = attempt.task "
+ "WHERE tasks.coursename = ? "
+ "GROUP BY tasks.id;";
stmt = c.prepareStatement(statement);
stmt.setString(1, course);
} else {
return;
}
rs = stmt.executeQuery();
response.setContentType("application/json");
JSONObject json = new JSONObject();
if (request.isUserInRole("tudeng")) {
try {
json.put("role", "tudeng");
while (rs.next()) {
json.append("id", rs.getString(1));
json.append("name", rs.getString(2));
json.append("deadline", rs.getDate(3).toString());
String tulemus = rs.getString(4);
if (tulemus == null) {
tulemus = "Esitamata";
}
json.append("result", tulemus);
}
} catch (JSONException e) {
logger.debug("JSONEXCEPTION", e);
}
}
else if (request.isUserInRole("admin") || request.isUserInRole("responsible")) {
try {
json.put("role", "admin");
while (rs.next()) {
json.append("id", rs.getString(1));
json.append("name", rs.getString(2));
json.append("deadline", rs.getDate(3).toString());
json.append("resultCount", rs.getInt(4));
json.append("successCount", rs.getInt(5));
}
} catch (JSONException e) {
logger.debug("JSONEXCEPTION", e);
}
} else {
response.sendRedirect("/automaatnehindaja/error.html");
return;
}
c.close();
response.getWriter().write(json.toString());
} catch (SQLException e) {
logger.debug("SQLEXCEPTION", e);
} catch (ClassNotFoundException f) {
logger.debug("CLASSNOTFOUNDEXCEPTION", f);
}
}
| protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
request.setCharacterEncoding("UTF-8");
Connection c = null;
PreparedStatement stmt = null;
ResultSet rs = null;
String statement;
String course = request.getParameter("course");
System.out.println(course);
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/automaatnehindaja", "ahindaja",
"k1rven2gu");
if (request.isUserInRole("tudeng")) {
statement = "SELECT "
+ "tasks.id, tasks.name, tasks.deadline, attempt.result "
+ "FROM tasks "
+ "LEFT OUTER JOIN "
+ "attempt on tasks.id = attempt.task " + "AND "
+ "attempt.username = ? "
+ "WHERE tasks.coursename = ?;";
stmt = c.prepareStatement(statement);
stmt.setString(2, course);
stmt.setString(1, request.getUserPrincipal().getName());
} else if (request.isUserInRole("admin") || request.isUserInRole("responsible")) {
statement = "SELECT tasks.id, tasks.name, tasks.deadline, count(attempt.task) AS attempts, "
+ "(SELECT count(*) FROM attempt where attempt.task = tasks.id AND "
+ "attempt.result = 'OK') AS successful "
+ "FROM tasks " + "LEFT JOIN attempt "
+ "ON tasks.id = attempt.task "
+ "WHERE tasks.coursename = ? "
+ "GROUP BY tasks.id;";
stmt = c.prepareStatement(statement);
stmt.setString(1, course);
} else {
return;
}
rs = stmt.executeQuery();
response.setContentType("application/json");
JSONObject json = new JSONObject();
if (request.isUserInRole("tudeng")) {
try {
json.put("role", "tudeng");
while (rs.next()) {
json.append("id", rs.getString(1));
json.append("name", rs.getString(2));
json.append("deadline", rs.getDate(3).toString());
String tulemus = rs.getString(4);
if (tulemus == null) {
tulemus = "Esitamata";
}
json.append("result", tulemus);
}
} catch (JSONException e) {
logger.debug("JSONEXCEPTION", e);
}
}
else if (request.isUserInRole("admin") || request.isUserInRole("responsible")) {
try {
json.put("role", "admin");
while (rs.next()) {
json.append("id", rs.getString(1));
json.append("name", rs.getString(2));
json.append("deadline", rs.getDate(3).toString());
json.append("resultCount", rs.getInt(4));
json.append("successCount", rs.getInt(5));
}
} catch (JSONException e) {
logger.debug("JSONEXCEPTION", e);
}
} else {
response.sendRedirect("/automaatnehindaja/error.html");
return;
}
c.close();
response.getWriter().write(json.toString());
} catch (SQLException e) {
logger.debug("SQLEXCEPTION", e);
} catch (ClassNotFoundException f) {
logger.debug("CLASSNOTFOUNDEXCEPTION", f);
}
}
|
diff --git a/SenBotRunner/src/main/java/com/gfk/senbot/framework/cucumber/stepdefinitions/CucumberReportingExtension.java b/SenBotRunner/src/main/java/com/gfk/senbot/framework/cucumber/stepdefinitions/CucumberReportingExtension.java
index e87cb99..b9c67dc 100644
--- a/SenBotRunner/src/main/java/com/gfk/senbot/framework/cucumber/stepdefinitions/CucumberReportingExtension.java
+++ b/SenBotRunner/src/main/java/com/gfk/senbot/framework/cucumber/stepdefinitions/CucumberReportingExtension.java
@@ -1,59 +1,59 @@
package com.gfk.senbot.framework.cucumber.stepdefinitions;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.gfk.senbot.framework.BaseServiceHub;
import com.gfk.senbot.framework.context.CucumberManager;
import com.gfk.senbot.framework.context.SenBotContext;
import com.gfk.senbot.framework.context.TestEnvironment;
import cucumber.api.Scenario;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.runtime.java.StepDefAnnotation;
/**
* A {@link StepDefAnnotation} for altering the generated report based on senario outcomes.
*
* @author joostschouten
*
*/
@StepDefAnnotation
public class CucumberReportingExtension extends BaseServiceHub {
private static Logger log = LoggerFactory.getLogger(CucumberManager.class);
@Before
public void beforeScenario(Scenario scenario) {
log.debug("Scenarion started");
ScenarioGlobals startNewScenario = getCucumberManager().startNewScenario();
}
/**
* Capture a selenium screenshot when a test fails and add it to the Cucumber generated report
* if the scenario has accessed selenium in its lifetime
* @throws InterruptedException
*/
@After
public void afterScenario(Scenario scenario) throws InterruptedException {
log.debug("Scenarion finished");
ScenarioGlobals scenarioGlobals = getCucumberManager().getCurrentScenarioGlobals();
TestEnvironment testNev = getSeleniumManager().getAssociatedTestEnvironment();
- if (testNev != null) {
+ if (testNev != null && scenarioGlobals != null) {
boolean scenarioUsedSelenium = testNev.isWebDriverAccessedSince(scenarioGlobals.getScenarioStart());
if (scenarioUsedSelenium) {
if (scenario.isFailed()) {
log.debug("Scenarion failed while using selenium, so capture screenshot");
TakesScreenshot seleniumDriver = (TakesScreenshot) SenBotContext.getSeleniumDriver();
byte[] screenshotAs = seleniumDriver.getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshotAs, "image/png");
}
}
}
getCucumberManager().stopNewScenario();
}
}
| true | true | public void afterScenario(Scenario scenario) throws InterruptedException {
log.debug("Scenarion finished");
ScenarioGlobals scenarioGlobals = getCucumberManager().getCurrentScenarioGlobals();
TestEnvironment testNev = getSeleniumManager().getAssociatedTestEnvironment();
if (testNev != null) {
boolean scenarioUsedSelenium = testNev.isWebDriverAccessedSince(scenarioGlobals.getScenarioStart());
if (scenarioUsedSelenium) {
if (scenario.isFailed()) {
log.debug("Scenarion failed while using selenium, so capture screenshot");
TakesScreenshot seleniumDriver = (TakesScreenshot) SenBotContext.getSeleniumDriver();
byte[] screenshotAs = seleniumDriver.getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshotAs, "image/png");
}
}
}
getCucumberManager().stopNewScenario();
}
| public void afterScenario(Scenario scenario) throws InterruptedException {
log.debug("Scenarion finished");
ScenarioGlobals scenarioGlobals = getCucumberManager().getCurrentScenarioGlobals();
TestEnvironment testNev = getSeleniumManager().getAssociatedTestEnvironment();
if (testNev != null && scenarioGlobals != null) {
boolean scenarioUsedSelenium = testNev.isWebDriverAccessedSince(scenarioGlobals.getScenarioStart());
if (scenarioUsedSelenium) {
if (scenario.isFailed()) {
log.debug("Scenarion failed while using selenium, so capture screenshot");
TakesScreenshot seleniumDriver = (TakesScreenshot) SenBotContext.getSeleniumDriver();
byte[] screenshotAs = seleniumDriver.getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshotAs, "image/png");
}
}
}
getCucumberManager().stopNewScenario();
}
|
diff --git a/MPDroid/src/com/namelessdev/mpdroid/PlaylistActivity.java b/MPDroid/src/com/namelessdev/mpdroid/PlaylistActivity.java
index 1cbc01cc..aff9e982 100644
--- a/MPDroid/src/com/namelessdev/mpdroid/PlaylistActivity.java
+++ b/MPDroid/src/com/namelessdev/mpdroid/PlaylistActivity.java
@@ -1,322 +1,326 @@
package com.namelessdev.mpdroid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.a0z.mpd.MPDPlaylist;
import org.a0z.mpd.MPDServerException;
import org.a0z.mpd.MPDStatus;
import org.a0z.mpd.Music;
import org.a0z.mpd.event.MPDConnectionStateChangedEvent;
import org.a0z.mpd.event.MPDPlaylistChangedEvent;
import org.a0z.mpd.event.MPDRandomChangedEvent;
import org.a0z.mpd.event.MPDRepeatChangedEvent;
import org.a0z.mpd.event.MPDStateChangedEvent;
import org.a0z.mpd.event.MPDTrackChangedEvent;
import org.a0z.mpd.event.MPDUpdateStateChangedEvent;
import org.a0z.mpd.event.MPDVolumeChangedEvent;
import org.a0z.mpd.event.StatusChangeListener;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class PlaylistActivity extends ListActivity implements OnClickListener, OnMenuItemClickListener, StatusChangeListener {
private ArrayList<HashMap<String, Object>> songlist;
private List<Music> musics;
private int arrayListId;
private int songId;
private String title;
public static final int MAIN = 0;
public static final int CLEAR = 1;
public static final int EDIT = 2;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
MPDApplication app = (MPDApplication) getApplication();
setContentView(R.layout.playlist_activity);
this.setTitle(R.string.nowPlaying);
app.oMPDAsyncHelper.addStatusChangeListener(this);
ListView list = getListView();
/*
* LinearLayout test = (LinearLayout)list.getChildAt(1); ImageView img = (ImageView)test.findViewById(R.id.picture); //ImageView img =
* (ImageView)((LinearLayout)list.getItemAtPosition(3)).findViewById(R.id.picture);
* img.setImageDrawable(getResources().getDrawable(R.drawable.gmpcnocover));
*/
registerForContextMenu(list);
Button button = (Button) findViewById(R.id.headerButton);
button.setVisibility(View.VISIBLE);
button.setOnClickListener(this);
TextView title = (TextView) findViewById(R.id.headerText);
title.setText(this.getTitle());
ImageView icon = (ImageView) findViewById(R.id.headerIcon);
icon.setImageDrawable(getResources().getDrawable(R.drawable.ic_tab_playlists_selected));
}
protected void update() {
MPDApplication app = (MPDApplication) getApplicationContext();
try {
MPDPlaylist playlist = app.oMPDAsyncHelper.oMPD.getPlaylist();
playlist.refresh();
songlist = new ArrayList<HashMap<String, Object>>();
musics = playlist.getMusics();
int playingID = app.oMPDAsyncHelper.oMPD.getStatus().getSongId();
for (Music m : musics) {
HashMap<String, Object> item = new HashMap<String, Object>();
item.put("songid", m.getSongId());
item.put("artist", m.getArtist());
item.put("title", m.getTitle());
if (m.getSongId() == playingID)
item.put("play", android.R.drawable.ic_media_play);
else
item.put("play", 0);
songlist.add(item);
}
SimpleAdapter songs = new SimpleAdapter(this, songlist, R.layout.playlist_list_item, new String[] { "play", "title", "artist" },
new int[] { R.id.picture, android.R.id.text1, android.R.id.text2 });
setListAdapter(songs);
} catch (MPDServerException e) {
}
}
@Override
protected void onStart() {
super.onStart();
MPDApplication app = (MPDApplication) getApplicationContext();
app.setActivity(this);
update();
}
@Override
protected void onResume() {
super.onResume();
update();
}
@Override
protected void onStop() {
super.onStop();
MPDApplication app = (MPDApplication) getApplicationContext();
app.unsetActivity(this);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
arrayListId = info.position;
songId = (Integer) songlist.get(info.position).get("songid");
title = (String) songlist.get(info.position).get("title");
menu.setHeaderTitle(title);
MenuItem skipTo = menu.add(ContextMenu.NONE, 0, 0, R.string.skipToHere);
skipTo.setOnMenuItemClickListener(this);
MenuItem moveNext = menu.add(ContextMenu.NONE, 1, 1, R.string.playNext);
moveNext.setOnMenuItemClickListener(this);
MenuItem moveTop = menu.add(ContextMenu.NONE, 2, 2, R.string.moveFirst);
moveTop.setOnMenuItemClickListener(this);
MenuItem moveBot = menu.add(ContextMenu.NONE, 3, 3, R.string.moveLast);
moveBot.setOnMenuItemClickListener(this);
MenuItem removeSong = menu.add(ContextMenu.NONE, 5, 5, R.string.removeFromPlaylist);
removeSong.setOnMenuItemClickListener(this);
}
public boolean onMenuItemClick(MenuItem item) {
MPDApplication app = (MPDApplication) getApplication();
switch (item.getItemId()) {
case 0:
// skip to selected Song
try {
app.oMPDAsyncHelper.oMPD.skipTo(songId);
} catch (MPDServerException e) {
}
return true;
case 1:
try { // Move song to next in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
- app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getSongPos() + 1);
+ if (arrayListId < status.getSongPos()) {
+ app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getSongPos());
+ } else {
+ app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getSongPos() + 1);
+ }
MainMenuActivity.notifyUser("Song moved to next in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 2:
try { // Move song to first in playlist
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, 0);
MainMenuActivity.notifyUser("Song moved to first in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 3:
try { // Move song to last in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getPlaylistLength() - 1);
MainMenuActivity.notifyUser("Song moved to last in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 5:
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().removeSong(songId);
MainMenuActivity.notifyUser(getResources().getString(R.string.deletedSongFromPlaylist), this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
/*
* Create Menu for Playlist View
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, MAIN, 0, R.string.mainMenu).setIcon(android.R.drawable.ic_menu_revert);
menu.add(0, CLEAR, 1, R.string.clear).setIcon(android.R.drawable.ic_menu_close_clear_cancel);
menu.add(0, EDIT, 2, R.string.editPlaylist).setIcon(android.R.drawable.ic_menu_edit);
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
MPDApplication app = (MPDApplication) getApplication();
// Menu actions...
switch (item.getItemId()) {
case MAIN:
Intent i = new Intent(this, MainMenuActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
return true;
case CLEAR:
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().clear();
songlist.clear();
MainMenuActivity.notifyUser(getResources().getString(R.string.playlistCleared), this);
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case EDIT:
i = new Intent(this, PlaylistRemoveActivity.class);
startActivityForResult(i, EDIT);
return true;
default:
return false;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
MPDApplication app = (MPDApplication) getApplication(); // Play selected Song
Music m = musics.get(position);
try {
app.oMPDAsyncHelper.oMPD.skipTo(m.getSongId());
} catch (MPDServerException e) {
}
}
@Override
public void connectionStateChanged(MPDConnectionStateChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void playlistChanged(MPDPlaylistChangedEvent event) {
update();
}
@Override
public void randomChanged(MPDRandomChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void repeatChanged(MPDRepeatChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void stateChanged(MPDStateChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void trackChanged(MPDTrackChangedEvent event) {
// Mark running track...
for (HashMap<String, Object> song : songlist) {
if (((Integer) song.get("songid")).intValue() == event.getMpdStatus().getSongId())
song.put("play", android.R.drawable.ic_media_play);
else
song.put("play", 0);
}
((SimpleAdapter) getListAdapter()).notifyDataSetChanged();
}
@Override
public void updateStateChanged(MPDUpdateStateChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void volumeChanged(MPDVolumeChangedEvent event) {
// TODO Auto-generated method stub
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.headerButton:
Intent i = new Intent(this, PlaylistRemoveActivity.class);
startActivityForResult(i, EDIT);
break;
default:
break;
}
}
}
| true | true | public boolean onMenuItemClick(MenuItem item) {
MPDApplication app = (MPDApplication) getApplication();
switch (item.getItemId()) {
case 0:
// skip to selected Song
try {
app.oMPDAsyncHelper.oMPD.skipTo(songId);
} catch (MPDServerException e) {
}
return true;
case 1:
try { // Move song to next in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getSongPos() + 1);
MainMenuActivity.notifyUser("Song moved to next in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 2:
try { // Move song to first in playlist
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, 0);
MainMenuActivity.notifyUser("Song moved to first in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 3:
try { // Move song to last in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getPlaylistLength() - 1);
MainMenuActivity.notifyUser("Song moved to last in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 5:
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().removeSong(songId);
MainMenuActivity.notifyUser(getResources().getString(R.string.deletedSongFromPlaylist), this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
| public boolean onMenuItemClick(MenuItem item) {
MPDApplication app = (MPDApplication) getApplication();
switch (item.getItemId()) {
case 0:
// skip to selected Song
try {
app.oMPDAsyncHelper.oMPD.skipTo(songId);
} catch (MPDServerException e) {
}
return true;
case 1:
try { // Move song to next in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
if (arrayListId < status.getSongPos()) {
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getSongPos());
} else {
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getSongPos() + 1);
}
MainMenuActivity.notifyUser("Song moved to next in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 2:
try { // Move song to first in playlist
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, 0);
MainMenuActivity.notifyUser("Song moved to first in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 3:
try { // Move song to last in playlist
MPDStatus status = app.oMPDAsyncHelper.oMPD.getStatus();
app.oMPDAsyncHelper.oMPD.getPlaylist().move(songId, status.getPlaylistLength() - 1);
MainMenuActivity.notifyUser("Song moved to last in list", this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
case 5:
try {
app.oMPDAsyncHelper.oMPD.getPlaylist().removeSong(songId);
MainMenuActivity.notifyUser(getResources().getString(R.string.deletedSongFromPlaylist), this);
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
return false;
}
|
diff --git a/modules/elastic-grid-core/src/main/java/com/elasticgrid/boot/BannerProviderImpl.java b/modules/elastic-grid-core/src/main/java/com/elasticgrid/boot/BannerProviderImpl.java
index f86edafa..4173dce5 100755
--- a/modules/elastic-grid-core/src/main/java/com/elasticgrid/boot/BannerProviderImpl.java
+++ b/modules/elastic-grid-core/src/main/java/com/elasticgrid/boot/BannerProviderImpl.java
@@ -1,38 +1,38 @@
/**
* Elastic Grid
* Copyright (C) 2008-2009 Elastic Grid, LLC.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.elasticgrid.boot;
import org.rioproject.util.BannerProvider;
/**
* Banner provider.
*
* @author Jerome Bernard
*/
public class BannerProviderImpl implements BannerProvider {
public String getBanner(String service) {
StringBuffer banner = new StringBuffer();
banner.append("\n");
banner.append("____ _ ____ ____ ___ _ ____ ____ ____ _ ___\n");
- banner.append("|___ | |__| [__ | | | | __ |__/ | | \\ "+ service + "\n");
- banner.append("|___ |___ | | ___] | | |___ |__] | \\ | |__/ Version: ${pom.version}\n");
+ banner.append("|___ | |__| [__ | | | | __ |__/ | | \\ ").append(service).append("\n");
+ banner.append("|___ |___ | | ___] | | |___ |__] | \\ | |__/ Version: ${pom.version}\n");
banner.append("\n");
- banner.append("Elastic Grid Home: " + System.getProperty("EG_HOME"));
+ banner.append("Elastic Grid Home: ").append(System.getProperty("EG_HOME"));
return banner.toString();
}
}
| false | true | public String getBanner(String service) {
StringBuffer banner = new StringBuffer();
banner.append("\n");
banner.append("____ _ ____ ____ ___ _ ____ ____ ____ _ ___\n");
banner.append("|___ | |__| [__ | | | | __ |__/ | | \\ "+ service + "\n");
banner.append("|___ |___ | | ___] | | |___ |__] | \\ | |__/ Version: ${pom.version}\n");
banner.append("\n");
banner.append("Elastic Grid Home: " + System.getProperty("EG_HOME"));
return banner.toString();
}
| public String getBanner(String service) {
StringBuffer banner = new StringBuffer();
banner.append("\n");
banner.append("____ _ ____ ____ ___ _ ____ ____ ____ _ ___\n");
banner.append("|___ | |__| [__ | | | | __ |__/ | | \\ ").append(service).append("\n");
banner.append("|___ |___ | | ___] | | |___ |__] | \\ | |__/ Version: ${pom.version}\n");
banner.append("\n");
banner.append("Elastic Grid Home: ").append(System.getProperty("EG_HOME"));
return banner.toString();
}
|
diff --git a/java/gadgets/src/main/java/org/apache/shindig/gadgets/uri/DefaultIframeUriManager.java b/java/gadgets/src/main/java/org/apache/shindig/gadgets/uri/DefaultIframeUriManager.java
index fc3fe5d0e..8639b7877 100644
--- a/java/gadgets/src/main/java/org/apache/shindig/gadgets/uri/DefaultIframeUriManager.java
+++ b/java/gadgets/src/main/java/org/apache/shindig/gadgets/uri/DefaultIframeUriManager.java
@@ -1,332 +1,332 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shindig.gadgets.uri;
import com.google.common.collect.Lists;
import com.google.inject.ImplementedBy;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import org.apache.shindig.auth.SecurityToken;
import org.apache.shindig.auth.SecurityTokenDecoder;
import org.apache.shindig.auth.SecurityTokenException;
import org.apache.shindig.common.uri.Uri;
import org.apache.shindig.common.uri.UriBuilder;
import org.apache.shindig.config.ContainerConfig;
import org.apache.shindig.gadgets.Gadget;
import org.apache.shindig.gadgets.GadgetContext;
import org.apache.shindig.gadgets.UserPrefs;
import org.apache.shindig.gadgets.spec.UserPref;
import org.apache.shindig.gadgets.spec.View;
import org.apache.shindig.gadgets.uri.UriCommon.Param;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class DefaultIframeUriManager implements IframeUriManager {
// By default, fills in values that could otherwise be templated for client population.
private static final boolean DEFAULT_USE_TEMPLATES = false;
static final String IFRAME_BASE_PATH_KEY = "gadgets.uri.iframe.basePath";
static final String LOCKED_DOMAIN_REQUIRED_KEY = "gadgets.uri.iframe.lockedDomainRequired";
public static final String LOCKED_DOMAIN_SUFFIX_KEY = "gadgets.uri.iframe.lockedDomainSuffix";
public static final String UNLOCKED_DOMAIN_KEY = "gadgets.uri.iframe.unlockedDomain";
public static final String SECURITY_TOKEN_ALWAYS_KEY = "gadgets.uri.iframe.alwaysAppendSecurityToken";
public static final String LOCKED_DOMAIN_FEATURE_NAME = "locked-domain";
public static final String SECURITY_TOKEN_FEATURE_NAME = "security-token";
private boolean ldEnabled = true;
private TemplatingSignal tplSignal = null;
private Versioner versioner = null;
private final ContainerConfig config;
private final LockedDomainPrefixGenerator ldGen;
private final SecurityTokenDecoder securityTokenCodec;
private final List<String> ldSuffixes;
@Inject
public DefaultIframeUriManager(ContainerConfig config,
LockedDomainPrefixGenerator ldGen,
SecurityTokenDecoder securityTokenCodec) {
this.config = config;
this.ldGen = ldGen;
this.securityTokenCodec = securityTokenCodec;
Collection<String> containers = config.getContainers();
List<String> ldSuffixes = Lists.newArrayListWithCapacity(containers.size());
for (String container : containers) {
ldSuffixes.add(getReqVal(container, LOCKED_DOMAIN_SUFFIX_KEY));
}
this.ldSuffixes = Collections.unmodifiableList(ldSuffixes);
}
@Inject(optional = true)
public void setLockedDomainEnabled(
@Named("shindig.locked-domain.enabled") Boolean ldEnabled) {
this.ldEnabled = ldEnabled;
}
@Inject(optional = true)
public void setVersioner(Versioner versioner) {
this.versioner = versioner;
}
@Inject(optional = true)
public void setTemplatingSignal(TemplatingSignal tplSignal) {
this.tplSignal = tplSignal;
}
public Uri makeRenderingUri(Gadget gadget) {
UriBuilder uri;
View view = gadget.getCurrentView();
GadgetContext context = gadget.getContext();
String container = context.getContainer();
if (View.ContentType.URL.equals(view.getType())) {
// A. type=url. Initializes all except standard parameters.
uri = new UriBuilder(view.getHref());
} else {
// B. Others, aka. type=html and html_sanitized.
uri = new UriBuilder();
// 1. Set base path.
uri.setPath(getReqVal(container, IFRAME_BASE_PATH_KEY));
// 2. Set host/authority.
String host;
if (usingLockedDomain(gadget, container)) {
host = ldGen.getLockedDomainPrefix(gadget.getSpec().getUrl()) +
getReqVal(container, LOCKED_DOMAIN_SUFFIX_KEY);
} else {
host = getReqVal(container, UNLOCKED_DOMAIN_KEY);
}
uri.setAuthority(host);
// 3. Set protocol/schema.
uri.setScheme(getScheme(gadget, container));
// 4. Add the URL.
uri.addQueryParameter(Param.URL.getKey(), context.getUrl().toString());
}
// Add container, whose input derived other components of the URI.
uri.addQueryParameter(Param.CONTAINER.getKey(), container);
// Add remaining non-url standard parameters, in templated or filled form.
boolean useTpl = tplSignal != null ? tplSignal.useTemplates() : DEFAULT_USE_TEMPLATES;
addParam(uri, Param.VIEW.getKey(), view.getName(), useTpl, false);
addParam(uri, Param.LANG.getKey(), context.getLocale().getLanguage(), useTpl, false);
addParam(uri, Param.COUNTRY.getKey(), context.getLocale().getCountry(), useTpl, false);
addParam(uri, Param.DEBUG.getKey(), context.getDebug() ? "1" : "0", useTpl, false);
addParam(uri, Param.NO_CACHE.getKey(), context.getIgnoreCache() ? "1" : "0", useTpl, false);
// Add all UserPrefs
UserPrefs prefs = context.getUserPrefs();
for (UserPref up : gadget.getSpec().getUserPrefs()) {
String name = up.getName();
String data = prefs.getPref(name);
if (data == null) {
data = up.getDefaultValue();
}
boolean upInFragment = !view.needsUserPrefSubstitution();
addParam(uri, UriCommon.USER_PREF_PREFIX + up.getName(), data, useTpl, upInFragment);
}
if (versioner != null) {
// Added on the query string, obviously not templated.
addParam(uri, Param.VERSION.getKey(),
versioner.version(gadget.getSpec().getUrl(), container), false, false);
}
if (wantsSecurityToken(gadget)) {
boolean securityTokenOnQuery = isTokenNeededForRendering(gadget);
String securityToken = generateSecurityToken(gadget);
- addParam(uri, Param.SECURITY_TOKEN.getKey(), securityToken, securityToken != null,
+ addParam(uri, Param.SECURITY_TOKEN.getKey(), securityToken, securityToken == null,
!securityTokenOnQuery);
}
addExtras(uri);
return uri.toUri();
}
protected String generateSecurityToken(Gadget gadget) {
// Find a security token in the context
try {
SecurityToken token = gadget.getContext().getToken();
if (securityTokenCodec != null && token != null) {
return securityTokenCodec.encodeToken(token);
}
} catch (SecurityTokenException e) {
// ignore -- no security token
}
return null;
}
protected boolean wantsSecurityToken(Gadget gadget) {
return gadget.getAllFeatures().contains(SECURITY_TOKEN_FEATURE_NAME) ||
config.getBool(gadget.getContext().getContainer(), SECURITY_TOKEN_ALWAYS_KEY);
}
// This method should be overridden to provide better caching characteristics
// for rendering Uris. In particular, it should return true only when the gadget
// uses server-side processing of such things as OpenSocial templates, Data pipelining,
// and Preloads. The default implementation is naive, returning true for all URIs,
// as this is the conservative result that will always functionally work.
protected boolean isTokenNeededForRendering(Gadget gadget) {
return true;
}
public UriStatus validateRenderingUri(Uri inUri) {
UriBuilder uri = new UriBuilder(inUri);
String gadgetStr = uri.getQueryParameter(Param.URL.getKey());
Uri gadgetUri = null;
try {
gadgetUri = Uri.parse(gadgetStr);
} catch (Exception e) {
// RuntimeException eg. InvalidArgumentException
return UriStatus.BAD_URI;
}
String container = uri.getQueryParameter(Param.CONTAINER.getKey());
if (container == null) {
container = ContainerConfig.DEFAULT_CONTAINER;
}
// Validate domain.
String host = uri.getAuthority().toLowerCase();
String gadgetLdPrefix = ldGen.getLockedDomainPrefix(gadgetUri).toLowerCase();
// If the uri starts with gadget's locked domain prefix, then the suffix
// must be an exact match as well.
// Lower-case to prevent casing from being relevant.
if (ldEnabled && !lockedDomainExclusion()) {
if (host.startsWith(gadgetLdPrefix)) {
// Strip off prefix.
host = host.substring(gadgetLdPrefix.length());
String ldSuffix = getReqVal(container, LOCKED_DOMAIN_SUFFIX_KEY);
if (!ldSuffix.equalsIgnoreCase(host)) {
return UriStatus.INVALID_DOMAIN;
}
} else {
// We need to also ensure that the URI isn't that of another valid
// locked-domain gadget. We do this test second as it's less efficient.
// Also, since we've already tested the "valid" locked domain case
// we can simply say the URI is invalid if it ends with any valid
// locked domain suffix.
for (String ldSuffix : ldSuffixes) {
if (host.endsWith(ldSuffix)) {
return UriStatus.INVALID_DOMAIN;
}
}
}
}
String version = uri.getQueryParameter(Param.VERSION.getKey());
if (versioner == null || version == null) {
return UriStatus.VALID_UNVERSIONED;
}
return versioner.validate(gadgetUri, container, version);
}
public static String tplKey(String key) {
return '%' + key + '%';
}
/** Overridable methods for custom behavior */
protected boolean lockedDomainExclusion() {
// Subclass/override this to support a custom notion of dev-mode, other exclusions.
return false;
}
protected String getScheme(Gadget gadget, String container) {
// Scheme-relative by default. Override for specific use cases.
return null;
}
protected void addExtras(UriBuilder uri) {
// Add whatever custom flags are desired here.
}
private void addParam(UriBuilder uri, String key, String data, boolean templated,
boolean fragment) {
String value;
if (templated) {
value = tplKey(key);
} else {
value = data;
}
if (!fragment) {
uri.addQueryParameter(key, value);
} else {
uri.addFragmentParameter(key, value);
}
}
private boolean usingLockedDomain(Gadget gadget, String container) {
if (!ldEnabled) {
return false;
}
if (lockedDomainExclusion()) {
return false;
}
if (config.getBool(container, LOCKED_DOMAIN_REQUIRED_KEY)) {
return true;
}
return gadget.getAllFeatures().contains(LOCKED_DOMAIN_FEATURE_NAME);
}
private String getReqVal(String container, String key) {
String val = config.getString(container, key);
if (val == null) {
throw new RuntimeException("Missing required container config param, key: "
+ key + ", container: " + container);
}
return val;
}
@ImplementedBy(DefaultTemplatingSignal.class)
public static interface TemplatingSignal {
boolean useTemplates();
}
public static final class DefaultTemplatingSignal implements TemplatingSignal {
private boolean useTemplates = true;
@Inject(optional = true)
public void setUseTemplates(
@Named("shindig.urlgen.use-templates-default") Boolean useTemplates) {
this.useTemplates = useTemplates;
}
public boolean useTemplates() {
return useTemplates;
}
}
}
| true | true | public Uri makeRenderingUri(Gadget gadget) {
UriBuilder uri;
View view = gadget.getCurrentView();
GadgetContext context = gadget.getContext();
String container = context.getContainer();
if (View.ContentType.URL.equals(view.getType())) {
// A. type=url. Initializes all except standard parameters.
uri = new UriBuilder(view.getHref());
} else {
// B. Others, aka. type=html and html_sanitized.
uri = new UriBuilder();
// 1. Set base path.
uri.setPath(getReqVal(container, IFRAME_BASE_PATH_KEY));
// 2. Set host/authority.
String host;
if (usingLockedDomain(gadget, container)) {
host = ldGen.getLockedDomainPrefix(gadget.getSpec().getUrl()) +
getReqVal(container, LOCKED_DOMAIN_SUFFIX_KEY);
} else {
host = getReqVal(container, UNLOCKED_DOMAIN_KEY);
}
uri.setAuthority(host);
// 3. Set protocol/schema.
uri.setScheme(getScheme(gadget, container));
// 4. Add the URL.
uri.addQueryParameter(Param.URL.getKey(), context.getUrl().toString());
}
// Add container, whose input derived other components of the URI.
uri.addQueryParameter(Param.CONTAINER.getKey(), container);
// Add remaining non-url standard parameters, in templated or filled form.
boolean useTpl = tplSignal != null ? tplSignal.useTemplates() : DEFAULT_USE_TEMPLATES;
addParam(uri, Param.VIEW.getKey(), view.getName(), useTpl, false);
addParam(uri, Param.LANG.getKey(), context.getLocale().getLanguage(), useTpl, false);
addParam(uri, Param.COUNTRY.getKey(), context.getLocale().getCountry(), useTpl, false);
addParam(uri, Param.DEBUG.getKey(), context.getDebug() ? "1" : "0", useTpl, false);
addParam(uri, Param.NO_CACHE.getKey(), context.getIgnoreCache() ? "1" : "0", useTpl, false);
// Add all UserPrefs
UserPrefs prefs = context.getUserPrefs();
for (UserPref up : gadget.getSpec().getUserPrefs()) {
String name = up.getName();
String data = prefs.getPref(name);
if (data == null) {
data = up.getDefaultValue();
}
boolean upInFragment = !view.needsUserPrefSubstitution();
addParam(uri, UriCommon.USER_PREF_PREFIX + up.getName(), data, useTpl, upInFragment);
}
if (versioner != null) {
// Added on the query string, obviously not templated.
addParam(uri, Param.VERSION.getKey(),
versioner.version(gadget.getSpec().getUrl(), container), false, false);
}
if (wantsSecurityToken(gadget)) {
boolean securityTokenOnQuery = isTokenNeededForRendering(gadget);
String securityToken = generateSecurityToken(gadget);
addParam(uri, Param.SECURITY_TOKEN.getKey(), securityToken, securityToken != null,
!securityTokenOnQuery);
}
addExtras(uri);
return uri.toUri();
}
| public Uri makeRenderingUri(Gadget gadget) {
UriBuilder uri;
View view = gadget.getCurrentView();
GadgetContext context = gadget.getContext();
String container = context.getContainer();
if (View.ContentType.URL.equals(view.getType())) {
// A. type=url. Initializes all except standard parameters.
uri = new UriBuilder(view.getHref());
} else {
// B. Others, aka. type=html and html_sanitized.
uri = new UriBuilder();
// 1. Set base path.
uri.setPath(getReqVal(container, IFRAME_BASE_PATH_KEY));
// 2. Set host/authority.
String host;
if (usingLockedDomain(gadget, container)) {
host = ldGen.getLockedDomainPrefix(gadget.getSpec().getUrl()) +
getReqVal(container, LOCKED_DOMAIN_SUFFIX_KEY);
} else {
host = getReqVal(container, UNLOCKED_DOMAIN_KEY);
}
uri.setAuthority(host);
// 3. Set protocol/schema.
uri.setScheme(getScheme(gadget, container));
// 4. Add the URL.
uri.addQueryParameter(Param.URL.getKey(), context.getUrl().toString());
}
// Add container, whose input derived other components of the URI.
uri.addQueryParameter(Param.CONTAINER.getKey(), container);
// Add remaining non-url standard parameters, in templated or filled form.
boolean useTpl = tplSignal != null ? tplSignal.useTemplates() : DEFAULT_USE_TEMPLATES;
addParam(uri, Param.VIEW.getKey(), view.getName(), useTpl, false);
addParam(uri, Param.LANG.getKey(), context.getLocale().getLanguage(), useTpl, false);
addParam(uri, Param.COUNTRY.getKey(), context.getLocale().getCountry(), useTpl, false);
addParam(uri, Param.DEBUG.getKey(), context.getDebug() ? "1" : "0", useTpl, false);
addParam(uri, Param.NO_CACHE.getKey(), context.getIgnoreCache() ? "1" : "0", useTpl, false);
// Add all UserPrefs
UserPrefs prefs = context.getUserPrefs();
for (UserPref up : gadget.getSpec().getUserPrefs()) {
String name = up.getName();
String data = prefs.getPref(name);
if (data == null) {
data = up.getDefaultValue();
}
boolean upInFragment = !view.needsUserPrefSubstitution();
addParam(uri, UriCommon.USER_PREF_PREFIX + up.getName(), data, useTpl, upInFragment);
}
if (versioner != null) {
// Added on the query string, obviously not templated.
addParam(uri, Param.VERSION.getKey(),
versioner.version(gadget.getSpec().getUrl(), container), false, false);
}
if (wantsSecurityToken(gadget)) {
boolean securityTokenOnQuery = isTokenNeededForRendering(gadget);
String securityToken = generateSecurityToken(gadget);
addParam(uri, Param.SECURITY_TOKEN.getKey(), securityToken, securityToken == null,
!securityTokenOnQuery);
}
addExtras(uri);
return uri.toUri();
}
|
diff --git a/ttools/src/main/uk/ac/starlink/ttools/taplint/Reporter.java b/ttools/src/main/uk/ac/starlink/ttools/taplint/Reporter.java
index 6c5f207fc..ad2b24ce9 100644
--- a/ttools/src/main/uk/ac/starlink/ttools/taplint/Reporter.java
+++ b/ttools/src/main/uk/ac/starlink/ttools/taplint/Reporter.java
@@ -1,191 +1,199 @@
package uk.ac.starlink.ttools.taplint;
import java.util.Iterator;
import java.io.PrintStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import uk.ac.starlink.util.CountMap;
/**
* Handles logging for validation messages.
*
* @author Mark Taylor
*/
public class Reporter {
private final PrintStream out_;
private final int maxRepeat_;
private final boolean debug_;
private final int maxChar_;
private final CountMap<String> codeMap_;
private final CountMap<Type> typeMap_;
private final NumberFormat countFormat_;
private final String countXx_;
private String scode_;
private static final int CODE_LENGTH = 4;
public Reporter( PrintStream out, int maxRepeat, boolean debug,
int maxChar ) {
out_ = out;
maxRepeat_ = maxRepeat;
debug_ = debug;
maxChar_ = maxChar;
int maxDigit = (int) Math.ceil( Math.log10( maxRepeat_ + 1 ) );
countFormat_ = new DecimalFormat( repeatChar( '0', maxDigit ) );
countXx_ = repeatChar( 'x', maxDigit );
codeMap_ = new CountMap<String>();
typeMap_ = new CountMap<Type>();
}
public void startSection( String scode, String message ) {
println();
println( "Section " + scode + ": " + message );
scode_ = scode;
}
public String getSectionCode() {
return scode_;
}
public void summariseUnreportedMessages( String scode ) {
String dscode = "-" + scode + "-";
int lds = dscode.length();
for ( Iterator<String> it = codeMap_.keySet().iterator();
it.hasNext(); ) {
String ecode = it.next();
if ( dscode.equals( ecode.substring( 1, 1 + lds ) ) ) {
int count = codeMap_.getCount( ecode );
if ( count > maxRepeat_ ) {
println( ecode + "-" + countXx_
+ " (" + count + " more)" );
}
it.remove();
}
}
}
public void endSection() {
scode_ = null;
}
public void report( Type type, String code, String message ) {
report( type, code, message, null );
}
public void report( Type type, String code, String message,
Throwable err ) {
if ( message == null || message.trim().length() == 0 ) {
message = "?";
}
if ( code == null || code.length() == 0 ) {
code = createCode( message );
}
if ( code.length() > CODE_LENGTH ) {
code = code.substring( 0, CODE_LENGTH );
}
if ( code.length() < CODE_LENGTH ) {
code += repeatChar( 'X', CODE_LENGTH - code.length() );
}
assert code.length() == CODE_LENGTH;
StringBuffer codeBuf = new StringBuffer();
codeBuf.append( type.getChar() )
.append( '-' );
if ( scode_ != null ) {
codeBuf.append( scode_ )
.append( '-' );
}
codeBuf.append( code );
String ecode = codeBuf.toString();
typeMap_.addItem( type );
int count = codeMap_.addItem( ecode );
if ( count < maxRepeat_ ) {
String fcount = countFormat_.format( count );
- String[] lines = message.trim().split( "[\\n\\r]+" );
+ StringBuffer mbuf = new StringBuffer( message.trim() );
+ if ( err != null ) {
+ String emsg = err.getMessage();
+ mbuf.append( " [" )
+ .append( emsg == null || emsg.trim().length() == 0
+ ? err.toString() : emsg )
+ .append( "]" );
+ }
+ String[] lines = mbuf.toString().split( "[\\n\\r]+" );
for ( int il = 0; il < lines.length; il++ ) {
String line = lines[ il ];
if ( line.trim().length() > 0 ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( ecode )
.append( il == 0 ? '-' : '+' )
.append( fcount )
.append( ' ' )
.append( lines[ il ] );
println( sbuf.toString() );
}
}
}
if ( debug_ && err != null ) {
err.printStackTrace( out_ );
}
}
public void summariseUnreportedTypes( String code, Type[] types ) {
if ( types == null ) {
types = typeMap_.keySet().toArray( new Type[ 0 ] );
}
StringBuffer sbuf = new StringBuffer();
for ( int it = 0; it < types.length; it++ ) {
Type type = types[ it ];
if ( it > 0 ) {
sbuf.append( ", " );
}
sbuf.append( type.toString() )
.append( ": " )
.append( typeMap_.getCount( type ) );
}
report( Type.SUMMARY, code, sbuf.toString() );
}
public void clear() {
codeMap_.clear();
}
public String createCode( String msg ) {
int hash = msg.hashCode();
char[] chrs = new char[ CODE_LENGTH ];
for ( int i = 0; i < CODE_LENGTH; i++ ) {
chrs[ i ] = (char) ( 'A' + ( ( hash & 0x1f ) % ( 'Z' - 'A' ) ) );
hash >>= 5;
}
return new String( chrs );
}
private void println() {
println( "" );
}
private void println( String line ) {
int leng = line.length();
if ( leng > maxChar_ - 3 ) {
line = line.substring( 0, maxChar_ - 3 ) + "...";
}
out_.println( line );
}
private static String repeatChar( char chr, int count ) {
char[] chrs = new char[ count ];
for ( int i = 0; i < count; i++ ) {
chrs[ i ] = chr;
}
return new String( chrs );
}
public static enum Type {
SUMMARY( 'S' ),
INFO( 'I' ),
WARNING( 'W' ),
ERROR( 'E' ),
FAILURE( 'F' );
private final char chr_;
private Type( char chr ) {
chr_ = chr;
}
public char getChar() {
return chr_;
}
}
}
| true | true | public void report( Type type, String code, String message,
Throwable err ) {
if ( message == null || message.trim().length() == 0 ) {
message = "?";
}
if ( code == null || code.length() == 0 ) {
code = createCode( message );
}
if ( code.length() > CODE_LENGTH ) {
code = code.substring( 0, CODE_LENGTH );
}
if ( code.length() < CODE_LENGTH ) {
code += repeatChar( 'X', CODE_LENGTH - code.length() );
}
assert code.length() == CODE_LENGTH;
StringBuffer codeBuf = new StringBuffer();
codeBuf.append( type.getChar() )
.append( '-' );
if ( scode_ != null ) {
codeBuf.append( scode_ )
.append( '-' );
}
codeBuf.append( code );
String ecode = codeBuf.toString();
typeMap_.addItem( type );
int count = codeMap_.addItem( ecode );
if ( count < maxRepeat_ ) {
String fcount = countFormat_.format( count );
String[] lines = message.trim().split( "[\\n\\r]+" );
for ( int il = 0; il < lines.length; il++ ) {
String line = lines[ il ];
if ( line.trim().length() > 0 ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( ecode )
.append( il == 0 ? '-' : '+' )
.append( fcount )
.append( ' ' )
.append( lines[ il ] );
println( sbuf.toString() );
}
}
}
if ( debug_ && err != null ) {
err.printStackTrace( out_ );
}
}
| public void report( Type type, String code, String message,
Throwable err ) {
if ( message == null || message.trim().length() == 0 ) {
message = "?";
}
if ( code == null || code.length() == 0 ) {
code = createCode( message );
}
if ( code.length() > CODE_LENGTH ) {
code = code.substring( 0, CODE_LENGTH );
}
if ( code.length() < CODE_LENGTH ) {
code += repeatChar( 'X', CODE_LENGTH - code.length() );
}
assert code.length() == CODE_LENGTH;
StringBuffer codeBuf = new StringBuffer();
codeBuf.append( type.getChar() )
.append( '-' );
if ( scode_ != null ) {
codeBuf.append( scode_ )
.append( '-' );
}
codeBuf.append( code );
String ecode = codeBuf.toString();
typeMap_.addItem( type );
int count = codeMap_.addItem( ecode );
if ( count < maxRepeat_ ) {
String fcount = countFormat_.format( count );
StringBuffer mbuf = new StringBuffer( message.trim() );
if ( err != null ) {
String emsg = err.getMessage();
mbuf.append( " [" )
.append( emsg == null || emsg.trim().length() == 0
? err.toString() : emsg )
.append( "]" );
}
String[] lines = mbuf.toString().split( "[\\n\\r]+" );
for ( int il = 0; il < lines.length; il++ ) {
String line = lines[ il ];
if ( line.trim().length() > 0 ) {
StringBuffer sbuf = new StringBuffer();
sbuf.append( ecode )
.append( il == 0 ? '-' : '+' )
.append( fcount )
.append( ' ' )
.append( lines[ il ] );
println( sbuf.toString() );
}
}
}
if ( debug_ && err != null ) {
err.printStackTrace( out_ );
}
}
|
diff --git a/hudson-core/src/main/java/hudson/model/AbstractProject.java b/hudson-core/src/main/java/hudson/model/AbstractProject.java
index c728489d..d936f4df 100644
--- a/hudson-core/src/main/java/hudson/model/AbstractProject.java
+++ b/hudson-core/src/main/java/hudson/model/AbstractProject.java
@@ -1,2173 +1,2178 @@
/*******************************************************************************
*
* Copyright (c) 2004-2011 Oracle Corporation.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
*
* Kohsuke Kawaguchi, Brian Westrich, Erik Ramfelt, Ertan Deniz, Jean-Baptiste Quenot, Luca Domenico Milanesio,
* R. Tyler Ballance, Stephen Connolly, Tom Huybrechts, id:cactusman, Yahoo! Inc., Anton Kozak, Nikita Levyankov
*
*
*******************************************************************************/
package hudson.model;
import antlr.ANTLRException;
import hudson.AbortException;
import hudson.CopyOnWrite;
import hudson.FeedAdapter;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.cli.declarative.CLIMethod;
import hudson.cli.declarative.CLIResolver;
import hudson.diagnosis.OldDataMonitor;
import hudson.model.Cause.LegacyCodeCause;
import hudson.model.Cause.RemoteCause;
import hudson.model.Cause.UserCause;
import hudson.model.Descriptor.FormException;
import hudson.model.Fingerprint.RangeSet;
import hudson.model.Queue.Executable;
import hudson.model.Queue.Task;
import hudson.model.Queue.WaitingItem;
import hudson.model.RunMap.Constructor;
import hudson.model.labels.LabelAtom;
import hudson.model.labels.LabelExpression;
import hudson.util.CascadingUtil;
import hudson.util.DescribableListUtil;
import org.eclipse.hudson.api.model.IProjectProperty;
import org.eclipse.hudson.api.model.project.property.BooleanProjectProperty;
import org.eclipse.hudson.api.model.project.property.IntegerProjectProperty;
import hudson.model.queue.CauseOfBlockage;
import hudson.model.queue.SubTask;
import hudson.model.queue.SubTaskContributor;
import hudson.scm.ChangeLogSet;
import hudson.scm.ChangeLogSet.Entry;
import hudson.scm.NullSCM;
import hudson.scm.PollingResult;
import hudson.scm.SCM;
import hudson.scm.SCMRevisionState;
import hudson.scm.SCMS;
import hudson.search.SearchIndexBuilder;
import hudson.security.Permission;
import hudson.slaves.WorkspaceList;
import hudson.tasks.BuildStep;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildTrigger;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Mailer;
import hudson.tasks.Publisher;
import hudson.triggers.SCMTrigger;
import hudson.triggers.Trigger;
import hudson.triggers.TriggerDescriptor;
import hudson.util.AutoCompleteSeeder;
import hudson.util.DescribableList;
import hudson.util.EditDistance;
import hudson.util.FormValidation;
import hudson.widgets.BuildHistoryWidget;
import hudson.widgets.HistoryWidget;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.eclipse.hudson.api.model.IAbstractProject;
import org.eclipse.hudson.api.model.project.property.SCMProjectProperty;
import org.eclipse.hudson.api.model.project.property.StringProjectProperty;
import org.eclipse.hudson.api.model.project.property.TriggerProjectProperty;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.stapler.ForwardToView;
import org.kohsuke.stapler.HttpRedirect;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import static hudson.scm.PollingResult.BUILD_NOW;
import static hudson.scm.PollingResult.NO_CHANGES;
import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
/**
* Base implementation of {@link Job}s that build software.
*
* For now this is primarily the common part of {@link Project} and MavenModule.
*
* @author Kohsuke Kawaguchi
* @see AbstractBuild
*/
public abstract class AbstractProject<P extends AbstractProject<P,R>,R extends AbstractBuild<P,R>> extends Job<P,R> implements BuildableItem,
IAbstractProject {
public static final String CONCURRENT_BUILD_PROPERTY_NAME = "concurrentBuild";
public static final String CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME = "cleanWorkspaceRequired";
public static final String BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME = "blockBuildWhenDownstreamBuilding";
public static final String BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME = "blockBuildWhenUpstreamBuilding";
public static final String QUIET_PERIOD_PROPERTY_NAME = "quietPeriod";
public static final String SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME = "scmCheckoutRetryCount";
public static final String CUSTOM_WORKSPACE_PROPERTY_NAME = "customWorkspace";
public static final String JDK_PROPERTY_NAME = "jdk";
public static final String SCM_PROPERTY_NAME = "scm";
public static final String HAS_QUIET_PERIOD_PROPERTY_NAME = "hasQuietPeriod";
public static final String HAS_SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME = "hasScmCheckoutRetryCount";
/**
* {@link SCM} associated with the project.
* To allow derived classes to link {@link SCM} config to elsewhere,
* access to this variable should always go through {@link #getScm()}.
* @deprecated as of 2.2.0
* don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
@Deprecated
private volatile SCM scm = new NullSCM();
/**
* State returned from {@link SCM#poll(AbstractProject, Launcher, FilePath, TaskListener, SCMRevisionState)}.
*/
private volatile transient SCMRevisionState pollingBaseline = null;
/**
* All the builds keyed by their build number.
*/
protected transient /*almost final*/ RunMap<R> builds = new RunMap<R>();
/**
* The quiet period. Null to delegate to the system default.
* @deprecated as of 2.2.0
* don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*
*/
@Deprecated
private volatile Integer quietPeriod = null;
/**
* The retry count. Null to delegate to the system default.
* @deprecated as of 2.2.0
* don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
@Deprecated
private volatile Integer scmCheckoutRetryCount = null;
/**
* If this project is configured to be only built on a certain label,
* this value will be set to that label.
*
* For historical reasons, this is called 'assignedNode'. Also for
* a historical reason, null to indicate the affinity
* with the master node.
*
* @see #canRoam
*/
private String assignedNode;
/**
* Node list is dropdown or textfield
*/
private Boolean advancedAffinityChooser;
/**
* True if this project can be built on any node.
*
* <p>
* This somewhat ugly flag combination is so that we can migrate
* existing Hudson installations nicely.
*/
private volatile boolean canRoam;
/**
* True to suspend new builds.
*/
protected volatile boolean disabled;
/**
* True to keep builds of this project in queue when downstream projects are building.
*
* @deprecated as of 2.2.0. Don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
@Deprecated
protected volatile boolean blockBuildWhenDownstreamBuilding;
/**
* True to keep builds of this project in queue when upstream projects are building.
*
* @deprecated as of 2.2.0. Don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
@Deprecated
protected volatile boolean blockBuildWhenUpstreamBuilding;
/**
* Identifies {@link JDK} to be used.
* Null if no explicit configuration is required.
*
* <p>
* Can't store {@link JDK} directly because {@link Hudson} and {@link Project}
* are saved independently.
*
* @see Hudson#getJDK(String)
* @deprecated as of 2.2.0
* don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
@Deprecated
private volatile String jdk;
/**
* @deprecated since 2007-01-29.
*/
@Deprecated
private transient boolean enableRemoteTrigger;
private volatile BuildAuthorizationToken authToken = null;
/**
* List of all {@link Trigger}s for this project.
*
* @deprecated as of 2.2.0
*
* don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
protected List<Trigger<?>> triggers = new Vector<Trigger<?>>();
/**
* {@link Action}s contributed from subsidiary objects associated with
* {@link AbstractProject}, such as from triggers, builders, publishers, etc.
*
* We don't want to persist them separately, and these actions
* come and go as configuration change, so it's kept separate.
*/
@CopyOnWrite
protected transient volatile List<Action> transientActions = new Vector<Action>();
/**
* @deprecated as of 2.2.0 Don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
@Deprecated
private boolean concurrentBuild;
/**
* True to clean the workspace prior to each build.
*
* @deprecated as of 2.2.0 don't use this field directly, logic was moved to {@link org.eclipse.hudson.api.model.IProjectProperty}.
* Use getter/setter for accessing to this field.
*/
@Deprecated
private volatile boolean cleanWorkspaceRequired;
protected AbstractProject(ItemGroup parent, String name) {
super(parent, name);
if (Hudson.getInstance() != null && !Hudson.getInstance().getNodes().isEmpty()) {
// if a new job is configured with Hudson that already has slave nodes
// make it roamable by default
canRoam = true;
}
}
@Override
public void onCreatedFromScratch() {
super.onCreatedFromScratch();
// solicit initial contributions, especially from TransientProjectActionFactory
updateTransientActions();
setCreationTime(new GregorianCalendar().getTimeInMillis());
User user = User.current();
if (user != null){
setCreatedBy(user.getId());
grantProjectMatrixPermissions(user);
}
}
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
super.onLoad(parent, name);
this.builds = new RunMap<R>();
this.builds.load(this, new Constructor<R>() {
public R create(File dir) throws IOException {
return loadBuild(dir);
}
});
// boolean! Can't tell if xml file contained false..
if (enableRemoteTrigger) OldDataMonitor.report(this, "1.77");
for (Trigger t : getTriggerDescribableList()) {
t.start(this,false);
}
if(scm==null)
scm = new NullSCM(); // perhaps it was pointing to a plugin that no longer exists.
if(transientActions==null)
transientActions = new Vector<Action>(); // happens when loaded from disk
updateTransientActions();
getTriggerDescribableList().setOwner(this);
}
@Override
protected void buildProjectProperties() throws IOException {
super.buildProjectProperties();
convertBlockBuildWhenUpstreamBuildingProperty();
convertBlockBuildWhenDownstreamBuildingProperty();
convertConcurrentBuildProperty();
convertCleanWorkspaceRequiredProperty();
convertQuietPeriodProperty();
convertScmCheckoutRetryCountProperty();
convertJDKProperty();
convertTriggerProperties();
}
void convertBlockBuildWhenUpstreamBuildingProperty() throws IOException {
if (null == getProperty(BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME)) {
setBlockBuildWhenUpstreamBuilding(blockBuildWhenUpstreamBuilding);
blockBuildWhenUpstreamBuilding = false;
}
}
void convertBlockBuildWhenDownstreamBuildingProperty() throws IOException {
if (null == getProperty(BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME)) {
setBlockBuildWhenDownstreamBuilding(blockBuildWhenDownstreamBuilding);
blockBuildWhenDownstreamBuilding = false;
}
}
void convertConcurrentBuildProperty() throws IOException {
if (null == getProperty(CONCURRENT_BUILD_PROPERTY_NAME)) {
setConcurrentBuild(concurrentBuild);
concurrentBuild = false;
}
}
void convertCleanWorkspaceRequiredProperty() throws IOException {
if (null == getProperty(CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME)) {
setCleanWorkspaceRequired(cleanWorkspaceRequired);
cleanWorkspaceRequired = false;
}
}
void convertQuietPeriodProperty() throws IOException {
if (null != quietPeriod && null == getProperty(QUIET_PERIOD_PROPERTY_NAME)) {
setQuietPeriod(quietPeriod);
quietPeriod = null;
}
}
void convertScmCheckoutRetryCountProperty() throws IOException {
if (null != scmCheckoutRetryCount && null == getProperty(SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME)) {
setScmCheckoutRetryCount(scmCheckoutRetryCount);
scmCheckoutRetryCount = null;
}
}
void convertJDKProperty() throws IOException {
if (null != jdk && null == getProperty(JDK_PROPERTY_NAME)) {
setJDK(jdk);
jdk = null;
}
}
void convertScmProperty() throws IOException {
if (null != scm && null == getProperty(SCM_PROPERTY_NAME)) {
setScm(scm);
scm = null;
}
}
void convertTriggerProperties() {
if (triggers != null) {
setTriggers(triggers);
triggers = null;
}
}
@Override
protected void performDelete() throws IOException, InterruptedException {
// prevent a new build while a delete operation is in progress
makeDisabled(true);
FilePath ws = getWorkspace();
if(ws!=null) {
Node on = getLastBuiltOn();
getScm().processWorkspaceBeforeDeletion(this, ws, on);
if(on!=null)
on.getFileSystemProvisioner().discardWorkspace(this,ws);
}
super.performDelete();
}
/**
* Does this project perform concurrent builds?
* @since 1.319
*/
@Exported
public boolean isConcurrentBuild() {
return Hudson.CONCURRENT_BUILD
&& CascadingUtil.getBooleanProjectProperty(this, CONCURRENT_BUILD_PROPERTY_NAME).getValue();
}
public void setConcurrentBuild(boolean b) throws IOException {
CascadingUtil.getBooleanProjectProperty(this, CONCURRENT_BUILD_PROPERTY_NAME).setValue(b);
save();
}
public boolean isCleanWorkspaceRequired() {
return CascadingUtil.getBooleanProjectProperty(this, CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME).getValue();
}
public void setCleanWorkspaceRequired(boolean cleanWorkspaceRequired) {
CascadingUtil.getBooleanProjectProperty(this,
CLEAN_WORKSPACE_REQUIRED_PROPERTY_NAME).setValue(cleanWorkspaceRequired);
}
/**
* If this project is configured to be always built on this node,
* return that {@link Node}. Otherwise null.
*/
public Label getAssignedLabel() {
if(canRoam)
return null;
if(assignedNode==null)
return Hudson.getInstance().getSelfLabel();
return Hudson.getInstance().getLabel(assignedNode);
}
/**
* Gets the textual representation of the assigned label as it was entered by the user.
*/
public String getAssignedLabelString() {
if (canRoam || assignedNode==null) return null;
try {
LabelExpression.parseExpression(assignedNode);
return assignedNode;
} catch (ANTLRException e) {
// must be old label or host name that includes whitespace or other unsafe chars
return LabelAtom.escape(assignedNode);
}
}
/**
* Sets the assigned label.
*/
public void setAssignedLabel(Label l) throws IOException {
if(l==null) {
canRoam = true;
assignedNode = null;
} else {
canRoam = false;
if(l==Hudson.getInstance().getSelfLabel()) assignedNode = null;
else assignedNode = l.getExpression();
}
save();
}
/**
* Assigns this job to the given node. A convenience method over {@link #setAssignedLabel(Label)}.
*/
public void setAssignedNode(Node l) throws IOException {
setAssignedLabel(l.getSelfLabel());
}
/**
* Gets whether this project is using the advanced affinity chooser UI.
*
* @return true - advanced chooser, false - simple textfield.
*/
public boolean isAdvancedAffinityChooser() {
//For newly created project advanced chooser is not used.
//Set value to false in order to avoid NullPointerException
if (null == advancedAffinityChooser) {
advancedAffinityChooser = false;
}
return advancedAffinityChooser;
}
/**
* Sets whether this project is using the advanced affinity chooser UI.
*
* @param b true - advanced chooser, false - otherwise
*/
public void setAdvancedAffinityChooser(boolean b) throws IOException {
advancedAffinityChooser = b;
save();
}
/**
* Get the term used in the UI to represent this kind of {@link AbstractProject}.
* Must start with a capital letter.
*/
@Override
public String getPronoun() {
return Messages.AbstractProject_Pronoun();
}
/**
* Returns the root project value.
*
* @return the root project value.
*/
public AbstractProject getRootProject() {
if (this.getParent() instanceof Hudson) {
return this;
} else {
return ((AbstractProject) this.getParent()).getRootProject();
}
}
/**
* Gets the directory where the module is checked out.
*
* @return
* null if the workspace is on a slave that's not connected.
* @deprecated as of 1.319
* To support concurrent builds of the same project, this method is moved to {@link AbstractBuild}.
* For backward compatibility, this method returns the right {@link AbstractBuild#getWorkspace()} if called
* from {@link Executor}, and otherwise the workspace of the last build.
*
* <p>
* If you are calling this method during a build from an executor, switch it to {@link AbstractBuild#getWorkspace()}.
* If you are calling this method to serve a file from the workspace, doing a form validation, etc., then
* use {@link #getSomeWorkspace()}
*/
public final FilePath getWorkspace() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getWorkspace() : null;
}
/**
* Various deprecated methods in this class all need the 'current' build. This method returns
* the build suitable for that purpose.
*
* @return An AbstractBuild for deprecated methods to use.
*/
private AbstractBuild getBuildForDeprecatedMethods() {
Executor e = Executor.currentExecutor();
if(e!=null) {
Executable exe = e.getCurrentExecutable();
if (exe instanceof AbstractBuild) {
AbstractBuild b = (AbstractBuild) exe;
if(b.getProject()==this)
return b;
}
}
R lb = getLastBuild();
if(lb!=null) return lb;
return null;
}
/**
* Gets a workspace for some build of this project.
*
* <p>
* This is useful for obtaining a workspace for the purpose of form field validation, where exactly
* which build the workspace belonged is less important. The implementation makes a cursory effort
* to find some workspace.
*
* @return
* null if there's no available workspace.
* @since 1.319
*/
public final FilePath getSomeWorkspace() {
R b = getSomeBuildWithWorkspace();
return b!=null ? b.getWorkspace() : null;
}
/**
* Gets some build that has a live workspace.
*
* @return null if no such build exists.
*/
public final R getSomeBuildWithWorkspace() {
int cnt=0;
for (R b = getLastBuild(); cnt<5 && b!=null; b=b.getPreviousBuild()) {
FilePath ws = b.getWorkspace();
if (ws!=null) return b;
}
return null;
}
/**
* Returns the root directory of the checked-out module.
* <p>
* This is usually where <tt>pom.xml</tt>, <tt>build.xml</tt>
* and so on exists.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath getModuleRoot() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoot() : null;
}
/**
* Returns the root directories of all checked-out modules.
* <p>
* Some SCMs support checking out multiple modules into the same workspace.
* In these cases, the returned array will have a length greater than one.
* @return The roots of all modules checked out from the SCM.
*
* @deprecated as of 1.319
* See {@link #getWorkspace()} for a migration strategy.
*/
public FilePath[] getModuleRoots() {
AbstractBuild b = getBuildForDeprecatedMethods();
return b != null ? b.getModuleRoots() : null;
}
public int getQuietPeriod() {
IntegerProjectProperty property = CascadingUtil.getIntegerProjectProperty(this, QUIET_PERIOD_PROPERTY_NAME);
Integer value = property.getValue();
return property.getDefaultValue().equals(value) ? Hudson.getInstance().getQuietPeriod() : value;
}
/**
* Sets the custom quiet period of this project, or revert to the global default if null is given.
*
* @param seconds quiet period
* @throws IOException if any.
*/
public void setQuietPeriod(Integer seconds) throws IOException {
CascadingUtil.getIntegerProjectProperty(this, QUIET_PERIOD_PROPERTY_NAME).setValue(seconds);
save();
}
public int getScmCheckoutRetryCount() {
IntegerProjectProperty property = CascadingUtil.getIntegerProjectProperty(this,
SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME);
Integer value = property.getValue();
return property.getDefaultValue().equals(value) ? Hudson.getInstance().getScmCheckoutRetryCount() : value;
}
public void setScmCheckoutRetryCount(Integer retryCount) {
CascadingUtil.getIntegerProjectProperty(this, SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME).setValue(retryCount);
}
/**
* Sets scmCheckoutRetryCount, Uses {@link NumberUtils#isNumber(String)} for checking retryCount param.
* If it is not valid number, null will be set.
*
* @param scmCheckoutRetryCount retry count.
* @throws IOException if any.
*/
protected void setScmCheckoutRetryCount(String scmCheckoutRetryCount) throws IOException {
Integer retryCount = null;
if (NumberUtils.isNumber(scmCheckoutRetryCount)) {
retryCount = NumberUtils.createInteger(scmCheckoutRetryCount);
}
setScmCheckoutRetryCount(retryCount);
}
/**
* @return true if quiet period was configured.
* @deprecated as of 2.1.2
* This method was used only on UI side. No longer required.
*/
// ugly name because of EL
public boolean getHasCustomQuietPeriod() {
return null != CascadingUtil.getIntegerProjectProperty(this, QUIET_PERIOD_PROPERTY_NAME).getValue();
}
/**
* Sets quietPeriod, Uses {@link NumberUtils#isNumber(String)} for checking seconds param. If seconds is not valid
* number, null will be set.
*
* @param seconds quiet period.
* @throws IOException if any.
*/
protected void setQuietPeriod(String seconds) throws IOException {
Integer period = null;
if (NumberUtils.isNumber(seconds)) {
period = NumberUtils.createInteger(seconds);
}
setQuietPeriod(period);
}
/**
* Checks whether scmRetryCount is configured
*
* @return true if yes, false - otherwise.
* @deprecated as of 2.1.2
*/
public boolean hasCustomScmCheckoutRetryCount(){
return null != CascadingUtil.getIntegerProjectProperty(this, SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME).getValue();
}
@Override
public boolean isBuildable() {
return !isDisabled() && !isHoldOffBuildUntilSave();
}
/**
* Used in <tt>sidepanel.jelly</tt> to decide whether to display
* the config/delete/build links.
*/
public boolean isConfigurable() {
return true;
}
public boolean blockBuildWhenDownstreamBuilding() {
return CascadingUtil.getBooleanProjectProperty(this,
BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME).getValue();
}
public void setBlockBuildWhenDownstreamBuilding(boolean b) throws IOException {
CascadingUtil.getBooleanProjectProperty(this, BLOCK_BUILD_WHEN_DOWNSTREAM_BUILDING_PROPERTY_NAME).setValue(b);
save();
}
public boolean blockBuildWhenUpstreamBuilding() {
return CascadingUtil.getBooleanProjectProperty(this,
BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME).getValue();
}
public void setBlockBuildWhenUpstreamBuilding(boolean b) throws IOException {
CascadingUtil.getBooleanProjectProperty(this, BLOCK_BUILD_WHEN_UPSTREAM_BUILDING_PROPERTY_NAME).setValue(b);
save();
}
public boolean isDisabled() {
return disabled;
}
/**
* Validates the retry count Regex
*/
public FormValidation doCheckRetryCount(@QueryParameter String value)throws IOException,ServletException{
// retry count is optional so this is ok
if(value == null || value.trim().equals(""))
return FormValidation.ok();
if (!value.matches("[0-9]*")) {
return FormValidation.error("Invalid retry count");
}
return FormValidation.ok();
}
/**
* Marks the build as disabled.
*/
public void makeDisabled(boolean b) throws IOException {
if(disabled==b) return; // noop
this.disabled = b;
if(b)
Hudson.getInstance().getQueue().cancel(this);
save();
}
public void disable() throws IOException {
makeDisabled(true);
}
public void enable() throws IOException {
makeDisabled(false);
}
@Override
public BallColor getIconColor() {
if(isDisabled())
return BallColor.DISABLED;
else
return super.getIconColor();
}
/**
* effectively deprecated. Since using updateTransientActions correctly
* under concurrent environment requires a lock that can too easily cause deadlocks.
*
* <p>
* Override {@link #createTransientActions()} instead.
*/
protected void updateTransientActions() {
transientActions = createTransientActions();
}
protected List<Action> createTransientActions() {
Vector<Action> ta = new Vector<Action>();
for (JobProperty<? super P> p : properties)
ta.addAll(p.getJobActions((P)this));
for (TransientProjectActionFactory tpaf : TransientProjectActionFactory.all())
ta.addAll(Util.fixNull(tpaf.createFor(this))); // be defensive against null
return ta;
}
/**
* Returns the live list of all {@link Publisher}s configured for this project.
*
* <p>
* This method couldn't be called <tt>getPublishers()</tt> because existing methods
* in sub-classes return different inconsistent types.
*/
public abstract DescribableList<Publisher,Descriptor<Publisher>> getPublishersList();
@Override
public void addProperty(JobProperty<? super P> jobProp) throws IOException {
super.addProperty(jobProp);
updateTransientActions();
}
public List<ProminentProjectAction> getProminentActions() {
List<Action> a = getActions();
List<ProminentProjectAction> pa = new Vector<ProminentProjectAction>();
for (Action action : a) {
if(action instanceof ProminentProjectAction)
pa.add((ProminentProjectAction) action);
}
return pa;
}
@Override
public void doConfigSubmit( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, FormException {
super.doConfigSubmit(req,rsp);
updateTransientActions();
Set<AbstractProject> upstream = Collections.emptySet();
if(req.getParameter("pseudoUpstreamTrigger")!=null) {
upstream = new HashSet<AbstractProject>(Items.fromNameList(req.getParameter("upstreamProjects"),AbstractProject.class));
}
// dependency setting might have been changed by the user, so rebuild.
Hudson.getInstance().rebuildDependencyGraph();
// reflect the submission of the pseudo 'upstream build trriger'.
// this needs to be done after we release the lock on 'this',
// or otherwise we could dead-lock
for (AbstractProject<?,?> p : Hudson.getInstance().getAllItems(AbstractProject.class)) {
// Don't consider child projects such as MatrixConfiguration:
if (!p.isConfigurable()) continue;
boolean isUpstream = upstream.contains(p);
synchronized(p) {
// does 'p' include us in its BuildTrigger?
DescribableList<Publisher,Descriptor<Publisher>> pl = p.getPublishersList();
BuildTrigger trigger = pl.get(BuildTrigger.class);
List<AbstractProject> newChildProjects = trigger == null ? new ArrayList<AbstractProject>():trigger.getChildProjects();
if(isUpstream) {
if(!newChildProjects.contains(this))
newChildProjects.add(this);
} else {
newChildProjects.remove(this);
}
if(newChildProjects.isEmpty()) {
pl.remove(BuildTrigger.class);
} else {
// here, we just need to replace the old one with the new one,
// but there was a regression (we don't know when it started) that put multiple BuildTriggers
// into the list.
// for us not to lose the data, we need to merge them all.
List<BuildTrigger> existingList = pl.getAll(BuildTrigger.class);
BuildTrigger existing;
switch (existingList.size()) {
case 0:
existing = null;
break;
case 1:
existing = existingList.get(0);
break;
default:
pl.removeAll(BuildTrigger.class);
Set<AbstractProject> combinedChildren = new HashSet<AbstractProject>();
for (BuildTrigger bt : existingList)
combinedChildren.addAll(bt.getChildProjects());
existing = new BuildTrigger(new ArrayList<AbstractProject>(combinedChildren),existingList.get(0).getThreshold());
pl.add(existing);
break;
}
if(existing!=null && existing.hasSame(newChildProjects))
continue; // no need to touch
pl.replace(new BuildTrigger(newChildProjects,
existing==null?Result.SUCCESS:existing.getThreshold()));
}
p.putAllProjectProperties(DescribableListUtil.convertToProjectProperties(pl, p), false);
}
}
// notify the queue as the project might be now tied to different node
Hudson.getInstance().getQueue().scheduleMaintenance();
// this is to reflect the upstream build adjustments done above
Hudson.getInstance().rebuildDependencyGraph();
}
/**
* @deprecated
* Use {@link #scheduleBuild(Cause)}. Since 1.283
*/
public boolean scheduleBuild() {
return scheduleBuild(new LegacyCodeCause());
}
/**
* @deprecated
* Use {@link #scheduleBuild(int, Cause)}. Since 1.283
*/
public boolean scheduleBuild(int quietPeriod) {
return scheduleBuild(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project.
*
* @return
* true if the project is actually added to the queue.
* false if the queue contained it and therefore the add()
* was noop
*/
public boolean scheduleBuild(Cause c) {
return scheduleBuild(getQuietPeriod(), c);
}
public boolean scheduleBuild(int quietPeriod, Cause c) {
return scheduleBuild(quietPeriod, c, new Action[0]);
}
/**
* Schedules a build.
*
* Important: the actions should be persistable without outside references (e.g. don't store
* references to this project). To provide parameters for a parameterized project, add a ParametersAction. If
* no ParametersAction is provided for such a project, one will be created with the default parameter values.
*
* @param quietPeriod the quiet period to observer
* @param c the cause for this build which should be recorded
* @param actions a list of Actions that will be added to the build
* @return whether the build was actually scheduled
*/
public boolean scheduleBuild(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,actions)!=null;
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this array can contain null, and those will be silently ignored.
*/
public Future<R> scheduleBuild2(int quietPeriod, Cause c, Action... actions) {
return scheduleBuild2(quietPeriod,c,Arrays.asList(actions));
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*
* @param actions
* For the convenience of the caller, this collection can contain null, and those will be silently ignored.
* @since 1.383
*/
public Future<R> scheduleBuild2(int quietPeriod, Cause c, Collection<? extends Action> actions) {
if (!isBuildable())
return null;
List<Action> queueActions = new ArrayList<Action>(actions);
if (isParameterized() && Util.filter(queueActions, ParametersAction.class).isEmpty()) {
queueActions.add(new ParametersAction(getDefaultParametersValues()));
}
if (c != null) {
queueActions.add(new CauseAction(c));
}
WaitingItem i = Hudson.getInstance().getQueue().schedule(this, quietPeriod, queueActions);
if(i!=null)
return (Future)i.getFuture();
return null;
}
private List<ParameterValue> getDefaultParametersValues() {
ParametersDefinitionProperty paramDefProp = getProperty(ParametersDefinitionProperty.class);
ArrayList<ParameterValue> defValues = new ArrayList<ParameterValue>();
/*
* This check is made ONLY if someone will call this method even if isParametrized() is false.
*/
if(paramDefProp == null)
return defValues;
/* Scan for all parameter with an associated default values */
for(ParameterDefinition paramDefinition : paramDefProp.getParameterDefinitions())
{
ParameterValue defaultValue = paramDefinition.getDefaultParameterValue();
if(defaultValue != null)
defValues.add(defaultValue);
}
return defValues;
}
/**
* Schedules a build, and returns a {@link Future} object
* to wait for the completion of the build.
*
* <p>
* Production code shouldn't be using this, but for tests this is very convenient, so this isn't marked
* as deprecated.
*/
public Future<R> scheduleBuild2(int quietPeriod) {
return scheduleBuild2(quietPeriod, new LegacyCodeCause());
}
/**
* Schedules a build of this project, and returns a {@link Future} object
* to wait for the completion of the build.
*/
public Future<R> scheduleBuild2(int quietPeriod, Cause c) {
return scheduleBuild2(quietPeriod, c, new Action[0]);
}
/**
* Schedules a polling of this project.
*/
public boolean schedulePolling() {
if(isDisabled()) return false;
SCMTrigger scmt = getTrigger(SCMTrigger.class);
if(scmt==null) return false;
scmt.run();
return true;
}
/**
* Returns true if the build is in the queue.
*/
@Override
public boolean isInQueue() {
return Hudson.getInstance().getQueue().contains(this);
}
@Override
public Queue.Item getQueueItem() {
return Hudson.getInstance().getQueue().getItem(this);
}
/**
* @return name of jdk chosen for current project. Could taken from parent
*/
public String getJDKName() {
return CascadingUtil.getStringProjectProperty(this, JDK_PROPERTY_NAME).getValue();
}
/**
* @return JDK that this project is configured with, or null.
*/
public JDK getJDK() {
return Hudson.getInstance().getJDK(getJDKName());
}
/**
* Overwrites the JDK setting.
*/
public void setJDK(JDK jdk) throws IOException {
setJDK(jdk.getName());
save();
}
public void setJDK(String jdk) {
CascadingUtil.getStringProjectProperty(this, JDK_PROPERTY_NAME).setValue(jdk);
}
public BuildAuthorizationToken getAuthToken() {
return authToken;
}
@Override
public SortedMap<Integer, ? extends R> _getRuns() {
return builds.getView();
}
@Override
public void removeRun(R run) {
this.builds.remove(run);
}
/**
* Determines Class<R>.
*/
protected abstract Class<R> getBuildClass();
// keep track of the previous time we started a build
private transient long lastBuildStartTime;
/**
* Creates a new build of this project for immediate execution.
*/
protected synchronized R newBuild() throws IOException {
// make sure we don't start two builds in the same second
// so the build directories will be different too
long timeSinceLast = System.currentTimeMillis() - lastBuildStartTime;
if (timeSinceLast < 1000) {
try {
Thread.sleep(1000 - timeSinceLast);
} catch (InterruptedException e) {
}
}
lastBuildStartTime = System.currentTimeMillis();
try {
R lastBuild = getBuildClass().getConstructor(getClass()).newInstance(this);
builds.put(lastBuild);
return lastBuild;
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
private IOException handleInvocationTargetException(InvocationTargetException e) {
Throwable t = e.getTargetException();
if(t instanceof Error) throw (Error)t;
if(t instanceof RuntimeException) throw (RuntimeException)t;
if(t instanceof IOException) return (IOException)t;
throw new Error(t);
}
/**
* Loads an existing build record from disk.
*/
protected R loadBuild(File dir) throws IOException {
try {
return getBuildClass().getConstructor(getClass(),File.class).newInstance(this,dir);
} catch (InstantiationException e) {
throw new Error(e);
} catch (IllegalAccessException e) {
throw new Error(e);
} catch (InvocationTargetException e) {
throw handleInvocationTargetException(e);
} catch (NoSuchMethodException e) {
throw new Error(e);
}
}
/**
* {@inheritDoc}
*
* <p>
* Note that this method returns a read-only view of {@link Action}s.
* {@link BuildStep}s and others who want to add a project action
* should do so by implementing {@link BuildStep#getProjectActions(AbstractProject)}.
*
* @see TransientProjectActionFactory
*/
@Override
public synchronized List<Action> getActions() {
// add all the transient actions, too
List<Action> actions = new Vector<Action>(super.getActions());
actions.addAll(transientActions);
// return the read only list to cause a failure on plugins who try to add an action here
return Collections.unmodifiableList(actions);
}
/**
* Gets the {@link Node} where this project was last built on.
*
* @return
* null if no information is available (for example,
* if no build was done yet.)
*/
public Node getLastBuiltOn() {
// where was it built on?
AbstractBuild b = getLastBuild();
if(b==null)
return null;
else
return b.getBuiltOn();
}
public Object getSameNodeConstraint() {
return this; // in this way, any member that wants to run with the main guy can nominate the project itself
}
public final Task getOwnerTask() {
return this;
}
/**
* {@inheritDoc}
*
* <p>
* A project must be blocked if its own previous build is in progress,
* or if the blockBuildWhenUpstreamBuilding option is true and an upstream
* project is building, but derived classes can also check other conditions.
*/
public boolean isBuildBlocked() {
return getCauseOfBlockage()!=null;
}
public String getWhyBlocked() {
CauseOfBlockage cb = getCauseOfBlockage();
return cb!=null ? cb.getShortDescription() : null;
}
/**
* Blocked because the previous build is already in progress.
*/
public static class BecauseOfBuildInProgress extends CauseOfBlockage {
private final AbstractBuild<?,?> build;
public BecauseOfBuildInProgress(AbstractBuild<?, ?> build) {
this.build = build;
}
@Override
public String getShortDescription() {
Executor e = build.getExecutor();
String eta = "";
if (e != null)
eta = Messages.AbstractProject_ETA(e.getEstimatedRemainingTime());
int lbn = build.getNumber();
return Messages.AbstractProject_BuildInProgress(lbn, eta);
}
}
/**
* Because the downstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfDownstreamBuildInProgress extends CauseOfBlockage {
//TODO: review and check whether we can do it private
public final AbstractProject<?,?> up;
public AbstractProject getUp() {
return up;
}
public BecauseOfDownstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_DownstreamBuildInProgress(up.getName());
}
}
/**
* Because the upstream build is in progress, and we are configured to wait for that.
*/
public static class BecauseOfUpstreamBuildInProgress extends CauseOfBlockage {
//TODO: review and check whether we can do it private
public final AbstractProject<?,?> up;
public BecauseOfUpstreamBuildInProgress(AbstractProject<?,?> up) {
this.up = up;
}
public AbstractProject getUp() {
return up;
}
@Override
public String getShortDescription() {
return Messages.AbstractProject_UpstreamBuildInProgress(up.getName());
}
}
public CauseOfBlockage getCauseOfBlockage() {
if (isBuilding() && !isConcurrentBuild())
return new BecauseOfBuildInProgress(getLastBuild());
if (blockBuildWhenDownstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingDownstream();
if (bup!=null)
return new BecauseOfDownstreamBuildInProgress(bup);
} else if (blockBuildWhenUpstreamBuilding()) {
AbstractProject<?,?> bup = getBuildingUpstream();
if (bup!=null)
return new BecauseOfUpstreamBuildInProgress(bup);
}
return null;
}
/**
* Returns the project if any of the downstream project (or itself) is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
protected AbstractProject getBuildingDownstream() {
DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
Set<AbstractProject> tups = graph.getTransitiveDownstream(this);
tups.add(this);
for (AbstractProject tup : tups) {
if(tup!=this && (tup.isBuilding() || tup.isInQueue()))
return tup;
}
return null;
}
/**
* Returns the project if any of the upstream project (or itself) is either
* building or is in the queue.
* <p>
* This means eventually there will be an automatic triggering of
* the given project (provided that all builds went smoothly.)
*/
protected AbstractProject getBuildingUpstream() {
DependencyGraph graph = Hudson.getInstance().getDependencyGraph();
Set<AbstractProject> tups = graph.getTransitiveUpstream(this);
tups.add(this);
for (AbstractProject tup : tups) {
if(tup!=this && (tup.isBuilding() || tup.isInQueue()))
return tup;
}
return null;
}
public List<SubTask> getSubTasks() {
List<SubTask> r = new ArrayList<SubTask>();
r.add(this);
for (SubTaskContributor euc : SubTaskContributor.all())
r.addAll(euc.forProject(this));
for (JobProperty<? super P> p : properties)
r.addAll(p.getSubTasks());
return r;
}
public R createExecutable() throws IOException {
if(isDisabled()) return null;
return newBuild();
}
public void checkAbortPermission() {
checkPermission(AbstractProject.ABORT);
}
public boolean hasAbortPermission() {
return hasPermission(AbstractProject.ABORT);
}
/**
* Gets the {@link Resource} that represents the workspace of this project.
* Useful for locking and mutual exclusion control.
*
* @deprecated as of 1.319
* Projects no longer have a fixed workspace, ands builds will find an available workspace via
* {@link WorkspaceList} for each build (furthermore, that happens after a build is started.)
* So a {@link Resource} representation for a workspace at the project level no longer makes sense.
*
* <p>
* If you need to lock a workspace while you do some computation, see the source code of
* {@link #pollSCMChanges(TaskListener)} for how to obtain a lock of a workspace through {@link WorkspaceList}.
*/
public Resource getWorkspaceResource() {
return new Resource(getFullDisplayName()+" workspace");
}
/**
* List of necessary resources to perform the build of this project.
*/
public ResourceList getResourceList() {
final Set<ResourceActivity> resourceActivities = getResourceActivities();
final List<ResourceList> resourceLists = new ArrayList<ResourceList>(1 + resourceActivities.size());
for (ResourceActivity activity : resourceActivities) {
if (activity != this && activity != null) {
// defensive infinite recursion and null check
resourceLists.add(activity.getResourceList());
}
}
return ResourceList.union(resourceLists);
}
/**
* Set of child resource activities of the build of this project (override in child projects).
* @return The set of child resource activities of the build of this project.
*/
protected Set<ResourceActivity> getResourceActivities() {
return Collections.emptySet();
}
public boolean checkout(AbstractBuild build, Launcher launcher, BuildListener listener, File changelogFile) throws IOException, InterruptedException {
SCM scm = getScm();
if(scm==null)
return true; // no SCM
FilePath workspace = build.getWorkspace();
workspace.mkdirs();
boolean r = scm.checkout(build, launcher, workspace, listener, changelogFile);
calcPollingBaseline(build, launcher, listener);
return r;
}
/**
* Pushes the baseline up to the newly checked out revision.
*/
private void calcPollingBaseline(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
SCMRevisionState baseline = build.getAction(SCMRevisionState.class);
if (baseline==null) {
try {
baseline = getScm()._calcRevisionsFromBuild(build, launcher, listener);
} catch (AbstractMethodError e) {
baseline = SCMRevisionState.NONE; // pre-1.345 SCM implementations, which doesn't use the baseline in polling
}
if (baseline!=null)
build.addAction(baseline);
}
pollingBaseline = baseline;
}
/**
* For reasons I don't understand, if I inline this method, AbstractMethodError escapes try/catch block.
*/
private SCMRevisionState safeCalcRevisionsFromBuild(AbstractBuild build, Launcher launcher, TaskListener listener) throws IOException, InterruptedException {
return getScm()._calcRevisionsFromBuild(build, launcher, listener);
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* @deprecated as of 1.346
* Use {@link #poll(TaskListener)} instead.
*/
public boolean pollSCMChanges( TaskListener listener ) {
return poll(listener).hasChanges();
}
/**
* Checks if there's any update in SCM, and returns true if any is found.
*
* <p>
* The implementation is responsible for ensuring mutual exclusion between polling and builds
* if necessary.
*
* @since 1.345
*/
public PollingResult poll( TaskListener listener ) {
SCM scm = getScm();
if (scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return NO_CHANGES;
}
if (isDisabled()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return NO_CHANGES;
}
R lb = getLastBuild();
if (lb==null) {
listener.getLogger().println(Messages.AbstractProject_NoBuilds());
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
if (pollingBaseline==null) {
R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
for (R r=lb; r!=null; r=r.getPreviousBuild()) {
SCMRevisionState s = r.getAction(SCMRevisionState.class);
if (s!=null) {
pollingBaseline = s;
break;
}
if (r==success) break; // searched far enough
}
// NOTE-NO-BASELINE:
// if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
// as action, so we need to compute it. This happens later.
}
try {
if (scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=lb.getWorkspace();
if (ws==null || !ws.exists()) {
// workspace offline. build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
return NO_CHANGES;
}
listener.getLogger().println( ws==null
? Messages.AbstractProject_WorkspaceOffline()
: Messages.AbstractProject_NoWorkspace());
if (isInQueue()) {
listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
return NO_CHANGES;
} else {
listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
return BUILD_NOW;
}
} else {
- WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
+ Node node = lb.getBuiltOn();
+ if (node == null || node.toComputer() == null) {
+ LOGGER.log(Level.FINE, "Node on which this job previously was built is not available now, build is started on an available node");
+ return isInQueue() ? NO_CHANGES : BUILD_NOW;
+ }
+ WorkspaceList l = node.toComputer().getWorkspaceList();
// if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
Launcher launcher = ws.createLauncher(listener);
try {
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
} finally {
lease.release();
}
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
}
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
return NO_CHANGES;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
return NO_CHANGES;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
return NO_CHANGES;
}
}
/**
* Returns true if this user has made a commit to this project.
*
* @since 1.191
*/
public boolean hasParticipant(User user) {
for( R build = getLastBuild(); build!=null; build=build.getPreviousBuild())
if(build.hasParticipant(user))
return true;
return false;
}
@Exported
public SCM getScm() {
return (SCM) getProperty(SCM_PROPERTY_NAME, SCMProjectProperty.class).getValue();
}
@SuppressWarnings("unchecked")
public void setScm(SCM scm) throws IOException {
getProperty(SCM_PROPERTY_NAME, SCMProjectProperty.class).setValue(scm);
save();
}
/**
* Adds a new {@link Trigger} to this {@link Project} if not active yet.
*/
@SuppressWarnings("unchecked")
public void addTrigger(Trigger<?> trigger) throws IOException {
CascadingUtil.getTriggerProjectProperty(this, trigger.getDescriptor().getJsonSafeClassName()).setValue(trigger);
}
public void removeTrigger(TriggerDescriptor trigger) throws IOException {
CascadingUtil.getTriggerProjectProperty(this, trigger.getJsonSafeClassName()).setValue(null);
}
protected final synchronized <T extends Describable<T>>
void addToList( T item, List<T> collection ) throws IOException {
for( int i=0; i<collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item.getDescriptor()) {
// replace
collection.set(i, item);
save();
return;
}
}
// add
collection.add(item);
save();
updateTransientActions();
}
protected final synchronized <T extends Describable<T>>
void removeFromList(Descriptor<T> item, List<T> collection) throws IOException {
for( int i=0; i< collection.size(); i++ ) {
if(collection.get(i).getDescriptor()==item) {
// found it
collection.remove(i);
save();
updateTransientActions();
return;
}
}
}
public synchronized Map<TriggerDescriptor,Trigger> getTriggers() {
return (Map)Descriptor.toMap(getTriggerDescribableList());
}
/**
* @return list of {@link Trigger} elements.
*/
public List<Trigger<?>> getTriggersList() {
return getTriggerDescribableList().toList();
}
/**
* @return describable list of trigger elements.
*/
public DescribableList<Trigger<?>, TriggerDescriptor> getTriggerDescribableList() {
return DescribableListUtil.convertToDescribableList(Trigger.for_(this), this, TriggerProjectProperty.class);
}
/**
* Gets the specific trigger, or null if the propert is not configured for this job.
*/
public <T extends Trigger> T getTrigger(Class<T> clazz) {
for (Trigger p : getTriggersList()) {
if(clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
public void setTriggers(List<Trigger<?>> triggerList) {
for (Trigger trigger : triggerList) {
CascadingUtil.getTriggerProjectProperty(this, trigger.getDescriptor().getJsonSafeClassName()).setValue(trigger);
}
}
//
//
// fingerprint related
//
//
/**
* True if the builds of this project produces {@link Fingerprint} records.
*/
public abstract boolean isFingerprintConfigured();
/**
* Gets the other {@link AbstractProject}s that should be built
* when a build of this project is completed.
*/
@Exported
public final List<AbstractProject> getDownstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getDownstream(this);
}
@Exported
public final List<AbstractProject> getUpstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getUpstream(this);
}
/**
* Returns only those upstream projects that defines {@link BuildTrigger} to this project.
* This is a subset of {@link #getUpstreamProjects()}
*
* @return A List of upstream projects that has a {@link BuildTrigger} to this project.
*/
public final List<AbstractProject> getBuildTriggerUpstreamProjects() {
ArrayList<AbstractProject> result = new ArrayList<AbstractProject>();
for (AbstractProject<?,?> ap : getUpstreamProjects()) {
BuildTrigger buildTrigger = ap.getPublishersList().get(BuildTrigger.class);
if (buildTrigger != null)
if (buildTrigger.getChildProjects().contains(this))
result.add(ap);
}
return result;
}
/**
* Gets all the upstream projects including transitive upstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveUpstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getTransitiveUpstream(this);
}
/**
* Gets all the downstream projects including transitive downstream projects.
*
* @since 1.138
*/
public final Set<AbstractProject> getTransitiveDownstreamProjects() {
return Hudson.getInstance().getDependencyGraph().getTransitiveDownstream(this);
}
/**
* Gets the dependency relationship map between this project (as the source)
* and that project (as the sink.)
*
* @return
* can be empty but not null. build number of this project to the build
* numbers of that project.
*/
public SortedMap<Integer, RangeSet> getRelationship(AbstractProject that) {
TreeMap<Integer,RangeSet> r = new TreeMap<Integer,RangeSet>(REVERSE_INTEGER_COMPARATOR);
checkAndRecord(that, r, this.getBuilds());
// checkAndRecord(that, r, that.getBuilds());
return r;
}
/**
* Helper method for getDownstreamRelationship.
*
* For each given build, find the build number range of the given project and put that into the map.
*/
private void checkAndRecord(AbstractProject that, TreeMap<Integer, RangeSet> r, Collection<R> builds) {
for (R build : builds) {
RangeSet rs = build.getDownstreamRelationship(that);
if(rs==null || rs.isEmpty())
continue;
int n = build.getNumber();
RangeSet value = r.get(n);
if(value==null)
r.put(n,rs);
else
value.add(rs);
}
}
/**
* Builds the dependency graph.
* @see DependencyGraph
*/
protected abstract void buildDependencyGraph(DependencyGraph graph);
@Override
protected SearchIndexBuilder makeSearchIndex() {
SearchIndexBuilder sib = super.makeSearchIndex();
if(isBuildable() && hasPermission(Hudson.ADMINISTER))
sib.add("build","build");
return sib;
}
@Override
protected HistoryWidget createHistoryWidget() {
return new BuildHistoryWidget<R>(this,getBuilds(),HISTORY_ADAPTER);
}
public boolean isParameterized() {
return getProperty(ParametersDefinitionProperty.class) != null;
}
//
//
// actions
//
//
/**
* Schedules a new build command.
*/
public void doBuild( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
// if a build is parameterized, let that take over
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp._doBuild(req,rsp);
return;
}
if (!isBuildable())
throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,new IOException(getFullName()+" is not buildable"));
Hudson.getInstance().getQueue().schedule(this, getDelay(req), getBuildCause(req));
rsp.forwardToPreviousPage(req);
}
/**
* Computes the build cause, using RemoteCause or UserCause as appropriate.
*/
/*package*/ CauseAction getBuildCause(StaplerRequest req) {
Cause cause;
if (authToken != null && authToken.getToken() != null && req.getParameter("token") != null) {
// Optional additional cause text when starting via token
String causeText = req.getParameter("cause");
cause = new RemoteCause(req.getRemoteAddr(), causeText);
} else {
cause = new UserCause();
}
return new CauseAction(cause);
}
/**
* Computes the delay by taking the default value and the override in the request parameter into the account.
*/
public int getDelay(StaplerRequest req) throws ServletException {
String delay = req.getParameter("delay");
if (delay==null) return getQuietPeriod();
try {
// TODO: more unit handling
if(delay.endsWith("sec")) delay=delay.substring(0,delay.length()-3);
if(delay.endsWith("secs")) delay=delay.substring(0,delay.length()-4);
return Integer.parseInt(delay);
} catch (NumberFormatException e) {
throw new ServletException("Invalid delay parameter value: "+delay);
}
}
/**
* Supports build trigger with parameters via an HTTP GET or POST.
* Currently only String parameters are supported.
*/
public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
ParametersDefinitionProperty pp = getProperty(ParametersDefinitionProperty.class);
if (pp != null) {
pp.buildWithParameters(req,rsp);
} else {
throw new IllegalStateException("This build is not parameterized!");
}
}
/**
* Schedules a new SCM polling command.
*/
public void doPolling( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
BuildAuthorizationToken.checkPermission(this, authToken, req, rsp);
schedulePolling();
rsp.forwardToPreviousPage(req);
}
/**
* Cancels a scheduled build.
*/
public void doCancelQueue( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
checkPermission(BUILD);
Hudson.getInstance().getQueue().cancel(this);
rsp.forwardToPreviousPage(req);
}
@Override
protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException {
super.submit(req,rsp);
makeDisabled(null != req.getParameter("disable"));
setCascadingProjectName(StringUtils.trimToNull(req.getParameter("cascadingProjectName")));
setJDK(req.getParameter("jdk"));
setQuietPeriod(null != req.getParameter(HAS_QUIET_PERIOD_PROPERTY_NAME)
? req.getParameter("quiet_period") : null);
setScmCheckoutRetryCount(null != req.getParameter(HAS_SCM_CHECKOUT_RETRY_COUNT_PROPERTY_NAME)
? req.getParameter("scmCheckoutRetryCount") : null);
setBlockBuildWhenDownstreamBuilding(null != req.getParameter("blockBuildWhenDownstreamBuilding"));
setBlockBuildWhenUpstreamBuilding(null != req.getParameter("blockBuildWhenUpstreamBuilding"));
if (req.getParameter("hasSlaveAffinity") != null) {
// New logic for handling whether this choice came from the dropdown or textfield.
if ("basic".equals(req.getParameter("affinityChooser"))) {
assignedNode = Util.fixEmptyAndTrim(req.getParameter("slave"));
advancedAffinityChooser = false;
} else {
assignedNode = Util.fixEmptyAndTrim(req.getParameter("_.assignedLabelString"));
advancedAffinityChooser = true;
}
} else {
assignedNode = null;
advancedAffinityChooser = false;
}
setCleanWorkspaceRequired(null != req.getParameter("cleanWorkspaceRequired"));
canRoam = assignedNode==null;
setConcurrentBuild(req.getSubmittedForm().has("concurrentBuild"));
authToken = BuildAuthorizationToken.create(req);
setScm(SCMS.parseSCM(req,this));
buildTriggers(req, req.getSubmittedForm(), Trigger.for_(this));
}
/**
* @deprecated
* As of 1.261. Use {@link #buildDescribable(StaplerRequest, List)} instead.
*/
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors, String prefix) throws FormException, ServletException {
return buildDescribable(req,descriptors);
}
protected final <T extends Describable<T>> List<T> buildDescribable(StaplerRequest req, List<? extends Descriptor<T>> descriptors)
throws FormException, ServletException {
JSONObject data = req.getSubmittedForm();
List<T> r = new Vector<T>();
for (Descriptor<T> d : descriptors) {
String safeName = d.getJsonSafeClassName();
if (req.getParameter(safeName) != null) {
T instance = d.newInstance(req, data.getJSONObject(safeName));
r.add(instance);
}
}
return r;
}
protected void buildTriggers(StaplerRequest req, JSONObject json, List<TriggerDescriptor> descriptors)
throws FormException {
for (TriggerDescriptor d : descriptors) {
String propertyName = d.getJsonSafeClassName();
CascadingUtil.setChildrenTrigger(this, d, propertyName, req, json);
}
}
/**
* Serves the workspace files.
*/
public DirectoryBrowserSupport doWs( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException, InterruptedException {
checkPermission(AbstractProject.WORKSPACE);
FilePath ws = getSomeWorkspace();
if ((ws == null) || (!ws.exists())) {
// if there's no workspace, report a nice error message
rsp.setStatus(HttpServletResponse.SC_NOT_FOUND);
req.getView(this,"noWorkspace.jelly").forward(req,rsp);
return null;
} else {
return new DirectoryBrowserSupport(this, ws, getDisplayName()+" workspace", "folder.png", true);
}
}
/**
* Wipes out the workspace.
*/
public HttpResponse doDoWipeOutWorkspace() throws IOException, ServletException, InterruptedException {
if (cleanWorkspace()){
return new HttpRedirect(".");
}else{
return new ForwardToView(this,"wipeOutWorkspaceBlocked.jelly");
}
}
public boolean cleanWorkspace() throws IOException, InterruptedException{
checkPermission(BUILD);
R b = getSomeBuildWithWorkspace();
FilePath ws = b != null ? b.getWorkspace() : null;
if (ws != null && getScm().processWorkspaceBeforeDeletion(this, ws, b.getBuiltOn())) {
ws.deleteRecursive();
return true;
} else{
// If we get here, that means the SCM blocked the workspace deletion.
return false;
}
}
@CLIMethod(name="disable-job")
public HttpResponse doDisable() throws IOException, ServletException {
requirePOST();
checkPermission(CONFIGURE);
makeDisabled(true);
return new HttpRedirect(".");
}
@CLIMethod(name="enable-job")
public HttpResponse doEnable() throws IOException, ServletException {
requirePOST();
checkPermission(CONFIGURE);
makeDisabled(false);
return new HttpRedirect(".");
}
/**
* RSS feed for changes in this project.
*/
public void doRssChangelog( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
class FeedItem {
ChangeLogSet.Entry e;
int idx;
public FeedItem(Entry e, int idx) {
this.e = e;
this.idx = idx;
}
AbstractBuild<?,?> getBuild() {
return e.getParent().build;
}
}
List<FeedItem> entries = new ArrayList<FeedItem>();
for(R r=getLastBuild(); r!=null; r=r.getPreviousBuild()) {
int idx=0;
for( ChangeLogSet.Entry e : r.getChangeSet())
entries.add(new FeedItem(e,idx++));
}
RSS.forwardToRss(
getDisplayName()+' '+getScm().getDescriptor().getDisplayName()+" changes",
getUrl()+"changes",
entries, new FeedAdapter<FeedItem>() {
public String getEntryTitle(FeedItem item) {
return "#"+item.getBuild().number+' '+item.e.getMsg()+" ("+item.e.getAuthor()+")";
}
public String getEntryUrl(FeedItem item) {
return item.getBuild().getUrl()+"changes#detail"+item.idx;
}
public String getEntryID(FeedItem item) {
return getEntryUrl(item);
}
public String getEntryDescription(FeedItem item) {
StringBuilder buf = new StringBuilder();
for(String path : item.e.getAffectedPaths())
buf.append(path).append('\n');
return buf.toString();
}
public Calendar getEntryTimestamp(FeedItem item) {
return item.getBuild().getTimestamp();
}
public String getEntryAuthor(FeedItem entry) {
return Mailer.descriptor().getAdminAddress();
}
},
req, rsp );
}
/**
* {@link AbstractProject} subtypes should implement this base class as a descriptor.
*
* @since 1.294
*/
public static abstract class AbstractProjectDescriptor extends TopLevelItemDescriptor {
/**
* {@link AbstractProject} subtypes can override this method to veto some {@link Descriptor}s
* from showing up on their configuration screen. This is often useful when you are building
* a workflow/company specific project type, where you want to limit the number of choices
* given to the users.
*
* <p>
* Some {@link Descriptor}s define their own schemes for controlling applicability
* (such as {@link BuildStepDescriptor#isApplicable(Class)}),
* This method works like AND in conjunction with them;
* Both this method and that method need to return true in order for a given {@link Descriptor}
* to show up for the given {@link Project}.
*
* <p>
* The default implementation returns true for everything.
*
* @see BuildStepDescriptor#isApplicable(Class)
* @see BuildWrapperDescriptor#isApplicable(AbstractProject)
* @see TriggerDescriptor#isApplicable(Item)
*/
@Override
public boolean isApplicable(Descriptor descriptor) {
return true;
}
public FormValidation doCheckAssignedLabelString(@QueryParameter String value) {
if (Util.fixEmpty(value)==null)
return FormValidation.ok(); // nothing typed yet
try {
Label.parseExpression(value);
} catch (ANTLRException e) {
return FormValidation.error(e,
Messages.AbstractProject_AssignedLabelString_InvalidBooleanExpression(e.getMessage()));
}
// TODO: if there's an atom in the expression that is empty, report it
if (Hudson.getInstance().getLabel(value).isEmpty())
return FormValidation.warning(Messages.AbstractProject_AssignedLabelString_NoMatch());
return FormValidation.ok();
}
public AutoCompletionCandidates doAutoCompleteAssignedLabelString(@QueryParameter String value) {
AutoCompletionCandidates c = new AutoCompletionCandidates();
Set<Label> labels = Hudson.getInstance().getLabels();
List<String> queries = new AutoCompleteSeeder(value).getSeeds();
for (String term : queries) {
for (Label l : labels) {
if (l.getName().startsWith(term)) {
c.add(l.getName());
}
}
}
return c;
}
}
/**
* Finds a {@link AbstractProject} that has the name closest to the given name.
*/
public static AbstractProject findNearest(String name) {
List<AbstractProject> projects = Hudson.getInstance().getItems(AbstractProject.class);
String[] names = new String[projects.size()];
for( int i=0; i<projects.size(); i++ )
names[i] = projects.get(i).getName();
String nearest = EditDistance.findNearest(name, names);
return (AbstractProject)Hudson.getInstance().getItem(nearest);
}
private static final Comparator<Integer> REVERSE_INTEGER_COMPARATOR = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
};
private static final Logger LOGGER = Logger.getLogger(AbstractProject.class.getName());
/**
* Permission to abort a build. For now, let's make it the same as {@link #BUILD}
*/
public static final Permission ABORT = BUILD;
/**
* Used for CLI binding.
*/
@CLIResolver
public static AbstractProject resolveForCLI(
@Argument(required=true,metaVar="NAME",usage="Job name") String name) throws CmdLineException {
AbstractProject item = Hudson.getInstance().getItemByFullName(name, AbstractProject.class);
if (item==null)
throw new CmdLineException(null,Messages.AbstractItem_NoSuchJobExists(name,AbstractProject.findNearest(name).getFullName()));
return item;
}
}
| true | true | public PollingResult poll( TaskListener listener ) {
SCM scm = getScm();
if (scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return NO_CHANGES;
}
if (isDisabled()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return NO_CHANGES;
}
R lb = getLastBuild();
if (lb==null) {
listener.getLogger().println(Messages.AbstractProject_NoBuilds());
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
if (pollingBaseline==null) {
R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
for (R r=lb; r!=null; r=r.getPreviousBuild()) {
SCMRevisionState s = r.getAction(SCMRevisionState.class);
if (s!=null) {
pollingBaseline = s;
break;
}
if (r==success) break; // searched far enough
}
// NOTE-NO-BASELINE:
// if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
// as action, so we need to compute it. This happens later.
}
try {
if (scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=lb.getWorkspace();
if (ws==null || !ws.exists()) {
// workspace offline. build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
return NO_CHANGES;
}
listener.getLogger().println( ws==null
? Messages.AbstractProject_WorkspaceOffline()
: Messages.AbstractProject_NoWorkspace());
if (isInQueue()) {
listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
return NO_CHANGES;
} else {
listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
return BUILD_NOW;
}
} else {
WorkspaceList l = lb.getBuiltOn().toComputer().getWorkspaceList();
// if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
Launcher launcher = ws.createLauncher(listener);
try {
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
} finally {
lease.release();
}
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
}
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
return NO_CHANGES;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
return NO_CHANGES;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
return NO_CHANGES;
}
}
| public PollingResult poll( TaskListener listener ) {
SCM scm = getScm();
if (scm==null) {
listener.getLogger().println(Messages.AbstractProject_NoSCM());
return NO_CHANGES;
}
if (isDisabled()) {
listener.getLogger().println(Messages.AbstractProject_Disabled());
return NO_CHANGES;
}
R lb = getLastBuild();
if (lb==null) {
listener.getLogger().println(Messages.AbstractProject_NoBuilds());
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
if (pollingBaseline==null) {
R success = getLastSuccessfulBuild(); // if we have a persisted baseline, we'll find it by this
for (R r=lb; r!=null; r=r.getPreviousBuild()) {
SCMRevisionState s = r.getAction(SCMRevisionState.class);
if (s!=null) {
pollingBaseline = s;
break;
}
if (r==success) break; // searched far enough
}
// NOTE-NO-BASELINE:
// if we don't have baseline yet, it means the data is built by old Hudson that doesn't set the baseline
// as action, so we need to compute it. This happens later.
}
try {
if (scm.requiresWorkspaceForPolling()) {
// lock the workspace of the last build
FilePath ws=lb.getWorkspace();
if (ws==null || !ws.exists()) {
// workspace offline. build now, or nothing will ever be built
Label label = getAssignedLabel();
if (label != null && label.isSelfLabel()) {
// if the build is fixed on a node, then attempting a build will do us
// no good. We should just wait for the slave to come back.
listener.getLogger().println(Messages.AbstractProject_NoWorkspace());
return NO_CHANGES;
}
listener.getLogger().println( ws==null
? Messages.AbstractProject_WorkspaceOffline()
: Messages.AbstractProject_NoWorkspace());
if (isInQueue()) {
listener.getLogger().println(Messages.AbstractProject_AwaitingBuildForWorkspace());
return NO_CHANGES;
} else {
listener.getLogger().println(Messages.AbstractProject_NewBuildForWorkspace());
return BUILD_NOW;
}
} else {
Node node = lb.getBuiltOn();
if (node == null || node.toComputer() == null) {
LOGGER.log(Level.FINE, "Node on which this job previously was built is not available now, build is started on an available node");
return isInQueue() ? NO_CHANGES : BUILD_NOW;
}
WorkspaceList l = node.toComputer().getWorkspaceList();
// if doing non-concurrent build, acquire a workspace in a way that causes builds to block for this workspace.
// this prevents multiple workspaces of the same job --- the behavior of Hudson < 1.319.
//
// OTOH, if a concurrent build is chosen, the user is willing to create a multiple workspace,
// so better throughput is achieved over time (modulo the initial cost of creating that many workspaces)
// by having multiple workspaces
WorkspaceList.Lease lease = l.acquire(ws, !concurrentBuild);
Launcher launcher = ws.createLauncher(listener);
try {
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,launcher,listener);
PollingResult r = scm.poll(this, launcher, ws, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
} finally {
lease.release();
}
}
} else {
// polling without workspace
LOGGER.fine("Polling SCM changes of " + getName());
if (pollingBaseline==null) // see NOTE-NO-BASELINE above
calcPollingBaseline(lb,null,listener);
PollingResult r = scm.poll(this, null, null, listener, pollingBaseline);
pollingBaseline = r.remote;
return r;
}
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
listener.fatalError(Messages.AbstractProject_Aborted());
LOGGER.log(Level.FINE, "Polling "+this+" aborted",e);
return NO_CHANGES;
} catch (IOException e) {
e.printStackTrace(listener.fatalError(e.getMessage()));
return NO_CHANGES;
} catch (InterruptedException e) {
e.printStackTrace(listener.fatalError(Messages.AbstractProject_PollingABorted()));
return NO_CHANGES;
}
}
|
diff --git a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java
index 618583cf..aa726eea 100644
--- a/Essentials/src/com/earth2me/essentials/commands/Commandeco.java
+++ b/Essentials/src/com/earth2me/essentials/commands/Commandeco.java
@@ -1,84 +1,84 @@
package com.earth2me.essentials.commands;
import org.bukkit.Server;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.earth2me.essentials.User;
public class Commandeco extends EssentialsCommand
{
public Commandeco()
{
super("eco");
}
@Override
public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
EcoCommands cmd;
double amount;
try
{
cmd = EcoCommands.valueOf(args[0].toUpperCase());
amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", ""));
}
catch (Exception ex)
{
throw new NotEnoughArgumentsException(ex);
}
if (args[1].contentEquals("*"))
{
for (Player p : server.getOnlinePlayers())
{
User u = ess.getUser(p);
switch (cmd)
{
case GIVE:
u.giveMoney(amount);
break;
case TAKE:
u.takeMoney(amount);
break;
case RESET:
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}
}
else
{
User u = ess.getUser(args[1]);
if (u == null)
{
- u = ess.getOfflineUser(args[0]);
+ u = ess.getOfflineUser(args[1]);
}
switch (cmd)
{
case GIVE:
u.giveMoney(amount);
break;
case TAKE:
u.takeMoney(amount);
break;
case RESET:
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}
}
private enum EcoCommands
{
GIVE, TAKE, RESET
}
}
| true | true | public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
EcoCommands cmd;
double amount;
try
{
cmd = EcoCommands.valueOf(args[0].toUpperCase());
amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", ""));
}
catch (Exception ex)
{
throw new NotEnoughArgumentsException(ex);
}
if (args[1].contentEquals("*"))
{
for (Player p : server.getOnlinePlayers())
{
User u = ess.getUser(p);
switch (cmd)
{
case GIVE:
u.giveMoney(amount);
break;
case TAKE:
u.takeMoney(amount);
break;
case RESET:
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}
}
else
{
User u = ess.getUser(args[1]);
if (u == null)
{
u = ess.getOfflineUser(args[0]);
}
switch (cmd)
{
case GIVE:
u.giveMoney(amount);
break;
case TAKE:
u.takeMoney(amount);
break;
case RESET:
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}
}
| public void run(Server server, CommandSender sender, String commandLabel, String[] args) throws Exception
{
if (args.length < 2)
{
throw new NotEnoughArgumentsException();
}
EcoCommands cmd;
double amount;
try
{
cmd = EcoCommands.valueOf(args[0].toUpperCase());
amount = Double.parseDouble(args[2].replaceAll("[^0-9\\.]", ""));
}
catch (Exception ex)
{
throw new NotEnoughArgumentsException(ex);
}
if (args[1].contentEquals("*"))
{
for (Player p : server.getOnlinePlayers())
{
User u = ess.getUser(p);
switch (cmd)
{
case GIVE:
u.giveMoney(amount);
break;
case TAKE:
u.takeMoney(amount);
break;
case RESET:
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}
}
else
{
User u = ess.getUser(args[1]);
if (u == null)
{
u = ess.getOfflineUser(args[1]);
}
switch (cmd)
{
case GIVE:
u.giveMoney(amount);
break;
case TAKE:
u.takeMoney(amount);
break;
case RESET:
u.setMoney(amount == 0 ? ess.getSettings().getStartingBalance() : amount);
break;
}
}
}
|
diff --git a/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java b/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java
index aee2d9a..093800e 100644
--- a/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java
+++ b/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java
@@ -1,66 +1,68 @@
package gov.nih.ncgc.bard.tools;
import gov.nih.ncgc.bard.rest.BARDResource;
import gov.nih.ncgc.bard.search.SolrSearch;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.sql.SQLException;
/**
* This class is specified in the container configuration file (web.xml) as a registered listener.
* Methods handle initialization and destruction of application context.
*
* @author braistedjc
*/
public class BardServletContextListener implements ServletContextListener {
DBUtils db;
@Override
public void contextInitialized(ServletContextEvent contextEvent) {
db = new DBUtils();
BARDResource.setDb(db);
SolrSearch.setDb(db);
// should we initialize cache mgmt at all?
- boolean initHazelcast = System.getProperty("initHazelcast").toLowerCase().equals("true");
+ String sym = System.getProperty("initHazelcast");
+ boolean initHazelcast = true;
+ if (sym != null) initHazelcast = sym.toLowerCase().equals("true");
// initialize cache management parameters
if (initHazelcast) {
ServletContext servletContext = contextEvent.getServletContext();
String cachePrefixes = servletContext.getInitParameter("cache-management-cache-prefix-list");
String cacheMgrNodes = servletContext.getInitParameter("cache-manager-cluster-nodes");
if (cachePrefixes != null && cacheMgrNodes != null) {
DBUtils.initializeManagedCaches(cachePrefixes, cacheMgrNodes);
} else {
// if we don't have context, then try to initialize with the assumption that the
// server host is a member of the HazelCast cluster, use the host ip or if that fails, localhost
try {
String host = InetAddress.getLocalHost().getHostAddress();
//if we don't have context, send empty cache prefix list,
DBUtils.initializeManagedCaches("", host);
} catch (UnknownHostException unknownHostExcept) {
unknownHostExcept.printStackTrace();
DBUtils.initializeManagedCaches("", "localhost");
}
}
}
// additional initialization can go here ...
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
//closes the cache manger
DBUtils.shutdownCacheFlushManager();
DBUtils.flushCachePrefixNames = null;
try {
db.closeConnection();
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
| true | true | public void contextInitialized(ServletContextEvent contextEvent) {
db = new DBUtils();
BARDResource.setDb(db);
SolrSearch.setDb(db);
// should we initialize cache mgmt at all?
boolean initHazelcast = System.getProperty("initHazelcast").toLowerCase().equals("true");
// initialize cache management parameters
if (initHazelcast) {
ServletContext servletContext = contextEvent.getServletContext();
String cachePrefixes = servletContext.getInitParameter("cache-management-cache-prefix-list");
String cacheMgrNodes = servletContext.getInitParameter("cache-manager-cluster-nodes");
if (cachePrefixes != null && cacheMgrNodes != null) {
DBUtils.initializeManagedCaches(cachePrefixes, cacheMgrNodes);
} else {
// if we don't have context, then try to initialize with the assumption that the
// server host is a member of the HazelCast cluster, use the host ip or if that fails, localhost
try {
String host = InetAddress.getLocalHost().getHostAddress();
//if we don't have context, send empty cache prefix list,
DBUtils.initializeManagedCaches("", host);
} catch (UnknownHostException unknownHostExcept) {
unknownHostExcept.printStackTrace();
DBUtils.initializeManagedCaches("", "localhost");
}
}
}
// additional initialization can go here ...
}
| public void contextInitialized(ServletContextEvent contextEvent) {
db = new DBUtils();
BARDResource.setDb(db);
SolrSearch.setDb(db);
// should we initialize cache mgmt at all?
String sym = System.getProperty("initHazelcast");
boolean initHazelcast = true;
if (sym != null) initHazelcast = sym.toLowerCase().equals("true");
// initialize cache management parameters
if (initHazelcast) {
ServletContext servletContext = contextEvent.getServletContext();
String cachePrefixes = servletContext.getInitParameter("cache-management-cache-prefix-list");
String cacheMgrNodes = servletContext.getInitParameter("cache-manager-cluster-nodes");
if (cachePrefixes != null && cacheMgrNodes != null) {
DBUtils.initializeManagedCaches(cachePrefixes, cacheMgrNodes);
} else {
// if we don't have context, then try to initialize with the assumption that the
// server host is a member of the HazelCast cluster, use the host ip or if that fails, localhost
try {
String host = InetAddress.getLocalHost().getHostAddress();
//if we don't have context, send empty cache prefix list,
DBUtils.initializeManagedCaches("", host);
} catch (UnknownHostException unknownHostExcept) {
unknownHostExcept.printStackTrace();
DBUtils.initializeManagedCaches("", "localhost");
}
}
}
// additional initialization can go here ...
}
|
diff --git a/dev/android/transportmtl/src/net/rhatec/amtmobile/types/DateHelpers.java b/dev/android/transportmtl/src/net/rhatec/amtmobile/types/DateHelpers.java
index 925b82d..0798a80 100644
--- a/dev/android/transportmtl/src/net/rhatec/amtmobile/types/DateHelpers.java
+++ b/dev/android/transportmtl/src/net/rhatec/amtmobile/types/DateHelpers.java
@@ -1,210 +1,210 @@
package net.rhatec.amtmobile.types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Vector;
import net.rhatec.amtmobile.R;
import android.content.Context;
import android.text.format.Time;
/**
* Classe d'aide pour g�rer les dates.
*
*/
public class DateHelpers
{
static int LUNDI = 0x1;
static int MARDI = 0x2;
static int MERCREDI = 0x4;
static int JEUDI = 0x8;
static int VENDREDI = 0x10;
static int SAMEDI = 0x20;
static int DIMANCHE = 0x40;
static int JOURFERIE = 0x80;
static int LAST = 0x100;
public static String obtenirNomHoraire(int horaireId, HashMap<String,String> jf, Context c)
{
String nomHoraire = "Unknown";
//This need an helper method
if (horaireId == 31) //Semaine
nomHoraire = c.getString(R.string.jour_semaine);
else if (horaireId == 32)
nomHoraire = c.getString(R.string.jour_samedi);
else if (horaireId == 64)
nomHoraire = c.getString(R.string.jour_dimanche);
else if(horaireId < 255) //
{
//TODO: Mettre des majuscule, des . et des et comme il se doit
nomHoraire = "";
nomHoraire+= (horaireId & LUNDI) != 0 ? c.getString(R.string.jour_lundi) + ", " : "";
nomHoraire+= (horaireId & MARDI) != 0 ? c.getString(R.string.jour_mardi) + ", ": "";
nomHoraire+= (horaireId & MERCREDI) != 0 ? c.getString(R.string.jour_mercredi) + ", ": "";
nomHoraire+= (horaireId & JEUDI) != 0 ? c.getString(R.string.jour_jeudi) + ", ": "";
nomHoraire+= (horaireId & VENDREDI) != 0 ? c.getString(R.string.jour_vendredi) + ", ": "";
nomHoraire+= (horaireId & SAMEDI) != 0 ? c.getString(R.string.jour_samedi) + ", ": "";
nomHoraire+= (horaireId & DIMANCHE) != 0 ? c.getString(R.string.jour_dimanche) + ", ": "";
}
else
{
String nomHoraireF = jf.get(String.valueOf(horaireId));
if (nomHoraireF != null)
nomHoraire = nomHoraireF;
}
return nomHoraire;
}
public static Pair<Integer, Boolean> obtenirTypeHoraireActuelAConsulter(Vector<Horaire> listeHoraire)
{
Calendar unCalendrier = Calendar.getInstance();
return obtenirTypeHoraireActuelAConsulter(listeHoraire, unCalendrier);
}
/**
* Retourne le type d'horaire a consulter (Dimanche, Samedi, Semaine) selon
* l'heure actuelle.
* datecompenser
*
* @return Nom horaire
*
*/
public static Pair<Integer, Boolean> obtenirTypeHoraireActuelAConsulter(Vector<Horaire> listeHoraire, Calendar unCalendrier)
{
Pair<Integer, Boolean> horaireAConsulterPair = new Pair<Integer, Boolean>(-1, false);
//On v�rifie d'abord qu'il ne s'agit pas d'un horaire entre minuit et 4 heure du matin...
int hour = unCalendrier.get(Calendar.HOUR_OF_DAY);
- if(hour>=0 && hour<4) //Nous somme entre 4h et minuit... nous prendrons l'horaire pr�c�dent...
+ if(hour>=0 && hour<5) //Nous somme entre 5h et minuit... nous prendrons l'horaire pr�c�dent...
{
unCalendrier.add(Calendar.DATE, -1); //Nous prenons donc l'horaire d'hier
horaireAConsulterPair.setSecond(true); //Apr�s minuit
}
// On vérifie ensuite si il s'agit d'un jour férié.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(unCalendrier.getTime());
//AAAAMMJJ
Horaire h = null;
int nbHoraire = listeHoraire.size();
for(int i = 0; i < nbHoraire; ++i)
{
h = listeHoraire.get(i);
if(h.ObtenirNom().equals(date))
{
horaireAConsulterPair.first = i;
break;
}
}
if(horaireAConsulterPair.first == -1)
{
int jourActuel = unCalendrier.get(Calendar.DAY_OF_WEEK);
int jourCourantBit = 0;
switch(jourActuel)
{
case Calendar.MONDAY:
jourCourantBit = LUNDI;
break;
case Calendar.TUESDAY:
jourCourantBit = MARDI;
break;
case Calendar.WEDNESDAY:
jourCourantBit = MERCREDI;
break;
case Calendar.THURSDAY:
jourCourantBit = JEUDI;
break;
case Calendar.FRIDAY:
jourCourantBit = VENDREDI;
break;
case Calendar.SATURDAY:
jourCourantBit = SAMEDI;
break;
case Calendar.SUNDAY:
jourCourantBit = DIMANCHE;
break;
default:
break;
}
for(int i = 0; i < nbHoraire; ++i)
{
h = listeHoraire.get(i);
String horaire = h.ObtenirNom();
int horaireId = Integer.parseInt(horaire);
if(horaireId<LAST && ((horaireId&jourCourantBit) != 0))
{
horaireAConsulterPair.setFirst(i);
}
}
}
return horaireAConsulterPair;
}
public static boolean horaireApresMinuit(Time actuelTime)
{
// l'heure actuelle est comprise entre minuit et 5 heure du matin
if (actuelTime.hour >= 0 && actuelTime.hour < 4)
return true;
return false;
}
/**
* @function: obtenirObjetTimeActuel
* @description: Retourne la date et l'heure actuelle
* @author: Hocine
* @params[in]:
* @params[out]:
*/
public static Time obtenirObjetTimeActuel()
{
Calendar unCalendrier = Calendar.getInstance();
Time time = new Time();
time.year = unCalendrier.get(Calendar.YEAR);
time.month = unCalendrier.get(Calendar.MONTH);
time.monthDay = unCalendrier.get(Calendar.DAY_OF_MONTH);
time.hour = unCalendrier.get(Calendar.HOUR_OF_DAY);
time.minute = unCalendrier.get(Calendar.MINUTE);
return time;
}
/**
* @function: obtenirObjetDateActuel
* @description: Retourne la date courante
* @author: Jeep
* @params[in]:
* @params[out]:
*/
public static Date obtenirObjetDateActuel()
{
return Calendar.getInstance().getTime();
}
/**
* @function: obtenirPositionListeProchainPassage
* @description: Retourne la position dans la liste du prochain passage de
* l'autobus
* @author: JP
* @params[in]:
* @params[out]:
*/
public static int obtenirPositionListeProchainPassage(ArrayList<Temps> _listeHeure)
{
return 0;
}
}
| true | true | public static Pair<Integer, Boolean> obtenirTypeHoraireActuelAConsulter(Vector<Horaire> listeHoraire, Calendar unCalendrier)
{
Pair<Integer, Boolean> horaireAConsulterPair = new Pair<Integer, Boolean>(-1, false);
//On v�rifie d'abord qu'il ne s'agit pas d'un horaire entre minuit et 4 heure du matin...
int hour = unCalendrier.get(Calendar.HOUR_OF_DAY);
if(hour>=0 && hour<4) //Nous somme entre 4h et minuit... nous prendrons l'horaire pr�c�dent...
{
unCalendrier.add(Calendar.DATE, -1); //Nous prenons donc l'horaire d'hier
horaireAConsulterPair.setSecond(true); //Apr�s minuit
}
// On vérifie ensuite si il s'agit d'un jour férié.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(unCalendrier.getTime());
//AAAAMMJJ
Horaire h = null;
int nbHoraire = listeHoraire.size();
for(int i = 0; i < nbHoraire; ++i)
{
h = listeHoraire.get(i);
if(h.ObtenirNom().equals(date))
{
horaireAConsulterPair.first = i;
break;
}
}
if(horaireAConsulterPair.first == -1)
{
int jourActuel = unCalendrier.get(Calendar.DAY_OF_WEEK);
int jourCourantBit = 0;
switch(jourActuel)
{
case Calendar.MONDAY:
jourCourantBit = LUNDI;
break;
case Calendar.TUESDAY:
jourCourantBit = MARDI;
break;
case Calendar.WEDNESDAY:
jourCourantBit = MERCREDI;
break;
case Calendar.THURSDAY:
jourCourantBit = JEUDI;
break;
case Calendar.FRIDAY:
jourCourantBit = VENDREDI;
break;
case Calendar.SATURDAY:
jourCourantBit = SAMEDI;
break;
case Calendar.SUNDAY:
jourCourantBit = DIMANCHE;
break;
default:
break;
}
for(int i = 0; i < nbHoraire; ++i)
{
h = listeHoraire.get(i);
String horaire = h.ObtenirNom();
int horaireId = Integer.parseInt(horaire);
if(horaireId<LAST && ((horaireId&jourCourantBit) != 0))
{
horaireAConsulterPair.setFirst(i);
}
}
}
return horaireAConsulterPair;
}
| public static Pair<Integer, Boolean> obtenirTypeHoraireActuelAConsulter(Vector<Horaire> listeHoraire, Calendar unCalendrier)
{
Pair<Integer, Boolean> horaireAConsulterPair = new Pair<Integer, Boolean>(-1, false);
//On v�rifie d'abord qu'il ne s'agit pas d'un horaire entre minuit et 4 heure du matin...
int hour = unCalendrier.get(Calendar.HOUR_OF_DAY);
if(hour>=0 && hour<5) //Nous somme entre 5h et minuit... nous prendrons l'horaire pr�c�dent...
{
unCalendrier.add(Calendar.DATE, -1); //Nous prenons donc l'horaire d'hier
horaireAConsulterPair.setSecond(true); //Apr�s minuit
}
// On vérifie ensuite si il s'agit d'un jour férié.
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String date = sdf.format(unCalendrier.getTime());
//AAAAMMJJ
Horaire h = null;
int nbHoraire = listeHoraire.size();
for(int i = 0; i < nbHoraire; ++i)
{
h = listeHoraire.get(i);
if(h.ObtenirNom().equals(date))
{
horaireAConsulterPair.first = i;
break;
}
}
if(horaireAConsulterPair.first == -1)
{
int jourActuel = unCalendrier.get(Calendar.DAY_OF_WEEK);
int jourCourantBit = 0;
switch(jourActuel)
{
case Calendar.MONDAY:
jourCourantBit = LUNDI;
break;
case Calendar.TUESDAY:
jourCourantBit = MARDI;
break;
case Calendar.WEDNESDAY:
jourCourantBit = MERCREDI;
break;
case Calendar.THURSDAY:
jourCourantBit = JEUDI;
break;
case Calendar.FRIDAY:
jourCourantBit = VENDREDI;
break;
case Calendar.SATURDAY:
jourCourantBit = SAMEDI;
break;
case Calendar.SUNDAY:
jourCourantBit = DIMANCHE;
break;
default:
break;
}
for(int i = 0; i < nbHoraire; ++i)
{
h = listeHoraire.get(i);
String horaire = h.ObtenirNom();
int horaireId = Integer.parseInt(horaire);
if(horaireId<LAST && ((horaireId&jourCourantBit) != 0))
{
horaireAConsulterPair.setFirst(i);
}
}
}
return horaireAConsulterPair;
}
|
diff --git a/src/java/com/idega/block/creditcard/business/KortathjonustanAuthorizationException.java b/src/java/com/idega/block/creditcard/business/KortathjonustanAuthorizationException.java
index 9385089..65d8c23 100644
--- a/src/java/com/idega/block/creditcard/business/KortathjonustanAuthorizationException.java
+++ b/src/java/com/idega/block/creditcard/business/KortathjonustanAuthorizationException.java
@@ -1,54 +1,58 @@
/*
* Created on 15.4.2004
*
* To change the template for this generated file go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
package com.idega.block.creditcard.business;
import com.idega.idegaweb.IWResourceBundle;
/**
* @author gimmi
*
* To change the template for this generated type comment go to
* Window - Preferences - Java - Code Generation - Code and Comments
*/
public class KortathjonustanAuthorizationException extends CreditCardAuthorizationException {
public KortathjonustanAuthorizationException() {
super();
}
public KortathjonustanAuthorizationException(String arg0) {
super(arg0);
}
public KortathjonustanAuthorizationException(String arg0, Throwable arg1) {
super(arg0, arg1);
}
public KortathjonustanAuthorizationException(Throwable arg0) {
super(arg0);
}
public String getLocalizedMessage(IWResourceBundle iwrb) {
System.out.println("Kortathjonustan errormessage = " + this.getErrorMessage());
System.out.println("number = " + this.getErrorNumber());
System.out.println("display = " + this.getDisplayError());
int number = -2;
try {
number = Integer.parseInt(this.getErrorNumber());
} catch (NumberFormatException ignore) {}
switch (number) {
case 1029 :
return (iwrb.getLocalizedString("cc.creditcard_number_incorrect","Creditcard number incorrect"));
+// case 10909 :
+// return (iwrb.getLocalizedString("cc.error_maybe_CVC","An error occured, CVC code could be incorrect"));
case 10102 :
return (iwrb.getLocalizedString("cc.declined","Declined"));
+ case 10101 :
+ return (iwrb.getLocalizedString("cc.card_is_expired","Card is expired"));
default:
return (iwrb.getLocalizedString("cc.cannot_connect","Cannot communicate with server"));
}
}
}
| false | true | public String getLocalizedMessage(IWResourceBundle iwrb) {
System.out.println("Kortathjonustan errormessage = " + this.getErrorMessage());
System.out.println("number = " + this.getErrorNumber());
System.out.println("display = " + this.getDisplayError());
int number = -2;
try {
number = Integer.parseInt(this.getErrorNumber());
} catch (NumberFormatException ignore) {}
switch (number) {
case 1029 :
return (iwrb.getLocalizedString("cc.creditcard_number_incorrect","Creditcard number incorrect"));
case 10102 :
return (iwrb.getLocalizedString("cc.declined","Declined"));
default:
return (iwrb.getLocalizedString("cc.cannot_connect","Cannot communicate with server"));
}
}
| public String getLocalizedMessage(IWResourceBundle iwrb) {
System.out.println("Kortathjonustan errormessage = " + this.getErrorMessage());
System.out.println("number = " + this.getErrorNumber());
System.out.println("display = " + this.getDisplayError());
int number = -2;
try {
number = Integer.parseInt(this.getErrorNumber());
} catch (NumberFormatException ignore) {}
switch (number) {
case 1029 :
return (iwrb.getLocalizedString("cc.creditcard_number_incorrect","Creditcard number incorrect"));
// case 10909 :
// return (iwrb.getLocalizedString("cc.error_maybe_CVC","An error occured, CVC code could be incorrect"));
case 10102 :
return (iwrb.getLocalizedString("cc.declined","Declined"));
case 10101 :
return (iwrb.getLocalizedString("cc.card_is_expired","Card is expired"));
default:
return (iwrb.getLocalizedString("cc.cannot_connect","Cannot communicate with server"));
}
}
|
diff --git a/src/main/java/gov/usgs/cida/data/ASCIIGridDataFile.java b/src/main/java/gov/usgs/cida/data/ASCIIGridDataFile.java
index e15df78..b928152 100644
--- a/src/main/java/gov/usgs/cida/data/ASCIIGridDataFile.java
+++ b/src/main/java/gov/usgs/cida/data/ASCIIGridDataFile.java
@@ -1,165 +1,167 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package gov.usgs.cida.data;
import java.util.Map;
import org.joda.time.Duration;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.List;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.joda.time.Instant;
import org.joda.time.format.DateTimeFormat;
import static org.joda.time.DateTimeFieldType.*;
/**
*
* @author jwalker
*/
public class ASCIIGridDataFile {
private static final Logger LOG = LoggerFactory.getLogger(ASCIIGridDataFile.class);
private File underlyingFile;
private Instant startDate = null;
private int columns = -1;
private String varName = null;
private Map<Integer, List<Long>> dateIndices;
public ASCIIGridDataFile(File infile) {
this.underlyingFile = infile;
// ASSUMING VAR.TIMESTEP.grid
String filename = infile.getName();
this.varName = filename.split("\\.")[0].toLowerCase();
this.dateIndices = Maps.newLinkedHashMap();
}
/*
* Sets startDate, timesteps based on assumption that they are in first two lines
* firstline = "\ttimesteps"
* secondline = "firstTime\tvalueGRIDid1\t...\tvalueGRIDidn"
*/
public void inspectFile() throws FileNotFoundException, IOException {
BufferedReader buf = new BufferedReader(new FileReader(underlyingFile));
String line = null;
int year = -1;
List<Long> indices = Lists.newArrayList();
try {
if ((line = buf.readLine()) != null) {
columns = Integer.parseInt(line.trim());
}
while ((line = buf.readLine()) != null) {
String yyyymmdd = line.substring(0, 8);
if (startDate == null) {
startDate = Instant.parse(yyyymmdd, DateTimeFormat.forPattern("yyyyMMdd"));
year = startDate.get(year());
dateIndices.put(year, indices);
indices.add(0l);
}
else {
+ // !! There is a bug here that gives the wrong date for days between Apr 2x and Oct 2x
+ // it appears to be related to DST, though the exact cause is unknown !!
Instant thisDate = Instant.parse(yyyymmdd, DateTimeFormat.forPattern("yyyyMMdd"));
int thisYear = thisDate.get(year());
Duration daysSince = new Duration(startDate, thisDate);
if (thisYear == year) {
indices.add(daysSince.getStandardDays());
}
else {
year = thisYear;
indices = Lists.newArrayList();
dateIndices.put(year, indices);
indices.add(daysSince.getStandardDays());
}
}
}
if (columns == -1 || startDate == null) {
LOG.error("File doesn't look like it should, unable to pull date out of file");
throw ASCIIGrid2NetCDFConverter.rtex;
}
}
finally {
IOUtils.closeQuietly(buf);
}
}
/**
* Kind of convoluted way of converting to instant and back to date, but whatever
* Just want to create something netcdf can do something with
* @return formatted units for netcdf
*/
public String getTimeUnits() {
return "days since " + startDate.get(year()) + "-" +
pad(startDate.get(monthOfYear())) + "-" +
pad(startDate.get(dayOfMonth()));
}
private String pad(int monthOrDay) {
if (monthOrDay < 10) {
return "0" + monthOrDay;
}
return "" + monthOrDay;
}
public Map<Integer, List<Long>> getTimestepIndices() {
return dateIndices;
}
public String getVariableName() {
return varName;
}
private BufferedReader buffer = null;
private String[] currentLine = null;
private int marker = 1;
private int strideLength = -1;
public void openForReading(int strideLength) throws FileNotFoundException, IOException {
buffer = new BufferedReader(new FileReader(underlyingFile));
// First line has number with how many lines follow it
buffer.readLine();
this.strideLength = strideLength;
}
public boolean hasMoreStrides() {
// marker is at next place to read, has another stride if it ends
// up after the last index
return (marker + strideLength <= currentLine.length);
}
public boolean readNextLine() throws IOException {
String line = null;
if ((line = buffer.readLine()) != null) {
currentLine = line.split("\\s+");
marker = 1;
return true;
}
return false;
}
/**
* Please do not try to run this in any concurrent fashion
* it will break badly.
* @return
*/
public float[] readTimestepByStride() {
float[] strideVals = new float[strideLength];
for (int i=0; i<strideLength; i++) {
strideVals[i] = Float.parseFloat(currentLine[marker]);
marker++;
}
return strideVals;
}
public void closeForReading() {
IOUtils.closeQuietly(buffer);
}
}
| true | true | public void inspectFile() throws FileNotFoundException, IOException {
BufferedReader buf = new BufferedReader(new FileReader(underlyingFile));
String line = null;
int year = -1;
List<Long> indices = Lists.newArrayList();
try {
if ((line = buf.readLine()) != null) {
columns = Integer.parseInt(line.trim());
}
while ((line = buf.readLine()) != null) {
String yyyymmdd = line.substring(0, 8);
if (startDate == null) {
startDate = Instant.parse(yyyymmdd, DateTimeFormat.forPattern("yyyyMMdd"));
year = startDate.get(year());
dateIndices.put(year, indices);
indices.add(0l);
}
else {
Instant thisDate = Instant.parse(yyyymmdd, DateTimeFormat.forPattern("yyyyMMdd"));
int thisYear = thisDate.get(year());
Duration daysSince = new Duration(startDate, thisDate);
if (thisYear == year) {
indices.add(daysSince.getStandardDays());
}
else {
year = thisYear;
indices = Lists.newArrayList();
dateIndices.put(year, indices);
indices.add(daysSince.getStandardDays());
}
}
}
if (columns == -1 || startDate == null) {
LOG.error("File doesn't look like it should, unable to pull date out of file");
throw ASCIIGrid2NetCDFConverter.rtex;
}
}
finally {
IOUtils.closeQuietly(buf);
}
}
| public void inspectFile() throws FileNotFoundException, IOException {
BufferedReader buf = new BufferedReader(new FileReader(underlyingFile));
String line = null;
int year = -1;
List<Long> indices = Lists.newArrayList();
try {
if ((line = buf.readLine()) != null) {
columns = Integer.parseInt(line.trim());
}
while ((line = buf.readLine()) != null) {
String yyyymmdd = line.substring(0, 8);
if (startDate == null) {
startDate = Instant.parse(yyyymmdd, DateTimeFormat.forPattern("yyyyMMdd"));
year = startDate.get(year());
dateIndices.put(year, indices);
indices.add(0l);
}
else {
// !! There is a bug here that gives the wrong date for days between Apr 2x and Oct 2x
// it appears to be related to DST, though the exact cause is unknown !!
Instant thisDate = Instant.parse(yyyymmdd, DateTimeFormat.forPattern("yyyyMMdd"));
int thisYear = thisDate.get(year());
Duration daysSince = new Duration(startDate, thisDate);
if (thisYear == year) {
indices.add(daysSince.getStandardDays());
}
else {
year = thisYear;
indices = Lists.newArrayList();
dateIndices.put(year, indices);
indices.add(daysSince.getStandardDays());
}
}
}
if (columns == -1 || startDate == null) {
LOG.error("File doesn't look like it should, unable to pull date out of file");
throw ASCIIGrid2NetCDFConverter.rtex;
}
}
finally {
IOUtils.closeQuietly(buf);
}
}
|
diff --git a/src/java/com/homework/hw2/HomePage.java b/src/java/com/homework/hw2/HomePage.java
index 21cbfa9..e701826 100644
--- a/src/java/com/homework/hw2/HomePage.java
+++ b/src/java/com/homework/hw2/HomePage.java
@@ -1,35 +1,35 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.homework.hw2;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Ets
*/
public class HomePage extends HttpServlet {
//Constant
public static final String SESSION_ATTRIBUTE = "param";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object url_attribute = request.getParameter(SESSION_ATTRIBUTE);
request.getSession().setAttribute(SESSION_ATTRIBUTE, url_attribute);
String session_value = (String)request.getSession().getAttribute(SESSION_ATTRIBUTE);
String sessionId = request.getSession().getId();
response.getWriter().println("id is " + sessionId);
- response.getWriter().println("attribute is" + url_attribute);
+ response.getWriter().println("attribute is " + url_attribute);
}
}
| true | true | protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object url_attribute = request.getParameter(SESSION_ATTRIBUTE);
request.getSession().setAttribute(SESSION_ATTRIBUTE, url_attribute);
String session_value = (String)request.getSession().getAttribute(SESSION_ATTRIBUTE);
String sessionId = request.getSession().getId();
response.getWriter().println("id is " + sessionId);
response.getWriter().println("attribute is" + url_attribute);
}
| protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Object url_attribute = request.getParameter(SESSION_ATTRIBUTE);
request.getSession().setAttribute(SESSION_ATTRIBUTE, url_attribute);
String session_value = (String)request.getSession().getAttribute(SESSION_ATTRIBUTE);
String sessionId = request.getSession().getId();
response.getWriter().println("id is " + sessionId);
response.getWriter().println("attribute is " + url_attribute);
}
|
diff --git a/pmd/src/net/sourceforge/pmd/rules/strings/InefficientStringBuffering.java b/pmd/src/net/sourceforge/pmd/rules/strings/InefficientStringBuffering.java
index 051f46155..a30b17d96 100644
--- a/pmd/src/net/sourceforge/pmd/rules/strings/InefficientStringBuffering.java
+++ b/pmd/src/net/sourceforge/pmd/rules/strings/InefficientStringBuffering.java
@@ -1,130 +1,129 @@
/**
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.rules.strings;
import net.sourceforge.pmd.AbstractRule;
import net.sourceforge.pmd.ast.ASTAdditiveExpression;
import net.sourceforge.pmd.ast.ASTAllocationExpression;
import net.sourceforge.pmd.ast.ASTBlockStatement;
import net.sourceforge.pmd.ast.ASTClassOrInterfaceType;
import net.sourceforge.pmd.ast.ASTLiteral;
import net.sourceforge.pmd.ast.ASTName;
import net.sourceforge.pmd.ast.ASTStatementExpression;
import net.sourceforge.pmd.ast.Node;
import net.sourceforge.pmd.ast.SimpleNode;
import net.sourceforge.pmd.ast.ASTArgumentList;
import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
import java.util.Iterator;
import java.util.List;
/*
* How this rule works:
* find additive expressions: +
* check that the addition is between anything other than two literals
* if true and also the parent is StringBuffer constructor or append,
* report a violation.
*
* @author mgriffa
*/
public class InefficientStringBuffering extends AbstractRule {
public Object visit(ASTAdditiveExpression node, Object data) {
ASTBlockStatement bs = (ASTBlockStatement) node.getFirstParentOfType(ASTBlockStatement.class);
if (bs == null) {
return data;
}
int immediateLiterals = 0;
List nodes = node.findChildrenOfType(ASTLiteral.class);
for (Iterator i = nodes.iterator();i.hasNext();) {
ASTLiteral literal = (ASTLiteral)i.next();
if (literal.jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTAdditiveExpression) {
immediateLiterals++;
}
try {
Integer.parseInt(literal.getImage());
return data;
} catch (NumberFormatException nfe) {
// NFE means new StringBuffer("a" + "b"), want to flag those
}
}
- //if (immediateLiterals > 1) { // see patch http://sourceforge.net/tracker/index.php?func=detail&aid=1455282&group_id=56262&atid=479923
if (immediateLiterals > 1) {
return data;
}
// if literal + public static final, return
List nameNodes = node.findChildrenOfType(ASTName.class);
for (Iterator i = nameNodes.iterator(); i.hasNext();) {
ASTName name = (ASTName)i.next();
if (name.getNameDeclaration() instanceof VariableNameDeclaration) {
VariableNameDeclaration vnd = (VariableNameDeclaration)name.getNameDeclaration();
if (vnd.getAccessNodeParent().isFinal() && vnd.getAccessNodeParent().isStatic()) {
return data;
}
}
}
if (bs.isAllocation()) {
if (isAllocatedStringBuffer(node)) {
addViolation(data, node);
}
} else if (isInStringBufferAppend(node, 6)) {
addViolation(data, node);
}
return data;
}
protected static boolean isInStringBufferAppend(SimpleNode node, int length) {
if (!xParentIsStatementExpression(node, length)) {
return false;
}
ASTStatementExpression s = (ASTStatementExpression) node.getFirstParentOfType(ASTStatementExpression.class);
if (s == null) {
return false;
}
ASTName n = (ASTName)s.getFirstChildOfType(ASTName.class);
if (n == null || n.getImage().indexOf("append") == -1 || !(n.getNameDeclaration() instanceof VariableNameDeclaration)) {
return false;
}
// TODO having to hand-code this kind of dredging around is ridiculous
// we need something to support this in the framework
// but, "for now" (tm):
// if more than one arg to append(), skip it
ASTArgumentList argList = (ASTArgumentList)s.getFirstChildOfType(ASTArgumentList.class);
if (argList == null || argList.jjtGetNumChildren() > 1) {
return false;
}
return ((VariableNameDeclaration)n.getNameDeclaration()).getTypeImage().equals("StringBuffer");
}
// TODO move this method to SimpleNode
private static boolean xParentIsStatementExpression(SimpleNode node, int length) {
Node curr = node;
for (int i=0; i<length; i++) {
if (node.jjtGetParent() == null) {
return false;
}
curr = curr.jjtGetParent();
}
return curr instanceof ASTStatementExpression;
}
private boolean isAllocatedStringBuffer(ASTAdditiveExpression node) {
ASTAllocationExpression ao = (ASTAllocationExpression) node.getFirstParentOfType(ASTAllocationExpression.class);
if (ao == null) {
return false;
}
// note that the child can be an ArrayDimsAndInits, for example, from java.lang.FloatingDecimal: t = new int[ nWords+wordcount+1 ];
ASTClassOrInterfaceType an = (ASTClassOrInterfaceType) ao.getFirstChildOfType(ASTClassOrInterfaceType.class);
return an != null && (an.getImage().endsWith("StringBuffer") || an.getImage().endsWith("StringBuilder"));
}
}
| true | true | public Object visit(ASTAdditiveExpression node, Object data) {
ASTBlockStatement bs = (ASTBlockStatement) node.getFirstParentOfType(ASTBlockStatement.class);
if (bs == null) {
return data;
}
int immediateLiterals = 0;
List nodes = node.findChildrenOfType(ASTLiteral.class);
for (Iterator i = nodes.iterator();i.hasNext();) {
ASTLiteral literal = (ASTLiteral)i.next();
if (literal.jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTAdditiveExpression) {
immediateLiterals++;
}
try {
Integer.parseInt(literal.getImage());
return data;
} catch (NumberFormatException nfe) {
// NFE means new StringBuffer("a" + "b"), want to flag those
}
}
//if (immediateLiterals > 1) { // see patch http://sourceforge.net/tracker/index.php?func=detail&aid=1455282&group_id=56262&atid=479923
if (immediateLiterals > 1) {
return data;
}
// if literal + public static final, return
List nameNodes = node.findChildrenOfType(ASTName.class);
for (Iterator i = nameNodes.iterator(); i.hasNext();) {
ASTName name = (ASTName)i.next();
if (name.getNameDeclaration() instanceof VariableNameDeclaration) {
VariableNameDeclaration vnd = (VariableNameDeclaration)name.getNameDeclaration();
if (vnd.getAccessNodeParent().isFinal() && vnd.getAccessNodeParent().isStatic()) {
return data;
}
}
}
if (bs.isAllocation()) {
if (isAllocatedStringBuffer(node)) {
addViolation(data, node);
}
} else if (isInStringBufferAppend(node, 6)) {
addViolation(data, node);
}
return data;
}
| public Object visit(ASTAdditiveExpression node, Object data) {
ASTBlockStatement bs = (ASTBlockStatement) node.getFirstParentOfType(ASTBlockStatement.class);
if (bs == null) {
return data;
}
int immediateLiterals = 0;
List nodes = node.findChildrenOfType(ASTLiteral.class);
for (Iterator i = nodes.iterator();i.hasNext();) {
ASTLiteral literal = (ASTLiteral)i.next();
if (literal.jjtGetParent().jjtGetParent().jjtGetParent() instanceof ASTAdditiveExpression) {
immediateLiterals++;
}
try {
Integer.parseInt(literal.getImage());
return data;
} catch (NumberFormatException nfe) {
// NFE means new StringBuffer("a" + "b"), want to flag those
}
}
if (immediateLiterals > 1) {
return data;
}
// if literal + public static final, return
List nameNodes = node.findChildrenOfType(ASTName.class);
for (Iterator i = nameNodes.iterator(); i.hasNext();) {
ASTName name = (ASTName)i.next();
if (name.getNameDeclaration() instanceof VariableNameDeclaration) {
VariableNameDeclaration vnd = (VariableNameDeclaration)name.getNameDeclaration();
if (vnd.getAccessNodeParent().isFinal() && vnd.getAccessNodeParent().isStatic()) {
return data;
}
}
}
if (bs.isAllocation()) {
if (isAllocatedStringBuffer(node)) {
addViolation(data, node);
}
} else if (isInStringBufferAppend(node, 6)) {
addViolation(data, node);
}
return data;
}
|
diff --git a/beam-netcdf/src/main/java/org/esa/beam/dataio/netcdf/metadata/profiles/cf/CfBandPart.java b/beam-netcdf/src/main/java/org/esa/beam/dataio/netcdf/metadata/profiles/cf/CfBandPart.java
index 515d17422..e4b777874 100644
--- a/beam-netcdf/src/main/java/org/esa/beam/dataio/netcdf/metadata/profiles/cf/CfBandPart.java
+++ b/beam-netcdf/src/main/java/org/esa/beam/dataio/netcdf/metadata/profiles/cf/CfBandPart.java
@@ -1,298 +1,298 @@
/*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.beam.dataio.netcdf.metadata.profiles.cf;
import org.esa.beam.dataio.netcdf.ProfileReadContext;
import org.esa.beam.dataio.netcdf.ProfileWriteContext;
import org.esa.beam.dataio.netcdf.metadata.ProfilePartIO;
import org.esa.beam.dataio.netcdf.nc.NFileWriteable;
import org.esa.beam.dataio.netcdf.nc.NVariable;
import org.esa.beam.dataio.netcdf.util.Constants;
import org.esa.beam.dataio.netcdf.util.DataTypeUtils;
import org.esa.beam.dataio.netcdf.util.NetcdfMultiLevelImage;
import org.esa.beam.dataio.netcdf.util.ReaderUtils;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.DataNode;
import org.esa.beam.framework.datamodel.FlagCoding;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.framework.datamodel.RasterDataNode;
import org.esa.beam.jai.ImageManager;
import org.esa.beam.util.ForLoop;
import org.esa.beam.util.StringUtils;
import ucar.ma2.DataType;
import ucar.nc2.Attribute;
import ucar.nc2.Dimension;
import ucar.nc2.Variable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class CfBandPart extends ProfilePartIO {
private static final DataTypeWorkarounds dataTypeWorkarounds = new DataTypeWorkarounds();
@Override
public void decode(final ProfileReadContext ctx, final Product p) throws IOException {
for (final Variable variable : ctx.getRasterDigest().getRasterVariables()) {
final List<Dimension> dimensions = variable.getDimensions();
final int rank = dimensions.size();
final String bandBasename = variable.getName();
if (rank == 2) {
addBand(ctx, p, variable, bandBasename);
} else {
final int[] sizeArray = new int[rank - 2];
System.arraycopy(variable.getShape(), 0, sizeArray, 0, sizeArray.length);
ForLoop.execute(sizeArray, new ForLoop.Body() {
@Override
public void execute(int[] indexes, int[] sizes) {
final StringBuilder bandNameBuilder = new StringBuilder(bandBasename);
for (int i = 0; i < sizes.length; i++) {
final Dimension zDim = dimensions.get(i);
String zName = zDim.getName();
final String skipPrefix = "n_";
if (zName.toLowerCase().startsWith(skipPrefix)
&& zName.length() > skipPrefix.length()) {
zName = zName.substring(skipPrefix.length());
}
if (zDim.getLength() > 1) {
bandNameBuilder.append(String.format("_%s%d", zName, (indexes[i] + 1)));
}
}
addBand(ctx, p, variable, bandNameBuilder.toString());
}
});
}
}
p.setAutoGrouping(getAutoGrouping(ctx));
}
private static void addBand(ProfileReadContext ctx, Product p, Variable variable, String bandBasename) {
final int rasterDataType = getRasterDataType(variable, dataTypeWorkarounds);
if (variable.getDataType() == DataType.LONG) {
final Band lowerBand = p.addBand(bandBasename + "_lsb", rasterDataType);
readCfBandAttributes(variable, lowerBand);
if (lowerBand.getDescription() != null) {
lowerBand.setDescription(lowerBand.getDescription() + "(least significant bytes)");
}
lowerBand.setSourceImage(new NetcdfMultiLevelImage(lowerBand, variable, ctx));
addFlagCodingIfApplicable(p, lowerBand, variable, variable.getName() + "_lsb", false);
final Band upperBand = p.addBand(bandBasename + "_msb", rasterDataType);
readCfBandAttributes(variable, upperBand);
if (upperBand.getDescription() != null) {
upperBand.setDescription(upperBand.getDescription() + "(most significant bytes)");
}
upperBand.setSourceImage(new NetcdfMultiLevelImage(upperBand, variable, ctx));
addFlagCodingIfApplicable(p, upperBand, variable, variable.getName() + "_msb", true);
} else {
final Band band = p.addBand(bandBasename, rasterDataType);
readCfBandAttributes(variable, band);
band.setSourceImage(new NetcdfMultiLevelImage(band, variable, ctx));
addFlagCodingIfApplicable(p, band, variable, variable.getName(), false);
}
}
private String getAutoGrouping(ProfileReadContext ctx) {
ArrayList<String> bandNames = new ArrayList<String>();
for (final Variable variable : ctx.getRasterDigest().getRasterVariables()) {
final List<Dimension> dimensions = variable.getDimensions();
int rank = dimensions.size();
for (int i = 0; i < rank - 2; i++) {
Dimension dim = dimensions.get(i);
if (dim.getLength() > 1) {
bandNames.add(variable.getName());
break;
}
}
}
return StringUtils.join(bandNames, ":");
}
@Override
public void preEncode(ProfileWriteContext ctx, Product p) throws IOException {
// In order to inform the writer that it shall write the geophysical values of log-scaled bands
// we set this property here.
ctx.setProperty(Constants.CONVERT_LOGSCALED_BANDS_PROPERTY, true);
defineRasterDataNodes(ctx, p.getBands());
}
public static void readCfBandAttributes(Variable variable, RasterDataNode rasterDataNode) {
rasterDataNode.setDescription(variable.getDescription());
rasterDataNode.setUnit(variable.getUnitsString());
rasterDataNode.setScalingFactor(getScalingFactor(variable));
rasterDataNode.setScalingOffset(getAddOffset(variable));
final Number noDataValue = getNoDataValue(variable);
if (noDataValue != null) {
rasterDataNode.setNoDataValue(noDataValue.doubleValue());
rasterDataNode.setNoDataValueUsed(true);
}
}
public static void writeCfBandAttributes(RasterDataNode rasterDataNode, NVariable variable) throws IOException {
final String description = rasterDataNode.getDescription();
if (description != null) {
variable.addAttribute("long_name", description);
}
String unit = rasterDataNode.getUnit();
if (unit != null) {
unit = CfCompliantUnitMapper.tryFindUnitString(unit);
variable.addAttribute("units", unit);
}
final boolean unsigned = isUnsigned(rasterDataNode);
if (unsigned) {
variable.addAttribute("_Unsigned", String.valueOf(unsigned));
}
double noDataValue;
if (!rasterDataNode.isLog10Scaled()) {
final double scalingFactor = rasterDataNode.getScalingFactor();
if (scalingFactor != 1.0) {
variable.addAttribute(Constants.SCALE_FACTOR_ATT_NAME, scalingFactor);
}
final double scalingOffset = rasterDataNode.getScalingOffset();
if (scalingOffset != 0.0) {
variable.addAttribute(Constants.ADD_OFFSET_ATT_NAME, scalingOffset);
}
noDataValue = rasterDataNode.getNoDataValue();
} else {
// scaling information is not written anymore for log10 scaled bands
// instead we always write geophysical values
// we do this because log scaling is not supported by NetCDF-CF conventions
noDataValue = rasterDataNode.getGeophysicalNoDataValue();
}
if (rasterDataNode.isNoDataValueUsed()) {
Number fillValue = DataTypeUtils.convertTo(noDataValue, variable.getDataType());
variable.addAttribute(Constants.FILL_VALUE_ATT_NAME, fillValue);
}
variable.addAttribute("coordinates", "lat lon");
}
public static void defineRasterDataNodes(ProfileWriteContext ctx, RasterDataNode[] rasterDataNodes) throws
IOException {
final NFileWriteable ncFile = ctx.getNetcdfFileWriteable();
final String dimensions = ncFile.getDimensions();
for (RasterDataNode rasterDataNode : rasterDataNodes) {
String variableName = ReaderUtils.getVariableName(rasterDataNode);
int dataType;
if (rasterDataNode.isLog10Scaled()) {
dataType = rasterDataNode.getGeophysicalDataType();
} else {
dataType = rasterDataNode.getDataType();
}
DataType netcdfDataType = DataTypeUtils.getNetcdfDataType(dataType);
java.awt.Dimension tileSize = ImageManager.getPreferredTileSize(rasterDataNode.getProduct());
final NVariable variable = ncFile.addVariable(variableName, netcdfDataType, tileSize, dimensions);
writeCfBandAttributes(rasterDataNode, variable);
}
}
private static double getScalingFactor(Variable variable) {
Attribute attribute = variable.findAttribute(Constants.SCALE_FACTOR_ATT_NAME);
if (attribute == null) {
attribute = variable.findAttribute(Constants.SLOPE_ATT_NAME);
}
return attribute != null ? attribute.getNumericValue().doubleValue() : 1.0;
}
private static double getAddOffset(Variable variable) {
Attribute attribute = variable.findAttribute(Constants.ADD_OFFSET_ATT_NAME);
if (attribute == null) {
attribute = variable.findAttribute(Constants.INTERCEPT_ATT_NAME);
}
return attribute != null ? attribute.getNumericValue().doubleValue() : 0.0;
}
private static Number getNoDataValue(Variable variable) {
Attribute attribute = variable.findAttribute(Constants.FILL_VALUE_ATT_NAME);
if (attribute == null) {
attribute = variable.findAttribute(Constants.MISSING_VALUE_ATT_NAME);
}
return attribute != null ? attribute.getNumericValue().doubleValue() : null;
}
private static int getRasterDataType(Variable variable, DataTypeWorkarounds workarounds) {
if (workarounds != null && workarounds.hasWorkaround(variable.getName(), variable.getDataType())) {
return workarounds.getRasterDataType(variable.getName(), variable.getDataType());
}
int rasterDataType = DataTypeUtils.getRasterDataType(variable);
if (rasterDataType == -1) {
if (variable.getDataType() == DataType.LONG) {
rasterDataType = variable.isUnsigned() ? ProductData.TYPE_UINT32 : ProductData.TYPE_INT32;
}
}
return rasterDataType;
}
private static boolean isUnsigned(DataNode dataNode) {
return ProductData.isUIntType(dataNode.getDataType());
}
private static void addFlagCodingIfApplicable(Product p, Band band, Variable variable, String flagCodingName,
boolean msb) {
final Attribute flagMaskAttribute = variable.findAttribute("flag_masks");
final Attribute flagMeaningsAttribute = variable.findAttribute("flag_meanings");
if (flagMaskAttribute != null && flagMeaningsAttribute != null) {
if (!p.getFlagCodingGroup().contains(flagCodingName)) {
final FlagCoding flagCoding = new FlagCoding(flagCodingName);
final String[] flagMeanings = flagMeaningsAttribute.getStringValue().split(" ");
for (int i = 0; i < flagMaskAttribute.getLength(); i++) {
if (i < flagMeanings.length) {
final String flagMeaning = flagMeanings[i];
switch (flagMaskAttribute.getDataType()) {
case BYTE:
flagCoding.addFlag(flagMeaning,
DataType.unsignedByteToShort(
flagMaskAttribute.getNumericValue(i).byteValue()), null);
break;
case SHORT:
flagCoding.addFlag(flagMeaning,
DataType.unsignedShortToInt(
flagMaskAttribute.getNumericValue(i).shortValue()), null);
break;
case INT:
flagCoding.addFlag(flagMeaning, flagMaskAttribute.getNumericValue(i).intValue(), null);
break;
case LONG:
- final long value = flagMaskAttribute.getNumericValue().longValue();
+ final long value = flagMaskAttribute.getNumericValue(i).longValue();
if (msb) {
final long flagMask = value >>> 32;
if (flagMask > 0) {
flagCoding.addFlag(flagMeaning, (int) flagMask, null);
}
} else {
final long flagMask = value & 0x00000000FFFFFFFFL;
if (flagMask > 0) {
flagCoding.addFlag(flagMeaning, (int) flagMask, null);
}
}
break;
}
}
}
p.getFlagCodingGroup().add(flagCoding);
}
band.setSampleCoding(p.getFlagCodingGroup().get(flagCodingName));
}
}
}
| true | true | private static void addFlagCodingIfApplicable(Product p, Band band, Variable variable, String flagCodingName,
boolean msb) {
final Attribute flagMaskAttribute = variable.findAttribute("flag_masks");
final Attribute flagMeaningsAttribute = variable.findAttribute("flag_meanings");
if (flagMaskAttribute != null && flagMeaningsAttribute != null) {
if (!p.getFlagCodingGroup().contains(flagCodingName)) {
final FlagCoding flagCoding = new FlagCoding(flagCodingName);
final String[] flagMeanings = flagMeaningsAttribute.getStringValue().split(" ");
for (int i = 0; i < flagMaskAttribute.getLength(); i++) {
if (i < flagMeanings.length) {
final String flagMeaning = flagMeanings[i];
switch (flagMaskAttribute.getDataType()) {
case BYTE:
flagCoding.addFlag(flagMeaning,
DataType.unsignedByteToShort(
flagMaskAttribute.getNumericValue(i).byteValue()), null);
break;
case SHORT:
flagCoding.addFlag(flagMeaning,
DataType.unsignedShortToInt(
flagMaskAttribute.getNumericValue(i).shortValue()), null);
break;
case INT:
flagCoding.addFlag(flagMeaning, flagMaskAttribute.getNumericValue(i).intValue(), null);
break;
case LONG:
final long value = flagMaskAttribute.getNumericValue().longValue();
if (msb) {
final long flagMask = value >>> 32;
if (flagMask > 0) {
flagCoding.addFlag(flagMeaning, (int) flagMask, null);
}
} else {
final long flagMask = value & 0x00000000FFFFFFFFL;
if (flagMask > 0) {
flagCoding.addFlag(flagMeaning, (int) flagMask, null);
}
}
break;
}
}
}
p.getFlagCodingGroup().add(flagCoding);
}
band.setSampleCoding(p.getFlagCodingGroup().get(flagCodingName));
}
}
| private static void addFlagCodingIfApplicable(Product p, Band band, Variable variable, String flagCodingName,
boolean msb) {
final Attribute flagMaskAttribute = variable.findAttribute("flag_masks");
final Attribute flagMeaningsAttribute = variable.findAttribute("flag_meanings");
if (flagMaskAttribute != null && flagMeaningsAttribute != null) {
if (!p.getFlagCodingGroup().contains(flagCodingName)) {
final FlagCoding flagCoding = new FlagCoding(flagCodingName);
final String[] flagMeanings = flagMeaningsAttribute.getStringValue().split(" ");
for (int i = 0; i < flagMaskAttribute.getLength(); i++) {
if (i < flagMeanings.length) {
final String flagMeaning = flagMeanings[i];
switch (flagMaskAttribute.getDataType()) {
case BYTE:
flagCoding.addFlag(flagMeaning,
DataType.unsignedByteToShort(
flagMaskAttribute.getNumericValue(i).byteValue()), null);
break;
case SHORT:
flagCoding.addFlag(flagMeaning,
DataType.unsignedShortToInt(
flagMaskAttribute.getNumericValue(i).shortValue()), null);
break;
case INT:
flagCoding.addFlag(flagMeaning, flagMaskAttribute.getNumericValue(i).intValue(), null);
break;
case LONG:
final long value = flagMaskAttribute.getNumericValue(i).longValue();
if (msb) {
final long flagMask = value >>> 32;
if (flagMask > 0) {
flagCoding.addFlag(flagMeaning, (int) flagMask, null);
}
} else {
final long flagMask = value & 0x00000000FFFFFFFFL;
if (flagMask > 0) {
flagCoding.addFlag(flagMeaning, (int) flagMask, null);
}
}
break;
}
}
}
p.getFlagCodingGroup().add(flagCoding);
}
band.setSampleCoding(p.getFlagCodingGroup().get(flagCodingName));
}
}
|
diff --git a/app/models/Match.java b/app/models/Match.java
index 272907c..7c17b8d 100644
--- a/app/models/Match.java
+++ b/app/models/Match.java
@@ -1,160 +1,160 @@
package models;
import java.util.ArrayList;
import java.util.List;
public class Match {
private static final List<Match> matches = new ArrayList<Match>();
public String date;
public Team local;
public Team visit;
public String localScore;
public String visitScore;
public List<String> players;
public String summaryTitle;
public String summary;
public String commentarist;
public Match(String date, Team local, String localScore, Team visit,
String visitScore, List<String> players, String summaryTitle,
String summary, String commentarist) {
super();
this.date = date;
this.local = local;
this.visit = visit;
this.localScore = localScore;
this.visitScore = visitScore;
this.players = players;
this.summaryTitle = summaryTitle;
this.summary = summary;
this.commentarist = commentarist;
}
public Match() {
}
public static List<Match> all() {
if (matches.isEmpty()) {
Match match = new Match(
"09/03/2013 - Fecha 1 - Apertura 2013",
Team.get("la-naranja-mecanica"), "5",
Team.get("descanso-verde"), "1",
new ArrayList<String>(),
"En 4 minutos liquidó la historia",
"En otro partido por la primera fecha en la máxima categoría se enfrentaban La naranja Mecánica contra Descanso Verde. " +
"El partido empezaría con el tanto de Sánchez a los 3' primeros minutos de juego. " +
"Luego el partido estuvo parejo a pesar de que termino ganando la primera etapa la naranja., " +
"porque Descanso verde inquieto e hizo temblar el arco en varias ocasiones. " +
"En el final la naranja encontraría de nuevo el rumbo y terminaría de la mejor manera creando buenas situaciones.<br/> " +
"En el segundo tiempo Vázquez a los 6' minutos de juego empataría el partido y le daría un condimento a esta etapa. " +
"Pero le duro poco las esperanzas al conjunto celeste, porque vendría la seguidilla de goles de Sánchez x2 que darían vuelta el partido y " +
"abrió el camino para que vengan los goles de Márquez y Magallanes. Todo esto pasó en cuatro minutos de juego, " +
"la naranja en tan poco tiempo saco una gran ventaja y también gano el dominio de pelota y hasta el final del partido llevo el partido a su antojo. " +
"Y sonaría el pitido final y la naranja ganaría por 5 a 1.",
"Francisco Rolón");
matches.add(match);
match = new Match(
"16/03/2013 - Fecha 2 - Apertura 2013",
Team.get("hacha-y-tiza"), "7",
Team.get("la-naranja-mecanica"), "8",
new ArrayList<String>(),
"Fiebre Naranja",
"Dos pesos pesados se enfrentaban en un gran partido que se viviría como una verdadera final, La Naranja Mecánica frente a Hacha y Tiza. " +
"Tincho Jacomelli abriría la cuenta a los 6´, pero minutos más tarde Maxi Márquez igualaría tras un potente remate afuera del área. " +
"Pero inmediatamente responderían los celestes que de contra serían letales gracias a los buenos movimientos de Antico y Cáceres, " +
- "Jacomelli marcaría un doblete y el ya mencionado Cáceres aumentaría la diferencia. Sarán descontaba en la agonía. </p> " +
+ "Jacomelli marcaría un doblete y el ya mencionado Cáceres aumentaría la diferencia. Sarán descontaba en la agonía. <br/> " +
"La Naranja arrancaría con todo esta segundo tiempo y en una ráfaga de dos minutos lo daría vuelta gracias a los goles de Trapo, Keki y Lope " +
"para asombro de los rivales que rápidamente descontarían a través de su máximo artillero Jacomelli volviendo a marcar. " +
"Sin embargo, El Trapo, recién regresado de Europa, sería el héroe del partido con sus goles. " +
"Hacha buscó y buscó pero las buenas respuestas de Regojo le impidieron al menos llevarse un punto y la gloria fue toda Naranja, que no tiene a Cruyff, pero lo tiene al trapo.",
"Maximiliano Rodriguez");
matches.add(match);
match = new Match(
"23/03/2013 - Fecha 3 - Apertura 2013",
Team.get("la-naranja-mecanica"), "14",
Team.get("lmds"), "3",
new ArrayList<String>(),
"A Todo Trapo",
"La Naranja Mecánica goleó a LMDS por 14 a 3. No tuvo mucha chance LMDS, empezó perdiendo por 3 goles, todos de Rodrigo Saran. " +
"Después siguió ampliando la ventaja sin darle respiro al rival M. Márquez ponía el 4 a 0 a los 8 minutos. Mariano López anotó el quinto. " +
"La Naranja apretó y cada llegada era un golpe bajo para su rival, que no se recupero hasta el final que descontó Alejandro Soriano con un golazo de media chilena afuera del area. <br/>" +
"En el segundo tiempo volvió el Trapo a la cancha y siguió sumando 4 goles más otro de E. Sánchez para el 10 a 1. " +
"Al minuto 13 un descuido de la defensa llevaría al descuento de Lucas Gagliote. " +
"Pero 2 min después vuelve a convertir La Naranja esta vez 2 goles de G. Martínez, y sigue sumando Saran otro gol más al minuto 18. " +
"Cerca del final descuenta Alejandro Soriano de penal, y para cerrar la goleada de la Naranja R.Saran cierra el 14 a 3.",
"Jonatan Leites");
matches.add(match);
match = new Match(
"06/04/2013 - Fecha 4 - Apertura 2013",
Team.get("las-aguilas-de-niupi"), "4",
Team.get("la-naranja-mecanica"), "5",
new ArrayList<String>(),
"Sobre el final",
"Las Águilas del Niupi reciben a la Naranja Mecánica a las 13 horas jugando la Categoría “A” del torneo de los Sábados. " +
"Se espera un muy buen partido, por el buen nivel de los equipos y jugadores. " +
"Fue un primer tiempo parejo donde abre el partido las Águilas con el gol de Mariano Gómez a los 8 minutos, " +
"4 minutos después con el ingreso del “trapo” R. Saran llega el empate y a los 15 minutos pone a su equipo arriba. " +
"En una de las últimas del primer tiempo se pondrían iguales con un Bombazo de Martin Sisca que de un tiro libre pone el 2 a 2.<br/> " +
"En el segundo tiempo se pone arriba la naranja a los 2 minutos con el gol de Yiyo Martínez, pero 2 minutos después empatan las Águilas con el gol de Martin Saban de contrataque. " +
"Es un partido ida y vuelta, muy parejo, pero la naranja con el correr del tiempo empezó a presionar mas y a tomar el control. " +
"En el minuto 15 R. Saran pone arriba a la Naranja otra vez, minuto 18 con un puntazo cruzado empata el partido 4 a 4, " +
"pero parecía terminar en empate casi no queda tiempo pero en un contra ataque de la naranja pase cruzado y " +
"entra Mariano López para poner el 5 a 4 y darle los 2 puntos a la naranja en un Partido Muy parejo y reñido.",
"Jonatan Leites");
matches.add(match);
match = new Match(
"13/04/2013 - Fecha 5 - Apertura 2013",
Team.get("pelos"), "2",
Team.get("la-naranja-mecanica"), "3",
new ArrayList<String>(),
"Se complicó solo",
"Bien tempranito se jugaba el partido entre uno de los punteros, La Naranja Mecánica, y el siempre complicado Pelos. " +
"A los 5 minutos de comenzado el encuentro llegaría el tanto de Gabriel Zvaliauskas quien simplemente tendría que acertarle al arco luego de robar en la mitad de cancha. " +
"La Naranja Mecánica se hacía dueño del juego. Ezequiel Sánchez rompería el palo a los 9 minutos. " +
"Tres minutos después llegaría el empate por medio de Santiago Fernández aprovechando un corner. <br/>" +
"A los 4 minutos de la segunda parte Rodrigo Sarán aprovecharía un buen pase de Federico Ribera para dejar a los de casaca naranja arriba en el marcador. " +
"Guillermo Martínez estiraría la diferencia a los 7 minutos. " +
"Pelos no encontraba la forma de empatar el partido y por eso Gabriel Zvaliauskas pasaría al arco a cinco minutos del cierre. " +
"La Naranja Mecánica tenía el partido controlado sin embargo un penal que Gabriel Zvaliauskas cambiaría por gol iba a ponerle pimienta al final del partido. " +
"La Naranja sigue como puntero junto con Humildad y Talento que ganaría sin siquiera jugar gracias al faltazo (cacona) de los pibes de Flojo Licuado.",
"Conte-Grand, Tomás");
matches.add(match);
match = new Match(
"20/04/2013 - Fecha 6 - Apertura 2013",
Team.get("la-naranja-mecanica"), "3",
Team.get("cristal"), "2",
new ArrayList<String>(),
"Cronica",
"",
"");
matches.add(match);
}
return matches;
}
public static Match get(Integer index) {
if(index == 0 || index > all().size()) {
return null;
}
return all().get(index - 1);
}
@Override
public String toString() {
return local.name + " vs " + visit.name;
}
}
| true | true | public static List<Match> all() {
if (matches.isEmpty()) {
Match match = new Match(
"09/03/2013 - Fecha 1 - Apertura 2013",
Team.get("la-naranja-mecanica"), "5",
Team.get("descanso-verde"), "1",
new ArrayList<String>(),
"En 4 minutos liquidó la historia",
"En otro partido por la primera fecha en la máxima categoría se enfrentaban La naranja Mecánica contra Descanso Verde. " +
"El partido empezaría con el tanto de Sánchez a los 3' primeros minutos de juego. " +
"Luego el partido estuvo parejo a pesar de que termino ganando la primera etapa la naranja., " +
"porque Descanso verde inquieto e hizo temblar el arco en varias ocasiones. " +
"En el final la naranja encontraría de nuevo el rumbo y terminaría de la mejor manera creando buenas situaciones.<br/> " +
"En el segundo tiempo Vázquez a los 6' minutos de juego empataría el partido y le daría un condimento a esta etapa. " +
"Pero le duro poco las esperanzas al conjunto celeste, porque vendría la seguidilla de goles de Sánchez x2 que darían vuelta el partido y " +
"abrió el camino para que vengan los goles de Márquez y Magallanes. Todo esto pasó en cuatro minutos de juego, " +
"la naranja en tan poco tiempo saco una gran ventaja y también gano el dominio de pelota y hasta el final del partido llevo el partido a su antojo. " +
"Y sonaría el pitido final y la naranja ganaría por 5 a 1.",
"Francisco Rolón");
matches.add(match);
match = new Match(
"16/03/2013 - Fecha 2 - Apertura 2013",
Team.get("hacha-y-tiza"), "7",
Team.get("la-naranja-mecanica"), "8",
new ArrayList<String>(),
"Fiebre Naranja",
"Dos pesos pesados se enfrentaban en un gran partido que se viviría como una verdadera final, La Naranja Mecánica frente a Hacha y Tiza. " +
"Tincho Jacomelli abriría la cuenta a los 6´, pero minutos más tarde Maxi Márquez igualaría tras un potente remate afuera del área. " +
"Pero inmediatamente responderían los celestes que de contra serían letales gracias a los buenos movimientos de Antico y Cáceres, " +
"Jacomelli marcaría un doblete y el ya mencionado Cáceres aumentaría la diferencia. Sarán descontaba en la agonía. </p> " +
"La Naranja arrancaría con todo esta segundo tiempo y en una ráfaga de dos minutos lo daría vuelta gracias a los goles de Trapo, Keki y Lope " +
"para asombro de los rivales que rápidamente descontarían a través de su máximo artillero Jacomelli volviendo a marcar. " +
"Sin embargo, El Trapo, recién regresado de Europa, sería el héroe del partido con sus goles. " +
"Hacha buscó y buscó pero las buenas respuestas de Regojo le impidieron al menos llevarse un punto y la gloria fue toda Naranja, que no tiene a Cruyff, pero lo tiene al trapo.",
"Maximiliano Rodriguez");
matches.add(match);
match = new Match(
"23/03/2013 - Fecha 3 - Apertura 2013",
Team.get("la-naranja-mecanica"), "14",
Team.get("lmds"), "3",
new ArrayList<String>(),
"A Todo Trapo",
"La Naranja Mecánica goleó a LMDS por 14 a 3. No tuvo mucha chance LMDS, empezó perdiendo por 3 goles, todos de Rodrigo Saran. " +
"Después siguió ampliando la ventaja sin darle respiro al rival M. Márquez ponía el 4 a 0 a los 8 minutos. Mariano López anotó el quinto. " +
"La Naranja apretó y cada llegada era un golpe bajo para su rival, que no se recupero hasta el final que descontó Alejandro Soriano con un golazo de media chilena afuera del area. <br/>" +
"En el segundo tiempo volvió el Trapo a la cancha y siguió sumando 4 goles más otro de E. Sánchez para el 10 a 1. " +
"Al minuto 13 un descuido de la defensa llevaría al descuento de Lucas Gagliote. " +
"Pero 2 min después vuelve a convertir La Naranja esta vez 2 goles de G. Martínez, y sigue sumando Saran otro gol más al minuto 18. " +
"Cerca del final descuenta Alejandro Soriano de penal, y para cerrar la goleada de la Naranja R.Saran cierra el 14 a 3.",
"Jonatan Leites");
matches.add(match);
match = new Match(
"06/04/2013 - Fecha 4 - Apertura 2013",
Team.get("las-aguilas-de-niupi"), "4",
Team.get("la-naranja-mecanica"), "5",
new ArrayList<String>(),
"Sobre el final",
"Las Águilas del Niupi reciben a la Naranja Mecánica a las 13 horas jugando la Categoría “A” del torneo de los Sábados. " +
"Se espera un muy buen partido, por el buen nivel de los equipos y jugadores. " +
"Fue un primer tiempo parejo donde abre el partido las Águilas con el gol de Mariano Gómez a los 8 minutos, " +
"4 minutos después con el ingreso del “trapo” R. Saran llega el empate y a los 15 minutos pone a su equipo arriba. " +
"En una de las últimas del primer tiempo se pondrían iguales con un Bombazo de Martin Sisca que de un tiro libre pone el 2 a 2.<br/> " +
"En el segundo tiempo se pone arriba la naranja a los 2 minutos con el gol de Yiyo Martínez, pero 2 minutos después empatan las Águilas con el gol de Martin Saban de contrataque. " +
"Es un partido ida y vuelta, muy parejo, pero la naranja con el correr del tiempo empezó a presionar mas y a tomar el control. " +
"En el minuto 15 R. Saran pone arriba a la Naranja otra vez, minuto 18 con un puntazo cruzado empata el partido 4 a 4, " +
"pero parecía terminar en empate casi no queda tiempo pero en un contra ataque de la naranja pase cruzado y " +
"entra Mariano López para poner el 5 a 4 y darle los 2 puntos a la naranja en un Partido Muy parejo y reñido.",
"Jonatan Leites");
matches.add(match);
match = new Match(
"13/04/2013 - Fecha 5 - Apertura 2013",
Team.get("pelos"), "2",
Team.get("la-naranja-mecanica"), "3",
new ArrayList<String>(),
"Se complicó solo",
"Bien tempranito se jugaba el partido entre uno de los punteros, La Naranja Mecánica, y el siempre complicado Pelos. " +
"A los 5 minutos de comenzado el encuentro llegaría el tanto de Gabriel Zvaliauskas quien simplemente tendría que acertarle al arco luego de robar en la mitad de cancha. " +
"La Naranja Mecánica se hacía dueño del juego. Ezequiel Sánchez rompería el palo a los 9 minutos. " +
"Tres minutos después llegaría el empate por medio de Santiago Fernández aprovechando un corner. <br/>" +
"A los 4 minutos de la segunda parte Rodrigo Sarán aprovecharía un buen pase de Federico Ribera para dejar a los de casaca naranja arriba en el marcador. " +
"Guillermo Martínez estiraría la diferencia a los 7 minutos. " +
"Pelos no encontraba la forma de empatar el partido y por eso Gabriel Zvaliauskas pasaría al arco a cinco minutos del cierre. " +
"La Naranja Mecánica tenía el partido controlado sin embargo un penal que Gabriel Zvaliauskas cambiaría por gol iba a ponerle pimienta al final del partido. " +
"La Naranja sigue como puntero junto con Humildad y Talento que ganaría sin siquiera jugar gracias al faltazo (cacona) de los pibes de Flojo Licuado.",
"Conte-Grand, Tomás");
matches.add(match);
match = new Match(
"20/04/2013 - Fecha 6 - Apertura 2013",
Team.get("la-naranja-mecanica"), "3",
Team.get("cristal"), "2",
new ArrayList<String>(),
"Cronica",
"",
"");
matches.add(match);
}
return matches;
}
| public static List<Match> all() {
if (matches.isEmpty()) {
Match match = new Match(
"09/03/2013 - Fecha 1 - Apertura 2013",
Team.get("la-naranja-mecanica"), "5",
Team.get("descanso-verde"), "1",
new ArrayList<String>(),
"En 4 minutos liquidó la historia",
"En otro partido por la primera fecha en la máxima categoría se enfrentaban La naranja Mecánica contra Descanso Verde. " +
"El partido empezaría con el tanto de Sánchez a los 3' primeros minutos de juego. " +
"Luego el partido estuvo parejo a pesar de que termino ganando la primera etapa la naranja., " +
"porque Descanso verde inquieto e hizo temblar el arco en varias ocasiones. " +
"En el final la naranja encontraría de nuevo el rumbo y terminaría de la mejor manera creando buenas situaciones.<br/> " +
"En el segundo tiempo Vázquez a los 6' minutos de juego empataría el partido y le daría un condimento a esta etapa. " +
"Pero le duro poco las esperanzas al conjunto celeste, porque vendría la seguidilla de goles de Sánchez x2 que darían vuelta el partido y " +
"abrió el camino para que vengan los goles de Márquez y Magallanes. Todo esto pasó en cuatro minutos de juego, " +
"la naranja en tan poco tiempo saco una gran ventaja y también gano el dominio de pelota y hasta el final del partido llevo el partido a su antojo. " +
"Y sonaría el pitido final y la naranja ganaría por 5 a 1.",
"Francisco Rolón");
matches.add(match);
match = new Match(
"16/03/2013 - Fecha 2 - Apertura 2013",
Team.get("hacha-y-tiza"), "7",
Team.get("la-naranja-mecanica"), "8",
new ArrayList<String>(),
"Fiebre Naranja",
"Dos pesos pesados se enfrentaban en un gran partido que se viviría como una verdadera final, La Naranja Mecánica frente a Hacha y Tiza. " +
"Tincho Jacomelli abriría la cuenta a los 6´, pero minutos más tarde Maxi Márquez igualaría tras un potente remate afuera del área. " +
"Pero inmediatamente responderían los celestes que de contra serían letales gracias a los buenos movimientos de Antico y Cáceres, " +
"Jacomelli marcaría un doblete y el ya mencionado Cáceres aumentaría la diferencia. Sarán descontaba en la agonía. <br/> " +
"La Naranja arrancaría con todo esta segundo tiempo y en una ráfaga de dos minutos lo daría vuelta gracias a los goles de Trapo, Keki y Lope " +
"para asombro de los rivales que rápidamente descontarían a través de su máximo artillero Jacomelli volviendo a marcar. " +
"Sin embargo, El Trapo, recién regresado de Europa, sería el héroe del partido con sus goles. " +
"Hacha buscó y buscó pero las buenas respuestas de Regojo le impidieron al menos llevarse un punto y la gloria fue toda Naranja, que no tiene a Cruyff, pero lo tiene al trapo.",
"Maximiliano Rodriguez");
matches.add(match);
match = new Match(
"23/03/2013 - Fecha 3 - Apertura 2013",
Team.get("la-naranja-mecanica"), "14",
Team.get("lmds"), "3",
new ArrayList<String>(),
"A Todo Trapo",
"La Naranja Mecánica goleó a LMDS por 14 a 3. No tuvo mucha chance LMDS, empezó perdiendo por 3 goles, todos de Rodrigo Saran. " +
"Después siguió ampliando la ventaja sin darle respiro al rival M. Márquez ponía el 4 a 0 a los 8 minutos. Mariano López anotó el quinto. " +
"La Naranja apretó y cada llegada era un golpe bajo para su rival, que no se recupero hasta el final que descontó Alejandro Soriano con un golazo de media chilena afuera del area. <br/>" +
"En el segundo tiempo volvió el Trapo a la cancha y siguió sumando 4 goles más otro de E. Sánchez para el 10 a 1. " +
"Al minuto 13 un descuido de la defensa llevaría al descuento de Lucas Gagliote. " +
"Pero 2 min después vuelve a convertir La Naranja esta vez 2 goles de G. Martínez, y sigue sumando Saran otro gol más al minuto 18. " +
"Cerca del final descuenta Alejandro Soriano de penal, y para cerrar la goleada de la Naranja R.Saran cierra el 14 a 3.",
"Jonatan Leites");
matches.add(match);
match = new Match(
"06/04/2013 - Fecha 4 - Apertura 2013",
Team.get("las-aguilas-de-niupi"), "4",
Team.get("la-naranja-mecanica"), "5",
new ArrayList<String>(),
"Sobre el final",
"Las Águilas del Niupi reciben a la Naranja Mecánica a las 13 horas jugando la Categoría “A” del torneo de los Sábados. " +
"Se espera un muy buen partido, por el buen nivel de los equipos y jugadores. " +
"Fue un primer tiempo parejo donde abre el partido las Águilas con el gol de Mariano Gómez a los 8 minutos, " +
"4 minutos después con el ingreso del “trapo” R. Saran llega el empate y a los 15 minutos pone a su equipo arriba. " +
"En una de las últimas del primer tiempo se pondrían iguales con un Bombazo de Martin Sisca que de un tiro libre pone el 2 a 2.<br/> " +
"En el segundo tiempo se pone arriba la naranja a los 2 minutos con el gol de Yiyo Martínez, pero 2 minutos después empatan las Águilas con el gol de Martin Saban de contrataque. " +
"Es un partido ida y vuelta, muy parejo, pero la naranja con el correr del tiempo empezó a presionar mas y a tomar el control. " +
"En el minuto 15 R. Saran pone arriba a la Naranja otra vez, minuto 18 con un puntazo cruzado empata el partido 4 a 4, " +
"pero parecía terminar en empate casi no queda tiempo pero en un contra ataque de la naranja pase cruzado y " +
"entra Mariano López para poner el 5 a 4 y darle los 2 puntos a la naranja en un Partido Muy parejo y reñido.",
"Jonatan Leites");
matches.add(match);
match = new Match(
"13/04/2013 - Fecha 5 - Apertura 2013",
Team.get("pelos"), "2",
Team.get("la-naranja-mecanica"), "3",
new ArrayList<String>(),
"Se complicó solo",
"Bien tempranito se jugaba el partido entre uno de los punteros, La Naranja Mecánica, y el siempre complicado Pelos. " +
"A los 5 minutos de comenzado el encuentro llegaría el tanto de Gabriel Zvaliauskas quien simplemente tendría que acertarle al arco luego de robar en la mitad de cancha. " +
"La Naranja Mecánica se hacía dueño del juego. Ezequiel Sánchez rompería el palo a los 9 minutos. " +
"Tres minutos después llegaría el empate por medio de Santiago Fernández aprovechando un corner. <br/>" +
"A los 4 minutos de la segunda parte Rodrigo Sarán aprovecharía un buen pase de Federico Ribera para dejar a los de casaca naranja arriba en el marcador. " +
"Guillermo Martínez estiraría la diferencia a los 7 minutos. " +
"Pelos no encontraba la forma de empatar el partido y por eso Gabriel Zvaliauskas pasaría al arco a cinco minutos del cierre. " +
"La Naranja Mecánica tenía el partido controlado sin embargo un penal que Gabriel Zvaliauskas cambiaría por gol iba a ponerle pimienta al final del partido. " +
"La Naranja sigue como puntero junto con Humildad y Talento que ganaría sin siquiera jugar gracias al faltazo (cacona) de los pibes de Flojo Licuado.",
"Conte-Grand, Tomás");
matches.add(match);
match = new Match(
"20/04/2013 - Fecha 6 - Apertura 2013",
Team.get("la-naranja-mecanica"), "3",
Team.get("cristal"), "2",
new ArrayList<String>(),
"Cronica",
"",
"");
matches.add(match);
}
return matches;
}
|
diff --git a/src/view/AboutView.java b/src/view/AboutView.java
index 7238cbc..505f7df 100644
--- a/src/view/AboutView.java
+++ b/src/view/AboutView.java
@@ -1,160 +1,160 @@
package view;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
/**
* The about window
*/
public class AboutView extends JFrame
{
private static final long serialVersionUID = 1L;
private JLabel lbLogo;
private JLabel lbTitle;
private JLabel lbText;
private JButton btLicense;
private JButton btClose;
private JFrame licenseView;
/**
* Initialise the GUI
*/
public void initGUI()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setIconImage(new ImageIcon("septopus.png").getImage());
setResizable(false);
setTitle("About Septopus");
setSize(341, 240);
setLayout(null);
lbTitle = new JLabel("Septopus", JLabel.CENTER);
lbTitle.setFont(new Font("Dialog", Font.PLAIN, 24));
lbTitle.setBounds(58, 6, 194, 24);
getContentPane().add(lbTitle);
lbText = new JLabel("Advanced Vocab Trainer", JLabel.CENTER);
lbText.setBounds(47, 36, 227, 37);
getContentPane().add(lbText);
lbLogo = new JLabel(new ImageIcon("septopus.png"));
lbLogo.setBounds(105, 72, 114, 109);
getContentPane().add(lbLogo);
btLicense = new JButton("License");
btLicense.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
StringBuffer licenseText = new StringBuffer();
try
{
- BufferedReader bufRead = new BufferedReader(new FileReader(new File("COPYING")));
+ BufferedReader bufRead = new BufferedReader(new FileReader(new File("LICENSE")));
String line;
while (null != (line = bufRead.readLine()))
{
licenseText.append(line + "\n");
}
bufRead.close();
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
licenseView = new JFrame("License");
licenseView.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
licenseView.setSize(500, 300);
licenseView.setLayout(new BorderLayout());
licenseView.addWindowListener(new WindowListener() {
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
// re-enable parent
setEnabled(true);
}
public void windowClosing(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
// disable parent
setEnabled(false);
}
});
JTextArea textArea = new JTextArea(licenseText.toString());
textArea.setFont(new Font(null, 0, 10));
licenseView.add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
JButton btOkay = new JButton("Okay");
btOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
licenseView.dispose();
}
});
licenseView.add(btOkay, BorderLayout.SOUTH);
licenseView.setVisible(true);
}
});
btLicense.setBounds(40, 185, 114, 20);
getContentPane().add(btLicense);
btClose = new JButton("Close");
btClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
btClose.setBounds(160, 185, 114, 20);
getContentPane().add(btClose);
setVisible(true);
}
public static void main(String[] args)
{
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
AboutView view = new AboutView();
view.initGUI();
}
}
| true | true | public void initGUI()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setIconImage(new ImageIcon("septopus.png").getImage());
setResizable(false);
setTitle("About Septopus");
setSize(341, 240);
setLayout(null);
lbTitle = new JLabel("Septopus", JLabel.CENTER);
lbTitle.setFont(new Font("Dialog", Font.PLAIN, 24));
lbTitle.setBounds(58, 6, 194, 24);
getContentPane().add(lbTitle);
lbText = new JLabel("Advanced Vocab Trainer", JLabel.CENTER);
lbText.setBounds(47, 36, 227, 37);
getContentPane().add(lbText);
lbLogo = new JLabel(new ImageIcon("septopus.png"));
lbLogo.setBounds(105, 72, 114, 109);
getContentPane().add(lbLogo);
btLicense = new JButton("License");
btLicense.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
StringBuffer licenseText = new StringBuffer();
try
{
BufferedReader bufRead = new BufferedReader(new FileReader(new File("COPYING")));
String line;
while (null != (line = bufRead.readLine()))
{
licenseText.append(line + "\n");
}
bufRead.close();
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
licenseView = new JFrame("License");
licenseView.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
licenseView.setSize(500, 300);
licenseView.setLayout(new BorderLayout());
licenseView.addWindowListener(new WindowListener() {
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
// re-enable parent
setEnabled(true);
}
public void windowClosing(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
// disable parent
setEnabled(false);
}
});
JTextArea textArea = new JTextArea(licenseText.toString());
textArea.setFont(new Font(null, 0, 10));
licenseView.add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
JButton btOkay = new JButton("Okay");
btOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
licenseView.dispose();
}
});
licenseView.add(btOkay, BorderLayout.SOUTH);
licenseView.setVisible(true);
}
});
btLicense.setBounds(40, 185, 114, 20);
getContentPane().add(btLicense);
btClose = new JButton("Close");
btClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
btClose.setBounds(160, 185, 114, 20);
getContentPane().add(btClose);
setVisible(true);
}
| public void initGUI()
{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setIconImage(new ImageIcon("septopus.png").getImage());
setResizable(false);
setTitle("About Septopus");
setSize(341, 240);
setLayout(null);
lbTitle = new JLabel("Septopus", JLabel.CENTER);
lbTitle.setFont(new Font("Dialog", Font.PLAIN, 24));
lbTitle.setBounds(58, 6, 194, 24);
getContentPane().add(lbTitle);
lbText = new JLabel("Advanced Vocab Trainer", JLabel.CENTER);
lbText.setBounds(47, 36, 227, 37);
getContentPane().add(lbText);
lbLogo = new JLabel(new ImageIcon("septopus.png"));
lbLogo.setBounds(105, 72, 114, 109);
getContentPane().add(lbLogo);
btLicense = new JButton("License");
btLicense.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
StringBuffer licenseText = new StringBuffer();
try
{
BufferedReader bufRead = new BufferedReader(new FileReader(new File("LICENSE")));
String line;
while (null != (line = bufRead.readLine()))
{
licenseText.append(line + "\n");
}
bufRead.close();
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e1)
{
e1.printStackTrace();
}
licenseView = new JFrame("License");
licenseView.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
licenseView.setSize(500, 300);
licenseView.setLayout(new BorderLayout());
licenseView.addWindowListener(new WindowListener() {
public void windowActivated(WindowEvent e) {
}
public void windowClosed(WindowEvent e) {
// re-enable parent
setEnabled(true);
}
public void windowClosing(WindowEvent e) {
}
public void windowDeactivated(WindowEvent e) {
}
public void windowDeiconified(WindowEvent e) {
}
public void windowIconified(WindowEvent e) {
}
public void windowOpened(WindowEvent e) {
// disable parent
setEnabled(false);
}
});
JTextArea textArea = new JTextArea(licenseText.toString());
textArea.setFont(new Font(null, 0, 10));
licenseView.add(new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
JButton btOkay = new JButton("Okay");
btOkay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
licenseView.dispose();
}
});
licenseView.add(btOkay, BorderLayout.SOUTH);
licenseView.setVisible(true);
}
});
btLicense.setBounds(40, 185, 114, 20);
getContentPane().add(btLicense);
btClose = new JButton("Close");
btClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
btClose.setBounds(160, 185, 114, 20);
getContentPane().add(btClose);
setVisible(true);
}
|
diff --git a/src/prettify/lang/LangErlang.java b/src/prettify/lang/LangErlang.java
index 24fb9aa..57ce401 100644
--- a/src/prettify/lang/LangErlang.java
+++ b/src/prettify/lang/LangErlang.java
@@ -1,105 +1,105 @@
// Copyright (C) 2013 Andrew Allen
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prettify.lang;
import prettify.parser.Prettify;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
/**
* This is similar to the lang-erlang.js in JavaScript Prettify.
* <p/>
* All comments are adapted from the JavaScript Prettify.
* <p/>
* <p/>
* <p/>
* Derived from https://raw.github.com/erlang/otp/dev/lib/compiler/src/core_parse.yrl
* Modified from Mike Samuel's Haskell plugin for google-code-prettify
*
* @author [email protected]
*/
public class LangErlang extends Lang {
public LangErlang() {
List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>();
List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>();
// Whitespace
// whitechar -> newline | vertab | space | tab | uniWhite
// newline -> return linefeed | return | linefeed | formfeed
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("\\t\\n\\x0B\\x0C\\r ]+"), null, "\t\n" + Character.toString((char) 0x0B) + Character.toString((char) 0x0C) + "\r "}));
// Single line double-quoted strings.
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)"), null, "\""}));
// Handle atoms
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[a-z][a-zA-Z0-9_]*")}));
// Handle single quoted atoms
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])+\\'?"), null, "'"}));
// Handle macros. Just to be extra clear on this one, it detects the ?
// then uses the regexp to end it so be very careful about matching
// all the terminal elements
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\?[^ \\t\\n({]+"), null, "?"}));
// decimal -> digit{digit}
// octal -> octit{octit}
// hexadecimal -> hexit{hexit}
// integer -> decimal
// | 0o octal | 0O octal
// | 0x hexadecimal | 0X hexadecimal
// float -> decimal . decimal [exponent]
// | decimal exponent
// exponent -> (e | E) [+ | -] decimal
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)", Pattern.CASE_INSENSITIVE), null, "0123456789"}));
// TODO: catch @declarations inside comments
// Comments in erlang are started with % and go till a newline
- _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n]*"), null}));
+ _fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n\\r]*")}));
// Catch macros
//[PR['PR_TAG'], /?[^( \n)]+/],
/**
* %% Keywords (atoms are assumed to always be single-quoted).
* 'module' 'attributes' 'do' 'let' 'in' 'letrec'
* 'apply' 'call' 'primop'
* 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after'
*/
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\\b")}));
/**
* Catch definitions (usually defined at the top of the file)
* Anything that starts -something
*/
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-[a-z_]+")}));
// Catch variables
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_TYPE, Pattern.compile("^[A-Z_][a-zA-Z0-9_]*")}));
// matches the symbol production
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[.,;]")}));
setShortcutStylePatterns(_shortcutStylePatterns);
setFallthroughStylePatterns(_fallthroughStylePatterns);
}
public static List<String> getFileExtensions() {
return Arrays.asList(new String[]{"erlang", "erl"});
}
}
| true | true | public LangErlang() {
List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>();
List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>();
// Whitespace
// whitechar -> newline | vertab | space | tab | uniWhite
// newline -> return linefeed | return | linefeed | formfeed
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("\\t\\n\\x0B\\x0C\\r ]+"), null, "\t\n" + Character.toString((char) 0x0B) + Character.toString((char) 0x0C) + "\r "}));
// Single line double-quoted strings.
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)"), null, "\""}));
// Handle atoms
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[a-z][a-zA-Z0-9_]*")}));
// Handle single quoted atoms
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])+\\'?"), null, "'"}));
// Handle macros. Just to be extra clear on this one, it detects the ?
// then uses the regexp to end it so be very careful about matching
// all the terminal elements
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\?[^ \\t\\n({]+"), null, "?"}));
// decimal -> digit{digit}
// octal -> octit{octit}
// hexadecimal -> hexit{hexit}
// integer -> decimal
// | 0o octal | 0O octal
// | 0x hexadecimal | 0X hexadecimal
// float -> decimal . decimal [exponent]
// | decimal exponent
// exponent -> (e | E) [+ | -] decimal
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)", Pattern.CASE_INSENSITIVE), null, "0123456789"}));
// TODO: catch @declarations inside comments
// Comments in erlang are started with % and go till a newline
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n]*"), null}));
// Catch macros
//[PR['PR_TAG'], /?[^( \n)]+/],
/**
* %% Keywords (atoms are assumed to always be single-quoted).
* 'module' 'attributes' 'do' 'let' 'in' 'letrec'
* 'apply' 'call' 'primop'
* 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after'
*/
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\\b")}));
/**
* Catch definitions (usually defined at the top of the file)
* Anything that starts -something
*/
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-[a-z_]+")}));
// Catch variables
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_TYPE, Pattern.compile("^[A-Z_][a-zA-Z0-9_]*")}));
// matches the symbol production
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[.,;]")}));
setShortcutStylePatterns(_shortcutStylePatterns);
setFallthroughStylePatterns(_fallthroughStylePatterns);
}
| public LangErlang() {
List<List<Object>> _shortcutStylePatterns = new ArrayList<List<Object>>();
List<List<Object>> _fallthroughStylePatterns = new ArrayList<List<Object>>();
// Whitespace
// whitechar -> newline | vertab | space | tab | uniWhite
// newline -> return linefeed | return | linefeed | formfeed
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PLAIN, Pattern.compile("\\t\\n\\x0B\\x0C\\r ]+"), null, "\t\n" + Character.toString((char) 0x0B) + Character.toString((char) 0x0C) + "\r "}));
// Single line double-quoted strings.
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_STRING, Pattern.compile("^\\\"(?:[^\\\"\\\\\\n\\x0C\\r]|\\\\[\\s\\S])*(?:\\\"|$)"), null, "\""}));
// Handle atoms
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^[a-z][a-zA-Z0-9_]*")}));
// Handle single quoted atoms
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\'(?:[^\\'\\\\\\n\\x0C\\r]|\\\\[^&])+\\'?"), null, "'"}));
// Handle macros. Just to be extra clear on this one, it detects the ?
// then uses the regexp to end it so be very careful about matching
// all the terminal elements
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^\\?[^ \\t\\n({]+"), null, "?"}));
// decimal -> digit{digit}
// octal -> octit{octit}
// hexadecimal -> hexit{hexit}
// integer -> decimal
// | 0o octal | 0O octal
// | 0x hexadecimal | 0X hexadecimal
// float -> decimal . decimal [exponent]
// | decimal exponent
// exponent -> (e | E) [+ | -] decimal
_shortcutStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_LITERAL, Pattern.compile("^(?:0o[0-7]+|0x[\\da-f]+|\\d+(?:\\.\\d+)?(?:e[+\\-]?\\d+)?)", Pattern.CASE_INSENSITIVE), null, "0123456789"}));
// TODO: catch @declarations inside comments
// Comments in erlang are started with % and go till a newline
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_COMMENT, Pattern.compile("^%[^\\n\\r]*")}));
// Catch macros
//[PR['PR_TAG'], /?[^( \n)]+/],
/**
* %% Keywords (atoms are assumed to always be single-quoted).
* 'module' 'attributes' 'do' 'let' 'in' 'letrec'
* 'apply' 'call' 'primop'
* 'case' 'of' 'end' 'when' 'fun' 'try' 'catch' 'receive' 'after'
*/
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^(?:module|attributes|do|let|in|letrec|apply|call|primop|case|of|end|when|fun|try|catch|receive|after|char|integer|float,atom,string,var)\\b")}));
/**
* Catch definitions (usually defined at the top of the file)
* Anything that starts -something
*/
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_KEYWORD, Pattern.compile("^-[a-z_]+")}));
// Catch variables
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_TYPE, Pattern.compile("^[A-Z_][a-zA-Z0-9_]*")}));
// matches the symbol production
_fallthroughStylePatterns.add(Arrays.asList(new Object[]{Prettify.PR_PUNCTUATION, Pattern.compile("^[.,;]")}));
setShortcutStylePatterns(_shortcutStylePatterns);
setFallthroughStylePatterns(_fallthroughStylePatterns);
}
|
diff --git a/src/com/nadmm/airports/wx/TafFragment.java b/src/com/nadmm/airports/wx/TafFragment.java
index 19683d8c..0241cce6 100644
--- a/src/com/nadmm/airports/wx/TafFragment.java
+++ b/src/com/nadmm/airports/wx/TafFragment.java
@@ -1,486 +1,487 @@
/*
* FlightIntel for Pilots
*
* Copyright 2012 Nadeem Hasan <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nadmm.airports.wx;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.view.Menu;
import android.support.v4.view.MenuItem;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.nadmm.airports.DatabaseManager;
import com.nadmm.airports.DatabaseManager.Airports;
import com.nadmm.airports.DatabaseManager.Awos1;
import com.nadmm.airports.DatabaseManager.Wxs;
import com.nadmm.airports.FragmentBase;
import com.nadmm.airports.R;
import com.nadmm.airports.utils.CursorAsyncTask;
import com.nadmm.airports.utils.FormatUtils;
import com.nadmm.airports.utils.GeoUtils;
import com.nadmm.airports.utils.TimeUtils;
import com.nadmm.airports.wx.Taf.Forecast;
import com.nadmm.airports.wx.Taf.IcingCondition;
import com.nadmm.airports.wx.Taf.TurbulenceCondition;
public class TafFragment extends FragmentBase {
private final int TAF_RADIUS = 25;
protected Location mLocation;
protected CursorAsyncTask mTask;
protected BroadcastReceiver mReceiver;
protected String mStationId;
protected Forecast mLastForecast;
@Override
public void onCreate( Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
setHasOptionsMenu( true );
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive( Context context, Intent intent ) {
showTaf( intent );
}
};
}
@Override
public void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction( NoaaService.ACTION_GET_TAF );
getActivity().registerReceiver( mReceiver, filter );
Bundle args = getArguments();
String stationId = args.getString( NoaaService.STATION_ID );
mTask = new TafDetailTask();
mTask.execute( stationId );
super.onResume();
}
@Override
public void onPause() {
mTask.cancel( true );
getActivity().unregisterReceiver( mReceiver );
super.onPause();
}
@Override
public View onCreateView( LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState ) {
View view = inflater.inflate( R.layout.taf_detail_view, container, false );
return createContentView( view );
}
private final class TafDetailTask extends CursorAsyncTask {
@Override
protected Cursor[] doInBackground( String... params ) {
String stationId = params[ 0 ];
Cursor[] cursors = new Cursor[ 2 ];
SQLiteDatabase db = getDbManager().getDatabase( DatabaseManager.DB_FADDS );
SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
builder.setTables( Wxs.TABLE_NAME );
String selection = Wxs.STATION_ID+"=?";
Cursor c = builder.query( db, new String[] { "*" }, selection,
new String[] { stationId }, null, null, null, null );
c.moveToFirst();
String siteTypes = c.getString( c.getColumnIndex( Wxs.STATION_SITE_TYPES ) );
if ( !siteTypes.contains( "TAF" ) ) {
// There is no TAF available at this station, search for the nearest
double lat = c.getDouble( c.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) );
double lon = c.getDouble( c.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) );
Location location = new Location( "" );
location.setLatitude( lat );
location.setLongitude( lon );
c.close();
// Get the bounding box first to do a quick query as a first cut
double[] box = GeoUtils.getBoundingBox( location, TAF_RADIUS );
double radLatMin = box[ 0 ];
double radLatMax = box[ 1 ];
double radLonMin = box[ 2 ];
double radLonMax = box[ 3 ];
// Check if 180th Meridian lies within the bounding Box
boolean isCrossingMeridian180 = ( radLonMin > radLonMax );
selection = "("
+Wxs.STATION_LATITUDE_DEGREES+">=? AND "+Wxs.STATION_LATITUDE_DEGREES+"<=?"
+") AND ("+Wxs.STATION_LONGITUDE_DEGREES+">=? "
+(isCrossingMeridian180? "OR " : "AND ")+Wxs.STATION_LONGITUDE_DEGREES+"<=?)";
String[] selectionArgs = {
String.valueOf( Math.toDegrees( radLatMin ) ),
String.valueOf( Math.toDegrees( radLatMax ) ),
String.valueOf( Math.toDegrees( radLonMin ) ),
String.valueOf( Math.toDegrees( radLonMax ) )
};
c = builder.query( db, new String[] { "*" }, selection, selectionArgs,
null, null, null, null );
stationId = "";
if ( c.moveToFirst() ) {
float distance = Float.MAX_VALUE;
do {
siteTypes = c.getString( c.getColumnIndex( Wxs.STATION_SITE_TYPES ) );
if ( !siteTypes.contains( "TAF" ) ) {
continue;
}
// Get the location of this station
float[] results = new float[ 2 ];
Location.distanceBetween(
location.getLatitude(),
location.getLongitude(),
c.getDouble( c.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) ),
c.getDouble( c.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) ),
results );
results[ 0 ] /= GeoUtils.METERS_PER_NAUTICAL_MILE;
if ( results[ 0 ] <= TAF_RADIUS && results[ 0 ] < distance ) {
stationId = c.getString( c.getColumnIndex( Wxs.STATION_ID ) );
distance = results[ 0 ];
}
} while ( c.moveToNext() );
}
}
c.close();
if ( stationId.length() > 0 ) {
// We have the station with TAF
builder = new SQLiteQueryBuilder();
builder.setTables( Wxs.TABLE_NAME );
selection = Wxs.STATION_ID+"=?";
c = builder.query( db, new String[] { "*" }, selection,
new String[] { stationId }, null, null, null, null );
cursors[ 0 ] = c;
String[] wxColumns = new String[] {
Awos1.WX_SENSOR_IDENT,
Awos1.WX_SENSOR_TYPE,
Awos1.STATION_FREQUENCY,
Awos1.SECOND_STATION_FREQUENCY,
Awos1.STATION_PHONE_NUMBER,
Airports.ASSOC_CITY,
Airports.ASSOC_STATE
};
builder = new SQLiteQueryBuilder();
builder.setTables( Airports.TABLE_NAME+" a"
+" LEFT JOIN "+Awos1.TABLE_NAME+" w"
+" ON a."+Airports.FAA_CODE+" = w."+Awos1.WX_SENSOR_IDENT );
selection = "a."+Airports.ICAO_CODE+"=?";
c = builder.query( db, wxColumns, selection, new String[] { stationId },
null, null, null, null );
cursors[ 1 ] = c;
}
return cursors;
}
@Override
protected void onResult( Cursor[] result ) {
Cursor wxs = result[ 0 ];
if ( wxs == null || !wxs.moveToFirst() ) {
// No station with TAF was found nearby
Bundle args = getArguments();
String stationId = args.getString( NoaaService.STATION_ID );
View detail = findViewById( R.id.wx_detail_layout );
detail.setVisibility( View.GONE );
LinearLayout layout = (LinearLayout) findViewById( R.id.wx_status_layout );
layout.removeAllViews();
layout.setVisibility( View.GONE );
TextView tv =(TextView) findViewById( R.id.status_msg );
tv.setVisibility( View.VISIBLE );
tv.setText( String.format( "No wx station with TAF was found near %s"
+" within %dNM radius", stationId, TAF_RADIUS ) );
View title = findViewById( R.id.wx_title_layout );
title.setVisibility( View.GONE );
stopRefreshAnimation();
setContentShown( true );
return;
}
mLocation = new Location( "" );
float lat = wxs.getFloat( wxs.getColumnIndex( Wxs.STATION_LATITUDE_DEGREES ) );
float lon = wxs.getFloat( wxs.getColumnIndex( Wxs.STATION_LONGITUDE_DEGREES ) );
mLocation.setLatitude( lat );
mLocation.setLongitude( lon );
// Show the weather station info
showWxTitle( result );
// Now request the weather
mStationId = wxs.getString( wxs.getColumnIndex( Wxs.STATION_ID ) );
requestTaf( mStationId, false );
}
}
protected void requestTaf( String stationId, boolean refresh ) {
Intent service = new Intent( getActivity(), TafService.class );
service.setAction( NoaaService.ACTION_GET_TAF );
service.putExtra( NoaaService.STATION_ID, stationId );
service.putExtra( NoaaService.FORCE_REFRESH, refresh );
getActivity().startService( service );
}
protected void showTaf( Intent intent ) {
if ( getActivity() == null ) {
// Not ready to do this yet
return;
}
Taf taf = (Taf) intent.getSerializableExtra( NoaaService.RESULT );
View detail = findViewById( R.id.wx_detail_layout );
LinearLayout layout = (LinearLayout) findViewById( R.id.wx_status_layout );
TextView tv =(TextView) findViewById( R.id.status_msg );
layout.removeAllViews();
if ( !taf.isValid ) {
tv.setVisibility( View.VISIBLE );
layout.setVisibility( View.VISIBLE );
tv.setText( "Unable to get TAF for this location." );
addRow( layout, "This could be due to the following reasons:" );
addBulletedRow( layout, "Network connection is not available" );
addBulletedRow( layout, "ADDS does not publish TAF for this station" );
addBulletedRow( layout, "Station is currently out of service" );
addBulletedRow( layout, "Station has not updated the TAF for more than 12 hours" );
detail.setVisibility( View.GONE );
stopRefreshAnimation();
setContentShown( true );
return;
} else {
tv.setText( "" );
tv.setVisibility( View.GONE );
layout.setVisibility( View.GONE );
detail.setVisibility( View.VISIBLE );
}
tv = (TextView) findViewById( R.id.wx_age );
tv.setText( TimeUtils.formatElapsedTime( taf.issueTime ) );
// Raw Text
tv = (TextView) findViewById( R.id.wx_raw_taf );
tv.setText( taf.rawText.replaceAll( "(FM|BECMG|TEMPO)", "\n $1" ) );
layout = (LinearLayout) findViewById( R.id.taf_summary_layout );
layout.removeAllViews();
String fcstType;
if ( taf.rawText.startsWith( "TAF AMD " ) ) {
fcstType = "Amendment";
} else if ( taf.rawText.startsWith( "TAF COR " ) ) {
fcstType = "Correction";
} else {
fcstType = "Normal";
}
addRow( layout, "Forecast type", fcstType );
addSeparator( layout );
addRow( layout, "Issued at", TimeUtils.formatDateTime( getActivity(), taf.issueTime ) );
addSeparator( layout );
addRow( layout, "Valid from", TimeUtils.formatDateTime( getActivity(), taf.validTimeFrom ) );
addSeparator( layout );
addRow( layout, "Valid to", TimeUtils.formatDateTime( getActivity(), taf.validTimeTo ) );
if ( taf.remarks != null && taf.remarks.length() > 0 && !taf.remarks.equals( "AMD" ) ) {
addSeparator( layout );
addRow( layout, "\u2022 "+taf.remarks );
}
LinearLayout topLayout = (LinearLayout) findViewById( R.id.taf_forecasts_layout );
topLayout.removeAllViews();
StringBuilder sb = new StringBuilder();
for ( Forecast forecast : taf.forecasts ) {
RelativeLayout grp_layout = (RelativeLayout) inflate( R.layout.grouped_detail_item );
// Keep track of forecast conditions across all change groups
- if ( mLastForecast == null || forecast.changeIndicator.equals( "FM" ) ) {
+ if ( mLastForecast == null || forecast.changeIndicator == null
+ || forecast.changeIndicator.equals( "FM" ) ) {
mLastForecast = forecast;
} else {
if ( forecast.visibilitySM < Float.MAX_VALUE ) {
mLastForecast.visibilitySM = forecast.visibilitySM;
}
if ( forecast.skyConditions.size() > 0 ) {
mLastForecast.skyConditions = forecast.skyConditions;
}
}
sb.setLength( 0 );
if ( forecast.changeIndicator != null ) {
sb.append( forecast.changeIndicator );
sb.append( " " );
}
sb.append( TimeUtils.formatDateRange(
getActivity(), forecast.timeFrom, forecast.timeTo ) );
tv = (TextView) grp_layout.findViewById( R.id.group_name );
tv.setText( sb.toString() );
String flightCategory = WxUtils.computeFlightCategory(
mLastForecast.skyConditions, mLastForecast.visibilitySM );
WxUtils.setFlightCategoryDrawable( tv, flightCategory );
LinearLayout fcst_layout = (LinearLayout) grp_layout.findViewById( R.id.group_details );
if ( forecast.probability < Integer.MAX_VALUE ) {
addRow( fcst_layout, "Probability", String.format( "%d%%", forecast.probability ) );
}
if ( forecast.changeIndicator != null
&& forecast.changeIndicator.equals( "BECMG" ) ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Becoming at", TimeUtils.formatDateTime(
getActivity(), forecast.timeBecoming ) );
}
if ( forecast.windSpeedKnots < Integer.MAX_VALUE ) {
String wind;
if ( forecast.windDirDegrees == 0 && forecast.windSpeedKnots == 0 ) {
wind = "Calm";
} else if ( forecast.windDirDegrees == 0 ) {
wind = String.format( "Variable at %d knots", forecast.windSpeedKnots );
} else {
wind = String.format( "%s (%03d\u00B0 true) at %d knots",
GeoUtils.getCardinalDirection( forecast.windDirDegrees ),
forecast.windDirDegrees, forecast.windSpeedKnots );
}
String gust = "";
if ( forecast.windGustKnots < Integer.MAX_VALUE ) {
gust = String.format( "Gusting to %d knots", forecast.windGustKnots );
}
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Winds", wind, gust );
}
if ( forecast.visibilitySM < Float.MAX_VALUE ) {
String value = forecast.visibilitySM > 6? "6+ SM"
: FormatUtils.formatVisibility( forecast.visibilitySM );
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Visibility", value );
}
if ( forecast.vertVisibilityFeet < Integer.MAX_VALUE ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Visibility",
FormatUtils.formatFeetAgl( forecast.vertVisibilityFeet ) );
}
for ( WxSymbol wx : forecast.wxList ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Weather", wx.toString() );
}
for ( SkyCondition sky : forecast.skyConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Clouds", sky.toString() );
}
if ( forecast.windShearSpeedKnots < Integer.MAX_VALUE ) {
String shear = String.format( "%s (%03d\u00B0 true) at %d knots",
GeoUtils.getCardinalDirection( forecast.windShearDirDegrees ),
forecast.windShearDirDegrees, forecast.windShearSpeedKnots );
String height = FormatUtils.formatFeetAgl( forecast.windShearHeightFeetAGL );
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Wind shear", shear, height );
}
if ( forecast.altimeterHg < Float.MAX_VALUE ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Altimeter",
FormatUtils.formatAltimeter( forecast.altimeterHg ) );
}
for ( TurbulenceCondition turbulence : forecast.turbulenceConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
String value = WxUtils.decodeTurbulenceIntensity( turbulence.intensity );
String height = FormatUtils.formatFeetRangeAgl(
turbulence.minAltitudeFeetAGL, turbulence.maxAltitudeFeetAGL );
addRow( fcst_layout, "Turbulence", value, height );
}
for ( IcingCondition icing : forecast.icingConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
String value = WxUtils.decodeIcingIntensity( icing.intensity );
String height = FormatUtils.formatFeetRangeAgl(
icing.minAltitudeFeetAGL, icing.maxAltitudeFeetAGL );
addRow( fcst_layout, "Icing", value, height );
}
topLayout.addView( grp_layout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT );
}
tv = (TextView) findViewById( R.id.wx_fetch_time );
tv.setText( "Fetched on "+TimeUtils.formatDateTime( getActivity(), taf.fetchTime ) );
tv.setVisibility( View.VISIBLE );
stopRefreshAnimation();
setContentShown( true );
}
@Override
public void onPrepareOptionsMenu( Menu menu ) {
setRefreshItemVisible( true );
}
@Override
public boolean onOptionsItemSelected( MenuItem item ) {
// Handle item selection
switch ( item.getItemId() ) {
case R.id.menu_refresh:
startRefreshAnimation();
requestTaf( mStationId, true );
return true;
default:
return super.onOptionsItemSelected( item );
}
}
}
| true | true | protected void showTaf( Intent intent ) {
if ( getActivity() == null ) {
// Not ready to do this yet
return;
}
Taf taf = (Taf) intent.getSerializableExtra( NoaaService.RESULT );
View detail = findViewById( R.id.wx_detail_layout );
LinearLayout layout = (LinearLayout) findViewById( R.id.wx_status_layout );
TextView tv =(TextView) findViewById( R.id.status_msg );
layout.removeAllViews();
if ( !taf.isValid ) {
tv.setVisibility( View.VISIBLE );
layout.setVisibility( View.VISIBLE );
tv.setText( "Unable to get TAF for this location." );
addRow( layout, "This could be due to the following reasons:" );
addBulletedRow( layout, "Network connection is not available" );
addBulletedRow( layout, "ADDS does not publish TAF for this station" );
addBulletedRow( layout, "Station is currently out of service" );
addBulletedRow( layout, "Station has not updated the TAF for more than 12 hours" );
detail.setVisibility( View.GONE );
stopRefreshAnimation();
setContentShown( true );
return;
} else {
tv.setText( "" );
tv.setVisibility( View.GONE );
layout.setVisibility( View.GONE );
detail.setVisibility( View.VISIBLE );
}
tv = (TextView) findViewById( R.id.wx_age );
tv.setText( TimeUtils.formatElapsedTime( taf.issueTime ) );
// Raw Text
tv = (TextView) findViewById( R.id.wx_raw_taf );
tv.setText( taf.rawText.replaceAll( "(FM|BECMG|TEMPO)", "\n $1" ) );
layout = (LinearLayout) findViewById( R.id.taf_summary_layout );
layout.removeAllViews();
String fcstType;
if ( taf.rawText.startsWith( "TAF AMD " ) ) {
fcstType = "Amendment";
} else if ( taf.rawText.startsWith( "TAF COR " ) ) {
fcstType = "Correction";
} else {
fcstType = "Normal";
}
addRow( layout, "Forecast type", fcstType );
addSeparator( layout );
addRow( layout, "Issued at", TimeUtils.formatDateTime( getActivity(), taf.issueTime ) );
addSeparator( layout );
addRow( layout, "Valid from", TimeUtils.formatDateTime( getActivity(), taf.validTimeFrom ) );
addSeparator( layout );
addRow( layout, "Valid to", TimeUtils.formatDateTime( getActivity(), taf.validTimeTo ) );
if ( taf.remarks != null && taf.remarks.length() > 0 && !taf.remarks.equals( "AMD" ) ) {
addSeparator( layout );
addRow( layout, "\u2022 "+taf.remarks );
}
LinearLayout topLayout = (LinearLayout) findViewById( R.id.taf_forecasts_layout );
topLayout.removeAllViews();
StringBuilder sb = new StringBuilder();
for ( Forecast forecast : taf.forecasts ) {
RelativeLayout grp_layout = (RelativeLayout) inflate( R.layout.grouped_detail_item );
// Keep track of forecast conditions across all change groups
if ( mLastForecast == null || forecast.changeIndicator.equals( "FM" ) ) {
mLastForecast = forecast;
} else {
if ( forecast.visibilitySM < Float.MAX_VALUE ) {
mLastForecast.visibilitySM = forecast.visibilitySM;
}
if ( forecast.skyConditions.size() > 0 ) {
mLastForecast.skyConditions = forecast.skyConditions;
}
}
sb.setLength( 0 );
if ( forecast.changeIndicator != null ) {
sb.append( forecast.changeIndicator );
sb.append( " " );
}
sb.append( TimeUtils.formatDateRange(
getActivity(), forecast.timeFrom, forecast.timeTo ) );
tv = (TextView) grp_layout.findViewById( R.id.group_name );
tv.setText( sb.toString() );
String flightCategory = WxUtils.computeFlightCategory(
mLastForecast.skyConditions, mLastForecast.visibilitySM );
WxUtils.setFlightCategoryDrawable( tv, flightCategory );
LinearLayout fcst_layout = (LinearLayout) grp_layout.findViewById( R.id.group_details );
if ( forecast.probability < Integer.MAX_VALUE ) {
addRow( fcst_layout, "Probability", String.format( "%d%%", forecast.probability ) );
}
if ( forecast.changeIndicator != null
&& forecast.changeIndicator.equals( "BECMG" ) ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Becoming at", TimeUtils.formatDateTime(
getActivity(), forecast.timeBecoming ) );
}
if ( forecast.windSpeedKnots < Integer.MAX_VALUE ) {
String wind;
if ( forecast.windDirDegrees == 0 && forecast.windSpeedKnots == 0 ) {
wind = "Calm";
} else if ( forecast.windDirDegrees == 0 ) {
wind = String.format( "Variable at %d knots", forecast.windSpeedKnots );
} else {
wind = String.format( "%s (%03d\u00B0 true) at %d knots",
GeoUtils.getCardinalDirection( forecast.windDirDegrees ),
forecast.windDirDegrees, forecast.windSpeedKnots );
}
String gust = "";
if ( forecast.windGustKnots < Integer.MAX_VALUE ) {
gust = String.format( "Gusting to %d knots", forecast.windGustKnots );
}
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Winds", wind, gust );
}
if ( forecast.visibilitySM < Float.MAX_VALUE ) {
String value = forecast.visibilitySM > 6? "6+ SM"
: FormatUtils.formatVisibility( forecast.visibilitySM );
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Visibility", value );
}
if ( forecast.vertVisibilityFeet < Integer.MAX_VALUE ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Visibility",
FormatUtils.formatFeetAgl( forecast.vertVisibilityFeet ) );
}
for ( WxSymbol wx : forecast.wxList ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Weather", wx.toString() );
}
for ( SkyCondition sky : forecast.skyConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Clouds", sky.toString() );
}
if ( forecast.windShearSpeedKnots < Integer.MAX_VALUE ) {
String shear = String.format( "%s (%03d\u00B0 true) at %d knots",
GeoUtils.getCardinalDirection( forecast.windShearDirDegrees ),
forecast.windShearDirDegrees, forecast.windShearSpeedKnots );
String height = FormatUtils.formatFeetAgl( forecast.windShearHeightFeetAGL );
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Wind shear", shear, height );
}
if ( forecast.altimeterHg < Float.MAX_VALUE ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Altimeter",
FormatUtils.formatAltimeter( forecast.altimeterHg ) );
}
for ( TurbulenceCondition turbulence : forecast.turbulenceConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
String value = WxUtils.decodeTurbulenceIntensity( turbulence.intensity );
String height = FormatUtils.formatFeetRangeAgl(
turbulence.minAltitudeFeetAGL, turbulence.maxAltitudeFeetAGL );
addRow( fcst_layout, "Turbulence", value, height );
}
for ( IcingCondition icing : forecast.icingConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
String value = WxUtils.decodeIcingIntensity( icing.intensity );
String height = FormatUtils.formatFeetRangeAgl(
icing.minAltitudeFeetAGL, icing.maxAltitudeFeetAGL );
addRow( fcst_layout, "Icing", value, height );
}
topLayout.addView( grp_layout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT );
}
tv = (TextView) findViewById( R.id.wx_fetch_time );
tv.setText( "Fetched on "+TimeUtils.formatDateTime( getActivity(), taf.fetchTime ) );
tv.setVisibility( View.VISIBLE );
stopRefreshAnimation();
setContentShown( true );
}
| protected void showTaf( Intent intent ) {
if ( getActivity() == null ) {
// Not ready to do this yet
return;
}
Taf taf = (Taf) intent.getSerializableExtra( NoaaService.RESULT );
View detail = findViewById( R.id.wx_detail_layout );
LinearLayout layout = (LinearLayout) findViewById( R.id.wx_status_layout );
TextView tv =(TextView) findViewById( R.id.status_msg );
layout.removeAllViews();
if ( !taf.isValid ) {
tv.setVisibility( View.VISIBLE );
layout.setVisibility( View.VISIBLE );
tv.setText( "Unable to get TAF for this location." );
addRow( layout, "This could be due to the following reasons:" );
addBulletedRow( layout, "Network connection is not available" );
addBulletedRow( layout, "ADDS does not publish TAF for this station" );
addBulletedRow( layout, "Station is currently out of service" );
addBulletedRow( layout, "Station has not updated the TAF for more than 12 hours" );
detail.setVisibility( View.GONE );
stopRefreshAnimation();
setContentShown( true );
return;
} else {
tv.setText( "" );
tv.setVisibility( View.GONE );
layout.setVisibility( View.GONE );
detail.setVisibility( View.VISIBLE );
}
tv = (TextView) findViewById( R.id.wx_age );
tv.setText( TimeUtils.formatElapsedTime( taf.issueTime ) );
// Raw Text
tv = (TextView) findViewById( R.id.wx_raw_taf );
tv.setText( taf.rawText.replaceAll( "(FM|BECMG|TEMPO)", "\n $1" ) );
layout = (LinearLayout) findViewById( R.id.taf_summary_layout );
layout.removeAllViews();
String fcstType;
if ( taf.rawText.startsWith( "TAF AMD " ) ) {
fcstType = "Amendment";
} else if ( taf.rawText.startsWith( "TAF COR " ) ) {
fcstType = "Correction";
} else {
fcstType = "Normal";
}
addRow( layout, "Forecast type", fcstType );
addSeparator( layout );
addRow( layout, "Issued at", TimeUtils.formatDateTime( getActivity(), taf.issueTime ) );
addSeparator( layout );
addRow( layout, "Valid from", TimeUtils.formatDateTime( getActivity(), taf.validTimeFrom ) );
addSeparator( layout );
addRow( layout, "Valid to", TimeUtils.formatDateTime( getActivity(), taf.validTimeTo ) );
if ( taf.remarks != null && taf.remarks.length() > 0 && !taf.remarks.equals( "AMD" ) ) {
addSeparator( layout );
addRow( layout, "\u2022 "+taf.remarks );
}
LinearLayout topLayout = (LinearLayout) findViewById( R.id.taf_forecasts_layout );
topLayout.removeAllViews();
StringBuilder sb = new StringBuilder();
for ( Forecast forecast : taf.forecasts ) {
RelativeLayout grp_layout = (RelativeLayout) inflate( R.layout.grouped_detail_item );
// Keep track of forecast conditions across all change groups
if ( mLastForecast == null || forecast.changeIndicator == null
|| forecast.changeIndicator.equals( "FM" ) ) {
mLastForecast = forecast;
} else {
if ( forecast.visibilitySM < Float.MAX_VALUE ) {
mLastForecast.visibilitySM = forecast.visibilitySM;
}
if ( forecast.skyConditions.size() > 0 ) {
mLastForecast.skyConditions = forecast.skyConditions;
}
}
sb.setLength( 0 );
if ( forecast.changeIndicator != null ) {
sb.append( forecast.changeIndicator );
sb.append( " " );
}
sb.append( TimeUtils.formatDateRange(
getActivity(), forecast.timeFrom, forecast.timeTo ) );
tv = (TextView) grp_layout.findViewById( R.id.group_name );
tv.setText( sb.toString() );
String flightCategory = WxUtils.computeFlightCategory(
mLastForecast.skyConditions, mLastForecast.visibilitySM );
WxUtils.setFlightCategoryDrawable( tv, flightCategory );
LinearLayout fcst_layout = (LinearLayout) grp_layout.findViewById( R.id.group_details );
if ( forecast.probability < Integer.MAX_VALUE ) {
addRow( fcst_layout, "Probability", String.format( "%d%%", forecast.probability ) );
}
if ( forecast.changeIndicator != null
&& forecast.changeIndicator.equals( "BECMG" ) ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Becoming at", TimeUtils.formatDateTime(
getActivity(), forecast.timeBecoming ) );
}
if ( forecast.windSpeedKnots < Integer.MAX_VALUE ) {
String wind;
if ( forecast.windDirDegrees == 0 && forecast.windSpeedKnots == 0 ) {
wind = "Calm";
} else if ( forecast.windDirDegrees == 0 ) {
wind = String.format( "Variable at %d knots", forecast.windSpeedKnots );
} else {
wind = String.format( "%s (%03d\u00B0 true) at %d knots",
GeoUtils.getCardinalDirection( forecast.windDirDegrees ),
forecast.windDirDegrees, forecast.windSpeedKnots );
}
String gust = "";
if ( forecast.windGustKnots < Integer.MAX_VALUE ) {
gust = String.format( "Gusting to %d knots", forecast.windGustKnots );
}
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Winds", wind, gust );
}
if ( forecast.visibilitySM < Float.MAX_VALUE ) {
String value = forecast.visibilitySM > 6? "6+ SM"
: FormatUtils.formatVisibility( forecast.visibilitySM );
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Visibility", value );
}
if ( forecast.vertVisibilityFeet < Integer.MAX_VALUE ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Visibility",
FormatUtils.formatFeetAgl( forecast.vertVisibilityFeet ) );
}
for ( WxSymbol wx : forecast.wxList ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Weather", wx.toString() );
}
for ( SkyCondition sky : forecast.skyConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Clouds", sky.toString() );
}
if ( forecast.windShearSpeedKnots < Integer.MAX_VALUE ) {
String shear = String.format( "%s (%03d\u00B0 true) at %d knots",
GeoUtils.getCardinalDirection( forecast.windShearDirDegrees ),
forecast.windShearDirDegrees, forecast.windShearSpeedKnots );
String height = FormatUtils.formatFeetAgl( forecast.windShearHeightFeetAGL );
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Wind shear", shear, height );
}
if ( forecast.altimeterHg < Float.MAX_VALUE ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
addRow( fcst_layout, "Altimeter",
FormatUtils.formatAltimeter( forecast.altimeterHg ) );
}
for ( TurbulenceCondition turbulence : forecast.turbulenceConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
String value = WxUtils.decodeTurbulenceIntensity( turbulence.intensity );
String height = FormatUtils.formatFeetRangeAgl(
turbulence.minAltitudeFeetAGL, turbulence.maxAltitudeFeetAGL );
addRow( fcst_layout, "Turbulence", value, height );
}
for ( IcingCondition icing : forecast.icingConditions ) {
if ( fcst_layout.getChildCount() > 0 ) {
addSeparator( fcst_layout );
}
String value = WxUtils.decodeIcingIntensity( icing.intensity );
String height = FormatUtils.formatFeetRangeAgl(
icing.minAltitudeFeetAGL, icing.maxAltitudeFeetAGL );
addRow( fcst_layout, "Icing", value, height );
}
topLayout.addView( grp_layout, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT );
}
tv = (TextView) findViewById( R.id.wx_fetch_time );
tv.setText( "Fetched on "+TimeUtils.formatDateTime( getActivity(), taf.fetchTime ) );
tv.setVisibility( View.VISIBLE );
stopRefreshAnimation();
setContentShown( true );
}
|
diff --git a/src/edu/wpi/first/wpilibj/templates/debugging/InfoState.java b/src/edu/wpi/first/wpilibj/templates/debugging/InfoState.java
index a58d2e6..a358886 100644
--- a/src/edu/wpi/first/wpilibj/templates/debugging/InfoState.java
+++ b/src/edu/wpi/first/wpilibj/templates/debugging/InfoState.java
@@ -1,42 +1,43 @@
package edu.wpi.first.wpilibj.templates.debugging;
/**
* This is a DebugInfo that stores states of things. This will push only to the
* SmartDashboard, not to console. This should be used for classes that have two
* or three different "states", each that is identified with a String. For
* instance, use this with something that has a "Extending" and "Retracting"
* state.
*
* @author daboross
*/
public class InfoState extends DebugInfo {
private String key;
private String message;
private int level;
public InfoState(String owner, String state, int level) {
this.key = owner + ":State";
this.message = state;
+ this.level = level;
}
protected String key() {
return key;
}
protected String message() {
return message;
}
protected boolean isConsole() {
return true;
}
protected boolean isDashboard() {
return true;
}
protected int debugLevel() {
return level;
}
}
| true | true | public InfoState(String owner, String state, int level) {
this.key = owner + ":State";
this.message = state;
}
| public InfoState(String owner, String state, int level) {
this.key = owner + ":State";
this.message = state;
this.level = level;
}
|
diff --git a/webapp/src/test/java/com/tort/trade/journals/GoodsBalanceIT.java b/webapp/src/test/java/com/tort/trade/journals/GoodsBalanceIT.java
index d485d95..0edd918 100644
--- a/webapp/src/test/java/com/tort/trade/journals/GoodsBalanceIT.java
+++ b/webapp/src/test/java/com/tort/trade/journals/GoodsBalanceIT.java
@@ -1,16 +1,16 @@
package com.tort.trade.journals;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.*;
@Test(groups = {"functional"})
public class GoodsBalanceIT extends FunctionalTest {
- public void getBalance(){
- _selenium.open("/webapp/journal.html");
- _selenium.click("a[@name='balance']");
+ public void getBalance() throws InterruptedException{
+ _selenium.open("/webapp/journal");
+ _selenium.click("//a[@name='balance']");
- _selenium.waitForPageToLoad("5000");
+ waitForElement("//table[@id='balance']//tr[5]");
assertEquals("Goods balance", _selenium.getTitle());
}
}
| false | true | public void getBalance(){
_selenium.open("/webapp/journal.html");
_selenium.click("a[@name='balance']");
_selenium.waitForPageToLoad("5000");
assertEquals("Goods balance", _selenium.getTitle());
}
| public void getBalance() throws InterruptedException{
_selenium.open("/webapp/journal");
_selenium.click("//a[@name='balance']");
waitForElement("//table[@id='balance']//tr[5]");
assertEquals("Goods balance", _selenium.getTitle());
}
|
diff --git a/openelis/test/org/bahmni/feed/openelis/event/OpenelisAtomfeedClientServiceEventWorkerTest.java b/openelis/test/org/bahmni/feed/openelis/event/OpenelisAtomfeedClientServiceEventWorkerTest.java
index a8d221e8..8bd090c6 100644
--- a/openelis/test/org/bahmni/feed/openelis/event/OpenelisAtomfeedClientServiceEventWorkerTest.java
+++ b/openelis/test/org/bahmni/feed/openelis/event/OpenelisAtomfeedClientServiceEventWorkerTest.java
@@ -1,89 +1,89 @@
package org.bahmni.feed.openelis.event;
import org.bahmni.feed.openelis.utils.AtomfeedClientUtils;
import org.hibernate.Transaction;
import org.ict4h.atomfeed.client.domain.Event;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import us.mn.state.health.lims.hibernate.HibernateUtil;
import us.mn.state.health.lims.login.dao.LoginDAO;
import us.mn.state.health.lims.login.valueholder.Login;
import us.mn.state.health.lims.panel.dao.PanelDAO;
import us.mn.state.health.lims.panel.daoimpl.PanelDAOImpl;
import us.mn.state.health.lims.panel.valueholder.Panel;
import us.mn.state.health.lims.siteinformation.dao.SiteInformationDAO;
import us.mn.state.health.lims.siteinformation.valueholder.SiteInformation;
import java.util.ArrayList;
import java.util.List;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
public class OpenelisAtomfeedClientServiceEventWorkerTest {
static final String EVENT_CONTENT = " {\"category\": \"panel\", \"list_price\": \"0.0\", \"name\": \"ECHO\", \"type\": \"service\", \"standard_price\": \"0.0\", \"uom_id\": 1, \"uom_po_id\": 1, \"categ_id\": 33, \"id\": 193}";
@Mock
LoginDAO loginDAO;
@Mock
SiteInformationDAO siteInformationDAO;
OpenelisAtomfeedClientServiceEventWorker eventWorker;
@Before
public void setUp(){
initMocks(this);
eventWorker = new OpenelisAtomfeedClientServiceEventWorker("hosts/feed/recent");
}
@Test
public void testProcess() throws Exception {
- AtomfeedClientUtils.setLoginDao(loginDAO);
+ /*AtomfeedClientUtils.setLoginDao(loginDAO);
AtomfeedClientUtils.setSiteInformationDao(siteInformationDAO);
when(loginDAO.getUserProfile(any(String.class))).thenReturn(createLoginInfo());
when(siteInformationDAO.getSiteInformationByName(any(String.class))).thenReturn(createSiteInfo());
eventWorker.process(createEvent());
PanelDAO panelDao = new PanelDAOImpl();
Panel panel = panelDao.getPanelByName("ECHO");
Assert.assertNotNull(panel);
panel.setSysUserId("1");
Assert.assertEquals("Panel Name :","ECHO",panel.getPanelName());
List<Panel> panels = new ArrayList<Panel>();
panels.add(panel);
Transaction transaction = HibernateUtil.getSession().beginTransaction();
panelDao.deleteData(panels);
transaction.commit();
panel = panelDao.getPanelByName("ECHO");
- Assert.assertNull(panel);
+ Assert.assertNull(panel);*/
}
private Event createEvent(){
Event event = new Event("4234332",EVENT_CONTENT);
return event;
}
private SiteInformation createSiteInfo(){
SiteInformation siteInfo = new SiteInformation();
siteInfo.setValue("admin");
return siteInfo;
}
private Login createLoginInfo(){
Login loginInfo = new Login() ;
loginInfo.setSysUserId("1");
return loginInfo;
}
}
| false | true | public void testProcess() throws Exception {
AtomfeedClientUtils.setLoginDao(loginDAO);
AtomfeedClientUtils.setSiteInformationDao(siteInformationDAO);
when(loginDAO.getUserProfile(any(String.class))).thenReturn(createLoginInfo());
when(siteInformationDAO.getSiteInformationByName(any(String.class))).thenReturn(createSiteInfo());
eventWorker.process(createEvent());
PanelDAO panelDao = new PanelDAOImpl();
Panel panel = panelDao.getPanelByName("ECHO");
Assert.assertNotNull(panel);
panel.setSysUserId("1");
Assert.assertEquals("Panel Name :","ECHO",panel.getPanelName());
List<Panel> panels = new ArrayList<Panel>();
panels.add(panel);
Transaction transaction = HibernateUtil.getSession().beginTransaction();
panelDao.deleteData(panels);
transaction.commit();
panel = panelDao.getPanelByName("ECHO");
Assert.assertNull(panel);
}
| public void testProcess() throws Exception {
/*AtomfeedClientUtils.setLoginDao(loginDAO);
AtomfeedClientUtils.setSiteInformationDao(siteInformationDAO);
when(loginDAO.getUserProfile(any(String.class))).thenReturn(createLoginInfo());
when(siteInformationDAO.getSiteInformationByName(any(String.class))).thenReturn(createSiteInfo());
eventWorker.process(createEvent());
PanelDAO panelDao = new PanelDAOImpl();
Panel panel = panelDao.getPanelByName("ECHO");
Assert.assertNotNull(panel);
panel.setSysUserId("1");
Assert.assertEquals("Panel Name :","ECHO",panel.getPanelName());
List<Panel> panels = new ArrayList<Panel>();
panels.add(panel);
Transaction transaction = HibernateUtil.getSession().beginTransaction();
panelDao.deleteData(panels);
transaction.commit();
panel = panelDao.getPanelByName("ECHO");
Assert.assertNull(panel);*/
}
|
diff --git a/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerAccessor.java b/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerAccessor.java
index 88aa05073..07ac232ea 100644
--- a/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerAccessor.java
+++ b/org.springframework.context.support/src/main/java/org/springframework/scheduling/quartz/SchedulerAccessor.java
@@ -1,417 +1,417 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.scheduling.quartz;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Calendar;
import org.quartz.JobDetail;
import org.quartz.JobListener;
import org.quartz.ObjectAlreadyExistsException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerListener;
import org.quartz.Trigger;
import org.quartz.TriggerListener;
import org.quartz.spi.ClassLoadHelper;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
/**
* Common base class for accessing a Quartz Scheduler, i.e. for registering jobs,
* triggers and listeners on a {@link org.quartz.Scheduler} instance.
*
* <p>For concrete usage, check out the {@link SchedulerFactoryBean} and
* {@link SchedulerAccessorBean} classes.
*
* @author Juergen Hoeller
* @since 2.5.6
*/
public abstract class SchedulerAccessor implements ResourceLoaderAware {
protected final Log logger = LogFactory.getLog(getClass());
private boolean overwriteExistingJobs = false;
private String[] jobSchedulingDataLocations;
private List<JobDetail> jobDetails;
private Map<String, Calendar> calendars;
private List<Trigger> triggers;
private SchedulerListener[] schedulerListeners;
private JobListener[] globalJobListeners;
private JobListener[] jobListeners;
private TriggerListener[] globalTriggerListeners;
private TriggerListener[] triggerListeners;
private PlatformTransactionManager transactionManager;
protected ResourceLoader resourceLoader;
/**
* Set whether any jobs defined on this SchedulerFactoryBean should overwrite
* existing job definitions. Default is "false", to not overwrite already
* registered jobs that have been read in from a persistent job store.
*/
public void setOverwriteExistingJobs(boolean overwriteExistingJobs) {
this.overwriteExistingJobs = overwriteExistingJobs;
}
/**
* Set the location of a Quartz job definition XML file that follows the
* "job_scheduling_data_1_5" XSD. Can be specified to automatically
* register jobs that are defined in such a file, possibly in addition
* to jobs defined directly on this SchedulerFactoryBean.
* @see org.quartz.xml.JobSchedulingDataProcessor
*/
public void setJobSchedulingDataLocation(String jobSchedulingDataLocation) {
this.jobSchedulingDataLocations = new String[] {jobSchedulingDataLocation};
}
/**
* Set the locations of Quartz job definition XML files that follow the
* "job_scheduling_data_1_5" XSD. Can be specified to automatically
* register jobs that are defined in such files, possibly in addition
* to jobs defined directly on this SchedulerFactoryBean.
* @see org.quartz.xml.JobSchedulingDataProcessor
*/
public void setJobSchedulingDataLocations(String[] jobSchedulingDataLocations) {
this.jobSchedulingDataLocations = jobSchedulingDataLocations;
}
/**
* Register a list of JobDetail objects with the Scheduler that
* this FactoryBean creates, to be referenced by Triggers.
* <p>This is not necessary when a Trigger determines the JobDetail
* itself: In this case, the JobDetail will be implicitly registered
* in combination with the Trigger.
* @see #setTriggers
* @see org.quartz.JobDetail
* @see JobDetailBean
* @see JobDetailAwareTrigger
* @see org.quartz.Trigger#setJobName
*/
public void setJobDetails(JobDetail[] jobDetails) {
// Use modifiable ArrayList here, to allow for further adding of
// JobDetail objects during autodetection of JobDetailAwareTriggers.
this.jobDetails = new ArrayList<JobDetail>(Arrays.asList(jobDetails));
}
/**
* Register a list of Quartz Calendar objects with the Scheduler
* that this FactoryBean creates, to be referenced by Triggers.
* @param calendars Map with calendar names as keys as Calendar
* objects as values
* @see org.quartz.Calendar
* @see org.quartz.Trigger#setCalendarName
*/
public void setCalendars(Map<String, Calendar> calendars) {
this.calendars = calendars;
}
/**
* Register a list of Trigger objects with the Scheduler that
* this FactoryBean creates.
* <p>If the Trigger determines the corresponding JobDetail itself,
* the job will be automatically registered with the Scheduler.
* Else, the respective JobDetail needs to be registered via the
* "jobDetails" property of this FactoryBean.
* @see #setJobDetails
* @see org.quartz.JobDetail
* @see JobDetailAwareTrigger
* @see CronTriggerBean
* @see SimpleTriggerBean
*/
public void setTriggers(Trigger[] triggers) {
this.triggers = Arrays.asList(triggers);
}
/**
* Specify Quartz SchedulerListeners to be registered with the Scheduler.
*/
public void setSchedulerListeners(SchedulerListener[] schedulerListeners) {
this.schedulerListeners = schedulerListeners;
}
/**
* Specify global Quartz JobListeners to be registered with the Scheduler.
* Such JobListeners will apply to all Jobs in the Scheduler.
*/
public void setGlobalJobListeners(JobListener[] globalJobListeners) {
this.globalJobListeners = globalJobListeners;
}
/**
* Specify named Quartz JobListeners to be registered with the Scheduler.
* Such JobListeners will only apply to Jobs that explicitly activate
* them via their name.
* @see org.quartz.JobListener#getName
* @see org.quartz.JobDetail#addJobListener
* @see JobDetailBean#setJobListenerNames
*/
public void setJobListeners(JobListener[] jobListeners) {
this.jobListeners = jobListeners;
}
/**
* Specify global Quartz TriggerListeners to be registered with the Scheduler.
* Such TriggerListeners will apply to all Triggers in the Scheduler.
*/
public void setGlobalTriggerListeners(TriggerListener[] globalTriggerListeners) {
this.globalTriggerListeners = globalTriggerListeners;
}
/**
* Specify named Quartz TriggerListeners to be registered with the Scheduler.
* Such TriggerListeners will only apply to Triggers that explicitly activate
* them via their name.
* @see org.quartz.TriggerListener#getName
* @see org.quartz.Trigger#addTriggerListener
* @see CronTriggerBean#setTriggerListenerNames
* @see SimpleTriggerBean#setTriggerListenerNames
*/
public void setTriggerListeners(TriggerListener[] triggerListeners) {
this.triggerListeners = triggerListeners;
}
/**
* Set the transaction manager to be used for registering jobs and triggers
* that are defined by this SchedulerFactoryBean. Default is none; setting
* this only makes sense when specifying a DataSource for the Scheduler.
*/
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
/**
* Register jobs and triggers (within a transaction, if possible).
*/
protected void registerJobsAndTriggers() throws SchedulerException {
TransactionStatus transactionStatus = null;
if (this.transactionManager != null) {
transactionStatus = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
}
try {
if (this.jobSchedulingDataLocations != null) {
ClassLoadHelper clh = new ResourceLoaderClassLoadHelper(this.resourceLoader);
clh.initialize();
try {
// Quartz 1.8 or higher?
- Class dataProcessorClass = getClass().getClassLoader().loadClass("import org.quartz.xml.XMLSchedulingDataProcessor");
+ Class dataProcessorClass = getClass().getClassLoader().loadClass("org.quartz.xml.XMLSchedulingDataProcessor");
logger.debug("Using Quartz 1.8 XMLSchedulingDataProcessor");
Object dataProcessor = dataProcessorClass.getConstructor(ClassLoadHelper.class).newInstance(clh);
Method processFileAndScheduleJobs = dataProcessorClass.getMethod("processFileAndScheduleJobs", String.class, Scheduler.class);
for (String location : this.jobSchedulingDataLocations) {
processFileAndScheduleJobs.invoke(dataProcessor, location, getScheduler());
}
}
catch (ClassNotFoundException ex) {
// Quartz 1.6
- Class dataProcessorClass = getClass().getClassLoader().loadClass("import org.quartz.xml.JobSchedulingDataProcessor");
+ Class dataProcessorClass = getClass().getClassLoader().loadClass("org.quartz.xml.JobSchedulingDataProcessor");
logger.debug("Using Quartz 1.6 JobSchedulingDataProcessor");
Object dataProcessor = dataProcessorClass.getConstructor(ClassLoadHelper.class, boolean.class, boolean.class).newInstance(clh, true, true);
Method processFileAndScheduleJobs = dataProcessorClass.getMethod("processFileAndScheduleJobs", String.class, Scheduler.class, boolean.class);
for (String location : this.jobSchedulingDataLocations) {
processFileAndScheduleJobs.invoke(dataProcessor, location, getScheduler(), this.overwriteExistingJobs);
}
}
}
// Register JobDetails.
if (this.jobDetails != null) {
for (JobDetail jobDetail : this.jobDetails) {
addJobToScheduler(jobDetail);
}
}
else {
// Create empty list for easier checks when registering triggers.
this.jobDetails = new LinkedList<JobDetail>();
}
// Register Calendars.
if (this.calendars != null) {
for (String calendarName : this.calendars.keySet()) {
Calendar calendar = this.calendars.get(calendarName);
getScheduler().addCalendar(calendarName, calendar, true, true);
}
}
// Register Triggers.
if (this.triggers != null) {
for (Trigger trigger : this.triggers) {
addTriggerToScheduler(trigger);
}
}
}
catch (Throwable ex) {
if (transactionStatus != null) {
try {
this.transactionManager.rollback(transactionStatus);
}
catch (TransactionException tex) {
logger.error("Job registration exception overridden by rollback exception", ex);
throw tex;
}
}
if (ex instanceof SchedulerException) {
throw (SchedulerException) ex;
}
if (ex instanceof Exception) {
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage(), ex);
}
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage());
}
if (transactionStatus != null) {
this.transactionManager.commit(transactionStatus);
}
}
/**
* Add the given job to the Scheduler, if it doesn't already exist.
* Overwrites the job in any case if "overwriteExistingJobs" is set.
* @param jobDetail the job to add
* @return <code>true</code> if the job was actually added,
* <code>false</code> if it already existed before
* @see #setOverwriteExistingJobs
*/
private boolean addJobToScheduler(JobDetail jobDetail) throws SchedulerException {
if (this.overwriteExistingJobs ||
getScheduler().getJobDetail(jobDetail.getName(), jobDetail.getGroup()) == null) {
getScheduler().addJob(jobDetail, true);
return true;
}
else {
return false;
}
}
/**
* Add the given trigger to the Scheduler, if it doesn't already exist.
* Overwrites the trigger in any case if "overwriteExistingJobs" is set.
* @param trigger the trigger to add
* @return <code>true</code> if the trigger was actually added,
* <code>false</code> if it already existed before
* @see #setOverwriteExistingJobs
*/
private boolean addTriggerToScheduler(Trigger trigger) throws SchedulerException {
boolean triggerExists = (getScheduler().getTrigger(trigger.getName(), trigger.getGroup()) != null);
if (!triggerExists || this.overwriteExistingJobs) {
// Check if the Trigger is aware of an associated JobDetail.
if (trigger instanceof JobDetailAwareTrigger) {
JobDetail jobDetail = ((JobDetailAwareTrigger) trigger).getJobDetail();
// Automatically register the JobDetail too.
if (!this.jobDetails.contains(jobDetail) && addJobToScheduler(jobDetail)) {
this.jobDetails.add(jobDetail);
}
}
if (!triggerExists) {
try {
getScheduler().scheduleJob(trigger);
}
catch (ObjectAlreadyExistsException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Unexpectedly found existing trigger, assumably due to cluster race condition: " +
ex.getMessage() + " - can safely be ignored");
}
if (this.overwriteExistingJobs) {
getScheduler().rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);
}
}
}
else {
getScheduler().rescheduleJob(trigger.getName(), trigger.getGroup(), trigger);
}
return true;
}
else {
return false;
}
}
/**
* Register all specified listeners with the Scheduler.
*/
protected void registerListeners() throws SchedulerException {
if (this.schedulerListeners != null) {
for (SchedulerListener listener : this.schedulerListeners) {
getScheduler().addSchedulerListener(listener);
}
}
if (this.globalJobListeners != null) {
for (JobListener listener : this.globalJobListeners) {
getScheduler().addGlobalJobListener(listener);
}
}
if (this.jobListeners != null) {
for (JobListener listener : this.jobListeners) {
getScheduler().addJobListener(listener);
}
}
if (this.globalTriggerListeners != null) {
for (TriggerListener listener : this.globalTriggerListeners) {
getScheduler().addGlobalTriggerListener(listener);
}
}
if (this.triggerListeners != null) {
for (TriggerListener listener : this.triggerListeners) {
getScheduler().addTriggerListener(listener);
}
}
}
/**
* Template method that determines the Scheduler to operate on.
* To be implemented by subclasses.
*/
protected abstract Scheduler getScheduler();
}
| false | true | protected void registerJobsAndTriggers() throws SchedulerException {
TransactionStatus transactionStatus = null;
if (this.transactionManager != null) {
transactionStatus = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
}
try {
if (this.jobSchedulingDataLocations != null) {
ClassLoadHelper clh = new ResourceLoaderClassLoadHelper(this.resourceLoader);
clh.initialize();
try {
// Quartz 1.8 or higher?
Class dataProcessorClass = getClass().getClassLoader().loadClass("import org.quartz.xml.XMLSchedulingDataProcessor");
logger.debug("Using Quartz 1.8 XMLSchedulingDataProcessor");
Object dataProcessor = dataProcessorClass.getConstructor(ClassLoadHelper.class).newInstance(clh);
Method processFileAndScheduleJobs = dataProcessorClass.getMethod("processFileAndScheduleJobs", String.class, Scheduler.class);
for (String location : this.jobSchedulingDataLocations) {
processFileAndScheduleJobs.invoke(dataProcessor, location, getScheduler());
}
}
catch (ClassNotFoundException ex) {
// Quartz 1.6
Class dataProcessorClass = getClass().getClassLoader().loadClass("import org.quartz.xml.JobSchedulingDataProcessor");
logger.debug("Using Quartz 1.6 JobSchedulingDataProcessor");
Object dataProcessor = dataProcessorClass.getConstructor(ClassLoadHelper.class, boolean.class, boolean.class).newInstance(clh, true, true);
Method processFileAndScheduleJobs = dataProcessorClass.getMethod("processFileAndScheduleJobs", String.class, Scheduler.class, boolean.class);
for (String location : this.jobSchedulingDataLocations) {
processFileAndScheduleJobs.invoke(dataProcessor, location, getScheduler(), this.overwriteExistingJobs);
}
}
}
// Register JobDetails.
if (this.jobDetails != null) {
for (JobDetail jobDetail : this.jobDetails) {
addJobToScheduler(jobDetail);
}
}
else {
// Create empty list for easier checks when registering triggers.
this.jobDetails = new LinkedList<JobDetail>();
}
// Register Calendars.
if (this.calendars != null) {
for (String calendarName : this.calendars.keySet()) {
Calendar calendar = this.calendars.get(calendarName);
getScheduler().addCalendar(calendarName, calendar, true, true);
}
}
// Register Triggers.
if (this.triggers != null) {
for (Trigger trigger : this.triggers) {
addTriggerToScheduler(trigger);
}
}
}
catch (Throwable ex) {
if (transactionStatus != null) {
try {
this.transactionManager.rollback(transactionStatus);
}
catch (TransactionException tex) {
logger.error("Job registration exception overridden by rollback exception", ex);
throw tex;
}
}
if (ex instanceof SchedulerException) {
throw (SchedulerException) ex;
}
if (ex instanceof Exception) {
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage(), ex);
}
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage());
}
if (transactionStatus != null) {
this.transactionManager.commit(transactionStatus);
}
}
| protected void registerJobsAndTriggers() throws SchedulerException {
TransactionStatus transactionStatus = null;
if (this.transactionManager != null) {
transactionStatus = this.transactionManager.getTransaction(new DefaultTransactionDefinition());
}
try {
if (this.jobSchedulingDataLocations != null) {
ClassLoadHelper clh = new ResourceLoaderClassLoadHelper(this.resourceLoader);
clh.initialize();
try {
// Quartz 1.8 or higher?
Class dataProcessorClass = getClass().getClassLoader().loadClass("org.quartz.xml.XMLSchedulingDataProcessor");
logger.debug("Using Quartz 1.8 XMLSchedulingDataProcessor");
Object dataProcessor = dataProcessorClass.getConstructor(ClassLoadHelper.class).newInstance(clh);
Method processFileAndScheduleJobs = dataProcessorClass.getMethod("processFileAndScheduleJobs", String.class, Scheduler.class);
for (String location : this.jobSchedulingDataLocations) {
processFileAndScheduleJobs.invoke(dataProcessor, location, getScheduler());
}
}
catch (ClassNotFoundException ex) {
// Quartz 1.6
Class dataProcessorClass = getClass().getClassLoader().loadClass("org.quartz.xml.JobSchedulingDataProcessor");
logger.debug("Using Quartz 1.6 JobSchedulingDataProcessor");
Object dataProcessor = dataProcessorClass.getConstructor(ClassLoadHelper.class, boolean.class, boolean.class).newInstance(clh, true, true);
Method processFileAndScheduleJobs = dataProcessorClass.getMethod("processFileAndScheduleJobs", String.class, Scheduler.class, boolean.class);
for (String location : this.jobSchedulingDataLocations) {
processFileAndScheduleJobs.invoke(dataProcessor, location, getScheduler(), this.overwriteExistingJobs);
}
}
}
// Register JobDetails.
if (this.jobDetails != null) {
for (JobDetail jobDetail : this.jobDetails) {
addJobToScheduler(jobDetail);
}
}
else {
// Create empty list for easier checks when registering triggers.
this.jobDetails = new LinkedList<JobDetail>();
}
// Register Calendars.
if (this.calendars != null) {
for (String calendarName : this.calendars.keySet()) {
Calendar calendar = this.calendars.get(calendarName);
getScheduler().addCalendar(calendarName, calendar, true, true);
}
}
// Register Triggers.
if (this.triggers != null) {
for (Trigger trigger : this.triggers) {
addTriggerToScheduler(trigger);
}
}
}
catch (Throwable ex) {
if (transactionStatus != null) {
try {
this.transactionManager.rollback(transactionStatus);
}
catch (TransactionException tex) {
logger.error("Job registration exception overridden by rollback exception", ex);
throw tex;
}
}
if (ex instanceof SchedulerException) {
throw (SchedulerException) ex;
}
if (ex instanceof Exception) {
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage(), ex);
}
throw new SchedulerException("Registration of jobs and triggers failed: " + ex.getMessage());
}
if (transactionStatus != null) {
this.transactionManager.commit(transactionStatus);
}
}
|
diff --git a/src/main/java/net/praqma/hudson/notifier/CCUCMNotifier.java b/src/main/java/net/praqma/hudson/notifier/CCUCMNotifier.java
index 1164c69..7ae18c4 100644
--- a/src/main/java/net/praqma/hudson/notifier/CCUCMNotifier.java
+++ b/src/main/java/net/praqma/hudson/notifier/CCUCMNotifier.java
@@ -1,373 +1,373 @@
package net.praqma.hudson.notifier;
import java.io.IOException;
import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import hudson.AbortException;
import org.kohsuke.stapler.StaplerRequest;
import net.praqma.clearcase.exceptions.UnableToPromoteBaselineException;
import net.praqma.clearcase.ucm.entities.Baseline;
import net.praqma.clearcase.ucm.entities.Stream;
import net.praqma.clearcase.util.ExceptionUtils;
import net.praqma.hudson.CCUCMBuildAction;
import net.praqma.hudson.Config;
import net.praqma.hudson.exception.CCUCMException;
import net.praqma.hudson.exception.NotifierException;
import net.praqma.hudson.nametemplates.NameTemplate;
import net.praqma.hudson.remoting.RemoteUtil;
import net.praqma.hudson.scm.CCUCMScm;
import net.sf.json.JSONObject;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.remoting.VirtualChannel;
import hudson.scm.SCM;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Notifier;
import hudson.tasks.Publisher;
public class CCUCMNotifier extends Notifier {
private PrintStream out;
private Status status;
private String id = "";
private static Logger logger = Logger.getLogger( CCUCMNotifier.class.getName() );
private String jobName = "";
private Integer jobNumber = 0;
public static String logShortPrefix = String.format("[%s]", Config.nameShort);
public CCUCMNotifier() {
}
/**
* This constructor is used in the inner class <code>DescriptorImpl</code>.
*/
public CCUCMNotifier( boolean recommended, boolean makeTag, boolean setDescription ) {
}
/**
* This indicates whether to let CCUCM run after(true) the job is done or
* before(false)
*/
@Override
public boolean needsToRunAfterFinalized() {
return false;
}
@Override
public BuildStepMonitor getRequiredMonitorService() {
return BuildStepMonitor.NONE;
}
@Override
public boolean perform( AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener ) throws InterruptedException, IOException {
boolean result = true;
out = listener.getLogger();
status = new Status();
/* Prepare job variables */
jobName = build.getParent().getDisplayName().replace( ' ', '_' );
jobNumber = build.getNumber();
this.id = "[" + jobName + "::" + jobNumber + "]";
SCM scmTemp = build.getProject().getScm();
if( !( scmTemp instanceof CCUCMScm ) ) {
/* SCM is not ClearCase ucm, just move it along... Not fail it, duh! */
return true;
}
Baseline baseline = null;
CCUCMBuildAction action = build.getAction( CCUCMBuildAction.class );
if( action != null ) {
logger.fine( action.stringify() );
baseline = action.getBaseline();
} else {
logger.warning( "WHOA, what happened!?" );
throw new AbortException( "No ClearCase Action object found" );
}
/* There's a valid baseline, lets process it */
if( baseline != null ) {
out.println( "Processing baseline" );
status.setErrorMessage( action.getError() );
try {
processBuild( build, launcher, listener, action );
if( action.doSetDescription() ) {
String d = build.getDescription();
logger.fine( String.format( "build.getDesciption() is: %s",d ) );
if( d != null ) {
build.setDescription( ( d.length() > 0 ? d + "<br/>" : "" ) + status.getBuildDescr() );
} else {
logger.fine( String.format( "Setting build description to: %s",status.getBuildDescr() ) );
build.setDescription( status.getBuildDescr() );
}
}
} catch( NotifierException ne ) {
out.println( ne.getMessage() );
} catch( IOException e ) {
out.println( String.format( "%s Couldn't set build description",logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Couldn't set build description." );
}
} else {
//out.println( "[" + Config.nameShort + "] Nothing to do!" );
out.println( String.format( "%s Nothing to do!", logShortPrefix ) );
String d = build.getDescription();
if( d != null ) {
build.setDescription( ( d.length() > 0 ? d + "<br/>" : "" ) + "Nothing to do" );
} else {
build.setDescription( "Nothing to do" );
}
build.setResult( Result.NOT_BUILT );
}
if( action != null && action.getViewTag() != null ) {
/* End the view */
try {
logger.fine( "Ending view " + action.getViewTag() );
RemoteUtil.endView( build.getWorkspace(), action.getViewTag() );
} catch( CCUCMException e ) {
out.println( e.getMessage() );
logger.warning( e.getMessage() );
}
}
out.println( "[" + Config.nameShort + "] Post build steps done" );
return result;
}
/**
* This is where all the meat is. When the baseline is validated, the actual
* post build steps are performed. <br>
* First the baseline is delivered(if chosen), then tagged, promoted and
* recommended.
*
* @param build
* The build object in which the post build action is selected
* @param launcher
* The launcher of the build
* @param listener
* The listener of the build
* @throws NotifierException
*/
private void processBuild( AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, CCUCMBuildAction pstate ) throws NotifierException {
Result buildResult = build.getResult();
VirtualChannel ch = launcher.getChannel();
if( ch == null ) {
logger.fine( "The channel was null" );
}
FilePath workspace = build.getExecutor().getCurrentWorkspace();
if( workspace == null ) {
logger.warning( "Workspace is null" );
throw new NotifierException( "Workspace is null" );
}
out.println(String.format("%s Build result: %s",logShortPrefix,buildResult));
//out.println( "[" + Config.nameShort + "] Build result: " + buildResult );
CCUCMBuildAction action = build.getAction( CCUCMBuildAction.class );
/* Initialize variables for post build steps */
Stream targetstream = null;
targetstream = pstate.getBaseline().getStream();
Stream sourcestream = targetstream;
Baseline sourcebaseline = pstate.getBaseline();
Baseline targetbaseline = sourcebaseline;
logger.fine(String.format("NTBC: %s",pstate.doNeedsToBeCompleted()));
//logger.fine( "NTBC: " + pstate.doNeedsToBeCompleted() );
/*
* Determine whether to treat the build as successful
*
* Success: - deliver complete - create baseline - recommend
*
* Fail: - deliver cancel
*/
boolean treatSuccessful = buildResult.isBetterThan( pstate.getUnstable().treatSuccessful() ? Result.FAILURE : Result.UNSTABLE );
/*
* Finalize CCUCM, deliver + baseline Only do this for child and sibling
* polling
*/
if( pstate.doNeedsToBeCompleted() && pstate.getPolling().isPollingOther() ) {
status.setBuildStatus( buildResult );
try {
out.print( logShortPrefix + " " + ( treatSuccessful ? "Completing" : "Cancelling" ) + " the deliver. " );
RemoteUtil.completeRemoteDeliver( workspace, listener, pstate.getBaseline(), pstate.getStream(), action.getViewTag(), action.getViewPath(), treatSuccessful );
out.println( "Success." );
/* If deliver was completed, create the baseline */
if( treatSuccessful && pstate.doCreateBaseline() ) {
try {
out.println( String.format( "%s Creating baseline on Integration stream.", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Creating baseline on Integration stream. " );
pstate.setWorkspace( workspace );
NameTemplate.validateTemplates( pstate );
String name = NameTemplate.parseTemplate( pstate.getNameTemplate(), pstate );
targetbaseline = RemoteUtil.createRemoteBaseline( workspace, listener, name, pstate.getBaseline().getComponent(), action.getViewPath(), pstate.getBaseline().getUser() );
if( action != null ) {
action.setCreatedBaseline( targetbaseline );
}
} catch( Exception e ) {
ExceptionUtils.print( e, out, false );
logger.warning( "Failed to create baseline on stream" );
logger.log( Level.WARNING, "", e );
/* We cannot recommend a baseline that is not created */
if( pstate.doRecommend() ) {
out.println( String.format( "%s Cannot recommend Baseline when not created", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Cannot recommend Baseline when not created" );
}
/* Set unstable? */
logger.warning( "Failing build because baseline could not be created" );
build.setResult( Result.FAILURE );
pstate.setRecommend( false );
}
}
} catch( Exception e ) {
status.setBuildStatus( buildResult );
status.setStable( false );
out.println( "Failed." );
logger.log( Level.WARNING, "", e );
/* We cannot recommend a baseline that is not created */
if( pstate.doRecommend() ) {
out.println( String.format( "%s Cannot recommend a baseline when deliver failed", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Cannot recommend a baseline when deliver failed" );
}
pstate.setRecommend( false );
/* If trying to complete and it failed, try to cancel it */
if( treatSuccessful ) {
try {
out.println( String.format("%s Trying to cancel the deliver.", logShortPrefix) );
//out.print( "[" + Config.nameShort + "] Trying to cancel the deliver. " );
RemoteUtil.completeRemoteDeliver( workspace, listener, pstate.getBaseline(), pstate.getStream(), action.getViewTag(), action.getViewPath(), false );
out.println( "Success." );
} catch( Exception e1 ) {
out.println( " Failed." );
logger.warning( "Failed to cancel deliver" );
logger.log( Level.WARNING, "Exception caught - RemoteUtil.completeRemoteDeliver() - TreatSuccesful == true", e1 );
}
} else {
logger.warning( "Failed to cancel deliver" );
logger.log( Level.WARNING, "TreatSuccesful == false", e );
}
}
}
if( pstate.getPolling().isPollingOther() ) {
targetstream = pstate.getStream();
}
/* Remote post build step, common to all types */
try {
logger.fine( String.format( "%sRemote post build step", id ) );
out.println( String.format( "%s Performing common post build steps",logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Performing common post build steps" );
status = workspace.act( new RemotePostBuild( buildResult, status, listener, pstate.doMakeTag(), pstate.doRecommend(), pstate.getUnstable(), ( pstate.getPromotionLevel() == null ? true : false ), sourcebaseline, targetbaseline, sourcestream, targetstream, build.getParent().getDisplayName(), Integer.toString( build.getNumber() ) ) );
} catch( Exception e ) {
status.setStable( false );
logger.log( Level.WARNING, "", e );
out.println( String.format( "%s Error: Post build failed", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Error: Post build failed" );
Throwable cause = net.praqma.util.ExceptionUtils.unpackFrom( IOException.class, e );
ExceptionUtils.print( cause, out, true );
}
/* If the promotion level of the baseline was changed on the remote */
if( status.getPromotedLevel() != null ) {
logger.fine("Baseline promotion level was changed on the remote: promotedLevel != null");
try {
- logger.fine( String.format( "%sBaselines promotion planned to be set to %", id, status.getPromotedLevel().toString() ) );
+ logger.fine( String.format( "%sBaselines promotion planned to be set to %s", id, status.getPromotedLevel().toString() ) );
pstate.getBaseline().setPromotionLevel( status.getPromotedLevel() );
- logger.fine( String.format( "%sBaselines promotion level updates to %", id, status.getPromotedLevel().toString() ) );
+ logger.fine( String.format( "%sBaselines promotion level updates to %s", id, status.getPromotedLevel().toString() ) );
} catch( UnableToPromoteBaselineException e ) {
logger.warning( "===UnableToPromoteBaseline===" );
logger.warning( String.format( "Unable to set promotion level of baseline %s to %s",e.getEntity() != null ? e.getEntity().getFullyQualifiedName() : "null", e.getPromotionLevel() ) );
- e.print( out );
- logger.warning( "===UnableToPromoteBaseline===" );
+ e.print( out );
+ logger.warning( "===UnableToPromoteBaseline===" );
}
}
logger.fine("Setting build status on Status object");
status.setBuildStatus( buildResult );
if( !status.isStable() ) {
logger.fine("BuildStatus object marked build unstable");
build.setResult( Result.UNSTABLE );
}
}
/**
* This class is used by Hudson to define the plugin.
*
* @author Troels Selch
* @author Margit Bennetzen
*
*/
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Publisher> {
public DescriptorImpl() {
super( CCUCMNotifier.class );
load();
}
@Override
public String getDisplayName() {
return Config.nameLong;
}
/**
* Hudson uses this method to create a new instance of
* <code>CCUCMNotifier</code>. The method gets information from Hudson
* config page. This information is about the configuration, which
* Hudson saves.
*/
@Override
public Notifier newInstance( StaplerRequest req, JSONObject formData ) throws FormException {
save();
return new CCUCMNotifier();
}
@Override
public boolean isApplicable( Class<? extends AbstractProject> arg0 ) {
return true;
}
}
}
| false | true | private void processBuild( AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, CCUCMBuildAction pstate ) throws NotifierException {
Result buildResult = build.getResult();
VirtualChannel ch = launcher.getChannel();
if( ch == null ) {
logger.fine( "The channel was null" );
}
FilePath workspace = build.getExecutor().getCurrentWorkspace();
if( workspace == null ) {
logger.warning( "Workspace is null" );
throw new NotifierException( "Workspace is null" );
}
out.println(String.format("%s Build result: %s",logShortPrefix,buildResult));
//out.println( "[" + Config.nameShort + "] Build result: " + buildResult );
CCUCMBuildAction action = build.getAction( CCUCMBuildAction.class );
/* Initialize variables for post build steps */
Stream targetstream = null;
targetstream = pstate.getBaseline().getStream();
Stream sourcestream = targetstream;
Baseline sourcebaseline = pstate.getBaseline();
Baseline targetbaseline = sourcebaseline;
logger.fine(String.format("NTBC: %s",pstate.doNeedsToBeCompleted()));
//logger.fine( "NTBC: " + pstate.doNeedsToBeCompleted() );
/*
* Determine whether to treat the build as successful
*
* Success: - deliver complete - create baseline - recommend
*
* Fail: - deliver cancel
*/
boolean treatSuccessful = buildResult.isBetterThan( pstate.getUnstable().treatSuccessful() ? Result.FAILURE : Result.UNSTABLE );
/*
* Finalize CCUCM, deliver + baseline Only do this for child and sibling
* polling
*/
if( pstate.doNeedsToBeCompleted() && pstate.getPolling().isPollingOther() ) {
status.setBuildStatus( buildResult );
try {
out.print( logShortPrefix + " " + ( treatSuccessful ? "Completing" : "Cancelling" ) + " the deliver. " );
RemoteUtil.completeRemoteDeliver( workspace, listener, pstate.getBaseline(), pstate.getStream(), action.getViewTag(), action.getViewPath(), treatSuccessful );
out.println( "Success." );
/* If deliver was completed, create the baseline */
if( treatSuccessful && pstate.doCreateBaseline() ) {
try {
out.println( String.format( "%s Creating baseline on Integration stream.", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Creating baseline on Integration stream. " );
pstate.setWorkspace( workspace );
NameTemplate.validateTemplates( pstate );
String name = NameTemplate.parseTemplate( pstate.getNameTemplate(), pstate );
targetbaseline = RemoteUtil.createRemoteBaseline( workspace, listener, name, pstate.getBaseline().getComponent(), action.getViewPath(), pstate.getBaseline().getUser() );
if( action != null ) {
action.setCreatedBaseline( targetbaseline );
}
} catch( Exception e ) {
ExceptionUtils.print( e, out, false );
logger.warning( "Failed to create baseline on stream" );
logger.log( Level.WARNING, "", e );
/* We cannot recommend a baseline that is not created */
if( pstate.doRecommend() ) {
out.println( String.format( "%s Cannot recommend Baseline when not created", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Cannot recommend Baseline when not created" );
}
/* Set unstable? */
logger.warning( "Failing build because baseline could not be created" );
build.setResult( Result.FAILURE );
pstate.setRecommend( false );
}
}
} catch( Exception e ) {
status.setBuildStatus( buildResult );
status.setStable( false );
out.println( "Failed." );
logger.log( Level.WARNING, "", e );
/* We cannot recommend a baseline that is not created */
if( pstate.doRecommend() ) {
out.println( String.format( "%s Cannot recommend a baseline when deliver failed", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Cannot recommend a baseline when deliver failed" );
}
pstate.setRecommend( false );
/* If trying to complete and it failed, try to cancel it */
if( treatSuccessful ) {
try {
out.println( String.format("%s Trying to cancel the deliver.", logShortPrefix) );
//out.print( "[" + Config.nameShort + "] Trying to cancel the deliver. " );
RemoteUtil.completeRemoteDeliver( workspace, listener, pstate.getBaseline(), pstate.getStream(), action.getViewTag(), action.getViewPath(), false );
out.println( "Success." );
} catch( Exception e1 ) {
out.println( " Failed." );
logger.warning( "Failed to cancel deliver" );
logger.log( Level.WARNING, "Exception caught - RemoteUtil.completeRemoteDeliver() - TreatSuccesful == true", e1 );
}
} else {
logger.warning( "Failed to cancel deliver" );
logger.log( Level.WARNING, "TreatSuccesful == false", e );
}
}
}
if( pstate.getPolling().isPollingOther() ) {
targetstream = pstate.getStream();
}
/* Remote post build step, common to all types */
try {
logger.fine( String.format( "%sRemote post build step", id ) );
out.println( String.format( "%s Performing common post build steps",logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Performing common post build steps" );
status = workspace.act( new RemotePostBuild( buildResult, status, listener, pstate.doMakeTag(), pstate.doRecommend(), pstate.getUnstable(), ( pstate.getPromotionLevel() == null ? true : false ), sourcebaseline, targetbaseline, sourcestream, targetstream, build.getParent().getDisplayName(), Integer.toString( build.getNumber() ) ) );
} catch( Exception e ) {
status.setStable( false );
logger.log( Level.WARNING, "", e );
out.println( String.format( "%s Error: Post build failed", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Error: Post build failed" );
Throwable cause = net.praqma.util.ExceptionUtils.unpackFrom( IOException.class, e );
ExceptionUtils.print( cause, out, true );
}
/* If the promotion level of the baseline was changed on the remote */
if( status.getPromotedLevel() != null ) {
logger.fine("Baseline promotion level was changed on the remote: promotedLevel != null");
try {
logger.fine( String.format( "%sBaselines promotion planned to be set to %", id, status.getPromotedLevel().toString() ) );
pstate.getBaseline().setPromotionLevel( status.getPromotedLevel() );
logger.fine( String.format( "%sBaselines promotion level updates to %", id, status.getPromotedLevel().toString() ) );
} catch( UnableToPromoteBaselineException e ) {
logger.warning( "===UnableToPromoteBaseline===" );
logger.warning( String.format( "Unable to set promotion level of baseline %s to %s",e.getEntity() != null ? e.getEntity().getFullyQualifiedName() : "null", e.getPromotionLevel() ) );
e.print( out );
logger.warning( "===UnableToPromoteBaseline===" );
}
}
logger.fine("Setting build status on Status object");
status.setBuildStatus( buildResult );
if( !status.isStable() ) {
logger.fine("BuildStatus object marked build unstable");
build.setResult( Result.UNSTABLE );
}
}
| private void processBuild( AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, CCUCMBuildAction pstate ) throws NotifierException {
Result buildResult = build.getResult();
VirtualChannel ch = launcher.getChannel();
if( ch == null ) {
logger.fine( "The channel was null" );
}
FilePath workspace = build.getExecutor().getCurrentWorkspace();
if( workspace == null ) {
logger.warning( "Workspace is null" );
throw new NotifierException( "Workspace is null" );
}
out.println(String.format("%s Build result: %s",logShortPrefix,buildResult));
//out.println( "[" + Config.nameShort + "] Build result: " + buildResult );
CCUCMBuildAction action = build.getAction( CCUCMBuildAction.class );
/* Initialize variables for post build steps */
Stream targetstream = null;
targetstream = pstate.getBaseline().getStream();
Stream sourcestream = targetstream;
Baseline sourcebaseline = pstate.getBaseline();
Baseline targetbaseline = sourcebaseline;
logger.fine(String.format("NTBC: %s",pstate.doNeedsToBeCompleted()));
//logger.fine( "NTBC: " + pstate.doNeedsToBeCompleted() );
/*
* Determine whether to treat the build as successful
*
* Success: - deliver complete - create baseline - recommend
*
* Fail: - deliver cancel
*/
boolean treatSuccessful = buildResult.isBetterThan( pstate.getUnstable().treatSuccessful() ? Result.FAILURE : Result.UNSTABLE );
/*
* Finalize CCUCM, deliver + baseline Only do this for child and sibling
* polling
*/
if( pstate.doNeedsToBeCompleted() && pstate.getPolling().isPollingOther() ) {
status.setBuildStatus( buildResult );
try {
out.print( logShortPrefix + " " + ( treatSuccessful ? "Completing" : "Cancelling" ) + " the deliver. " );
RemoteUtil.completeRemoteDeliver( workspace, listener, pstate.getBaseline(), pstate.getStream(), action.getViewTag(), action.getViewPath(), treatSuccessful );
out.println( "Success." );
/* If deliver was completed, create the baseline */
if( treatSuccessful && pstate.doCreateBaseline() ) {
try {
out.println( String.format( "%s Creating baseline on Integration stream.", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Creating baseline on Integration stream. " );
pstate.setWorkspace( workspace );
NameTemplate.validateTemplates( pstate );
String name = NameTemplate.parseTemplate( pstate.getNameTemplate(), pstate );
targetbaseline = RemoteUtil.createRemoteBaseline( workspace, listener, name, pstate.getBaseline().getComponent(), action.getViewPath(), pstate.getBaseline().getUser() );
if( action != null ) {
action.setCreatedBaseline( targetbaseline );
}
} catch( Exception e ) {
ExceptionUtils.print( e, out, false );
logger.warning( "Failed to create baseline on stream" );
logger.log( Level.WARNING, "", e );
/* We cannot recommend a baseline that is not created */
if( pstate.doRecommend() ) {
out.println( String.format( "%s Cannot recommend Baseline when not created", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Cannot recommend Baseline when not created" );
}
/* Set unstable? */
logger.warning( "Failing build because baseline could not be created" );
build.setResult( Result.FAILURE );
pstate.setRecommend( false );
}
}
} catch( Exception e ) {
status.setBuildStatus( buildResult );
status.setStable( false );
out.println( "Failed." );
logger.log( Level.WARNING, "", e );
/* We cannot recommend a baseline that is not created */
if( pstate.doRecommend() ) {
out.println( String.format( "%s Cannot recommend a baseline when deliver failed", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Cannot recommend a baseline when deliver failed" );
}
pstate.setRecommend( false );
/* If trying to complete and it failed, try to cancel it */
if( treatSuccessful ) {
try {
out.println( String.format("%s Trying to cancel the deliver.", logShortPrefix) );
//out.print( "[" + Config.nameShort + "] Trying to cancel the deliver. " );
RemoteUtil.completeRemoteDeliver( workspace, listener, pstate.getBaseline(), pstate.getStream(), action.getViewTag(), action.getViewPath(), false );
out.println( "Success." );
} catch( Exception e1 ) {
out.println( " Failed." );
logger.warning( "Failed to cancel deliver" );
logger.log( Level.WARNING, "Exception caught - RemoteUtil.completeRemoteDeliver() - TreatSuccesful == true", e1 );
}
} else {
logger.warning( "Failed to cancel deliver" );
logger.log( Level.WARNING, "TreatSuccesful == false", e );
}
}
}
if( pstate.getPolling().isPollingOther() ) {
targetstream = pstate.getStream();
}
/* Remote post build step, common to all types */
try {
logger.fine( String.format( "%sRemote post build step", id ) );
out.println( String.format( "%s Performing common post build steps",logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Performing common post build steps" );
status = workspace.act( new RemotePostBuild( buildResult, status, listener, pstate.doMakeTag(), pstate.doRecommend(), pstate.getUnstable(), ( pstate.getPromotionLevel() == null ? true : false ), sourcebaseline, targetbaseline, sourcestream, targetstream, build.getParent().getDisplayName(), Integer.toString( build.getNumber() ) ) );
} catch( Exception e ) {
status.setStable( false );
logger.log( Level.WARNING, "", e );
out.println( String.format( "%s Error: Post build failed", logShortPrefix ) );
//out.println( "[" + Config.nameShort + "] Error: Post build failed" );
Throwable cause = net.praqma.util.ExceptionUtils.unpackFrom( IOException.class, e );
ExceptionUtils.print( cause, out, true );
}
/* If the promotion level of the baseline was changed on the remote */
if( status.getPromotedLevel() != null ) {
logger.fine("Baseline promotion level was changed on the remote: promotedLevel != null");
try {
logger.fine( String.format( "%sBaselines promotion planned to be set to %s", id, status.getPromotedLevel().toString() ) );
pstate.getBaseline().setPromotionLevel( status.getPromotedLevel() );
logger.fine( String.format( "%sBaselines promotion level updates to %s", id, status.getPromotedLevel().toString() ) );
} catch( UnableToPromoteBaselineException e ) {
logger.warning( "===UnableToPromoteBaseline===" );
logger.warning( String.format( "Unable to set promotion level of baseline %s to %s",e.getEntity() != null ? e.getEntity().getFullyQualifiedName() : "null", e.getPromotionLevel() ) );
e.print( out );
logger.warning( "===UnableToPromoteBaseline===" );
}
}
logger.fine("Setting build status on Status object");
status.setBuildStatus( buildResult );
if( !status.isStable() ) {
logger.fine("BuildStatus object marked build unstable");
build.setResult( Result.UNSTABLE );
}
}
|
diff --git a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsWebNature.java b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsWebNature.java
index 8e4b3f842..6b7c8bf3d 100644
--- a/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsWebNature.java
+++ b/bundles/org.eclipse.wst.jsdt.web.core/src/org/eclipse/wst/jsdt/web/core/internal/project/JsWebNature.java
@@ -1,260 +1,259 @@
package org.eclipse.wst.jsdt.web.core.internal.project;
import java.util.Arrays;
import java.util.Vector;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.wst.jsdt.core.IClasspathEntry;
import org.eclipse.wst.jsdt.core.JavaCore;
import org.eclipse.wst.jsdt.core.LibrarySuperType;
import org.eclipse.wst.jsdt.internal.core.JavaProject;
import org.eclipse.wst.jsdt.ui.PreferenceConstants;
import org.eclipse.wst.jsdt.web.core.internal.java.WebRootFinder;
public class JsWebNature implements IProjectNature {
//private static final String FILENAME_CLASSPATH = ".classpath"; //$NON-NLS-1$
// private static final String NATURE_IDS[] =
// {"org.eclipse.wst.jsdt.web.core.embeded.jsNature",JavaCore.NATURE_ID};
// //$NON-NLS-1$
private static final String NATURE_IDS[] = { JavaCore.NATURE_ID };
public static final IPath VIRTUAL_BROWSER_CLASSPATH = new Path("org.eclipse.wst.jsdt.launching.baseBrowserLibrary");
public static final String VIRTUAL_CONTAINER = "org.eclipse.wst.jsdt.launching.WebProject";
public static final IClasspathEntry VIRTUAL_SCOPE_ENTRY = JavaCore.newContainerEntry(new Path(VIRTUAL_CONTAINER));
private static final String SUPER_TYPE_NAME = "Window";
private static final String SUPER_TYPE_LIBRARY = "org.eclipse.wst.jsdt.launching.baseBrowserLibrary";
public static void addJsNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (monitor != null && monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (!JsWebNature.hasNature(project)) {
IProjectDescription description = project.getDescription();
String[] prevNatures = description.getNatureIds();
String[] newNatures = new String[prevNatures.length + JsWebNature.NATURE_IDS.length];
System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length);
// newNatures[prevNatures.length] = JavaCore.NATURE_ID;
for (int i = 0; i < JsWebNature.NATURE_IDS.length; i++) {
newNatures[prevNatures.length + i] = JsWebNature.NATURE_IDS[i];
}
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
} else {
if (monitor != null) {
monitor.worked(1);
}
}
}
public static boolean hasNature(IProject project) {
try {
for (int i = 0; i < JsWebNature.NATURE_IDS.length; i++) {
if (!project.hasNature(JsWebNature.NATURE_IDS[i])) {
return false;
}
}
} catch (CoreException ex) {
return false;
}
return true;
}
public static void removeJsNature(IProject project, IProgressMonitor monitor) throws CoreException {
if (monitor != null && monitor.isCanceled()) {
throw new OperationCanceledException();
}
if (JsWebNature.hasNature(project)) {
IProjectDescription description = project.getDescription();
String[] prevNatures = description.getNatureIds();
String[] newNatures = new String[prevNatures.length - JsWebNature.NATURE_IDS.length];
int k = 0;
head: for (int i = 0; i < prevNatures.length; i++) {
for (int j = 0; j < JsWebNature.NATURE_IDS.length; j++) {
if (prevNatures[i] == JsWebNature.NATURE_IDS[j]) {
continue head;
}
}
newNatures[k++] = prevNatures[i];
}
description.setNatureIds(newNatures);
project.setDescription(description, monitor);
} else {
if (monitor != null) {
monitor.worked(1);
}
}
}
private Vector classPathEntries = new Vector();
private boolean DEBUG = false;
private IProject fCurrProject;
private JavaProject fJavaProject;
private IPath fOutputLocation;
private IProgressMonitor monitor;
public JsWebNature() {
monitor = new NullProgressMonitor();
}
public JsWebNature(IProject project, IProgressMonitor monitor) {
fCurrProject = project;
if (monitor != null) {
this.monitor = monitor;
} else {
monitor = new NullProgressMonitor();
}
}
public void configure() throws CoreException {
initOutputPath();
createSourceClassPath();
initJREEntry();
initLocalClassPath();
if (hasProjectClassPathFile()) {
IClasspathEntry[] entries = getRawClassPath();
if (entries != null && entries.length > 0) {
classPathEntries.removeAll(Arrays.asList(entries));
classPathEntries.addAll(Arrays.asList(entries));
}
}
JsWebNature.addJsNature(fCurrProject, monitor);
fJavaProject = (JavaProject) JavaCore.create(fCurrProject);
fJavaProject.setProject(fCurrProject);
try {
// , fOutputLocation
if (!hasProjectClassPathFile()) {
fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), fOutputLocation, monitor);
- }
- if (hasProjectClassPathFile()) {
+ }else{
fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), monitor);
}
} catch (Exception e) {
System.out.println(e);
}
LibrarySuperType superType = new LibrarySuperType(new Path( SUPER_TYPE_LIBRARY), getJavaProject(), SUPER_TYPE_NAME);
getJavaProject().setCommonSuperType(superType);
// getJavaProject().addToBuildSpec(BUILDER_ID);
fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
private void createSourceClassPath() {
if (hasAValidSourcePath()) {
return;
}
// IPath projectPath = fCurrProject.getFullPath();
// classPathEntries.add(JavaCore.newSourceEntry(projectPath));
}
public void deconfigure() throws CoreException {
Vector badEntries = new Vector();
IClasspathEntry[] defaultJRELibrary = PreferenceConstants.getDefaultJRELibrary();
IClasspathEntry[] localEntries = initLocalClassPath();
badEntries.addAll(Arrays.asList(defaultJRELibrary));
badEntries.addAll(Arrays.asList(localEntries));
IClasspathEntry[] entries = getRawClassPath();
Vector goodEntries = new Vector();
for (int i = 0; i < entries.length; i++) {
if (!badEntries.contains(entries[i])) {
goodEntries.add(entries[i]);
}
}
// getJavaProject().removeFromBuildSpec(BUILDER_ID);
IPath outputLocation = getJavaProject().getOutputLocation();
getJavaProject().setRawClasspath((IClasspathEntry[]) goodEntries.toArray(new IClasspathEntry[] {}), outputLocation, monitor);
getJavaProject().deconfigure();
JsWebNature.removeJsNature(fCurrProject, monitor);
fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
public JavaProject getJavaProject() {
if (fJavaProject == null) {
fJavaProject = (JavaProject) JavaCore.create(fCurrProject);
fJavaProject.setProject(fCurrProject);
}
return fJavaProject;
}
public IProject getProject() {
return this.fCurrProject;
}
private IClasspathEntry[] getRawClassPath() {
JavaProject proj = new JavaProject();
proj.setProject(fCurrProject);
return proj.readRawClasspath();
}
private boolean hasAValidSourcePath() {
if (hasProjectClassPathFile()) {
try {
IClasspathEntry[] entries = getRawClassPath();
for (int i = 0; i < entries.length; i++) {
if (entries[i].getEntryKind() == IClasspathEntry.CPE_SOURCE) {
return true;
}
}
} catch (Exception e) {
if (DEBUG) {
System.out.println("Error checking sourcepath:" + e);
}
}
}
return false;
}
private boolean hasProjectClassPathFile() {
if (fCurrProject == null) {
return false;
}
return fCurrProject.getFile(JavaProject.CLASSPATH_FILENAME).exists();
}
private void initJREEntry() {
IClasspathEntry[] defaultJRELibrary = PreferenceConstants.getDefaultJRELibrary();
try {
IClasspathEntry[] entries = getRawClassPath();
for (int i = 0; i < entries.length; i++) {
if (entries[i] == defaultJRELibrary[0]) {
return;
}
}
classPathEntries.add(defaultJRELibrary[0]);
} catch (Exception e) {
if (DEBUG) {
System.out.println("Error checking sourcepath:" + e);
}
}
}
private IClasspathEntry[] initLocalClassPath() {
classPathEntries.add(JsWebNature.VIRTUAL_SCOPE_ENTRY);
IClasspathEntry browserLibrary = JavaCore.newContainerEntry( VIRTUAL_BROWSER_CLASSPATH);
classPathEntries.add(browserLibrary);
//IPath webRoot = WebRootFinder.getWebContentFolder(fCurrProject);
// IClasspathEntry source = JavaCore.newSourceEntry(fCurrProject.getFullPath().append(webRoot).append("/"));
// classPathEntries.add(source);
return new IClasspathEntry[] { JsWebNature.VIRTUAL_SCOPE_ENTRY , browserLibrary/*,source*/};
}
private void initOutputPath() {
if (fOutputLocation == null) {
fOutputLocation = fCurrProject.getFullPath();
}
}
public void setProject(IProject project) {
this.fCurrProject = project;
}
}
| true | true | public void configure() throws CoreException {
initOutputPath();
createSourceClassPath();
initJREEntry();
initLocalClassPath();
if (hasProjectClassPathFile()) {
IClasspathEntry[] entries = getRawClassPath();
if (entries != null && entries.length > 0) {
classPathEntries.removeAll(Arrays.asList(entries));
classPathEntries.addAll(Arrays.asList(entries));
}
}
JsWebNature.addJsNature(fCurrProject, monitor);
fJavaProject = (JavaProject) JavaCore.create(fCurrProject);
fJavaProject.setProject(fCurrProject);
try {
// , fOutputLocation
if (!hasProjectClassPathFile()) {
fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), fOutputLocation, monitor);
}
if (hasProjectClassPathFile()) {
fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), monitor);
}
} catch (Exception e) {
System.out.println(e);
}
LibrarySuperType superType = new LibrarySuperType(new Path( SUPER_TYPE_LIBRARY), getJavaProject(), SUPER_TYPE_NAME);
getJavaProject().setCommonSuperType(superType);
// getJavaProject().addToBuildSpec(BUILDER_ID);
fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
| public void configure() throws CoreException {
initOutputPath();
createSourceClassPath();
initJREEntry();
initLocalClassPath();
if (hasProjectClassPathFile()) {
IClasspathEntry[] entries = getRawClassPath();
if (entries != null && entries.length > 0) {
classPathEntries.removeAll(Arrays.asList(entries));
classPathEntries.addAll(Arrays.asList(entries));
}
}
JsWebNature.addJsNature(fCurrProject, monitor);
fJavaProject = (JavaProject) JavaCore.create(fCurrProject);
fJavaProject.setProject(fCurrProject);
try {
// , fOutputLocation
if (!hasProjectClassPathFile()) {
fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), fOutputLocation, monitor);
}else{
fJavaProject.setRawClasspath((IClasspathEntry[]) classPathEntries.toArray(new IClasspathEntry[] {}), monitor);
}
} catch (Exception e) {
System.out.println(e);
}
LibrarySuperType superType = new LibrarySuperType(new Path( SUPER_TYPE_LIBRARY), getJavaProject(), SUPER_TYPE_NAME);
getJavaProject().setCommonSuperType(superType);
// getJavaProject().addToBuildSpec(BUILDER_ID);
fCurrProject.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
|
diff --git a/src/main/java/agaricus/plugins/IncompatiblePlugin/SamplePlugin.java b/src/main/java/agaricus/plugins/IncompatiblePlugin/SamplePlugin.java
index 34cd91a..c7bad1a 100644
--- a/src/main/java/agaricus/plugins/IncompatiblePlugin/SamplePlugin.java
+++ b/src/main/java/agaricus/plugins/IncompatiblePlugin/SamplePlugin.java
@@ -1,240 +1,240 @@
package agaricus.plugins.IncompatiblePlugin;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import com.google.common.io.CharStreams;
import net.minecraft.server.v1_5_R2.*;
import net.minecraft.v1_5_R2.org.bouncycastle.asn1.bc.BCObjectIdentifiers;
import org.bukkit.*;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.craftbukkit.libs.com.google.gson.Gson;
import org.bukkit.craftbukkit.libs.com.google.gson.GsonBuilder;
import org.bukkit.craftbukkit.v1_5_R2.CraftChunk;
import org.bukkit.craftbukkit.v1_5_R2.CraftWorld;
import org.bukkit.craftbukkit.v1_5_R2.inventory.RecipeIterator;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.FurnaceRecipe;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.ShapelessRecipe;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import sun.misc.IOUtils;
import java.io.*;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* Sample plugin for Bukkit
*
* @author Dinnerbone
*/
public class SamplePlugin extends JavaPlugin {
private final SamplePlayerListener playerListener = new SamplePlayerListener(this);
private final SampleBlockListener blockListener = new SampleBlockListener();
private final HashMap<Player, Boolean> debugees = new HashMap<Player, Boolean>();
@Override
public void onDisable() {
// TODO: Place any custom disable code here
// NOTE: All registered events are automatically unregistered when a plugin is disabled
// EXAMPLE: Custom code, here we just output some info so we can check all is well
getLogger().info("Goodbye world!");
}
@Override
public void onEnable() {
// TODO: Place any custom enable code here including the registration of any events
System.out.println("IncompatiblePlugin");
// show enums for https://github.com/MinecraftPortCentral/MCPC-Plus/issues/417
StringBuffer sb = new StringBuffer();
for (Biome biome : Biome.values()) {
sb.append(biome.ordinal()+"="+biome.toString()+"("+biome.name()+") ");
}
System.out.println("Biome ("+Biome.values().length+"): " + sb.toString());
sb = new StringBuffer();
for (EntityType entityType : EntityType.values()) {
sb.append(entityType.ordinal()+"="+entityType.toString()+"("+entityType.name()+") ");
}
System.out.println("EntityType ("+EntityType.values().length+"): " + sb.toString());
// demonstrate https://github.com/MinecraftPortCentral/MCPC-Plus/issues/75
try {
System.out.println("codeSource URI="+getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
System.out.println(" file = ="+new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()));
System.out.println("new canonical file = ="+(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())).getCanonicalFile());
} catch (Throwable t) {
System.out.println("codeSource URI exception="+t);
t.printStackTrace();
}
// from sqlite NestedDB.java:63 _open https://github.com/MinecraftPortCentral/MCPC-Plus/issues/218
// make sure we don't break SQLite by ASM choking on its excessive classfile size
System.out.println("forName SQLite");
try {
Object sqlite = Class.forName("org.sqlite.SQLite").newInstance();
System.out.println("org.sqlite.SQLite newInstance="+sqlite);
} catch (Throwable t) {
System.out.println("t="+t);
t.printStackTrace();
}
// recipe sorting error - java.lang.IllegalArgumentException: Comparison method violates its general contract!
// https://github.com/MinecraftPortCentral/MCPC-Plus/issues/238
ShapelessRecipe shapelessRecipe = new ShapelessRecipe(new org.bukkit.inventory.ItemStack(Material.DIAMOND));
shapelessRecipe.addIngredient(Material.DIRT);
org.bukkit.Bukkit.addRecipe(shapelessRecipe);
// reflection remapping https://github.com/MinecraftPortCentral/MCPC-Plus/issues/13
try {
- Field field = TileEntityMobSpawner.class.getDeclaredField("mobName");
+ Field field = TileEntityChest.class.getDeclaredField("items"); // MCP csv chestContents, srg field_70428_i, obf i
System.out.println("field="+field);
} catch (Exception ex) {
ex.printStackTrace();
}
// null EntityType test - Bukkit wrappers for mobs https://github.com/MinecraftPortCentral/MCPC-Plus/issues/16
// see https://github.com/xGhOsTkiLLeRx/SilkSpawners/blob/master/src/main/java/de/dustplanet/silkspawners/SilkSpawners.java#L157
try {
// https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/EntityTypes.java#L21
// f.put(s, Integer.valueOf(i)); --> Name of ID
Field field = EntityTypes.class.getDeclaredField("f");
field.setAccessible(true);
Map<String, Integer> map = (Map<String, Integer>) field.get(null);
for (Map.Entry<String,Integer> entry: map.entrySet()) {
String mobID = entry.getKey();
int entityID = entry.getValue();
EntityType bukkitEntityType = EntityType.fromId(entityID);
if (bukkitEntityType == null) {
System.out.println("Missing Bukkit EntityType for entityID="+entityID+", mobID="+mobID);
} else {
Class bukkitEntityClass = bukkitEntityType.getEntityClass();
if (bukkitEntityClass == null) {
System.out.println("Missing Bukkit getEntityClass() for entityID="+entityID+", mobID="+mobID+", bukkitEntityType="+bukkitEntityType);
}
}
}
} catch (Exception e) {
Bukkit.getServer().getLogger().severe("Failed to dump entity map: " + e);
e.printStackTrace();
}
// method naming conflict test https://github.com/MinecraftPortCentral/MCPC-Plus/issues/169
net.minecraft.server.v1_5_R2.PlayerConnection playerConnection = null;
try {
System.out.println("getPlayer = "+playerConnection.getPlayer());
} catch (NoSuchMethodError ex) {
System.out.println("failed to call playerConnection.getPlayer()");
ex.printStackTrace();
} catch (NullPointerException ex) {
System.out.println("playerConnection.getPlayer successful");
}
// null Material test https://github.com/MinecraftPortCentral/MCPC-Plus/issues/172
for (int i = 0; i < Item.byId.length; i++) {
Item nmsItem = Item.byId[i];
net.minecraft.server.v1_5_R2.Block nmsBlock = i < 4096 ? net.minecraft.server.v1_5_R2.Block.byId[i] : null;
org.bukkit.Material bukkitMaterial = org.bukkit.Material.getMaterial(i);
if (nmsItem == null && nmsBlock == null && bukkitMaterial == null) continue; // must not exist
if (bukkitMaterial == null)
System.out.println("Item "+i+" = item="+nmsItem+", block="+nmsBlock+", bukkit Material="+bukkitMaterial);
}
// null recipe output test for https://github.com/MinecraftPortCentral/MCPC-Plus/issues/139
System.out.println("recipe iterator..");
RecipeIterator recipeIterator = new RecipeIterator();
int nulls = 0, nonVanillaRecipes = 0;
while(recipeIterator.hasNext()) {
Recipe recipe = recipeIterator.next();
if (recipe instanceof ShapedRecipe || recipe instanceof ShapelessRecipe || recipe instanceof FurnaceRecipe) continue; // skip vanilla
if (recipe == null) {
nulls += 1;
}
nonVanillaRecipes += 1;
}
System.out.println("null recipes? " + nulls + ", non-vanilla=" + nonVanillaRecipes);
// test un-renamed map
System.out.println("net.minecraft.server.v1_5_R2.MinecraftServer.currentTick = "+MinecraftServer.currentTick);
// test bouncycastle is available
System.out.println("bouncycastle="+net.minecraft.v1_5_R2.org.bouncycastle.asn1.bc.BCObjectIdentifiers.class);
System.out.println("SNOW.id="+net.minecraft.server.v1_5_R2.Block.SNOW.id);
// test tasks
Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 100, 0);
System.out.println("a="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0));
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 99, 0);
System.out.println("a(task)="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0));
}
}, 0);
// test nms inheritance remapping
net.minecraft.server.v1_5_R2.WorldServer worldServer = ((CraftWorld)Bukkit.getServer().getWorlds().get(0)).getHandle();
System.out.println("calling getTileEntity on nms World");
// if this breaks - Caused by: java.lang.NoSuchMethodError: in.getTileEntity(III)Lany;
// because WorldServer inherits from World, but isn't in mc-dev to obf mappings (since is added by CB)
worldServer.getTileEntity(0, 0, 0);
System.out.println("nms inheritance successful");
// test plugin inheritance remapping
getLogger().info("creating class inheriting from NMS...");
IInventory iInventory = new SamplePluginNMSInheritor();
getLogger().info("iInventory= "+iInventory);
// if subclass/implementator not remapped: java.lang.AbstractMethodError: SamplePluginNMSInheritor.k_()I
getLogger().info("getSize="+iInventory.getSize());
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(playerListener, this);
pm.registerEvents(blockListener, this);
// Register our commands
getCommand("pos").setExecutor(new SamplePosCommand());
getCommand("debug").setExecutor(new SampleDebugCommand(this));
// EXAMPLE: Custom code, here we just output some info so we can check all is well
PluginDescriptionFile pdfFile = this.getDescription();
getLogger().info( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}
public boolean isDebugging(final Player player) {
if (debugees.containsKey(player)) {
return debugees.get(player);
} else {
return false;
}
}
public void setDebugging(final Player player, final boolean value) {
debugees.put(player, value);
}
}
| true | true | public void onEnable() {
// TODO: Place any custom enable code here including the registration of any events
System.out.println("IncompatiblePlugin");
// show enums for https://github.com/MinecraftPortCentral/MCPC-Plus/issues/417
StringBuffer sb = new StringBuffer();
for (Biome biome : Biome.values()) {
sb.append(biome.ordinal()+"="+biome.toString()+"("+biome.name()+") ");
}
System.out.println("Biome ("+Biome.values().length+"): " + sb.toString());
sb = new StringBuffer();
for (EntityType entityType : EntityType.values()) {
sb.append(entityType.ordinal()+"="+entityType.toString()+"("+entityType.name()+") ");
}
System.out.println("EntityType ("+EntityType.values().length+"): " + sb.toString());
// demonstrate https://github.com/MinecraftPortCentral/MCPC-Plus/issues/75
try {
System.out.println("codeSource URI="+getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
System.out.println(" file = ="+new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()));
System.out.println("new canonical file = ="+(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())).getCanonicalFile());
} catch (Throwable t) {
System.out.println("codeSource URI exception="+t);
t.printStackTrace();
}
// from sqlite NestedDB.java:63 _open https://github.com/MinecraftPortCentral/MCPC-Plus/issues/218
// make sure we don't break SQLite by ASM choking on its excessive classfile size
System.out.println("forName SQLite");
try {
Object sqlite = Class.forName("org.sqlite.SQLite").newInstance();
System.out.println("org.sqlite.SQLite newInstance="+sqlite);
} catch (Throwable t) {
System.out.println("t="+t);
t.printStackTrace();
}
// recipe sorting error - java.lang.IllegalArgumentException: Comparison method violates its general contract!
// https://github.com/MinecraftPortCentral/MCPC-Plus/issues/238
ShapelessRecipe shapelessRecipe = new ShapelessRecipe(new org.bukkit.inventory.ItemStack(Material.DIAMOND));
shapelessRecipe.addIngredient(Material.DIRT);
org.bukkit.Bukkit.addRecipe(shapelessRecipe);
// reflection remapping https://github.com/MinecraftPortCentral/MCPC-Plus/issues/13
try {
Field field = TileEntityMobSpawner.class.getDeclaredField("mobName");
System.out.println("field="+field);
} catch (Exception ex) {
ex.printStackTrace();
}
// null EntityType test - Bukkit wrappers for mobs https://github.com/MinecraftPortCentral/MCPC-Plus/issues/16
// see https://github.com/xGhOsTkiLLeRx/SilkSpawners/blob/master/src/main/java/de/dustplanet/silkspawners/SilkSpawners.java#L157
try {
// https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/EntityTypes.java#L21
// f.put(s, Integer.valueOf(i)); --> Name of ID
Field field = EntityTypes.class.getDeclaredField("f");
field.setAccessible(true);
Map<String, Integer> map = (Map<String, Integer>) field.get(null);
for (Map.Entry<String,Integer> entry: map.entrySet()) {
String mobID = entry.getKey();
int entityID = entry.getValue();
EntityType bukkitEntityType = EntityType.fromId(entityID);
if (bukkitEntityType == null) {
System.out.println("Missing Bukkit EntityType for entityID="+entityID+", mobID="+mobID);
} else {
Class bukkitEntityClass = bukkitEntityType.getEntityClass();
if (bukkitEntityClass == null) {
System.out.println("Missing Bukkit getEntityClass() for entityID="+entityID+", mobID="+mobID+", bukkitEntityType="+bukkitEntityType);
}
}
}
} catch (Exception e) {
Bukkit.getServer().getLogger().severe("Failed to dump entity map: " + e);
e.printStackTrace();
}
// method naming conflict test https://github.com/MinecraftPortCentral/MCPC-Plus/issues/169
net.minecraft.server.v1_5_R2.PlayerConnection playerConnection = null;
try {
System.out.println("getPlayer = "+playerConnection.getPlayer());
} catch (NoSuchMethodError ex) {
System.out.println("failed to call playerConnection.getPlayer()");
ex.printStackTrace();
} catch (NullPointerException ex) {
System.out.println("playerConnection.getPlayer successful");
}
// null Material test https://github.com/MinecraftPortCentral/MCPC-Plus/issues/172
for (int i = 0; i < Item.byId.length; i++) {
Item nmsItem = Item.byId[i];
net.minecraft.server.v1_5_R2.Block nmsBlock = i < 4096 ? net.minecraft.server.v1_5_R2.Block.byId[i] : null;
org.bukkit.Material bukkitMaterial = org.bukkit.Material.getMaterial(i);
if (nmsItem == null && nmsBlock == null && bukkitMaterial == null) continue; // must not exist
if (bukkitMaterial == null)
System.out.println("Item "+i+" = item="+nmsItem+", block="+nmsBlock+", bukkit Material="+bukkitMaterial);
}
// null recipe output test for https://github.com/MinecraftPortCentral/MCPC-Plus/issues/139
System.out.println("recipe iterator..");
RecipeIterator recipeIterator = new RecipeIterator();
int nulls = 0, nonVanillaRecipes = 0;
while(recipeIterator.hasNext()) {
Recipe recipe = recipeIterator.next();
if (recipe instanceof ShapedRecipe || recipe instanceof ShapelessRecipe || recipe instanceof FurnaceRecipe) continue; // skip vanilla
if (recipe == null) {
nulls += 1;
}
nonVanillaRecipes += 1;
}
System.out.println("null recipes? " + nulls + ", non-vanilla=" + nonVanillaRecipes);
// test un-renamed map
System.out.println("net.minecraft.server.v1_5_R2.MinecraftServer.currentTick = "+MinecraftServer.currentTick);
// test bouncycastle is available
System.out.println("bouncycastle="+net.minecraft.v1_5_R2.org.bouncycastle.asn1.bc.BCObjectIdentifiers.class);
System.out.println("SNOW.id="+net.minecraft.server.v1_5_R2.Block.SNOW.id);
// test tasks
Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 100, 0);
System.out.println("a="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0));
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 99, 0);
System.out.println("a(task)="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0));
}
}, 0);
// test nms inheritance remapping
net.minecraft.server.v1_5_R2.WorldServer worldServer = ((CraftWorld)Bukkit.getServer().getWorlds().get(0)).getHandle();
System.out.println("calling getTileEntity on nms World");
// if this breaks - Caused by: java.lang.NoSuchMethodError: in.getTileEntity(III)Lany;
// because WorldServer inherits from World, but isn't in mc-dev to obf mappings (since is added by CB)
worldServer.getTileEntity(0, 0, 0);
System.out.println("nms inheritance successful");
// test plugin inheritance remapping
getLogger().info("creating class inheriting from NMS...");
IInventory iInventory = new SamplePluginNMSInheritor();
getLogger().info("iInventory= "+iInventory);
// if subclass/implementator not remapped: java.lang.AbstractMethodError: SamplePluginNMSInheritor.k_()I
getLogger().info("getSize="+iInventory.getSize());
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(playerListener, this);
pm.registerEvents(blockListener, this);
// Register our commands
getCommand("pos").setExecutor(new SamplePosCommand());
getCommand("debug").setExecutor(new SampleDebugCommand(this));
// EXAMPLE: Custom code, here we just output some info so we can check all is well
PluginDescriptionFile pdfFile = this.getDescription();
getLogger().info( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}
| public void onEnable() {
// TODO: Place any custom enable code here including the registration of any events
System.out.println("IncompatiblePlugin");
// show enums for https://github.com/MinecraftPortCentral/MCPC-Plus/issues/417
StringBuffer sb = new StringBuffer();
for (Biome biome : Biome.values()) {
sb.append(biome.ordinal()+"="+biome.toString()+"("+biome.name()+") ");
}
System.out.println("Biome ("+Biome.values().length+"): " + sb.toString());
sb = new StringBuffer();
for (EntityType entityType : EntityType.values()) {
sb.append(entityType.ordinal()+"="+entityType.toString()+"("+entityType.name()+") ");
}
System.out.println("EntityType ("+EntityType.values().length+"): " + sb.toString());
// demonstrate https://github.com/MinecraftPortCentral/MCPC-Plus/issues/75
try {
System.out.println("codeSource URI="+getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
System.out.println(" file = ="+new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()));
System.out.println("new canonical file = ="+(new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI())).getCanonicalFile());
} catch (Throwable t) {
System.out.println("codeSource URI exception="+t);
t.printStackTrace();
}
// from sqlite NestedDB.java:63 _open https://github.com/MinecraftPortCentral/MCPC-Plus/issues/218
// make sure we don't break SQLite by ASM choking on its excessive classfile size
System.out.println("forName SQLite");
try {
Object sqlite = Class.forName("org.sqlite.SQLite").newInstance();
System.out.println("org.sqlite.SQLite newInstance="+sqlite);
} catch (Throwable t) {
System.out.println("t="+t);
t.printStackTrace();
}
// recipe sorting error - java.lang.IllegalArgumentException: Comparison method violates its general contract!
// https://github.com/MinecraftPortCentral/MCPC-Plus/issues/238
ShapelessRecipe shapelessRecipe = new ShapelessRecipe(new org.bukkit.inventory.ItemStack(Material.DIAMOND));
shapelessRecipe.addIngredient(Material.DIRT);
org.bukkit.Bukkit.addRecipe(shapelessRecipe);
// reflection remapping https://github.com/MinecraftPortCentral/MCPC-Plus/issues/13
try {
Field field = TileEntityChest.class.getDeclaredField("items"); // MCP csv chestContents, srg field_70428_i, obf i
System.out.println("field="+field);
} catch (Exception ex) {
ex.printStackTrace();
}
// null EntityType test - Bukkit wrappers for mobs https://github.com/MinecraftPortCentral/MCPC-Plus/issues/16
// see https://github.com/xGhOsTkiLLeRx/SilkSpawners/blob/master/src/main/java/de/dustplanet/silkspawners/SilkSpawners.java#L157
try {
// https://github.com/Bukkit/mc-dev/blob/master/net/minecraft/server/EntityTypes.java#L21
// f.put(s, Integer.valueOf(i)); --> Name of ID
Field field = EntityTypes.class.getDeclaredField("f");
field.setAccessible(true);
Map<String, Integer> map = (Map<String, Integer>) field.get(null);
for (Map.Entry<String,Integer> entry: map.entrySet()) {
String mobID = entry.getKey();
int entityID = entry.getValue();
EntityType bukkitEntityType = EntityType.fromId(entityID);
if (bukkitEntityType == null) {
System.out.println("Missing Bukkit EntityType for entityID="+entityID+", mobID="+mobID);
} else {
Class bukkitEntityClass = bukkitEntityType.getEntityClass();
if (bukkitEntityClass == null) {
System.out.println("Missing Bukkit getEntityClass() for entityID="+entityID+", mobID="+mobID+", bukkitEntityType="+bukkitEntityType);
}
}
}
} catch (Exception e) {
Bukkit.getServer().getLogger().severe("Failed to dump entity map: " + e);
e.printStackTrace();
}
// method naming conflict test https://github.com/MinecraftPortCentral/MCPC-Plus/issues/169
net.minecraft.server.v1_5_R2.PlayerConnection playerConnection = null;
try {
System.out.println("getPlayer = "+playerConnection.getPlayer());
} catch (NoSuchMethodError ex) {
System.out.println("failed to call playerConnection.getPlayer()");
ex.printStackTrace();
} catch (NullPointerException ex) {
System.out.println("playerConnection.getPlayer successful");
}
// null Material test https://github.com/MinecraftPortCentral/MCPC-Plus/issues/172
for (int i = 0; i < Item.byId.length; i++) {
Item nmsItem = Item.byId[i];
net.minecraft.server.v1_5_R2.Block nmsBlock = i < 4096 ? net.minecraft.server.v1_5_R2.Block.byId[i] : null;
org.bukkit.Material bukkitMaterial = org.bukkit.Material.getMaterial(i);
if (nmsItem == null && nmsBlock == null && bukkitMaterial == null) continue; // must not exist
if (bukkitMaterial == null)
System.out.println("Item "+i+" = item="+nmsItem+", block="+nmsBlock+", bukkit Material="+bukkitMaterial);
}
// null recipe output test for https://github.com/MinecraftPortCentral/MCPC-Plus/issues/139
System.out.println("recipe iterator..");
RecipeIterator recipeIterator = new RecipeIterator();
int nulls = 0, nonVanillaRecipes = 0;
while(recipeIterator.hasNext()) {
Recipe recipe = recipeIterator.next();
if (recipe instanceof ShapedRecipe || recipe instanceof ShapelessRecipe || recipe instanceof FurnaceRecipe) continue; // skip vanilla
if (recipe == null) {
nulls += 1;
}
nonVanillaRecipes += 1;
}
System.out.println("null recipes? " + nulls + ", non-vanilla=" + nonVanillaRecipes);
// test un-renamed map
System.out.println("net.minecraft.server.v1_5_R2.MinecraftServer.currentTick = "+MinecraftServer.currentTick);
// test bouncycastle is available
System.out.println("bouncycastle="+net.minecraft.v1_5_R2.org.bouncycastle.asn1.bc.BCObjectIdentifiers.class);
System.out.println("SNOW.id="+net.minecraft.server.v1_5_R2.Block.SNOW.id);
// test tasks
Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 100, 0);
System.out.println("a="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0));
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(this, new Runnable() {
public void run() {
Block b = Bukkit.getServer().getWorlds().get(0).getBlockAt(0, 99, 0);
System.out.println("a(task)="+((CraftChunk)b.getChunk()).getHandle().a(b.getX() & 15, b.getY(), b.getZ() & 15, 48, 0));
}
}, 0);
// test nms inheritance remapping
net.minecraft.server.v1_5_R2.WorldServer worldServer = ((CraftWorld)Bukkit.getServer().getWorlds().get(0)).getHandle();
System.out.println("calling getTileEntity on nms World");
// if this breaks - Caused by: java.lang.NoSuchMethodError: in.getTileEntity(III)Lany;
// because WorldServer inherits from World, but isn't in mc-dev to obf mappings (since is added by CB)
worldServer.getTileEntity(0, 0, 0);
System.out.println("nms inheritance successful");
// test plugin inheritance remapping
getLogger().info("creating class inheriting from NMS...");
IInventory iInventory = new SamplePluginNMSInheritor();
getLogger().info("iInventory= "+iInventory);
// if subclass/implementator not remapped: java.lang.AbstractMethodError: SamplePluginNMSInheritor.k_()I
getLogger().info("getSize="+iInventory.getSize());
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvents(playerListener, this);
pm.registerEvents(blockListener, this);
// Register our commands
getCommand("pos").setExecutor(new SamplePosCommand());
getCommand("debug").setExecutor(new SampleDebugCommand(this));
// EXAMPLE: Custom code, here we just output some info so we can check all is well
PluginDescriptionFile pdfFile = this.getDescription();
getLogger().info( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}
|
diff --git a/billing/src/main/java/com/carlos/projects/billing/ui/controllers/ImportComponentsController.java b/billing/src/main/java/com/carlos/projects/billing/ui/controllers/ImportComponentsController.java
index af7d43f..2e0604d 100755
--- a/billing/src/main/java/com/carlos/projects/billing/ui/controllers/ImportComponentsController.java
+++ b/billing/src/main/java/com/carlos/projects/billing/ui/controllers/ImportComponentsController.java
@@ -1,41 +1,41 @@
package com.carlos.projects.billing.ui.controllers;
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.carlos.projects.billing.domain.FileUpload;
/**
* @author Carlos Fernandez
*
* @date 19 Jul 2009
*
* Controller to import the document with the list of components
*
*/
public class ImportComponentsController extends SimpleFormController {
public ImportComponentsController() {
super();
}
/* (non-Javadoc)
* @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(java.lang.Object)
*/
@Override
protected ModelAndView onSubmit(Object command)
throws Exception {
//Cast the bean
FileUpload bean = (FileUpload) command;
MultipartFile file = bean.getFile();
Map<String, Object> model = new HashMap<String, Object>();
model.put("file", file);
- return new ModelAndView("storeComponents", model);
+ return new ModelAndView("showComponents", model);
}
}
| true | true | protected ModelAndView onSubmit(Object command)
throws Exception {
//Cast the bean
FileUpload bean = (FileUpload) command;
MultipartFile file = bean.getFile();
Map<String, Object> model = new HashMap<String, Object>();
model.put("file", file);
return new ModelAndView("storeComponents", model);
}
| protected ModelAndView onSubmit(Object command)
throws Exception {
//Cast the bean
FileUpload bean = (FileUpload) command;
MultipartFile file = bean.getFile();
Map<String, Object> model = new HashMap<String, Object>();
model.put("file", file);
return new ModelAndView("showComponents", model);
}
|
diff --git a/solr/src/common/org/apache/solr/common/SolrDocumentList.java b/solr/src/common/org/apache/solr/common/SolrDocumentList.java
index 9aca8d778..a7f3d4b15 100644
--- a/solr/src/common/org/apache/solr/common/SolrDocumentList.java
+++ b/solr/src/common/org/apache/solr/common/SolrDocumentList.java
@@ -1,68 +1,68 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.common;
import java.util.ArrayList;
/**
* Represent a list of SolrDocuments returned from a search. This includes
* position and offset information.
*
* @version $Id$
* @since solr 1.3
*/
public class SolrDocumentList extends ArrayList<SolrDocument>
{
private long numFound = 0;
private long start = 0;
private Float maxScore = null;
public Float getMaxScore() {
return maxScore;
}
public void setMaxScore(Float maxScore) {
this.maxScore = maxScore;
}
public long getNumFound() {
return numFound;
}
public void setNumFound(long numFound) {
this.numFound = numFound;
}
public long getStart() {
return start;
}
public void setStart(long start) {
this.start = start;
}
@Override
public String toString() {
return "{numFound="+numFound
+",start="+start
- + (maxScore!=null ? ""+maxScore : "")
+ + (maxScore!=null ? ",maxScore="+maxScore : "")
+",docs="+super.toString()
+"}";
}
}
| true | true | public String toString() {
return "{numFound="+numFound
+",start="+start
+ (maxScore!=null ? ""+maxScore : "")
+",docs="+super.toString()
+"}";
}
| public String toString() {
return "{numFound="+numFound
+",start="+start
+ (maxScore!=null ? ",maxScore="+maxScore : "")
+",docs="+super.toString()
+"}";
}
|
diff --git a/opentaps/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/EntityLookupAndSuggestService.java b/opentaps/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/EntityLookupAndSuggestService.java
index 257c5b7c3..b426d5528 100644
--- a/opentaps/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/EntityLookupAndSuggestService.java
+++ b/opentaps/opentaps-common/src/common/org/opentaps/gwt/common/server/lookup/EntityLookupAndSuggestService.java
@@ -1,161 +1,165 @@
/*
* Copyright (c) 2006 - 2009 Open Source Strategies, Inc.
*
* Opentaps is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Opentaps is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Opentaps. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentaps.gwt.common.server.lookup;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.ofbiz.base.util.Debug;
import org.ofbiz.entity.condition.EntityCondition;
import org.ofbiz.entity.condition.EntityFunction;
import org.ofbiz.entity.condition.EntityOperator;
import org.opentaps.foundation.entity.EntityInterface;
import org.opentaps.gwt.common.client.lookup.UtilLookup;
import org.opentaps.gwt.common.server.InputProviderInterface;
/**
* The base service to perform entity lookups and / or suggest.
*/
public abstract class EntityLookupAndSuggestService extends EntityLookupService {
// for autocompleters
private String suggestQuery;
protected EntityLookupAndSuggestService(InputProviderInterface provider, List<String> fields) {
super(provider, fields);
suggestQuery = provider.getParameter(UtilLookup.PARAM_SUGGEST_QUERY);
}
/**
* Gets the query string that should be used as the filter for a suggest.
* @return a <code>String</code> value
*/
public String getSuggestQuery() {
return suggestQuery;
}
/**
* Builds the query for suggesters that will lookup the list of given fields for the given query string.
*
* For example:
* <code>findSuggestMatchesAnyOf(Product.class, UtilMisc.toList("internalName", "productName"))</code>
* finds all <code>Product</code> for which the "internalName" OR the "productName" matches the <code>suggestQuery</code>
* passed as parameter.
* The match is done by looking values containing the <code>suggestQuery</code>, case insensitive.
*
* @param <T> the entity class to return
* @param entity the entity class to return
* @param fields the list of fields to lookup
* @return the list of entities found, or <code>null</code> if an error occurred
* @throws RepositoryException if an error occurs
*/
protected <T extends EntityInterface> List<T> findSuggestMatchesAnyOf(Class<T> entity, List<String> fields) {
return findSuggestMatchesAnyOf(entity, getSuggestQuery(), fields);
}
/**
* Builds the query for suggesters that will lookup the list of given fields for the given query string.
*
* For example:
* <code>findSuggestMatchesAnyOf(Product.class, UtilMisc.toList("internalName", "productName"))</code>
* finds all <code>Product</code> for which the "internalName" OR the "productName" matches the <code>suggestQuery</code>
* passed as parameter.
* The match is done by looking values containing the <code>suggestQuery</code>, case insensitive.
*
* @param <T> the entity class to return
* @param entity the entity class to return
* @param fields the list of fields to lookup
* @param additionalFilter a condition to restrict the possible matches
* @return the list of entities found, or <code>null</code> if an error occurred
* @throws RepositoryException if an error occurs
*/
protected <T extends EntityInterface> List<T> findSuggestMatchesAnyOf(Class<T> entity, List<String> fields, EntityCondition additionalFilter) {
return findSuggestMatchesAnyOf(entity, getSuggestQuery(), fields, additionalFilter);
}
/**
* Builds the query for suggesters that will lookup the list of given fields for the given query string.
*
* For example:
* <code>findSuggestMatchesAnyOf(Product.class, UtilMisc.toList("internalName", "productName"))</code>
* finds all <code>Product</code> for which the "internalName" OR the "productName" matches the given <code>query</code>
* passed as parameter.
* The match is done by looking values containing the <code>query</code>, case insensitive.
*
* @param <T> the entity class to return
* @param entity the entity class to return
* @param query the string to lookup
* @param fields the list of fields to lookup
* @return the list of entities found, or <code>null</code> if an error occurred
*/
protected <T extends EntityInterface> List<T> findSuggestMatchesAnyOf(Class<T> entity, String query, List<String> fields) {
return findSuggestMatchesAnyOf(entity, query, fields, null);
}
/**
* Builds the query for suggesters that will lookup the list of given fields for the given query string.
*
* For example:
* <code>findSuggestMatchesAnyOf(Product.class, UtilMisc.toList("internalName", "productName"))</code>
* finds all <code>Product</code> for which the "internalName" OR the "productName" matches the given <code>query</code>
* passed as parameter.
* The match is done by looking values containing the <code>query</code>, case insensitive.
*
* @param <T> the entity class to return
* @param entity the entity class to return
* @param query the string to lookup
* @param fields the list of fields to lookup
* @param additionalFilter a condition to restrict the possible matches
* @return the list of entities found, or <code>null</code> if an error occurred
*/
protected <T extends EntityInterface> List<T> findSuggestMatchesAnyOf(Class<T> entity, String query, List<String> fields, EntityCondition additionalFilter) {
Debug.logInfo("findSuggestMatchesAnyOf: entity=" + entity.getName() + ", query=" + query + ", fields=" + fields, "");
if (query == null || fields.isEmpty()) {
- return findAll(entity);
+ if (additionalFilter == null) {
+ return findAll(entity);
+ } else {
+ return findList(entity, additionalFilter);
+ }
}
List<EntityCondition> suggestConds = new ArrayList<EntityCondition>();
for (String field : fields) {
suggestConds.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(field), EntityOperator.LIKE, EntityFunction.UPPER("%" + query + "%")));
}
EntityCondition conditions = EntityCondition.makeCondition(suggestConds, EntityOperator.OR);
if (additionalFilter != null) {
conditions = EntityCondition.makeCondition(EntityOperator.AND, conditions, additionalFilter);
}
return findList(entity, conditions);
}
/**
* Makes the display string that should be displayed in the auto-completer from the entity found.
* @param value the entity value
* @return the display string that should be displayed in the auto-completer
*/
public abstract String makeSuggestDisplayedText(EntityInterface value);
/**
* Makes extra values to be returned in the response.
* @param value the entity value
* @return the Map of field -> value that should be set
*/
public Map<String, String> makeExtraSuggestValues(EntityInterface value) {
return null;
}
}
| true | true | protected <T extends EntityInterface> List<T> findSuggestMatchesAnyOf(Class<T> entity, String query, List<String> fields, EntityCondition additionalFilter) {
Debug.logInfo("findSuggestMatchesAnyOf: entity=" + entity.getName() + ", query=" + query + ", fields=" + fields, "");
if (query == null || fields.isEmpty()) {
return findAll(entity);
}
List<EntityCondition> suggestConds = new ArrayList<EntityCondition>();
for (String field : fields) {
suggestConds.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(field), EntityOperator.LIKE, EntityFunction.UPPER("%" + query + "%")));
}
EntityCondition conditions = EntityCondition.makeCondition(suggestConds, EntityOperator.OR);
if (additionalFilter != null) {
conditions = EntityCondition.makeCondition(EntityOperator.AND, conditions, additionalFilter);
}
return findList(entity, conditions);
}
| protected <T extends EntityInterface> List<T> findSuggestMatchesAnyOf(Class<T> entity, String query, List<String> fields, EntityCondition additionalFilter) {
Debug.logInfo("findSuggestMatchesAnyOf: entity=" + entity.getName() + ", query=" + query + ", fields=" + fields, "");
if (query == null || fields.isEmpty()) {
if (additionalFilter == null) {
return findAll(entity);
} else {
return findList(entity, additionalFilter);
}
}
List<EntityCondition> suggestConds = new ArrayList<EntityCondition>();
for (String field : fields) {
suggestConds.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD(field), EntityOperator.LIKE, EntityFunction.UPPER("%" + query + "%")));
}
EntityCondition conditions = EntityCondition.makeCondition(suggestConds, EntityOperator.OR);
if (additionalFilter != null) {
conditions = EntityCondition.makeCondition(EntityOperator.AND, conditions, additionalFilter);
}
return findList(entity, conditions);
}
|
diff --git a/src/org/mythtv/provider/MythtvProvider.java b/src/org/mythtv/provider/MythtvProvider.java
index 49177c05..a7ff04a2 100644
--- a/src/org/mythtv/provider/MythtvProvider.java
+++ b/src/org/mythtv/provider/MythtvProvider.java
@@ -1,441 +1,441 @@
/**
* This file is part of MythTV for Android
*
* MythTV for Android is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* MythTV for Android is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with MythTV for Android. If not, see <http://www.gnu.org/licenses/>.
*
* This software can be found at <https://github.com/MythTV-Android/mythtv-for-android/>
*
*/
package org.mythtv.provider;
import org.mythtv.db.DatabaseHelper;
import org.mythtv.db.channel.ChannelConstants;
import org.mythtv.db.dvr.ProgramConstants;
//import org.mythtv.db.dvr.ProgramGroupConstants;
import org.mythtv.db.dvr.RecordingConstants;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.net.Uri;
import android.text.TextUtils;
/**
* @author Daniel Frey
*
*/
public class MythtvProvider extends AbstractMythtvContentProvider {
public static final String AUTHORITY = "org.mythtv.provider.MythtvProvider";
private static final UriMatcher URI_MATCHER;
private static final String PROGRAM_CONTENT_TYPE = "vnd.mythtv.cursor.dir/program";
private static final String PROGRAM_CONTENT_ITEM_TYPE = "vnd.mythtv.cursor.item/program";
private static final int PROGRAMS = 1;
private static final int PROGRAM_ID = 2;
private static final int PROGRAM_GROUPS = 3;
private static final String RECORDING_CONTENT_TYPE = "vnd.mythtv.cursor.dir/recording";
private static final String RECORDING_CONTENT_ITEM_TYPE = "vnd.mythtv.cursor.item/recording";
private static final int RECORDINGS = 4;
private static final int RECORDING_ID = 5;
private static final String CHANNEL_CONTENT_TYPE = "vnd.mythtv.cursor.dir/channel";
private static final String CHANNEL_CONTENT_ITEM_TYPE = "vnd.mythtv.cursor.item/channel";
private static final int CHANNELS = 6;
private static final int CHANNEL_ID = 7;
static {
URI_MATCHER = new UriMatcher( UriMatcher.NO_MATCH );
URI_MATCHER.addURI( AUTHORITY, ProgramConstants.TABLE_NAME, PROGRAMS );
URI_MATCHER.addURI( AUTHORITY, ProgramConstants.TABLE_NAME + "/#", PROGRAM_ID );
URI_MATCHER.addURI( AUTHORITY, ProgramConstants.TABLE_NAME + "/programGroups", PROGRAM_GROUPS );
URI_MATCHER.addURI( AUTHORITY, RecordingConstants.TABLE_NAME, RECORDINGS );
URI_MATCHER.addURI( AUTHORITY, RecordingConstants.TABLE_NAME + "/#", RECORDING_ID );
URI_MATCHER.addURI( AUTHORITY, ChannelConstants.TABLE_NAME, CHANNELS );
URI_MATCHER.addURI( AUTHORITY, ChannelConstants.TABLE_NAME + "/#", CHANNEL_ID );
}
private DatabaseHelper database = null;
/* (non-Javadoc)
* @see android.content.ContentProvider#onCreate()
*/
@Override
public boolean onCreate() {
database = new DatabaseHelper( getContext() );
return ( null == database ? false : true );
}
/* (non-Javadoc)
* @see android.content.ContentProvider#getType(android.net.Uri)
*/
@Override
public String getType( Uri uri ) {
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
return PROGRAM_CONTENT_TYPE;
case PROGRAM_ID:
return PROGRAM_CONTENT_ITEM_TYPE;
case PROGRAM_GROUPS:
return PROGRAM_CONTENT_TYPE;
case RECORDINGS:
return RECORDING_CONTENT_TYPE;
case RECORDING_ID:
return RECORDING_CONTENT_ITEM_TYPE;
case CHANNELS:
return CHANNEL_CONTENT_TYPE;
case CHANNEL_ID:
return CHANNEL_CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException( "Unknown URI " + uri );
}
}
/* (non-Javadoc)
* @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
*/
@Override
public int delete( Uri uri, String selection, String[] selectionArgs ) {
final SQLiteDatabase db = database.getWritableDatabase();
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
return db.delete( ProgramConstants.TABLE_NAME, selection, selectionArgs );
case PROGRAM_ID:
return db.delete( ProgramConstants.TABLE_NAME, ProgramConstants._ID
+ "="
+ Long.toString( ContentUris.parseId( uri ) )
+ ( !TextUtils.isEmpty( selection ) ? " AND (" + selection + ')' : "" ), selectionArgs );
case RECORDINGS:
return db.delete( RecordingConstants.TABLE_NAME, selection, selectionArgs );
case RECORDING_ID:
return db.delete( RecordingConstants.TABLE_NAME, ProgramConstants._ID
+ "="
+ Long.toString( ContentUris.parseId( uri ) )
+ ( !TextUtils.isEmpty( selection ) ? " AND (" + selection + ')' : "" ), selectionArgs );
case CHANNELS:
return db.delete( ChannelConstants.TABLE_NAME, selection, selectionArgs );
case CHANNEL_ID:
return db.delete( ChannelConstants.TABLE_NAME, ChannelConstants._ID
+ "="
+ Long.toString( ContentUris.parseId( uri ) )
+ ( !TextUtils.isEmpty( selection ) ? " AND (" + selection + ')' : "" ), selectionArgs );
default:
throw new IllegalArgumentException( "Unknown URI " + uri );
}
}
/* (non-Javadoc)
* @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
*/
@Override
public Uri insert( Uri uri, ContentValues values ) {
final SQLiteDatabase db = database.getWritableDatabase();
Uri newUri = null;
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
newUri = ContentUris.withAppendedId( ProgramConstants.CONTENT_URI, db.insertOrThrow( ProgramConstants.TABLE_NAME, null, values ) );
getContext().getContentResolver().notifyChange( newUri, null );
return newUri;
case RECORDINGS:
newUri = ContentUris.withAppendedId( RecordingConstants.CONTENT_URI, db.insertOrThrow( RecordingConstants.TABLE_NAME, null, values ) );
getContext().getContentResolver().notifyChange( newUri, null );
return newUri;
case CHANNELS:
newUri = ContentUris.withAppendedId( ChannelConstants.CONTENT_URI, db.insertOrThrow( ChannelConstants.TABLE_NAME, null, values ) );
getContext().getContentResolver().notifyChange( newUri, null );
return newUri;
default:
throw new IllegalArgumentException( "Unknown URI " + uri );
}
}
/* (non-Javadoc)
* @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
*/
@Override
public Cursor query( Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder ) {
final SQLiteDatabase db = database.getReadableDatabase();
Cursor cursor = null;
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
cursor = db.query( ProgramConstants.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder );
cursor.setNotificationUri( getContext().getContentResolver(), uri );
return cursor;
case PROGRAM_ID:
selection = appendRowId( selection, Long.parseLong( uri.getPathSegments().get( 1 ) ) );
cursor = db.query( ProgramConstants.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder );
cursor.setNotificationUri( getContext().getContentResolver(), uri );
return cursor;
case PROGRAM_GROUPS:
cursor = db.query( ProgramConstants.TABLE_NAME, projection, selection, selectionArgs, ProgramConstants.FIELD_PROGRAM_GROUP, "COUNT(" + ProgramConstants.FIELD_PROGRAM_GROUP + ") > 0", sortOrder );
cursor.setNotificationUri( getContext().getContentResolver(), uri );
return cursor;
case RECORDINGS:
cursor = db.query( RecordingConstants.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder );
cursor.setNotificationUri( getContext().getContentResolver(), uri );
return cursor;
case RECORDING_ID:
selection = appendRowId( selection, Long.parseLong( uri.getPathSegments().get( 1 ) ) );
cursor = db.query( RecordingConstants.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder );
cursor.setNotificationUri( getContext().getContentResolver(), uri );
return cursor;
case CHANNELS:
cursor = db.query( ChannelConstants.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder );
cursor.setNotificationUri( getContext().getContentResolver(), uri );
return cursor;
case CHANNEL_ID:
selection = appendRowId( selection, Long.parseLong( uri.getPathSegments().get( 1 ) ) );
cursor = db.query( ChannelConstants.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder );
cursor.setNotificationUri( getContext().getContentResolver(), uri );
return null;
default:
throw new IllegalArgumentException( "Unknown URI " + uri );
}
}
/* (non-Javadoc)
* @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
*/
@Override
public int update( Uri uri, ContentValues values, String selection, String[] selectionArgs ) {
final SQLiteDatabase db = database.getWritableDatabase();
int affected = 0;
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
affected = db.update( ProgramConstants.TABLE_NAME, values, selection , selectionArgs );
getContext().getContentResolver().notifyChange( uri, null );
return affected;
case PROGRAM_ID:
selection = appendRowId( selection, Long.parseLong( uri.getPathSegments().get( 1 ) ) );
affected = db.update( ProgramConstants.TABLE_NAME, values, selection , selectionArgs );
getContext().getContentResolver().notifyChange( uri, null );
return affected;
case RECORDINGS:
affected = db.update( RecordingConstants.TABLE_NAME, values, selection , selectionArgs );
getContext().getContentResolver().notifyChange( uri, null );
return affected;
case RECORDING_ID:
selection = appendRowId( selection, Long.parseLong( uri.getPathSegments().get( 1 ) ) );
affected = db.update( RecordingConstants.TABLE_NAME, values, selection , selectionArgs );
getContext().getContentResolver().notifyChange( uri, null );
return affected;
case CHANNELS:
affected = db.update( ChannelConstants.TABLE_NAME, values, selection , selectionArgs );
getContext().getContentResolver().notifyChange( uri, null );
return affected;
case CHANNEL_ID:
selection = appendRowId( selection, Long.parseLong( uri.getPathSegments().get( 1 ) ) );
affected = db.update( ChannelConstants.TABLE_NAME, values, selection , selectionArgs );
getContext().getContentResolver().notifyChange( uri, null );
return affected;
default:
throw new IllegalArgumentException( "Unknown URI: " + uri );
}
}
/* (non-Javadoc)
* @see android.content.ContentProvider#bulkInsert(android.net.Uri, android.content.ContentValues[])
*/
@Override
public int bulkInsert( Uri uri, ContentValues[] values ) {
final SQLiteDatabase db = database.getWritableDatabase();
int numInserted = 0;
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
db.beginTransaction();
try {
//standard SQL insert statement, that can be reused
SQLiteStatement insert = db.compileStatement( ProgramConstants.INSERT_ROW );
for( ContentValues value : values ) {
insert.bindString( 1, value.getAsString( ProgramConstants.FIELD_PROGRAM_TYPE ) );
insert.bindString( 2, value.getAsString( ProgramConstants.FIELD_PROGRAM_GROUP ) );
insert.bindString( 3, value.getAsString( ProgramConstants.FIELD_START_DATE ) );
insert.bindString( 4, value.getAsString( ProgramConstants.FIELD_START_TIME ) );
insert.bindString( 5, value.getAsString( ProgramConstants.FIELD_END_TIME ) );
insert.bindString( 6, value.getAsString( ProgramConstants.FIELD_TITLE ) );
insert.bindString( 7, value.getAsString( ProgramConstants.FIELD_SUB_TITLE ) );
insert.bindString( 8, value.getAsString( ProgramConstants.FIELD_CATEGORY ) );
insert.bindString( 9, value.getAsString( ProgramConstants.FIELD_CATEGORY_TYPE ) );
insert.bindLong( 10, value.getAsInteger( ProgramConstants.FIELD_REPEAT ) );
insert.bindLong( 11, value.getAsInteger( ProgramConstants.FIELD_VIDEO_PROPS ) );
insert.bindLong( 12, value.getAsInteger( ProgramConstants.FIELD_AUDIO_PROPS ) );
insert.bindLong( 13, value.getAsInteger( ProgramConstants.FIELD_SUB_PROPS ) );
insert.bindString( 14, value.getAsString( ProgramConstants.FIELD_SERIES_ID ) );
insert.bindString( 15, value.getAsString( ProgramConstants.FIELD_PROGRAM_ID ) );
insert.bindDouble( 16, value.getAsFloat( ProgramConstants.FIELD_STARS ) );
insert.bindString( 17, value.getAsString( ProgramConstants.FIELD_FILE_SIZE ) );
insert.bindString( 18, value.getAsString( ProgramConstants.FIELD_LAST_MODIFIED ) );
insert.bindString( 19, value.getAsString( ProgramConstants.FIELD_PROGRAM_FLAGS ) );
insert.bindString( 20, value.getAsString( ProgramConstants.FIELD_HOSTNAME ) );
insert.bindString( 21, value.getAsString( ProgramConstants.FIELD_FILENAME ) );
insert.bindString( 22, value.getAsString( ProgramConstants.FIELD_AIR_DATE ) );
insert.bindString( 23, value.getAsString( ProgramConstants.FIELD_DESCRIPTION ) );
insert.bindString( 24, value.getAsString( ProgramConstants.FIELD_INETREF ) );
insert.bindString( 25, value.getAsString( ProgramConstants.FIELD_SEASON ) );
insert.bindString( 26, value.getAsString( ProgramConstants.FIELD_EPISODE ) );
- insert.bindLong( 27, value.getAsInteger( ProgramConstants.FIELD_CHANNEL_ID ) );
+ insert.bindString( 27, value.getAsString( ProgramConstants.FIELD_CHANNEL_ID ) );
insert.execute();
}
db.setTransactionSuccessful();
numInserted = values.length;
} finally {
db.endTransaction();
}
return numInserted;
case CHANNELS:
db.beginTransaction();
try {
//standard SQL insert statement, that can be reused
SQLiteStatement insert = db.compileStatement( ChannelConstants.INSERT_ROW );
for( ContentValues value : values ) {
insert.bindString( 1, value.getAsString( ChannelConstants.FIELD_CHAN_ID ) );
insert.bindString( 2, value.getAsString( ChannelConstants.FIELD_CHAN_NUM ) );
insert.bindString( 3, value.getAsString( ChannelConstants.FIELD_CALLSIGN ) );
insert.bindString( 4, value.getAsString( ChannelConstants.FIELD_ICON_URL ) );
insert.bindString( 5, value.getAsString( ChannelConstants.FIELD_CHANNEL_NAME ) );
insert.bindLong( 6, value.getAsInteger( ChannelConstants.FIELD_MPLEX_ID ) );
insert.bindLong( 7, value.getAsInteger( ChannelConstants.FIELD_TRANSPORT_ID ) );
insert.bindLong( 8, value.getAsInteger( ChannelConstants.FIELD_SERVICE_ID ) );
insert.bindLong( 9, value.getAsInteger( ChannelConstants.FIELD_NETWORK_ID ) );
insert.bindLong( 10, value.getAsInteger( ChannelConstants.FIELD_ATSC_MAJOR_CHAN ) );
insert.bindLong( 11, value.getAsInteger( ChannelConstants.FIELD_ATSC_MINOR_CHAN ) );
insert.bindString( 12, value.getAsString( ChannelConstants.FIELD_FORMAT ) );
insert.bindString( 13, value.getAsString( ChannelConstants.FIELD_MODULATION ) );
insert.bindLong( 14, value.getAsInteger( ChannelConstants.FIELD_FREQUENCY ) );
insert.bindString( 15, value.getAsString( ChannelConstants.FIELD_FREQUENCY_ID ) );
insert.bindString( 16, value.getAsString( ChannelConstants.FIELD_FREQUENCY_TABLE ) );
insert.bindLong( 17, value.getAsInteger( ChannelConstants.FIELD_FINE_TUNE ) );
insert.bindString( 18, value.getAsString( ChannelConstants.FIELD_SIS_STANDARD ) );
insert.bindString( 19, value.getAsString( ChannelConstants.FIELD_CHAN_FILTERS ) );
insert.bindLong( 20, value.getAsInteger( ChannelConstants.FIELD_SOURCE_ID ) );
insert.bindLong( 21, value.getAsInteger( ChannelConstants.FIELD_INPUT_ID ) );
insert.bindLong( 22, value.getAsInteger( ChannelConstants.FIELD_COMM_FREE ) );
insert.bindLong( 23, value.getAsInteger( ChannelConstants.FIELD_USE_EIT ) );
insert.bindLong( 24, value.getAsInteger( ChannelConstants.FIELD_VISIBLE ) );
insert.bindString( 25, value.getAsString( ChannelConstants.FIELD_XMLTV_ID ) );
insert.bindString( 26, value.getAsString( ChannelConstants.FIELD_DEFAULT_AUTH ) );
insert.execute();
}
db.setTransactionSuccessful();
numInserted = values.length;
} finally {
db.endTransaction();
}
return numInserted;
default:
throw new UnsupportedOperationException( "Unsupported URI: " + uri );
}
}
}
| true | true | public int bulkInsert( Uri uri, ContentValues[] values ) {
final SQLiteDatabase db = database.getWritableDatabase();
int numInserted = 0;
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
db.beginTransaction();
try {
//standard SQL insert statement, that can be reused
SQLiteStatement insert = db.compileStatement( ProgramConstants.INSERT_ROW );
for( ContentValues value : values ) {
insert.bindString( 1, value.getAsString( ProgramConstants.FIELD_PROGRAM_TYPE ) );
insert.bindString( 2, value.getAsString( ProgramConstants.FIELD_PROGRAM_GROUP ) );
insert.bindString( 3, value.getAsString( ProgramConstants.FIELD_START_DATE ) );
insert.bindString( 4, value.getAsString( ProgramConstants.FIELD_START_TIME ) );
insert.bindString( 5, value.getAsString( ProgramConstants.FIELD_END_TIME ) );
insert.bindString( 6, value.getAsString( ProgramConstants.FIELD_TITLE ) );
insert.bindString( 7, value.getAsString( ProgramConstants.FIELD_SUB_TITLE ) );
insert.bindString( 8, value.getAsString( ProgramConstants.FIELD_CATEGORY ) );
insert.bindString( 9, value.getAsString( ProgramConstants.FIELD_CATEGORY_TYPE ) );
insert.bindLong( 10, value.getAsInteger( ProgramConstants.FIELD_REPEAT ) );
insert.bindLong( 11, value.getAsInteger( ProgramConstants.FIELD_VIDEO_PROPS ) );
insert.bindLong( 12, value.getAsInteger( ProgramConstants.FIELD_AUDIO_PROPS ) );
insert.bindLong( 13, value.getAsInteger( ProgramConstants.FIELD_SUB_PROPS ) );
insert.bindString( 14, value.getAsString( ProgramConstants.FIELD_SERIES_ID ) );
insert.bindString( 15, value.getAsString( ProgramConstants.FIELD_PROGRAM_ID ) );
insert.bindDouble( 16, value.getAsFloat( ProgramConstants.FIELD_STARS ) );
insert.bindString( 17, value.getAsString( ProgramConstants.FIELD_FILE_SIZE ) );
insert.bindString( 18, value.getAsString( ProgramConstants.FIELD_LAST_MODIFIED ) );
insert.bindString( 19, value.getAsString( ProgramConstants.FIELD_PROGRAM_FLAGS ) );
insert.bindString( 20, value.getAsString( ProgramConstants.FIELD_HOSTNAME ) );
insert.bindString( 21, value.getAsString( ProgramConstants.FIELD_FILENAME ) );
insert.bindString( 22, value.getAsString( ProgramConstants.FIELD_AIR_DATE ) );
insert.bindString( 23, value.getAsString( ProgramConstants.FIELD_DESCRIPTION ) );
insert.bindString( 24, value.getAsString( ProgramConstants.FIELD_INETREF ) );
insert.bindString( 25, value.getAsString( ProgramConstants.FIELD_SEASON ) );
insert.bindString( 26, value.getAsString( ProgramConstants.FIELD_EPISODE ) );
insert.bindLong( 27, value.getAsInteger( ProgramConstants.FIELD_CHANNEL_ID ) );
insert.execute();
}
db.setTransactionSuccessful();
numInserted = values.length;
} finally {
db.endTransaction();
}
return numInserted;
case CHANNELS:
db.beginTransaction();
try {
//standard SQL insert statement, that can be reused
SQLiteStatement insert = db.compileStatement( ChannelConstants.INSERT_ROW );
for( ContentValues value : values ) {
insert.bindString( 1, value.getAsString( ChannelConstants.FIELD_CHAN_ID ) );
insert.bindString( 2, value.getAsString( ChannelConstants.FIELD_CHAN_NUM ) );
insert.bindString( 3, value.getAsString( ChannelConstants.FIELD_CALLSIGN ) );
insert.bindString( 4, value.getAsString( ChannelConstants.FIELD_ICON_URL ) );
insert.bindString( 5, value.getAsString( ChannelConstants.FIELD_CHANNEL_NAME ) );
insert.bindLong( 6, value.getAsInteger( ChannelConstants.FIELD_MPLEX_ID ) );
insert.bindLong( 7, value.getAsInteger( ChannelConstants.FIELD_TRANSPORT_ID ) );
insert.bindLong( 8, value.getAsInteger( ChannelConstants.FIELD_SERVICE_ID ) );
insert.bindLong( 9, value.getAsInteger( ChannelConstants.FIELD_NETWORK_ID ) );
insert.bindLong( 10, value.getAsInteger( ChannelConstants.FIELD_ATSC_MAJOR_CHAN ) );
insert.bindLong( 11, value.getAsInteger( ChannelConstants.FIELD_ATSC_MINOR_CHAN ) );
insert.bindString( 12, value.getAsString( ChannelConstants.FIELD_FORMAT ) );
insert.bindString( 13, value.getAsString( ChannelConstants.FIELD_MODULATION ) );
insert.bindLong( 14, value.getAsInteger( ChannelConstants.FIELD_FREQUENCY ) );
insert.bindString( 15, value.getAsString( ChannelConstants.FIELD_FREQUENCY_ID ) );
insert.bindString( 16, value.getAsString( ChannelConstants.FIELD_FREQUENCY_TABLE ) );
insert.bindLong( 17, value.getAsInteger( ChannelConstants.FIELD_FINE_TUNE ) );
insert.bindString( 18, value.getAsString( ChannelConstants.FIELD_SIS_STANDARD ) );
insert.bindString( 19, value.getAsString( ChannelConstants.FIELD_CHAN_FILTERS ) );
insert.bindLong( 20, value.getAsInteger( ChannelConstants.FIELD_SOURCE_ID ) );
insert.bindLong( 21, value.getAsInteger( ChannelConstants.FIELD_INPUT_ID ) );
insert.bindLong( 22, value.getAsInteger( ChannelConstants.FIELD_COMM_FREE ) );
insert.bindLong( 23, value.getAsInteger( ChannelConstants.FIELD_USE_EIT ) );
insert.bindLong( 24, value.getAsInteger( ChannelConstants.FIELD_VISIBLE ) );
insert.bindString( 25, value.getAsString( ChannelConstants.FIELD_XMLTV_ID ) );
insert.bindString( 26, value.getAsString( ChannelConstants.FIELD_DEFAULT_AUTH ) );
insert.execute();
}
db.setTransactionSuccessful();
numInserted = values.length;
} finally {
db.endTransaction();
}
return numInserted;
default:
throw new UnsupportedOperationException( "Unsupported URI: " + uri );
}
}
| public int bulkInsert( Uri uri, ContentValues[] values ) {
final SQLiteDatabase db = database.getWritableDatabase();
int numInserted = 0;
switch( URI_MATCHER.match( uri ) ) {
case PROGRAMS:
db.beginTransaction();
try {
//standard SQL insert statement, that can be reused
SQLiteStatement insert = db.compileStatement( ProgramConstants.INSERT_ROW );
for( ContentValues value : values ) {
insert.bindString( 1, value.getAsString( ProgramConstants.FIELD_PROGRAM_TYPE ) );
insert.bindString( 2, value.getAsString( ProgramConstants.FIELD_PROGRAM_GROUP ) );
insert.bindString( 3, value.getAsString( ProgramConstants.FIELD_START_DATE ) );
insert.bindString( 4, value.getAsString( ProgramConstants.FIELD_START_TIME ) );
insert.bindString( 5, value.getAsString( ProgramConstants.FIELD_END_TIME ) );
insert.bindString( 6, value.getAsString( ProgramConstants.FIELD_TITLE ) );
insert.bindString( 7, value.getAsString( ProgramConstants.FIELD_SUB_TITLE ) );
insert.bindString( 8, value.getAsString( ProgramConstants.FIELD_CATEGORY ) );
insert.bindString( 9, value.getAsString( ProgramConstants.FIELD_CATEGORY_TYPE ) );
insert.bindLong( 10, value.getAsInteger( ProgramConstants.FIELD_REPEAT ) );
insert.bindLong( 11, value.getAsInteger( ProgramConstants.FIELD_VIDEO_PROPS ) );
insert.bindLong( 12, value.getAsInteger( ProgramConstants.FIELD_AUDIO_PROPS ) );
insert.bindLong( 13, value.getAsInteger( ProgramConstants.FIELD_SUB_PROPS ) );
insert.bindString( 14, value.getAsString( ProgramConstants.FIELD_SERIES_ID ) );
insert.bindString( 15, value.getAsString( ProgramConstants.FIELD_PROGRAM_ID ) );
insert.bindDouble( 16, value.getAsFloat( ProgramConstants.FIELD_STARS ) );
insert.bindString( 17, value.getAsString( ProgramConstants.FIELD_FILE_SIZE ) );
insert.bindString( 18, value.getAsString( ProgramConstants.FIELD_LAST_MODIFIED ) );
insert.bindString( 19, value.getAsString( ProgramConstants.FIELD_PROGRAM_FLAGS ) );
insert.bindString( 20, value.getAsString( ProgramConstants.FIELD_HOSTNAME ) );
insert.bindString( 21, value.getAsString( ProgramConstants.FIELD_FILENAME ) );
insert.bindString( 22, value.getAsString( ProgramConstants.FIELD_AIR_DATE ) );
insert.bindString( 23, value.getAsString( ProgramConstants.FIELD_DESCRIPTION ) );
insert.bindString( 24, value.getAsString( ProgramConstants.FIELD_INETREF ) );
insert.bindString( 25, value.getAsString( ProgramConstants.FIELD_SEASON ) );
insert.bindString( 26, value.getAsString( ProgramConstants.FIELD_EPISODE ) );
insert.bindString( 27, value.getAsString( ProgramConstants.FIELD_CHANNEL_ID ) );
insert.execute();
}
db.setTransactionSuccessful();
numInserted = values.length;
} finally {
db.endTransaction();
}
return numInserted;
case CHANNELS:
db.beginTransaction();
try {
//standard SQL insert statement, that can be reused
SQLiteStatement insert = db.compileStatement( ChannelConstants.INSERT_ROW );
for( ContentValues value : values ) {
insert.bindString( 1, value.getAsString( ChannelConstants.FIELD_CHAN_ID ) );
insert.bindString( 2, value.getAsString( ChannelConstants.FIELD_CHAN_NUM ) );
insert.bindString( 3, value.getAsString( ChannelConstants.FIELD_CALLSIGN ) );
insert.bindString( 4, value.getAsString( ChannelConstants.FIELD_ICON_URL ) );
insert.bindString( 5, value.getAsString( ChannelConstants.FIELD_CHANNEL_NAME ) );
insert.bindLong( 6, value.getAsInteger( ChannelConstants.FIELD_MPLEX_ID ) );
insert.bindLong( 7, value.getAsInteger( ChannelConstants.FIELD_TRANSPORT_ID ) );
insert.bindLong( 8, value.getAsInteger( ChannelConstants.FIELD_SERVICE_ID ) );
insert.bindLong( 9, value.getAsInteger( ChannelConstants.FIELD_NETWORK_ID ) );
insert.bindLong( 10, value.getAsInteger( ChannelConstants.FIELD_ATSC_MAJOR_CHAN ) );
insert.bindLong( 11, value.getAsInteger( ChannelConstants.FIELD_ATSC_MINOR_CHAN ) );
insert.bindString( 12, value.getAsString( ChannelConstants.FIELD_FORMAT ) );
insert.bindString( 13, value.getAsString( ChannelConstants.FIELD_MODULATION ) );
insert.bindLong( 14, value.getAsInteger( ChannelConstants.FIELD_FREQUENCY ) );
insert.bindString( 15, value.getAsString( ChannelConstants.FIELD_FREQUENCY_ID ) );
insert.bindString( 16, value.getAsString( ChannelConstants.FIELD_FREQUENCY_TABLE ) );
insert.bindLong( 17, value.getAsInteger( ChannelConstants.FIELD_FINE_TUNE ) );
insert.bindString( 18, value.getAsString( ChannelConstants.FIELD_SIS_STANDARD ) );
insert.bindString( 19, value.getAsString( ChannelConstants.FIELD_CHAN_FILTERS ) );
insert.bindLong( 20, value.getAsInteger( ChannelConstants.FIELD_SOURCE_ID ) );
insert.bindLong( 21, value.getAsInteger( ChannelConstants.FIELD_INPUT_ID ) );
insert.bindLong( 22, value.getAsInteger( ChannelConstants.FIELD_COMM_FREE ) );
insert.bindLong( 23, value.getAsInteger( ChannelConstants.FIELD_USE_EIT ) );
insert.bindLong( 24, value.getAsInteger( ChannelConstants.FIELD_VISIBLE ) );
insert.bindString( 25, value.getAsString( ChannelConstants.FIELD_XMLTV_ID ) );
insert.bindString( 26, value.getAsString( ChannelConstants.FIELD_DEFAULT_AUTH ) );
insert.execute();
}
db.setTransactionSuccessful();
numInserted = values.length;
} finally {
db.endTransaction();
}
return numInserted;
default:
throw new UnsupportedOperationException( "Unsupported URI: " + uri );
}
}
|
diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMappingInfo.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMappingInfo.java
index a17aa6289..88352e249 100644
--- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMappingInfo.java
+++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/meta/ClassMappingInfo.java
@@ -1,341 +1,341 @@
/*
* Copyright 2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.openjpa.jdbc.meta;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.openjpa.jdbc.meta.strats.FullClassStrategy;
import org.apache.openjpa.jdbc.schema.Column;
import org.apache.openjpa.jdbc.schema.ForeignKey;
import org.apache.openjpa.jdbc.schema.Schema;
import org.apache.openjpa.jdbc.schema.SchemaGroup;
import org.apache.openjpa.jdbc.schema.Table;
import org.apache.openjpa.lib.meta.SourceTracker;
import org.apache.openjpa.lib.xml.Commentable;
/**
* Information about the mapping from a class to the schema, in raw form.
* The columns and tables used in mapping info will not be part of the
* {@link SchemaGroup} used at runtime. Rather, they will be structs
* with the relevant pieces of information filled in.
*
* @author Abe White
*/
public class ClassMappingInfo
extends MappingInfo
implements SourceTracker, Commentable {
private String _className = Object.class.getName();
private String _tableName = null;
private boolean _joined = false;
private Map _seconds = null;
private String _subStrat = null;
private File _file = null;
private int _srcType = SRC_OTHER;
private String[] _comments = null;
/**
* The described class name.
*/
public String getClassName() {
return _className;
}
/**
* The described class name.
*/
public void setClassName(String name) {
_className = name;
}
/**
* The default strategy for subclasses in this hierarchy.
*/
public String getHierarchyStrategy() {
return _subStrat;
}
/**
* The default strategy for subclasses in this hierarchy.
*/
public void setHierarchyStrategy(String strategy) {
_subStrat = strategy;
}
/**
* The given table name.
*/
public String getTableName() {
return _tableName;
}
/**
* The given table name.
*/
public void setTableName(String table) {
_tableName = table;
}
/**
* Whether there is a join to the superclass table.
*/
public boolean isJoinedSubclass() {
return _joined;
}
/**
* Whether there is a join to the superclass table.
*/
public void setJoinedSubclass(boolean joined) {
_joined = joined;
}
/**
* Return the class-level joined tables.
*/
public String[] getSecondaryTableNames() {
if (_seconds == null)
return new String[0];
return (String[]) _seconds.keySet().toArray(new String[]{ });
}
/**
* We allow fields to reference class-level joins using just the table
* name, whereas the class join might have schema, etc information.
* This method returns the name of the given table as listed in a
* class-level join, or the given name if no join exists.
*/
public String getSecondaryTableName(String tableName) {
// if no secondary table joins, bad table name, exact match,
// or an already-qualified table name, nothing to do
if (_seconds == null || tableName == null
|| _seconds.containsKey(tableName)
|| tableName.indexOf('.') != -1)
return tableName;
// decide which class-level join table is best match
String best = tableName;
int pts = 0;
String fullJoin;
String join;
int idx;
for (Iterator itr = _seconds.keySet().iterator(); itr.hasNext();) {
// award a caseless match without schema 2 points
fullJoin = (String) itr.next();
idx = fullJoin.lastIndexOf('.');
if (idx == -1 && pts < 2 && fullJoin.equalsIgnoreCase(tableName)) {
best = fullJoin;
pts = 2;
} else if (idx == -1)
continue;
// immediately return an exact match with schema
join = fullJoin.substring(idx + 1);
if (join.equals(tableName))
- return join;
+ return fullJoin;
// caseless match with schema worth 1 point
if (pts < 1 && join.equalsIgnoreCase(tableName)) {
best = fullJoin;
pts = 1;
}
}
return best;
}
/**
* Return any columns defined for the given class level join, or empty
* list if none.
*/
public List getSecondaryTableJoinColumns(String tableName) {
if (_seconds == null || tableName == null)
return Collections.EMPTY_LIST;
// get the columns for the join with the best match for table name
List cols = (List) _seconds.get(getSecondaryTableName(tableName));
if (cols == null) {
// possible that given table has extra info the join table
// doesn't have; strip it
int idx = tableName.lastIndexOf('.');
if (idx != -1) {
tableName = tableName.substring(idx + 1);
cols = (List) _seconds.get(getSecondaryTableName(tableName));
}
}
return (cols == null) ? Collections.EMPTY_LIST : cols;
}
/**
* Declare the given class-level join.
*/
public void setSecondaryTableJoinColumns(String tableName, List cols) {
if (cols == null)
cols = Collections.EMPTY_LIST;
if (_seconds == null)
_seconds = new HashMap();
_seconds.put(tableName, cols);
}
/**
* Return the table for the given class.
*/
public Table getTable(final ClassMapping cls, boolean adapt) {
return createTable(cls, new TableDefaults() {
public String get(Schema schema) {
// delay this so that we don't do schema reflection for unique
// table name unless necessary
return cls.getMappingRepository().getMappingDefaults().
getTableName(cls, schema);
}
}, null, _tableName, adapt);
}
/**
* Return the datastore identity columns for the given class, based on the
* given templates.
*/
public Column[] getDataStoreIdColumns(ClassMapping cls, Column[] tmplates,
Table table, boolean adapt) {
cls.getMappingRepository().getMappingDefaults().
populateDataStoreIdColumns(cls, table, tmplates);
return createColumns(cls, "datastoreid", tmplates, table, adapt);
}
/**
* Return the join from this class to its superclass. The table for
* this class must be set.
*/
public ForeignKey getSuperclassJoin(final ClassMapping cls, Table table,
boolean adapt) {
ClassMapping sup = cls.getJoinablePCSuperclassMapping();
if (sup == null)
return null;
ForeignKeyDefaults def = new ForeignKeyDefaults() {
public ForeignKey get(Table local, Table foreign, boolean inverse) {
return cls.getMappingRepository().getMappingDefaults().
getJoinForeignKey(cls, local, foreign);
}
public void populate(Table local, Table foreign, Column col,
Object target, boolean inverse, int pos, int cols) {
cls.getMappingRepository().getMappingDefaults().
populateJoinColumn(cls, local, foreign, col, target,
pos, cols);
}
};
return createForeignKey(cls, "superclass", getColumns(), def, table,
cls, sup, false, adapt);
}
/**
* Synchronize internal information with the mapping data for the given
* class.
*/
public void syncWith(ClassMapping cls) {
clear(false);
ClassMapping sup = cls.getMappedPCSuperclassMapping();
if (cls.getTable() != null && (sup == null
|| sup.getTable() != cls.getTable()))
_tableName = cls.getMappingRepository().getDBDictionary().
getFullName(cls.getTable(), true);
// set io before syncing cols
setColumnIO(cls.getColumnIO());
if (cls.getJoinForeignKey() != null && sup != null
&& sup.getTable() != null)
syncForeignKey(cls, cls.getJoinForeignKey(), cls.getTable(),
sup.getTable());
else if (cls.getIdentityType() == ClassMapping.ID_DATASTORE)
syncColumns(cls, cls.getPrimaryKeyColumns(), false);
// record inheritance strategy if class does not use default strategy
// for base classes, and for all subclasses so we can be sure subsequent
// mapping runs don't think subclass is unmapped
String strat = (cls.getStrategy() == null) ? null
: cls.getStrategy().getAlias();
if (strat != null && (cls.getPCSuperclass() != null
|| !FullClassStrategy.ALIAS.equals(strat)))
setStrategy(strat);
}
public boolean hasSchemaComponents() {
return super.hasSchemaComponents() || _tableName != null;
}
protected void clear(boolean canFlags) {
super.clear(canFlags);
_tableName = null;
}
public void copy(MappingInfo info) {
super.copy(info);
if (!(info instanceof ClassMappingInfo))
return;
ClassMappingInfo cinfo = (ClassMappingInfo) info;
if (_tableName == null)
_tableName = cinfo.getTableName();
if (_subStrat == null)
_subStrat = cinfo.getHierarchyStrategy();
if (cinfo._seconds != null) {
if (_seconds == null)
_seconds = new HashMap();
Object key;
for (Iterator itr = cinfo._seconds.keySet().iterator();
itr.hasNext();) {
key = itr.next();
if (!_seconds.containsKey(key))
_seconds.put(key, cinfo._seconds.get(key));
}
}
}
public File getSourceFile() {
return _file;
}
public Object getSourceScope() {
return null;
}
public int getSourceType() {
return _srcType;
}
public void setSource(File file, int srcType) {
_file = file;
_srcType = srcType;
}
public String getResourceName() {
return _className;
}
public String[] getComments() {
return (_comments == null) ? EMPTY_COMMENTS : _comments;
}
public void setComments(String[] comments) {
_comments = comments;
}
}
| true | true | public String getSecondaryTableName(String tableName) {
// if no secondary table joins, bad table name, exact match,
// or an already-qualified table name, nothing to do
if (_seconds == null || tableName == null
|| _seconds.containsKey(tableName)
|| tableName.indexOf('.') != -1)
return tableName;
// decide which class-level join table is best match
String best = tableName;
int pts = 0;
String fullJoin;
String join;
int idx;
for (Iterator itr = _seconds.keySet().iterator(); itr.hasNext();) {
// award a caseless match without schema 2 points
fullJoin = (String) itr.next();
idx = fullJoin.lastIndexOf('.');
if (idx == -1 && pts < 2 && fullJoin.equalsIgnoreCase(tableName)) {
best = fullJoin;
pts = 2;
} else if (idx == -1)
continue;
// immediately return an exact match with schema
join = fullJoin.substring(idx + 1);
if (join.equals(tableName))
return join;
// caseless match with schema worth 1 point
if (pts < 1 && join.equalsIgnoreCase(tableName)) {
best = fullJoin;
pts = 1;
}
}
return best;
}
| public String getSecondaryTableName(String tableName) {
// if no secondary table joins, bad table name, exact match,
// or an already-qualified table name, nothing to do
if (_seconds == null || tableName == null
|| _seconds.containsKey(tableName)
|| tableName.indexOf('.') != -1)
return tableName;
// decide which class-level join table is best match
String best = tableName;
int pts = 0;
String fullJoin;
String join;
int idx;
for (Iterator itr = _seconds.keySet().iterator(); itr.hasNext();) {
// award a caseless match without schema 2 points
fullJoin = (String) itr.next();
idx = fullJoin.lastIndexOf('.');
if (idx == -1 && pts < 2 && fullJoin.equalsIgnoreCase(tableName)) {
best = fullJoin;
pts = 2;
} else if (idx == -1)
continue;
// immediately return an exact match with schema
join = fullJoin.substring(idx + 1);
if (join.equals(tableName))
return fullJoin;
// caseless match with schema worth 1 point
if (pts < 1 && join.equalsIgnoreCase(tableName)) {
best = fullJoin;
pts = 1;
}
}
return best;
}
|
diff --git a/common/logisticspipes/blocks/crafting/LogisticsCraftingTableTileEntity.java b/common/logisticspipes/blocks/crafting/LogisticsCraftingTableTileEntity.java
index 7edb995c..4b6f0bc3 100644
--- a/common/logisticspipes/blocks/crafting/LogisticsCraftingTableTileEntity.java
+++ b/common/logisticspipes/blocks/crafting/LogisticsCraftingTableTileEntity.java
@@ -1,215 +1,216 @@
package logisticspipes.blocks.crafting;
import logisticspipes.Configs;
import logisticspipes.api.IRoutedPowerProvider;
import logisticspipes.proxy.MainProxy;
import logisticspipes.utils.CraftingUtil;
import logisticspipes.utils.ISimpleInventoryEventHandler;
import logisticspipes.utils.ItemIdentifier;
import logisticspipes.utils.ItemIdentifierStack;
import logisticspipes.utils.SimpleInventory;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.SlotCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
public class LogisticsCraftingTableTileEntity extends TileEntity implements ISimpleInventoryEventHandler, IInventory {
public SimpleInventory inv = new SimpleInventory(18, "Crafting Resources", 64);
public SimpleInventory matrix = new SimpleInventory(9, "Crafting Matrix", 1);
public SimpleInventory resultInv = new SimpleInventory(1, "Crafting Result", 1);
private IRecipe cache;
private EntityPlayer fake;
public LogisticsCraftingTableTileEntity() {
matrix.addListener(this);
}
public void cacheRecipe() {
cache = null;
resultInv.clearInventorySlotContents(0);
AutoCraftingInventory craftInv = new AutoCraftingInventory();
for(int i=0; i<9;i++) {
craftInv.setInventorySlotContents(i, matrix.getStackInSlot(i));
}
for(IRecipe r : CraftingUtil.getRecipeList()) {
if(r.matches(craftInv, getWorldObj())) {
cache = r;
resultInv.setInventorySlotContents(0, r.getCraftingResult(craftInv));
break;
}
}
}
public ItemStack getOutput(ItemIdentifier wanted, IRoutedPowerProvider power) {
if(cache == null) {
cacheRecipe();
if(cache == null) return null;
}
int[] toUse = new int[9];
int[] used = new int[inv.getSizeInventory()];
outer:
for(int i=0;i<9;i++) {
ItemIdentifierStack item = matrix.getIDStackInSlot(i);
if(item == null) {
toUse[i] = -1;
continue;
}
ItemIdentifier ident = item.getItem();
for(int j=0;j<inv.getSizeInventory();j++) {
item = inv.getIDStackInSlot(j);
if(item == null) continue;
if(ident.equalsForCrafting(item.getItem())) {
if(item.stackSize > used[j]) {
used[j]++;
toUse[i] = j;
continue outer;
}
}
}
//Not enough material
return null;
}
AutoCraftingInventory crafter = new AutoCraftingInventory();
for(int i=0;i<9;i++) {
int j = toUse[i];
if(j != -1) crafter.setInventorySlotContents(i, inv.getStackInSlot(j));
}
+ if(!cache.matches(crafter, getWorldObj())) return null; //Fix MystCraft
ItemStack result = cache.getCraftingResult(crafter);
if(result == null) return null;
if(!resultInv.getIDStackInSlot(0).getItem().equalsWithoutNBT(ItemIdentifier.get(result))) return null;
if(!wanted.equalsWithoutNBT(resultInv.getIDStackInSlot(0).getItem())) return null;
if(!power.useEnergy(Configs.LOGISTICS_CRAFTING_TABLE_POWER_USAGE)) return null;
crafter = new AutoCraftingInventory();
for(int i=0;i<9;i++) {
int j = toUse[i];
if(j != -1) crafter.setInventorySlotContents(i, inv.decrStackSize(j, 1));
}
result = cache.getCraftingResult(crafter);
if(fake == null) {
fake = MainProxy.getFakePlayer(this);
}
result = result.copy();
SlotCrafting craftingSlot = new SlotCrafting(fake, crafter, resultInv, 0, 0, 0);
craftingSlot.onPickupFromSlot(fake, result);
for(int i=0;i<9;i++) {
ItemStack left = crafter.getStackInSlot(i);
crafter.setInventorySlotContents(i, null);
if(left != null) {
left.stackSize = inv.addCompressed(left, false);
if(left.stackSize > 0) {
SimpleInventory.dropItems(worldObj, left, xCoord, yCoord, zCoord);
}
}
}
for(int i=0;i<fake.inventory.getSizeInventory();i++) {
ItemStack left = fake.inventory.getStackInSlot(i);
fake.inventory.setInventorySlotContents(i, null);
if(left != null) {
left.stackSize = inv.addCompressed(left, false);
if(left.stackSize > 0) {
SimpleInventory.dropItems(worldObj, left, xCoord, yCoord, zCoord);
}
}
}
return result;
}
public void onBlockBreak() {
inv.dropContents(worldObj, xCoord, yCoord, zCoord);
}
@Override
public void InventoryChanged(SimpleInventory inventory) {
if(inventory == matrix) {
cacheRecipe();
}
}
public void handleNEIRecipePacket(ItemStack[] content) {
for(int i=0;i<9;i++) {
matrix.setInventorySlotContents(i, content[i]);
}
cacheRecipe();
}
@Override
public void readFromNBT(NBTTagCompound par1nbtTagCompound) {
super.readFromNBT(par1nbtTagCompound);
inv.readFromNBT(par1nbtTagCompound, "inv");
matrix.readFromNBT(par1nbtTagCompound, "matrix");
cacheRecipe();
}
@Override
public void writeToNBT(NBTTagCompound par1nbtTagCompound) {
super.writeToNBT(par1nbtTagCompound);
inv.writeToNBT(par1nbtTagCompound, "inv");
matrix.writeToNBT(par1nbtTagCompound, "matrix");
}
@Override
public int getSizeInventory() {
return inv.getSizeInventory();
}
@Override
public ItemStack getStackInSlot(int i) {
return inv.getStackInSlot(i);
}
@Override
public ItemStack decrStackSize(int i, int j) {
return inv.decrStackSize(i, j);
}
@Override
public ItemStack getStackInSlotOnClosing(int i) {
return inv.getStackInSlotOnClosing(i);
}
@Override
public void setInventorySlotContents(int i, ItemStack itemstack) {
inv.setInventorySlotContents(i, itemstack);
}
@Override
public String getInvName() {
return "LogisticsCraftingTable";
}
@Override
public boolean isInvNameLocalized() {
return false;
}
@Override
public int getInventoryStackLimit() {
return inv.getInventoryStackLimit();
}
@Override
public boolean isUseableByPlayer(EntityPlayer entityplayer) {
return true;
}
@Override
public void openChest() {}
@Override
public void closeChest() {}
@Override
public boolean isItemValidForSlot(int i, ItemStack itemstack) {
if(i < 9 && i >= 0) {
ItemIdentifierStack stack = matrix.getIDStackInSlot(i);
if(stack != null && itemstack != null) {
return stack.getItem().equalsWithoutNBT(ItemIdentifier.get(itemstack));
}
}
return true;
}
}
| true | true | public ItemStack getOutput(ItemIdentifier wanted, IRoutedPowerProvider power) {
if(cache == null) {
cacheRecipe();
if(cache == null) return null;
}
int[] toUse = new int[9];
int[] used = new int[inv.getSizeInventory()];
outer:
for(int i=0;i<9;i++) {
ItemIdentifierStack item = matrix.getIDStackInSlot(i);
if(item == null) {
toUse[i] = -1;
continue;
}
ItemIdentifier ident = item.getItem();
for(int j=0;j<inv.getSizeInventory();j++) {
item = inv.getIDStackInSlot(j);
if(item == null) continue;
if(ident.equalsForCrafting(item.getItem())) {
if(item.stackSize > used[j]) {
used[j]++;
toUse[i] = j;
continue outer;
}
}
}
//Not enough material
return null;
}
AutoCraftingInventory crafter = new AutoCraftingInventory();
for(int i=0;i<9;i++) {
int j = toUse[i];
if(j != -1) crafter.setInventorySlotContents(i, inv.getStackInSlot(j));
}
ItemStack result = cache.getCraftingResult(crafter);
if(result == null) return null;
if(!resultInv.getIDStackInSlot(0).getItem().equalsWithoutNBT(ItemIdentifier.get(result))) return null;
if(!wanted.equalsWithoutNBT(resultInv.getIDStackInSlot(0).getItem())) return null;
if(!power.useEnergy(Configs.LOGISTICS_CRAFTING_TABLE_POWER_USAGE)) return null;
crafter = new AutoCraftingInventory();
for(int i=0;i<9;i++) {
int j = toUse[i];
if(j != -1) crafter.setInventorySlotContents(i, inv.decrStackSize(j, 1));
}
result = cache.getCraftingResult(crafter);
if(fake == null) {
fake = MainProxy.getFakePlayer(this);
}
result = result.copy();
SlotCrafting craftingSlot = new SlotCrafting(fake, crafter, resultInv, 0, 0, 0);
craftingSlot.onPickupFromSlot(fake, result);
for(int i=0;i<9;i++) {
ItemStack left = crafter.getStackInSlot(i);
crafter.setInventorySlotContents(i, null);
if(left != null) {
left.stackSize = inv.addCompressed(left, false);
if(left.stackSize > 0) {
SimpleInventory.dropItems(worldObj, left, xCoord, yCoord, zCoord);
}
}
}
for(int i=0;i<fake.inventory.getSizeInventory();i++) {
ItemStack left = fake.inventory.getStackInSlot(i);
fake.inventory.setInventorySlotContents(i, null);
if(left != null) {
left.stackSize = inv.addCompressed(left, false);
if(left.stackSize > 0) {
SimpleInventory.dropItems(worldObj, left, xCoord, yCoord, zCoord);
}
}
}
return result;
}
| public ItemStack getOutput(ItemIdentifier wanted, IRoutedPowerProvider power) {
if(cache == null) {
cacheRecipe();
if(cache == null) return null;
}
int[] toUse = new int[9];
int[] used = new int[inv.getSizeInventory()];
outer:
for(int i=0;i<9;i++) {
ItemIdentifierStack item = matrix.getIDStackInSlot(i);
if(item == null) {
toUse[i] = -1;
continue;
}
ItemIdentifier ident = item.getItem();
for(int j=0;j<inv.getSizeInventory();j++) {
item = inv.getIDStackInSlot(j);
if(item == null) continue;
if(ident.equalsForCrafting(item.getItem())) {
if(item.stackSize > used[j]) {
used[j]++;
toUse[i] = j;
continue outer;
}
}
}
//Not enough material
return null;
}
AutoCraftingInventory crafter = new AutoCraftingInventory();
for(int i=0;i<9;i++) {
int j = toUse[i];
if(j != -1) crafter.setInventorySlotContents(i, inv.getStackInSlot(j));
}
if(!cache.matches(crafter, getWorldObj())) return null; //Fix MystCraft
ItemStack result = cache.getCraftingResult(crafter);
if(result == null) return null;
if(!resultInv.getIDStackInSlot(0).getItem().equalsWithoutNBT(ItemIdentifier.get(result))) return null;
if(!wanted.equalsWithoutNBT(resultInv.getIDStackInSlot(0).getItem())) return null;
if(!power.useEnergy(Configs.LOGISTICS_CRAFTING_TABLE_POWER_USAGE)) return null;
crafter = new AutoCraftingInventory();
for(int i=0;i<9;i++) {
int j = toUse[i];
if(j != -1) crafter.setInventorySlotContents(i, inv.decrStackSize(j, 1));
}
result = cache.getCraftingResult(crafter);
if(fake == null) {
fake = MainProxy.getFakePlayer(this);
}
result = result.copy();
SlotCrafting craftingSlot = new SlotCrafting(fake, crafter, resultInv, 0, 0, 0);
craftingSlot.onPickupFromSlot(fake, result);
for(int i=0;i<9;i++) {
ItemStack left = crafter.getStackInSlot(i);
crafter.setInventorySlotContents(i, null);
if(left != null) {
left.stackSize = inv.addCompressed(left, false);
if(left.stackSize > 0) {
SimpleInventory.dropItems(worldObj, left, xCoord, yCoord, zCoord);
}
}
}
for(int i=0;i<fake.inventory.getSizeInventory();i++) {
ItemStack left = fake.inventory.getStackInSlot(i);
fake.inventory.setInventorySlotContents(i, null);
if(left != null) {
left.stackSize = inv.addCompressed(left, false);
if(left.stackSize > 0) {
SimpleInventory.dropItems(worldObj, left, xCoord, yCoord, zCoord);
}
}
}
return result;
}
|
diff --git a/org.envirocar.app/src/org/envirocar/app/storage/DbAdapterImpl.java b/org.envirocar.app/src/org/envirocar/app/storage/DbAdapterImpl.java
index 5dc4cf90..9d31dc88 100644
--- a/org.envirocar.app/src/org/envirocar/app/storage/DbAdapterImpl.java
+++ b/org.envirocar.app/src/org/envirocar/app/storage/DbAdapterImpl.java
@@ -1,354 +1,356 @@
package org.envirocar.app.storage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.envirocar.app.exception.TracksException;
import org.envirocar.app.logging.Logger;
import org.envirocar.app.model.Car;
import org.envirocar.app.model.Car.FuelType;
import org.envirocar.app.storage.Measurement.PropertyKey;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbAdapterImpl implements DbAdapter {
private static final Logger logger = Logger.getLogger(DbAdapterImpl.class);
public static final String TABLE_MEASUREMENT = "measurements";
public static final String KEY_MEASUREMENT_TIME = "time";
public static final String KEY_MEASUREMENT_LONGITUDE = "longitude";
public static final String KEY_MEASUREMENT_LATITUDE = "latitude";
public static final String KEY_MEASUREMENT_ROWID = "_id";
public static final String KEY_MEASUREMENT_PROPERTIES = "properties";
public static final String KEY_MEASUREMENT_TRACK = "track";
public static final String[] ALL_MEASUREMENT_KEYS = new String[]{
KEY_MEASUREMENT_ROWID,
KEY_MEASUREMENT_TIME,
KEY_MEASUREMENT_LONGITUDE,
KEY_MEASUREMENT_LATITUDE,
KEY_MEASUREMENT_PROPERTIES,
KEY_MEASUREMENT_TRACK
};
public static final String TABLE_TRACK = "tracks";
public static final String KEY_TRACK_ID = "_id";
public static final String KEY_TRACK_NAME = "name";
public static final String KEY_TRACK_DESCRIPTION = "descr";
public static final String KEY_TRACK_REMOTE = "remoteId";
public static final String KEY_TRACK_CAR_MANUFACTURER = "car_manufacturer";
public static final String KEY_TRACK_CAR_MODEL = "car_model";
public static final String KEY_TRACK_CAR_FUEL_TYPE = "fuel_type";
public static final String KEY_TRACK_CAR_ENGINE_DISPLACEMENT = "engine_displacement";
public static final String KEY_TRACK_CAR_VIN = "vin";
public static final String KEY_TRACK_CAR_ID = "carId";
public static final String[] ALL_TRACK_KEYS = new String[]{
KEY_TRACK_ID,
KEY_TRACK_NAME,
KEY_TRACK_DESCRIPTION,
KEY_TRACK_REMOTE,
KEY_TRACK_CAR_MANUFACTURER,
KEY_TRACK_CAR_MODEL,
KEY_TRACK_CAR_FUEL_TYPE,
KEY_TRACK_CAR_ENGINE_DISPLACEMENT,
KEY_TRACK_CAR_VIN,
KEY_TRACK_CAR_ID
};
private static final String DATABASE_NAME = "obd2";
private static final int DATABASE_VERSION = 6;
private static final String DATABASE_CREATE = "create table " + TABLE_MEASUREMENT + " " +
"(" + KEY_MEASUREMENT_ROWID + " INTEGER primary key autoincrement, " +
KEY_MEASUREMENT_LATITUDE + " BLOB, " +
KEY_MEASUREMENT_LONGITUDE + " BLOB, " +
KEY_MEASUREMENT_TIME + " BLOB, " +
KEY_MEASUREMENT_PROPERTIES + " BLOB, " +
KEY_MEASUREMENT_TRACK + " INTEGER);";
private static final String DATABASE_CREATE_TRACK = "create table " + TABLE_TRACK + " " +
"(" + KEY_TRACK_ID + " INTEGER primary key, " +
KEY_TRACK_NAME + " BLOB, " +
KEY_TRACK_DESCRIPTION + " BLOB, " +
KEY_TRACK_REMOTE + " BLOB, " +
KEY_TRACK_CAR_MANUFACTURER + " BLOB, " +
KEY_TRACK_CAR_MODEL + " BLOB, " +
KEY_TRACK_CAR_FUEL_TYPE + " BLOB, " +
KEY_TRACK_CAR_ENGINE_DISPLACEMENT + " BLOB, " +
KEY_TRACK_CAR_VIN + " BLOB, " +
KEY_TRACK_CAR_ID + " BLOB);";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private final Context mCtx;
public DbAdapterImpl(Context ctx) {
this.mCtx = ctx;
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE_TRACK);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
logger.info("Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS measurements");
db.execSQL("DROP TABLE IF EXISTS tracks");
onCreate(db);
}
}
@Override
public DbAdapter open() {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
@Override
public void close() {
mDb.close();
mDbHelper.close();
}
@Override
public boolean isOpen() {
return mDb.isOpen();
}
@Override
public void insertMeasurement(Measurement measurement) {
ContentValues values = new ContentValues();
values.put(KEY_MEASUREMENT_LATITUDE, measurement.getLatitude());
values.put(KEY_MEASUREMENT_LONGITUDE, measurement.getLongitude());
values.put(KEY_MEASUREMENT_TIME, measurement.getTime());
values.put(KEY_MEASUREMENT_TRACK, measurement.getTrack().getId());
String propertiesString = createJsonObjectForProperties(measurement).toString();
values.put(KEY_MEASUREMENT_PROPERTIES, propertiesString);
mDb.insert(TABLE_MEASUREMENT, null, values);
}
@Override
public long insertTrack(Track track) {
ContentValues values = createDbEntry(track);
return mDb.insert(TABLE_TRACK, null, values);
}
@Override
public boolean updateTrack(Track track) {
ContentValues values = createDbEntry(track);
long result = mDb.replace(TABLE_TRACK, null, values);
return (result != -1 ? true : false);
}
@Override
public ArrayList<Track> getAllTracks() {
ArrayList<Track> tracks = new ArrayList<Track>();
Cursor c = mDb.query(TABLE_TRACK, null, null, null, null, null, null);
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
long id = c.getLong(c.getColumnIndex(KEY_TRACK_ID));
tracks.add(getTrack(id));
c.moveToNext();
}
c.close();
return tracks;
}
@Override
public Track getTrack(long id) {
Cursor c = getCursorForTrackID(id);
c.moveToFirst();
Track track = Track.createDbTrack(c.getLong(c.getColumnIndex(KEY_TRACK_ID)));
track.setName(c.getString(c.getColumnIndex(KEY_TRACK_NAME)));
track.setDescription(c.getString(c.getColumnIndex(KEY_TRACK_DESCRIPTION)));
track.setVin(c.getString(c.getColumnIndex(KEY_TRACK_CAR_VIN)));
track.setRemoteID(c.getString(c.getColumnIndex(KEY_TRACK_REMOTE)));
String manufacturer = c.getString(c.getColumnIndex(KEY_TRACK_CAR_MANUFACTURER));
String model = c.getString(c.getColumnIndex(KEY_TRACK_CAR_MODEL));
String carId = c.getString(c.getColumnIndex(KEY_TRACK_CAR_ID));
FuelType fuelType = FuelType.valueOf(c.getString(c.getColumnIndex(KEY_TRACK_CAR_FUEL_TYPE)));
double engineDisplacement = c.getDouble(c.getColumnIndex(KEY_TRACK_CAR_ENGINE_DISPLACEMENT));
track.setCar(new Car(fuelType, manufacturer, model, carId, engineDisplacement));
c.close();
ArrayList<Measurement> measurements = getAllMeasurementsForTrack(track);
track.setMeasurementsAsArrayList(measurements);
return track;
}
@Override
public boolean hasTrack(long id) {
Cursor cursor = getCursorForTrackID(id);
if (cursor.getCount() > 0) {
return true;
} else {
return false;
}
}
@Override
public void deleteAllTracks() {
mDb.delete(TABLE_MEASUREMENT, null, null);
mDb.delete(TABLE_TRACK, null, null);
}
@Override
public int getNumberOfStoredTracks() {
Cursor cursor = mDb.rawQuery("SELECT COUNT(" + KEY_TRACK_ID + ") FROM " + TABLE_TRACK, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
return count;
}
@Override
public Track getLastUsedTrack() throws TracksException {
ArrayList<Track> trackList = getAllTracks();
if (trackList.size() > 0) {
return trackList.get(trackList.size() - 1);
} else
throw new TracksException("No tracks in local database!");
}
@Override
public void deleteTrack(long id) {
mDb.delete(TABLE_MEASUREMENT, KEY_MEASUREMENT_TRACK + "='" + id + "'", null);
mDb.delete(TABLE_TRACK, KEY_TRACK_ID + "='" + id + "'", null);
}
@Override
public int getNumberOfRemoteTracks() {
// TODO Auto-generated method stub
logger.warn("implement it!!!");
return 0;
}
@Override
public int getNumberOfLocalTracks() {
// TODO Auto-generated method stub
logger.warn("implement it!!!");
return 0;
}
@Override
public void deleteAllLocalTracks() {
// TODO Auto-generated method stub
logger.warn("implement it!!!");
}
@Override
public void deleteAllRemoteTracks() {
// TODO Auto-generated method stub
logger.warn("implement it!!!");
}
@Override
public List<Track> getAllLocalTracks() {
ArrayList<Track> tracks = new ArrayList<Track>();
Cursor c = mDb.query(TABLE_TRACK, ALL_TRACK_KEYS, KEY_TRACK_REMOTE + " IS NULL", null, null, null, null);
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
tracks.add(getTrack(c.getLong(c.getColumnIndex(KEY_TRACK_ID))));
c.moveToNext();
}
c.close();
return tracks;
}
private ContentValues createDbEntry(Track track) {
ContentValues values = new ContentValues();
if (track.getId() != 0) {
values.put(KEY_TRACK_ID, track.getId());
}
values.put(KEY_TRACK_NAME, track.getName());
values.put(KEY_TRACK_DESCRIPTION, track.getDescription());
values.put(KEY_TRACK_REMOTE, track.getRemoteID());
if (track.getCar() != null) {
values.put(KEY_TRACK_CAR_MANUFACTURER, track.getCar().getManufacturer());
values.put(KEY_TRACK_CAR_MODEL, track.getCar().getModel());
values.put(KEY_TRACK_CAR_FUEL_TYPE, track.getCar().getFuelType().name());
values.put(KEY_TRACK_CAR_VIN, track.getVin());
values.put(KEY_TRACK_CAR_ID, track.getCar().getId());
values.put(KEY_TRACK_CAR_ENGINE_DISPLACEMENT, track.getCar().getEngineDisplacement());
}
return values;
}
private JSONObject createJsonObjectForProperties(Measurement measurement) {
HashMap<String, Double> map = new HashMap<String, Double>();
Map<PropertyKey, Double> properties = measurement.getAllProperties();
for (PropertyKey key : properties.keySet()) {
map.put(key.name(), properties.get(key));
}
return new JSONObject(map);
}
private Cursor getCursorForTrackID(long id) {
Cursor cursor = mDb.query(TABLE_TRACK, ALL_TRACK_KEYS, KEY_TRACK_ID + " = \"" + id + "\"", null, null, null, null);
return cursor;
}
private ArrayList<Measurement> getAllMeasurementsForTrack(Track track) {
ArrayList<Measurement> allMeasurements = new ArrayList<Measurement>();
Cursor c = mDb.query(TABLE_MEASUREMENT, ALL_MEASUREMENT_KEYS,
KEY_MEASUREMENT_TRACK + "=\"" + track.getId() + "\"", null, null, null, KEY_MEASUREMENT_TIME + " ASC");
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
String lat = c.getString(c.getColumnIndex(KEY_MEASUREMENT_LATITUDE));
String lon = c.getString(c.getColumnIndex(KEY_MEASUREMENT_LONGITUDE));
String time = c.getString(c.getColumnIndex(KEY_MEASUREMENT_TIME));
String rawData = c.getString(c.getColumnIndex(KEY_MEASUREMENT_PROPERTIES));
Measurement measurement = new Measurement(Float.valueOf(lat), Float.valueOf(lon));
measurement.setTime(Long.valueOf(time));
measurement.setTrack(track);
try {
JSONObject json = new JSONObject(rawData);
JSONArray names = json.names();
- for (int j = 0; j < names.length(); j++) {
- String key = names.getString(j);
- measurement.addProperty(PropertyKey.valueOf(key), json.getDouble(key));
+ if (names != null) {
+ for (int j = 0; j < names.length(); j++) {
+ String key = names.getString(j);
+ measurement.addProperty(PropertyKey.valueOf(key), json.getDouble(key));
+ }
}
} catch (JSONException e) {
logger.severe("could not load properties", e);
}
allMeasurements.add(measurement);
c.moveToNext();
}
c.close();
return allMeasurements;
}
}
| true | true | private ArrayList<Measurement> getAllMeasurementsForTrack(Track track) {
ArrayList<Measurement> allMeasurements = new ArrayList<Measurement>();
Cursor c = mDb.query(TABLE_MEASUREMENT, ALL_MEASUREMENT_KEYS,
KEY_MEASUREMENT_TRACK + "=\"" + track.getId() + "\"", null, null, null, KEY_MEASUREMENT_TIME + " ASC");
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
String lat = c.getString(c.getColumnIndex(KEY_MEASUREMENT_LATITUDE));
String lon = c.getString(c.getColumnIndex(KEY_MEASUREMENT_LONGITUDE));
String time = c.getString(c.getColumnIndex(KEY_MEASUREMENT_TIME));
String rawData = c.getString(c.getColumnIndex(KEY_MEASUREMENT_PROPERTIES));
Measurement measurement = new Measurement(Float.valueOf(lat), Float.valueOf(lon));
measurement.setTime(Long.valueOf(time));
measurement.setTrack(track);
try {
JSONObject json = new JSONObject(rawData);
JSONArray names = json.names();
for (int j = 0; j < names.length(); j++) {
String key = names.getString(j);
measurement.addProperty(PropertyKey.valueOf(key), json.getDouble(key));
}
} catch (JSONException e) {
logger.severe("could not load properties", e);
}
allMeasurements.add(measurement);
c.moveToNext();
}
c.close();
return allMeasurements;
}
| private ArrayList<Measurement> getAllMeasurementsForTrack(Track track) {
ArrayList<Measurement> allMeasurements = new ArrayList<Measurement>();
Cursor c = mDb.query(TABLE_MEASUREMENT, ALL_MEASUREMENT_KEYS,
KEY_MEASUREMENT_TRACK + "=\"" + track.getId() + "\"", null, null, null, KEY_MEASUREMENT_TIME + " ASC");
c.moveToFirst();
for (int i = 0; i < c.getCount(); i++) {
String lat = c.getString(c.getColumnIndex(KEY_MEASUREMENT_LATITUDE));
String lon = c.getString(c.getColumnIndex(KEY_MEASUREMENT_LONGITUDE));
String time = c.getString(c.getColumnIndex(KEY_MEASUREMENT_TIME));
String rawData = c.getString(c.getColumnIndex(KEY_MEASUREMENT_PROPERTIES));
Measurement measurement = new Measurement(Float.valueOf(lat), Float.valueOf(lon));
measurement.setTime(Long.valueOf(time));
measurement.setTrack(track);
try {
JSONObject json = new JSONObject(rawData);
JSONArray names = json.names();
if (names != null) {
for (int j = 0; j < names.length(); j++) {
String key = names.getString(j);
measurement.addProperty(PropertyKey.valueOf(key), json.getDouble(key));
}
}
} catch (JSONException e) {
logger.severe("could not load properties", e);
}
allMeasurements.add(measurement);
c.moveToNext();
}
c.close();
return allMeasurements;
}
|
diff --git a/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java b/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
index 30d3a4e07..4ff2527cd 100644
--- a/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
+++ b/src/main/org/codehaus/groovy/tools/javac/JavaStubGenerator.java
@@ -1,727 +1,734 @@
/*
* Copyright 2003-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.tools.javac;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.ListExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.control.ResolveVisitor;
import org.codehaus.groovy.tools.Utilities;
import org.objectweb.asm.Opcodes;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class JavaStubGenerator
{
private boolean java5 = false;
private boolean requireSuperResolved = false;
private File outputPath;
private List<String> toCompile = new ArrayList<String>();
private ArrayList<MethodNode> propertyMethods = new ArrayList<MethodNode>();
private Map<String, MethodNode> propertyMethodsWithSigs = new HashMap<String, MethodNode>();
private ArrayList<ConstructorNode> constructors = new ArrayList<ConstructorNode>();
private ModuleNode currentModule;
public JavaStubGenerator(final File outputPath, final boolean requireSuperResolved, final boolean java5) {
this.outputPath = outputPath;
this.requireSuperResolved = requireSuperResolved;
this.java5 = java5;
outputPath.mkdirs();
}
public JavaStubGenerator(final File outputPath) {
this(outputPath, false, false);
}
private void mkdirs(File parent, String relativeFile) {
int index = relativeFile.lastIndexOf('/');
if (index==-1) return;
File dir = new File(parent,relativeFile.substring(0,index));
dir.mkdirs();
}
public void generateClass(ClassNode classNode) throws FileNotFoundException {
// Only attempt to render our self if our super-class is resolved, else wait for it
if (requireSuperResolved && !classNode.getSuperClass().isResolved()) {
return;
}
// owner should take care for us
if (classNode instanceof InnerClassNode)
return;
// don't generate stubs for private classes, as they are only visible in the same file
if ((classNode.getModifiers() & Opcodes.ACC_PRIVATE) != 0) return;
String fileName = classNode.getName().replace('.', '/');
mkdirs(outputPath,fileName);
toCompile.add(fileName);
File file = new File(outputPath, fileName + ".java");
FileOutputStream fos = new FileOutputStream(file);
PrintWriter out = new PrintWriter(fos);
try {
String packageName = classNode.getPackageName();
if (packageName != null) {
out.println("package " + packageName + ";\n");
}
genImports(classNode, out);
genClassInner(classNode, out);
} finally {
try {
out.close();
} catch (Exception e) {
// ignore
}
try {
fos.close();
} catch (IOException e) {
// ignore
}
}
}
private void genClassInner(ClassNode classNode, PrintWriter out) throws FileNotFoundException {
if (classNode instanceof InnerClassNode && ((InnerClassNode) classNode).isAnonymous()) {
// if it is an anonymous inner class, don't generate the stub code for it.
return;
}
try {
Verifier verifier = new Verifier() {
public void addCovariantMethods(ClassNode cn) {}
protected void addTimeStamp(ClassNode node) {}
protected void addInitialization(ClassNode node) {}
protected void addPropertyMethod(MethodNode method) {
doAddMethod(method);
}
protected void addReturnIfNeeded(MethodNode node) {}
protected void addMethod(ClassNode node, boolean shouldBeSynthetic, String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) {
doAddMethod(new MethodNode(name, modifiers, returnType, parameters, exceptions, code));
}
protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode node) {
- constructors.add(new ConstructorNode(ctor.getModifiers(), newParams, ctor.getExceptions(), code));
+ if(code instanceof ExpressionStatement) {//GROOVY-4508
+ Statement temp = code;
+ code = new BlockStatement();
+ ((BlockStatement)code).addStatement(temp);
+ }
+ ConstructorNode ctrNode = new ConstructorNode(ctor.getModifiers(), newParams, ctor.getExceptions(), code);
+ ctrNode.setDeclaringClass(node);
+ constructors.add(ctrNode);
}
protected void addDefaultParameters(DefaultArgsAction action, MethodNode method) {
final Parameter[] parameters = method.getParameters();
final Expression [] saved = new Expression[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].hasInitialExpression())
saved[i] = parameters[i].getInitialExpression();
}
super.addDefaultParameters(action, method);
for (int i = 0; i < parameters.length; i++) {
if (saved[i] != null)
parameters[i].setInitialExpression(saved[i]);
}
}
private void doAddMethod(MethodNode method) {
String sig = method.getTypeDescriptor();
if(propertyMethodsWithSigs.containsKey(sig)) return;
propertyMethods.add(method);
propertyMethodsWithSigs.put(sig, method);
}
};
verifier.visitClass(classNode);
currentModule = classNode.getModule();
boolean isInterface = classNode.isInterface();
boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) !=0;
boolean isAnnotationDefinition = classNode.isAnnotationDefinition();
printAnnotations(out, classNode);
printModifiers(out, classNode.getModifiers()
& ~(isInterface ? Opcodes.ACC_ABSTRACT : 0));
if (isInterface) {
if(isAnnotationDefinition) {
out.print ("@");
}
out.print ("interface ");
} else if (isEnum) {
out.print ("enum ");
} else {
out.print ("class ");
}
String className = classNode.getNameWithoutPackage();
if (classNode instanceof InnerClassNode)
className = className.substring(className.lastIndexOf("$")+1);
out.println(className);
writeGenericsBounds(out, classNode, true);
ClassNode superClass = classNode.getUnresolvedSuperClass(false);
if (!isInterface && !isEnum) {
out.print(" extends ");
printType(superClass,out);
}
ClassNode[] interfaces = classNode.getInterfaces();
if (interfaces != null && interfaces.length > 0 && !isAnnotationDefinition) {
if (isInterface) {
out.println(" extends");
} else {
out.println(" implements");
}
for (int i = 0; i < interfaces.length - 1; ++i) {
out.print(" ");
printType(interfaces[i], out);
out.print(",");
}
out.print(" ");
printType(interfaces[interfaces.length - 1],out);
}
out.println(" {");
genFields(classNode, out);
genMethods(classNode, out, isEnum);
for (Iterator<InnerClassNode> inner = classNode.getInnerClasses(); inner.hasNext();) {
// GROOVY-4004: Clear the methods from the outer class so that they don't get duplicated in inner ones
propertyMethods.clear();
propertyMethodsWithSigs.clear();
constructors.clear();
genClassInner(inner.next(), out);
}
out.println("}");
}
finally {
propertyMethods.clear();
propertyMethodsWithSigs.clear();
constructors.clear();
currentModule = null;
}
}
private void genMethods(ClassNode classNode, PrintWriter out, boolean isEnum) {
if (!isEnum) getConstructors(classNode, out);
@SuppressWarnings("unchecked")
List<MethodNode> methods = (List)propertyMethods.clone();
methods.addAll(classNode.getMethods());
for (MethodNode method : methods) {
if (isEnum && method.isSynthetic()) {
// skip values() method and valueOf(String)
String name = method.getName();
Parameter[] params = method.getParameters();
if (name.equals("values") && params.length == 0) continue;
if (name.equals("valueOf") &&
params.length == 1 &&
params[0].getType().equals(ClassHelper.STRING_TYPE)) {
continue;
}
}
genMethod(classNode, method, out);
}
}
private void getConstructors(ClassNode classNode, PrintWriter out) {
List<ConstructorNode> constrs = (List<ConstructorNode>) constructors.clone();
constrs.addAll(classNode.getDeclaredConstructors());
if (constrs != null)
for (ConstructorNode constr : constrs) {
genConstructor(classNode, constr, out);
}
}
private void genFields(ClassNode classNode, PrintWriter out) {
boolean isInterface = classNode.isInterface();
List<FieldNode> fields = classNode.getFields();
if (fields == null) return;
List<FieldNode> enumFields = new ArrayList<FieldNode>(fields.size());
List<FieldNode> normalFields = new ArrayList<FieldNode>(fields.size());
for (FieldNode field : fields) {
boolean isSynthetic = (field.getModifiers() & Opcodes.ACC_SYNTHETIC) != 0;
if (field.isEnum()) {
enumFields.add(field);
} else if (!isSynthetic) {
normalFields.add(field);
}
}
genEnumFields(enumFields, out);
for (FieldNode normalField : normalFields) {
genField(normalField, out, isInterface);
}
}
private void genEnumFields(List<FieldNode> fields, PrintWriter out) {
if (fields.size()==0) return;
boolean first = true;
for (FieldNode field : fields) {
if (!first) {
out.print(", ");
} else {
first = false;
}
out.print(field.getName());
}
out.println(";");
}
private void genField(FieldNode fieldNode, PrintWriter out, boolean isInterface) {
if ((fieldNode.getModifiers()&Opcodes.ACC_PRIVATE)!=0) return;
printAnnotations(out, fieldNode);
if (!isInterface) {
printModifiers(out, fieldNode.getModifiers());
}
ClassNode type = fieldNode.getType();
printType(type, out);
out.print(" ");
out.print(fieldNode.getName());
if (isInterface) {
out.print(" = ");
if (ClassHelper.isPrimitiveType(type)) {
String val = type == ClassHelper.boolean_TYPE ? "false" : "0";
out.print("new " + ClassHelper.getWrapper(type) + "((" + type + ")" + val + ")");
} else {
out.print("null");
}
}
out.println(";");
}
private ConstructorCallExpression getConstructorCallExpression(
ConstructorNode constructorNode) {
Statement code = constructorNode.getCode();
if (!(code instanceof BlockStatement))
return null;
BlockStatement block = (BlockStatement) code;
List stats = block.getStatements();
if (stats == null || stats.size() == 0)
return null;
Statement stat = (Statement) stats.get(0);
if (!(stat instanceof ExpressionStatement))
return null;
Expression expr = ((ExpressionStatement) stat).getExpression();
if (!(expr instanceof ConstructorCallExpression))
return null;
return (ConstructorCallExpression) expr;
}
private void genConstructor(ClassNode clazz, ConstructorNode constructorNode, PrintWriter out) {
printAnnotations(out, constructorNode);
// printModifiers(out, constructorNode.getModifiers());
out.print("public "); // temporary hack
String className = clazz.getNameWithoutPackage();
if (clazz instanceof InnerClassNode)
className = className.substring(className.lastIndexOf("$")+1);
out.println(className);
printParams(constructorNode, out);
ConstructorCallExpression constrCall = getConstructorCallExpression(constructorNode);
if (constrCall == null || !constrCall.isSpecialCall()) {
out.println(" {}");
} else {
out.println(" {");
genSpecialConstructorArgs(out, constructorNode, constrCall);
out.println("}");
}
}
private Parameter[] selectAccessibleConstructorFromSuper(ConstructorNode node) {
ClassNode type = node.getDeclaringClass();
ClassNode superType = type.getSuperClass();
for (ConstructorNode c : superType.getDeclaredConstructors()) {
// Only look at things we can actually call
if (c.isPublic() || c.isProtected()) {
return c.getParameters();
}
}
// fall back for parameterless constructor
if (superType.isPrimaryClassNode()) {
return Parameter.EMPTY_ARRAY;
}
return null;
}
private void genSpecialConstructorArgs(PrintWriter out, ConstructorNode node, ConstructorCallExpression constrCall) {
// Select a constructor from our class, or super-class which is legal to call,
// then write out an invoke w/nulls using casts to avoid ambiguous crapo
Parameter[] params = selectAccessibleConstructorFromSuper(node);
if (params != null) {
out.print("super (");
for (int i=0; i<params.length; i++) {
printDefaultValue(out, params[i].getType());
if (i + 1 < params.length) {
out.print(", ");
}
}
out.println(");");
return;
}
// Otherwise try the older method based on the constructor's call expression
Expression arguments = constrCall.getArguments();
if (constrCall.isSuperCall()) {
out.print("super(");
}
else {
out.print("this(");
}
// Else try to render some arguments
if (arguments instanceof ArgumentListExpression) {
ArgumentListExpression argumentListExpression = (ArgumentListExpression) arguments;
List<Expression> args = argumentListExpression.getExpressions();
for (Expression arg : args) {
if (arg instanceof ConstantExpression) {
ConstantExpression expression = (ConstantExpression) arg;
Object o = expression.getValue();
if (o instanceof String) {
out.print("(String)null");
} else {
out.print(expression.getText());
}
} else {
ClassNode type = getConstructorArgumentType(arg, node);
printDefaultValue(out, type);
}
if (arg != args.get(args.size() - 1)) {
out.print(", ");
}
}
}
out.println(");");
}
private ClassNode getConstructorArgumentType(Expression arg, ConstructorNode node) {
if (!(arg instanceof VariableExpression)) return arg.getType();
VariableExpression vexp = (VariableExpression) arg;
String name = vexp.getName();
for (Parameter param : node.getParameters()) {
if (param.getName().equals(name)) {
return param.getType();
}
}
return vexp.getType();
}
private void genMethod(ClassNode clazz, MethodNode methodNode, PrintWriter out) {
if (methodNode.getName().equals("<clinit>")) return;
if (methodNode.isPrivate() || !Utilities.isJavaIdentifier(methodNode.getName())) return;
if (methodNode.isSynthetic() && methodNode.getName().equals("$getStaticMetaClass")) return;
printAnnotations(out, methodNode);
if (!clazz.isInterface()) printModifiers(out, methodNode.getModifiers());
writeGenericsBounds(out, methodNode.getGenericsTypes());
out.print(" ");
printType(methodNode.getReturnType(), out);
out.print(" ");
out.print(methodNode.getName());
printParams(methodNode, out);
ClassNode[] exceptions = methodNode.getExceptions();
for (int i=0; i<exceptions.length; i++) {
ClassNode exception = exceptions[i];
if (i==0) {
out.print("throws ");
} else {
out.print(", ");
}
printType(exception,out);
}
if ((methodNode.getModifiers() & Opcodes.ACC_ABSTRACT) != 0) {
out.println(";");
} else {
out.print(" { ");
ClassNode retType = methodNode.getReturnType();
printReturn(out, retType);
out.println("}");
}
}
private void printReturn(PrintWriter out, ClassNode retType) {
String retName = retType.getName();
if (!retName.equals("void")) {
out.print("return ");
printDefaultValue(out, retType);
out.print(";");
}
}
private void printDefaultValue(PrintWriter out, ClassNode type) {
if (type.redirect()!=ClassHelper.OBJECT_TYPE) {
out.print("(");
printType(type,out);
out.print(")");
}
if (ClassHelper.isPrimitiveType(type)) {
if (type==ClassHelper.boolean_TYPE){
out.print("false");
} else {
out.print("0");
}
} else {
out.print("null");
}
}
private void printType(ClassNode type, PrintWriter out) {
if (type.isArray()) {
printType(type.getComponentType(),out);
out.print("[]");
} else if (java5 && type.isGenericsPlaceHolder()) {
out.print(type.getGenericsTypes()[0].getName());
} else {
writeGenericsBounds(out,type,false);
}
}
private void printTypeName(ClassNode type, PrintWriter out) {
if (ClassHelper.isPrimitiveType(type)) {
if (type==ClassHelper.boolean_TYPE) {
out.print("boolean");
} else if (type==ClassHelper.char_TYPE) {
out.print("char");
} else if (type==ClassHelper.int_TYPE) {
out.print("int");
} else if (type==ClassHelper.short_TYPE) {
out.print("short");
} else if (type==ClassHelper.long_TYPE) {
out.print("long");
} else if (type==ClassHelper.float_TYPE) {
out.print("float");
} else if (type==ClassHelper.double_TYPE) {
out.print("double");
} else if (type==ClassHelper.byte_TYPE) {
out.print("byte");
} else {
out.print("void");
}
} else {
String name = type.getName();
// check for an alias
ClassNode alias = currentModule.getImportType(name);
if (alias != null) name = alias.getName();
out.print(name.replace('$', '.'));
}
}
private void writeGenericsBounds(PrintWriter out, ClassNode type, boolean skipName) {
if (!skipName) printTypeName(type,out);
if (!java5) return;
if (!ClassHelper.isCachedType(type)) {
writeGenericsBounds(out,type.getGenericsTypes());
}
}
private void writeGenericsBounds(PrintWriter out, GenericsType[] genericsTypes) {
if (genericsTypes==null || genericsTypes.length==0) return;
out.print('<');
for (int i = 0; i < genericsTypes.length; i++) {
if (i!=0) out.print(", ");
writeGenericsBounds(out,genericsTypes[i]);
}
out.print('>');
}
private void writeGenericsBounds(PrintWriter out, GenericsType genericsType) {
if (genericsType.isPlaceholder()) {
out.print(genericsType.getName());
} else {
printType(genericsType.getType(),out);
}
ClassNode[] upperBounds = genericsType.getUpperBounds();
ClassNode lowerBound = genericsType.getLowerBound();
if (upperBounds != null) {
out.print(" extends ");
for (int i = 0; i < upperBounds.length; i++) {
printType(upperBounds[i], out);
if (i + 1 < upperBounds.length) out.print(" & ");
}
} else if (lowerBound != null) {
out.print(" super ");
printType(lowerBound, out);
}
}
private void printParams(MethodNode methodNode, PrintWriter out) {
out.print("(");
Parameter[] parameters = methodNode.getParameters();
if (parameters != null && parameters.length != 0) {
for (int i = 0; i != parameters.length; ++i) {
printType(parameters[i].getType(), out);
out.print(" ");
out.print(parameters[i].getName());
if (i + 1 < parameters.length) {
out.print(", ");
}
}
}
out.print(")");
}
private void printAnnotations(PrintWriter out, AnnotatedNode annotated) {
if (!java5) return;
for (AnnotationNode annotation : annotated.getAnnotations()) {
out.print("@" + annotation.getClassNode().getName() + "(");
boolean first = true;
Map<String, Expression> members = annotation.getMembers();
for (String key : members.keySet()) {
if (first) first = false;
else out.print(", ");
out.print(key + "=" + getAnnotationValue(members.get(key)));
}
out.print(") ");
}
}
private String getAnnotationValue(Object memberValue) {
String val = "null";
if (memberValue instanceof ListExpression) {
StringBuilder sb = new StringBuilder("{");
boolean first = true;
ListExpression le = (ListExpression) memberValue;
for (Expression e : le.getExpressions()) {
if (first) first = false;
else sb.append(",");
sb.append(getAnnotationValue(e));
}
sb.append("}");
val = sb.toString();
} else if (memberValue instanceof ConstantExpression) {
ConstantExpression ce = (ConstantExpression) memberValue;
Object constValue = ce.getValue();
if (constValue instanceof Number || constValue instanceof Boolean)
val = constValue.toString();
else
val = "\"" + constValue + "\"";
} else if (memberValue instanceof PropertyExpression || memberValue instanceof VariableExpression) {
// assume must be static class field or enum value or class that Java can resolve
val = ((Expression) memberValue).getText();
} else if (memberValue instanceof ClosureExpression) {
// annotation closure; replaced with this specific class literal to cover the
// case where annotation type uses Class<? extends Closure> for the closure's type
val = "groovy.lang.Closure.class";
} else if (memberValue instanceof ClassExpression) {
val = ((Expression) memberValue).getText() + ".class";
}
return val;
}
private void printModifiers(PrintWriter out, int modifiers) {
if ((modifiers & Opcodes.ACC_PUBLIC) != 0)
out.print("public ");
if ((modifiers & Opcodes.ACC_PROTECTED) != 0)
out.print("protected ");
if ((modifiers & Opcodes.ACC_PRIVATE) != 0)
out.print("private ");
if ((modifiers & Opcodes.ACC_STATIC) != 0)
out.print("static ");
if ((modifiers & Opcodes.ACC_SYNCHRONIZED) != 0)
out.print("synchronized ");
if ((modifiers & Opcodes.ACC_ABSTRACT) != 0)
out.print("abstract ");
}
private void genImports(ClassNode classNode, PrintWriter out) {
List<String> imports = new ArrayList<String>();
ModuleNode moduleNode = classNode.getModule();
for (ImportNode importNode : moduleNode.getStarImports()) {
imports.add(importNode.getPackageName());
}
for (ImportNode imp : moduleNode.getImports()) {
if (imp.getAlias() == null)
imports.add(imp.getType().getName());
}
imports.addAll(Arrays.asList(ResolveVisitor.DEFAULT_IMPORTS));
for (String imp : imports) {
String s = new StringBuilder()
.append("import ")
.append(imp)
.append((imp.charAt(imp.length() - 1) == '.') ? "*;" : ";")
.toString()
.replace('$', '.');
out.println(s);
}
out.println();
}
public void clean() {
for (String path : toCompile) {
new File(outputPath, path + ".java").delete();
}
}
}
| true | true | private void genClassInner(ClassNode classNode, PrintWriter out) throws FileNotFoundException {
if (classNode instanceof InnerClassNode && ((InnerClassNode) classNode).isAnonymous()) {
// if it is an anonymous inner class, don't generate the stub code for it.
return;
}
try {
Verifier verifier = new Verifier() {
public void addCovariantMethods(ClassNode cn) {}
protected void addTimeStamp(ClassNode node) {}
protected void addInitialization(ClassNode node) {}
protected void addPropertyMethod(MethodNode method) {
doAddMethod(method);
}
protected void addReturnIfNeeded(MethodNode node) {}
protected void addMethod(ClassNode node, boolean shouldBeSynthetic, String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) {
doAddMethod(new MethodNode(name, modifiers, returnType, parameters, exceptions, code));
}
protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode node) {
constructors.add(new ConstructorNode(ctor.getModifiers(), newParams, ctor.getExceptions(), code));
}
protected void addDefaultParameters(DefaultArgsAction action, MethodNode method) {
final Parameter[] parameters = method.getParameters();
final Expression [] saved = new Expression[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].hasInitialExpression())
saved[i] = parameters[i].getInitialExpression();
}
super.addDefaultParameters(action, method);
for (int i = 0; i < parameters.length; i++) {
if (saved[i] != null)
parameters[i].setInitialExpression(saved[i]);
}
}
private void doAddMethod(MethodNode method) {
String sig = method.getTypeDescriptor();
if(propertyMethodsWithSigs.containsKey(sig)) return;
propertyMethods.add(method);
propertyMethodsWithSigs.put(sig, method);
}
};
verifier.visitClass(classNode);
currentModule = classNode.getModule();
boolean isInterface = classNode.isInterface();
boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) !=0;
boolean isAnnotationDefinition = classNode.isAnnotationDefinition();
printAnnotations(out, classNode);
printModifiers(out, classNode.getModifiers()
& ~(isInterface ? Opcodes.ACC_ABSTRACT : 0));
if (isInterface) {
if(isAnnotationDefinition) {
out.print ("@");
}
out.print ("interface ");
} else if (isEnum) {
out.print ("enum ");
} else {
out.print ("class ");
}
String className = classNode.getNameWithoutPackage();
if (classNode instanceof InnerClassNode)
className = className.substring(className.lastIndexOf("$")+1);
out.println(className);
writeGenericsBounds(out, classNode, true);
ClassNode superClass = classNode.getUnresolvedSuperClass(false);
if (!isInterface && !isEnum) {
out.print(" extends ");
printType(superClass,out);
}
ClassNode[] interfaces = classNode.getInterfaces();
if (interfaces != null && interfaces.length > 0 && !isAnnotationDefinition) {
if (isInterface) {
out.println(" extends");
} else {
out.println(" implements");
}
for (int i = 0; i < interfaces.length - 1; ++i) {
out.print(" ");
printType(interfaces[i], out);
out.print(",");
}
out.print(" ");
printType(interfaces[interfaces.length - 1],out);
}
out.println(" {");
genFields(classNode, out);
genMethods(classNode, out, isEnum);
for (Iterator<InnerClassNode> inner = classNode.getInnerClasses(); inner.hasNext();) {
// GROOVY-4004: Clear the methods from the outer class so that they don't get duplicated in inner ones
propertyMethods.clear();
propertyMethodsWithSigs.clear();
constructors.clear();
genClassInner(inner.next(), out);
}
out.println("}");
}
finally {
propertyMethods.clear();
propertyMethodsWithSigs.clear();
constructors.clear();
currentModule = null;
}
}
| private void genClassInner(ClassNode classNode, PrintWriter out) throws FileNotFoundException {
if (classNode instanceof InnerClassNode && ((InnerClassNode) classNode).isAnonymous()) {
// if it is an anonymous inner class, don't generate the stub code for it.
return;
}
try {
Verifier verifier = new Verifier() {
public void addCovariantMethods(ClassNode cn) {}
protected void addTimeStamp(ClassNode node) {}
protected void addInitialization(ClassNode node) {}
protected void addPropertyMethod(MethodNode method) {
doAddMethod(method);
}
protected void addReturnIfNeeded(MethodNode node) {}
protected void addMethod(ClassNode node, boolean shouldBeSynthetic, String name, int modifiers, ClassNode returnType, Parameter[] parameters, ClassNode[] exceptions, Statement code) {
doAddMethod(new MethodNode(name, modifiers, returnType, parameters, exceptions, code));
}
protected void addConstructor(Parameter[] newParams, ConstructorNode ctor, Statement code, ClassNode node) {
if(code instanceof ExpressionStatement) {//GROOVY-4508
Statement temp = code;
code = new BlockStatement();
((BlockStatement)code).addStatement(temp);
}
ConstructorNode ctrNode = new ConstructorNode(ctor.getModifiers(), newParams, ctor.getExceptions(), code);
ctrNode.setDeclaringClass(node);
constructors.add(ctrNode);
}
protected void addDefaultParameters(DefaultArgsAction action, MethodNode method) {
final Parameter[] parameters = method.getParameters();
final Expression [] saved = new Expression[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].hasInitialExpression())
saved[i] = parameters[i].getInitialExpression();
}
super.addDefaultParameters(action, method);
for (int i = 0; i < parameters.length; i++) {
if (saved[i] != null)
parameters[i].setInitialExpression(saved[i]);
}
}
private void doAddMethod(MethodNode method) {
String sig = method.getTypeDescriptor();
if(propertyMethodsWithSigs.containsKey(sig)) return;
propertyMethods.add(method);
propertyMethodsWithSigs.put(sig, method);
}
};
verifier.visitClass(classNode);
currentModule = classNode.getModule();
boolean isInterface = classNode.isInterface();
boolean isEnum = (classNode.getModifiers() & Opcodes.ACC_ENUM) !=0;
boolean isAnnotationDefinition = classNode.isAnnotationDefinition();
printAnnotations(out, classNode);
printModifiers(out, classNode.getModifiers()
& ~(isInterface ? Opcodes.ACC_ABSTRACT : 0));
if (isInterface) {
if(isAnnotationDefinition) {
out.print ("@");
}
out.print ("interface ");
} else if (isEnum) {
out.print ("enum ");
} else {
out.print ("class ");
}
String className = classNode.getNameWithoutPackage();
if (classNode instanceof InnerClassNode)
className = className.substring(className.lastIndexOf("$")+1);
out.println(className);
writeGenericsBounds(out, classNode, true);
ClassNode superClass = classNode.getUnresolvedSuperClass(false);
if (!isInterface && !isEnum) {
out.print(" extends ");
printType(superClass,out);
}
ClassNode[] interfaces = classNode.getInterfaces();
if (interfaces != null && interfaces.length > 0 && !isAnnotationDefinition) {
if (isInterface) {
out.println(" extends");
} else {
out.println(" implements");
}
for (int i = 0; i < interfaces.length - 1; ++i) {
out.print(" ");
printType(interfaces[i], out);
out.print(",");
}
out.print(" ");
printType(interfaces[interfaces.length - 1],out);
}
out.println(" {");
genFields(classNode, out);
genMethods(classNode, out, isEnum);
for (Iterator<InnerClassNode> inner = classNode.getInnerClasses(); inner.hasNext();) {
// GROOVY-4004: Clear the methods from the outer class so that they don't get duplicated in inner ones
propertyMethods.clear();
propertyMethodsWithSigs.clear();
constructors.clear();
genClassInner(inner.next(), out);
}
out.println("}");
}
finally {
propertyMethods.clear();
propertyMethodsWithSigs.clear();
constructors.clear();
currentModule = null;
}
}
|
diff --git a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/support/GrailsOpenSessionInViewInterceptor.java b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/support/GrailsOpenSessionInViewInterceptor.java
index b646453fb..0d3d8856b 100644
--- a/src/persistence/org/codehaus/groovy/grails/orm/hibernate/support/GrailsOpenSessionInViewInterceptor.java
+++ b/src/persistence/org/codehaus/groovy/grails/orm/hibernate/support/GrailsOpenSessionInViewInterceptor.java
@@ -1,82 +1,85 @@
/* Copyright 2004-2005 Graeme Rocher
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.orm.hibernate.support;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.WebRequest;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* An interceptor that extends the default spring OSIVI and doesn't flush the session if it has been set
* to MANUAL on the session itself
*
* @author Graeme Rocher
* @since 0.5
*
* <p/>
* Created: Feb 2, 2007
* Time: 12:24:11 AM
*/
public class GrailsOpenSessionInViewInterceptor extends OpenSessionInViewInterceptor {
private static final String IS_FLOW_REQUEST_ATTRIBUTE = "org.codehaus.groovy.grails.webflow.flow_request";
public void preHandle(WebRequest request) throws DataAccessException {
GrailsWebRequest webRequest = (GrailsWebRequest) request.getAttribute(GrailsApplicationAttributes.WEB_REQUEST, WebRequest.SCOPE_REQUEST);
final boolean isFlowRequest = webRequest.isFlowRequest();
if(isFlowRequest) {
webRequest.setAttribute(IS_FLOW_REQUEST_ATTRIBUTE, "true", WebRequest.SCOPE_REQUEST);
}
else {
super.preHandle(request);
}
}
public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
final boolean isFlowRequest = request.getAttribute(IS_FLOW_REQUEST_ATTRIBUTE, WebRequest.SCOPE_REQUEST) != null;
if(!isFlowRequest) {
- super.postHandle(request, model);
- SessionHolder sessionHolder =
- (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
+ try {
+ super.postHandle(request, model);
+ } finally {
+ SessionHolder sessionHolder =
+ (SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
- Session session = sessionHolder.getSession();
- session.setFlushMode(FlushMode.MANUAL);
+ Session session = sessionHolder.getSession();
+ session.setFlushMode(FlushMode.MANUAL);
+ }
}
}
public void afterCompletion(WebRequest request, Exception ex) throws DataAccessException {
final boolean isWebRequest = request.getAttribute(IS_FLOW_REQUEST_ATTRIBUTE, WebRequest.SCOPE_REQUEST) != null;
if(!isWebRequest) {
super.afterCompletion(request, ex);
}
}
protected void flushIfNecessary(Session session, boolean existingTransaction) throws HibernateException {
if(session != null && session.getFlushMode() != FlushMode.MANUAL) {
super.flushIfNecessary(session, existingTransaction);
}
}
}
| false | true | public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
final boolean isFlowRequest = request.getAttribute(IS_FLOW_REQUEST_ATTRIBUTE, WebRequest.SCOPE_REQUEST) != null;
if(!isFlowRequest) {
super.postHandle(request, model);
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
Session session = sessionHolder.getSession();
session.setFlushMode(FlushMode.MANUAL);
}
}
| public void postHandle(WebRequest request, ModelMap model) throws DataAccessException {
final boolean isFlowRequest = request.getAttribute(IS_FLOW_REQUEST_ATTRIBUTE, WebRequest.SCOPE_REQUEST) != null;
if(!isFlowRequest) {
try {
super.postHandle(request, model);
} finally {
SessionHolder sessionHolder =
(SessionHolder) TransactionSynchronizationManager.getResource(getSessionFactory());
Session session = sessionHolder.getSession();
session.setFlushMode(FlushMode.MANUAL);
}
}
}
|
diff --git a/WEB-INF/src/com/github/tosdan/utils/sql/MassiveQueryCompiler.java b/WEB-INF/src/com/github/tosdan/utils/sql/MassiveQueryCompiler.java
index f956d6e..4127a15 100644
--- a/WEB-INF/src/com/github/tosdan/utils/sql/MassiveQueryCompiler.java
+++ b/WEB-INF/src/com/github/tosdan/utils/sql/MassiveQueryCompiler.java
@@ -1,172 +1,173 @@
package com.github.tosdan.utils.sql;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.github.tosdan.utils.stringhe.MapFormatTypeValidator;
import com.github.tosdan.utils.stringhe.MapFormatTypeValidatorSQL;
import com.github.tosdan.utils.stringhe.TemplateCompiler;
import com.github.tosdan.utils.stringhe.TemplateCompilerException;
import com.github.tosdan.utils.stringhe.TemplatePicker;
/**
*
* @author Daniele
* @version 0.1.0-b2013-06-28
*/
public class MassiveQueryCompiler
{
/*************************************************************************/
/******************* Campi ***********************/
/*************************************************************************/
private List<Map<String, Object>> shiftingParamsMapsList;
private Map<String, String> repositoryIndex;
private String queriesRepoFolderPath;
private MapFormatTypeValidator validator;
private String templateAsString;
/**
* Oggetto che sia in grado di interpretare i dati forniti al fine di trovare il template contenutovi.
*/
private TemplatePicker picker;
/*************************************************************************/
/******************* Costruttori ***********************/
/*************************************************************************/
/**
*
* @param templateInputStram
*/
public MassiveQueryCompiler( String templateAsString ) {
this( templateAsString, null );
}
/**
*
* @param templateInputStram
* @param shiftingParamsMapsList
*/
public MassiveQueryCompiler( String templateAsString, List<Map<String, Object>> shiftingParamsMapsList ) {
this( null, null, shiftingParamsMapsList );
this.templateAsString = templateAsString;
}
/**
*
* @param nomiQueriesDaCompilare
* @param repositoryFilesIndex
* @param queriesRepoFolderFullPath
*/
public MassiveQueryCompiler(Map<String, String> repositoryFilesIndex, String queriesRepoFolderFullPath ) {
this( repositoryFilesIndex, queriesRepoFolderFullPath, null );
}
/**
*
* @param nomiQueriesDaCompilare Array di nomi/id delle queries da compilare.
* @param repositoryIndex Contiene le associazioni nome-query -> file-query-template. L'associazione da un id/nome di una query al file contenente il modello/template della query associata.
* @param queriesRepoFolderPath Percorso assoluto completo della cartella (radice) contenente i template delle queries da compilare
* @param shiftingParamsMapsList
*/
public MassiveQueryCompiler(Map<String, String> repositoryIndex, String queriesRepoFolderPath, List<Map<String, Object>> shiftingParamsMapsList) {
this.shiftingParamsMapsList = shiftingParamsMapsList;
this.repositoryIndex = repositoryIndex;
this.queriesRepoFolderPath = queriesRepoFolderPath;
// Istanzia l'oggetto di default per la validazione dei parametri rispetto ai valori effettivamente passati per evitare problemi sui Tipi
this.validator = new MapFormatTypeValidatorSQL();
}
/*************************************************************************/
/******************* Metodi ***********************/
/*************************************************************************/
/**
*
* @param nomeQueriesDaCompilare
* @param paramsMap Mappa per la sostituzione dei parameti nelle queries (parametriche) da compilare
* @return
* @throws TemplateCompilerException
*/
public Map<String, List<String>> getQueriesListMap(String nomeQueriesDaCompilare, Map<String, Object> paramsMap) throws TemplateCompilerException {
return this.getQueriesListMap( new String[] {nomeQueriesDaCompilare}, paramsMap );
}
/**
*
* @param nomiQueriesDaCompilare
* @param paramsMap Mappa per la sostituzione dei parameti nelle queries (parametriche) da compilare
* @return Mappa con chiave nome/id Query e per valore una lista di queries: se 'shiftingParamsMapsList' e' nullo la lista conteiene sempre una sola query
* @throws TemplateCompilerException
*/
public Map<String, List<String>> getQueriesListMap(String[] nomiQueriesDaCompilare, Map<String, Object> paramsMap) throws TemplateCompilerException {
Map<String, List<String>> queriesListMappedByName = new HashMap<String, List<String>>();
+ paramsMap = (paramsMap == null) ? (new HashMap<String, Object>()) : paramsMap;
for( int i = 0 ; i < nomiQueriesDaCompilare.length ; i++ ) {
List<String> compiledQueriesList = new ArrayList<String>();
if (this.shiftingParamsMapsList != null) {
Map<String, Object> tmpSingleShiftAndConstantParamsMap = null;
for( Map<String, Object> singleShiftParamsMap : this.shiftingParamsMapsList ) {
tmpSingleShiftAndConstantParamsMap = new HashMap<String, Object>();
tmpSingleShiftAndConstantParamsMap.putAll( paramsMap );
tmpSingleShiftAndConstantParamsMap.putAll( singleShiftParamsMap ); // sovrascrive eventuali parametri con stessa chiave presenti nella mappa dei parametri costanti
compiledQueriesList.add( this.getCompiledQuery(nomiQueriesDaCompilare[i], tmpSingleShiftAndConstantParamsMap) );
}
} else {
compiledQueriesList.add( this.getCompiledQuery(nomiQueriesDaCompilare[i], paramsMap) );
}
queriesListMappedByName.put( nomiQueriesDaCompilare[i], compiledQueriesList );
}
return queriesListMappedByName;
}
/**
*
* @param templateName
* @param substitutesValuesMap
* @return
* @throws TemplateCompilerException
*/
private String getCompiledQuery( String templateName, Map<String, Object> substitutesValuesMap)
throws TemplateCompilerException {
if (this.repositoryIndex != null && this.queriesRepoFolderPath != null)
return TemplateCompiler.compile( repositoryIndex, queriesRepoFolderPath, templateName, substitutesValuesMap, picker, validator );
else if (this.templateAsString != null) {
String s = TemplateCompiler.compile( templateAsString, templateName, substitutesValuesMap, picker, validator );
// System.out.println( s );
return s;
}
else
throw new IllegalArgumentException( "Errore " + this.getClass().getName() + ": repositoryIndex + queriesRepoFolderPath nulli o templateInputStram nullo. Deve esser forniuta una sorgente valida per recuperare il template da compilare." );
}
/**
*
* @param validator
*/
public void setValidator( MapFormatTypeValidator validator ) {
this.validator = validator;
}
/**
*
* @param picker Oggetto che sappia interpretare il template al fine di trovare la query sceltas.
*/
public void setPicker( TemplatePicker picker ) {
this.picker = picker;
}
}
| true | true | public Map<String, List<String>> getQueriesListMap(String[] nomiQueriesDaCompilare, Map<String, Object> paramsMap) throws TemplateCompilerException {
Map<String, List<String>> queriesListMappedByName = new HashMap<String, List<String>>();
for( int i = 0 ; i < nomiQueriesDaCompilare.length ; i++ ) {
List<String> compiledQueriesList = new ArrayList<String>();
if (this.shiftingParamsMapsList != null) {
Map<String, Object> tmpSingleShiftAndConstantParamsMap = null;
for( Map<String, Object> singleShiftParamsMap : this.shiftingParamsMapsList ) {
tmpSingleShiftAndConstantParamsMap = new HashMap<String, Object>();
tmpSingleShiftAndConstantParamsMap.putAll( paramsMap );
tmpSingleShiftAndConstantParamsMap.putAll( singleShiftParamsMap ); // sovrascrive eventuali parametri con stessa chiave presenti nella mappa dei parametri costanti
compiledQueriesList.add( this.getCompiledQuery(nomiQueriesDaCompilare[i], tmpSingleShiftAndConstantParamsMap) );
}
} else {
compiledQueriesList.add( this.getCompiledQuery(nomiQueriesDaCompilare[i], paramsMap) );
}
queriesListMappedByName.put( nomiQueriesDaCompilare[i], compiledQueriesList );
}
return queriesListMappedByName;
}
| public Map<String, List<String>> getQueriesListMap(String[] nomiQueriesDaCompilare, Map<String, Object> paramsMap) throws TemplateCompilerException {
Map<String, List<String>> queriesListMappedByName = new HashMap<String, List<String>>();
paramsMap = (paramsMap == null) ? (new HashMap<String, Object>()) : paramsMap;
for( int i = 0 ; i < nomiQueriesDaCompilare.length ; i++ ) {
List<String> compiledQueriesList = new ArrayList<String>();
if (this.shiftingParamsMapsList != null) {
Map<String, Object> tmpSingleShiftAndConstantParamsMap = null;
for( Map<String, Object> singleShiftParamsMap : this.shiftingParamsMapsList ) {
tmpSingleShiftAndConstantParamsMap = new HashMap<String, Object>();
tmpSingleShiftAndConstantParamsMap.putAll( paramsMap );
tmpSingleShiftAndConstantParamsMap.putAll( singleShiftParamsMap ); // sovrascrive eventuali parametri con stessa chiave presenti nella mappa dei parametri costanti
compiledQueriesList.add( this.getCompiledQuery(nomiQueriesDaCompilare[i], tmpSingleShiftAndConstantParamsMap) );
}
} else {
compiledQueriesList.add( this.getCompiledQuery(nomiQueriesDaCompilare[i], paramsMap) );
}
queriesListMappedByName.put( nomiQueriesDaCompilare[i], compiledQueriesList );
}
return queriesListMappedByName;
}
|
diff --git a/org.eclipse.mylyn.help.ui/src/org/eclipse/mylyn/internal/help/ui/anttask/MediaWikiImageFetcher.java b/org.eclipse.mylyn.help.ui/src/org/eclipse/mylyn/internal/help/ui/anttask/MediaWikiImageFetcher.java
index 2ec97b83a..14a43b87e 100644
--- a/org.eclipse.mylyn.help.ui/src/org/eclipse/mylyn/internal/help/ui/anttask/MediaWikiImageFetcher.java
+++ b/org.eclipse.mylyn.help.ui/src/org/eclipse/mylyn/internal/help/ui/anttask/MediaWikiImageFetcher.java
@@ -1,144 +1,144 @@
/*******************************************************************************
* Copyright (c) 2004, 2007 Mylyn project committers and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*******************************************************************************/
package org.eclipse.mylyn.internal.help.ui.anttask;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.Get;
/**
* Fetch images from a MediaWiki-generated HTML page source
*
* @author David Green
*/
public class MediaWikiImageFetcher extends Task {
private String base;
private File dest;
private File src;
@Override
public void execute() throws BuildException {
if (dest == null) {
throw new BuildException("Must specify @dest");
}
if (!dest.exists()) {
throw new BuildException("@dest does not exist: " + dest);
}
if (!dest.isDirectory()) {
throw new BuildException("@dest is not a directory: " + dest);
}
if (src == null) {
throw new BuildException("Must specify @src");
}
if (!src.exists()) {
throw new BuildException("@src does not exist: " + src);
}
if (!src.isFile()) {
throw new BuildException("@src is not a file: " + src);
}
if (base == null) {
throw new BuildException("Must specify @base");
}
if (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
Pattern fragmentUrlPattern = Pattern.compile("src=\"([^\"]+)\"");
- Pattern imagePattern = Pattern.compile("alt=\"Image:(.*)\"([^>]+)", Pattern.MULTILINE);
+ Pattern imagePattern = Pattern.compile("alt=\"Image:([^\"]*)\"([^>]+)", Pattern.MULTILINE);
String htmlSrc;
try {
htmlSrc = readSrc();
} catch (IOException e) {
throw new BuildException("Cannot read src: " + src + ": " + e.getMessage(), e);
}
log("Parsing " + src, Project.MSG_INFO);
int fileCount = 0;
Matcher imagePatternMatcher = imagePattern.matcher(htmlSrc);
while (imagePatternMatcher.find()) {
String alt = imagePatternMatcher.group(1);
String imageFragment = imagePatternMatcher.group(2);
if (imageFragment != null) {
Matcher fragmentUrlMatcher = fragmentUrlPattern.matcher(imageFragment);
if (fragmentUrlMatcher.find()) {
String url = fragmentUrlMatcher.group(1);
String qualifiedUrl = base + url;
log("Fetching " + qualifiedUrl, Project.MSG_INFO);
Get get = new Get();
get.setProject(getProject());
get.setLocation(getLocation());
try {
get.setSrc(new URL(qualifiedUrl));
} catch (MalformedURLException e) {
log("Skipping " + url + ": " + e.getMessage(), Project.MSG_WARN);
continue;
}
// note: we use the alt text for the name since for some files there is a case-difference between
// the server URL and the text used in the image src of the markup
String name = alt == null ? url.substring(url.lastIndexOf('/')) : alt;
get.setDest(new File(dest, name));
get.execute();
++fileCount;
}
}
}
log("Fetched " + fileCount + " image files for " + src, Project.MSG_INFO);
}
public String getBase() {
return base;
}
public File getDest() {
return dest;
}
public File getSrc() {
return src;
}
private String readSrc() throws IOException {
StringBuilder buf = new StringBuilder((int) src.length());
Reader reader = new BufferedReader(new FileReader(src));
try {
int i;
while ((i = reader.read()) != -1) {
buf.append((char) i);
}
} finally {
reader.close();
}
return buf.toString();
}
public void setBase(String base) {
this.base = base;
}
public void setDest(File dest) {
this.dest = dest;
}
public void setSrc(File src) {
this.src = src;
}
}
| true | true | public void execute() throws BuildException {
if (dest == null) {
throw new BuildException("Must specify @dest");
}
if (!dest.exists()) {
throw new BuildException("@dest does not exist: " + dest);
}
if (!dest.isDirectory()) {
throw new BuildException("@dest is not a directory: " + dest);
}
if (src == null) {
throw new BuildException("Must specify @src");
}
if (!src.exists()) {
throw new BuildException("@src does not exist: " + src);
}
if (!src.isFile()) {
throw new BuildException("@src is not a file: " + src);
}
if (base == null) {
throw new BuildException("Must specify @base");
}
if (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
Pattern fragmentUrlPattern = Pattern.compile("src=\"([^\"]+)\"");
Pattern imagePattern = Pattern.compile("alt=\"Image:(.*)\"([^>]+)", Pattern.MULTILINE);
String htmlSrc;
try {
htmlSrc = readSrc();
} catch (IOException e) {
throw new BuildException("Cannot read src: " + src + ": " + e.getMessage(), e);
}
log("Parsing " + src, Project.MSG_INFO);
int fileCount = 0;
Matcher imagePatternMatcher = imagePattern.matcher(htmlSrc);
while (imagePatternMatcher.find()) {
String alt = imagePatternMatcher.group(1);
String imageFragment = imagePatternMatcher.group(2);
if (imageFragment != null) {
Matcher fragmentUrlMatcher = fragmentUrlPattern.matcher(imageFragment);
if (fragmentUrlMatcher.find()) {
String url = fragmentUrlMatcher.group(1);
String qualifiedUrl = base + url;
log("Fetching " + qualifiedUrl, Project.MSG_INFO);
Get get = new Get();
get.setProject(getProject());
get.setLocation(getLocation());
try {
get.setSrc(new URL(qualifiedUrl));
} catch (MalformedURLException e) {
log("Skipping " + url + ": " + e.getMessage(), Project.MSG_WARN);
continue;
}
// note: we use the alt text for the name since for some files there is a case-difference between
// the server URL and the text used in the image src of the markup
String name = alt == null ? url.substring(url.lastIndexOf('/')) : alt;
get.setDest(new File(dest, name));
get.execute();
++fileCount;
}
}
}
log("Fetched " + fileCount + " image files for " + src, Project.MSG_INFO);
}
| public void execute() throws BuildException {
if (dest == null) {
throw new BuildException("Must specify @dest");
}
if (!dest.exists()) {
throw new BuildException("@dest does not exist: " + dest);
}
if (!dest.isDirectory()) {
throw new BuildException("@dest is not a directory: " + dest);
}
if (src == null) {
throw new BuildException("Must specify @src");
}
if (!src.exists()) {
throw new BuildException("@src does not exist: " + src);
}
if (!src.isFile()) {
throw new BuildException("@src is not a file: " + src);
}
if (base == null) {
throw new BuildException("Must specify @base");
}
if (base.endsWith("/")) {
base = base.substring(0, base.length() - 1);
}
Pattern fragmentUrlPattern = Pattern.compile("src=\"([^\"]+)\"");
Pattern imagePattern = Pattern.compile("alt=\"Image:([^\"]*)\"([^>]+)", Pattern.MULTILINE);
String htmlSrc;
try {
htmlSrc = readSrc();
} catch (IOException e) {
throw new BuildException("Cannot read src: " + src + ": " + e.getMessage(), e);
}
log("Parsing " + src, Project.MSG_INFO);
int fileCount = 0;
Matcher imagePatternMatcher = imagePattern.matcher(htmlSrc);
while (imagePatternMatcher.find()) {
String alt = imagePatternMatcher.group(1);
String imageFragment = imagePatternMatcher.group(2);
if (imageFragment != null) {
Matcher fragmentUrlMatcher = fragmentUrlPattern.matcher(imageFragment);
if (fragmentUrlMatcher.find()) {
String url = fragmentUrlMatcher.group(1);
String qualifiedUrl = base + url;
log("Fetching " + qualifiedUrl, Project.MSG_INFO);
Get get = new Get();
get.setProject(getProject());
get.setLocation(getLocation());
try {
get.setSrc(new URL(qualifiedUrl));
} catch (MalformedURLException e) {
log("Skipping " + url + ": " + e.getMessage(), Project.MSG_WARN);
continue;
}
// note: we use the alt text for the name since for some files there is a case-difference between
// the server URL and the text used in the image src of the markup
String name = alt == null ? url.substring(url.lastIndexOf('/')) : alt;
get.setDest(new File(dest, name));
get.execute();
++fileCount;
}
}
}
log("Fetched " + fileCount + " image files for " + src, Project.MSG_INFO);
}
|
diff --git a/src/edu/mit/mitmobile2/links/LinksModel.java b/src/edu/mit/mitmobile2/links/LinksModel.java
index e4b98f45..ea176088 100644
--- a/src/edu/mit/mitmobile2/links/LinksModel.java
+++ b/src/edu/mit/mitmobile2/links/LinksModel.java
@@ -1,71 +1,71 @@
package edu.mit.mitmobile2.links;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Handler;
import edu.mit.mitmobile2.MobileWebApi;
public class LinksModel {
private final static String LINKS_PREFS_NAME = "linksPreferences";
public static void fetchLinks(final Context context, final Handler uiHandler) {
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("module", "links");
- MobileWebApi webApi = new MobileWebApi(false, true, "People", context, uiHandler);
+ MobileWebApi webApi = new MobileWebApi(false, false, "People", context, uiHandler);
webApi.setIsSearchQuery(false);
webApi.requestJSONArray(parameters, new MobileWebApi.JSONArrayResponseListener(
new MobileWebApi.DefaultErrorListener(uiHandler), new MobileWebApi.DefaultCancelRequestListener(uiHandler) ) {
@Override
public void onResponse(JSONArray array) throws JSONException {
SharedPreferences preferences = context.getSharedPreferences(LINKS_PREFS_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("json", array.toString());
editor.commit();
ArrayList<LinkListItem> linkLists = new ArrayList<LinkListItem>();
for (int i = 0; i < array.length(); i++) {
linkLists.add(new LinkListItem(array.getJSONObject(i)));
}
MobileWebApi.sendSuccessMessage(uiHandler, linkLists);
}
});
}
public static ArrayList<LinkListItem> getCachedLinks(Context context) {
SharedPreferences preferences = context.getSharedPreferences(LINKS_PREFS_NAME, Context.MODE_PRIVATE);
String json = preferences.getString("json", "");
if (json.length() > 0) {
JSONArray array;
try {
array = new JSONArray(json);
ArrayList<LinkListItem> linkLists = new ArrayList<LinkListItem>();
for (int i = 0; i < array.length(); i++) {
linkLists.add(new LinkListItem(array.getJSONObject(i)));
}
return linkLists;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} else {
return null;
}
}
}
| true | true | public static void fetchLinks(final Context context, final Handler uiHandler) {
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("module", "links");
MobileWebApi webApi = new MobileWebApi(false, true, "People", context, uiHandler);
webApi.setIsSearchQuery(false);
webApi.requestJSONArray(parameters, new MobileWebApi.JSONArrayResponseListener(
new MobileWebApi.DefaultErrorListener(uiHandler), new MobileWebApi.DefaultCancelRequestListener(uiHandler) ) {
@Override
public void onResponse(JSONArray array) throws JSONException {
SharedPreferences preferences = context.getSharedPreferences(LINKS_PREFS_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("json", array.toString());
editor.commit();
ArrayList<LinkListItem> linkLists = new ArrayList<LinkListItem>();
for (int i = 0; i < array.length(); i++) {
linkLists.add(new LinkListItem(array.getJSONObject(i)));
}
MobileWebApi.sendSuccessMessage(uiHandler, linkLists);
}
});
}
| public static void fetchLinks(final Context context, final Handler uiHandler) {
HashMap<String, String> parameters = new HashMap<String, String>();
parameters.put("module", "links");
MobileWebApi webApi = new MobileWebApi(false, false, "People", context, uiHandler);
webApi.setIsSearchQuery(false);
webApi.requestJSONArray(parameters, new MobileWebApi.JSONArrayResponseListener(
new MobileWebApi.DefaultErrorListener(uiHandler), new MobileWebApi.DefaultCancelRequestListener(uiHandler) ) {
@Override
public void onResponse(JSONArray array) throws JSONException {
SharedPreferences preferences = context.getSharedPreferences(LINKS_PREFS_NAME, Context.MODE_PRIVATE);
Editor editor = preferences.edit();
editor.putString("json", array.toString());
editor.commit();
ArrayList<LinkListItem> linkLists = new ArrayList<LinkListItem>();
for (int i = 0; i < array.length(); i++) {
linkLists.add(new LinkListItem(array.getJSONObject(i)));
}
MobileWebApi.sendSuccessMessage(uiHandler, linkLists);
}
});
}
|
diff --git a/plugins/base-widgets/src/main/java/pl/net/bluesoft/rnd/processtool/ui/basewidgets/ProcessDataBlockWidget.java b/plugins/base-widgets/src/main/java/pl/net/bluesoft/rnd/processtool/ui/basewidgets/ProcessDataBlockWidget.java
index 8729c619..9d9f00f6 100644
--- a/plugins/base-widgets/src/main/java/pl/net/bluesoft/rnd/processtool/ui/basewidgets/ProcessDataBlockWidget.java
+++ b/plugins/base-widgets/src/main/java/pl/net/bluesoft/rnd/processtool/ui/basewidgets/ProcessDataBlockWidget.java
@@ -1,782 +1,782 @@
package pl.net.bluesoft.rnd.processtool.ui.basewidgets;
import com.vaadin.Application;
import com.vaadin.data.Container;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.Validatable;
import com.vaadin.data.Validator.InvalidValueException;
import com.vaadin.data.validator.RegexpValidator;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.Sizeable;
import com.vaadin.ui.*;
import com.vaadin.ui.Layout.AlignmentHandler;
import com.vaadin.ui.Layout.SpacingHandler;
import org.apache.commons.beanutils.NestedNullException;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.expression.DefaultResolver;
import org.apache.commons.beanutils.expression.Resolver;
import pl.net.bluesoft.rnd.processtool.ProcessToolContext;
import pl.net.bluesoft.rnd.processtool.bpm.ProcessToolBpmSession;
import pl.net.bluesoft.rnd.processtool.dict.ProcessDictionaryRegistry;
import pl.net.bluesoft.rnd.processtool.model.*;
import pl.net.bluesoft.rnd.processtool.model.config.ProcessStateConfiguration;
import pl.net.bluesoft.rnd.processtool.model.config.ProcessStateWidget;
import pl.net.bluesoft.rnd.processtool.model.dict.ProcessDictionary;
import pl.net.bluesoft.rnd.processtool.model.dict.ProcessDictionaryItem;
import pl.net.bluesoft.rnd.processtool.ui.basewidgets.editor.ProcessDataWidgetsDefinitionEditor;
import pl.net.bluesoft.rnd.processtool.ui.basewidgets.xml.WidgetDefinitionLoader;
import pl.net.bluesoft.rnd.processtool.ui.basewidgets.xml.XmlConstants;
import pl.net.bluesoft.rnd.processtool.ui.basewidgets.xml.jaxb.*;
import pl.net.bluesoft.rnd.processtool.ui.widgets.ProcessToolDataWidget;
import pl.net.bluesoft.rnd.processtool.ui.widgets.ProcessToolWidget;
import pl.net.bluesoft.rnd.processtool.ui.widgets.annotations.*;
import pl.net.bluesoft.rnd.processtool.ui.widgets.impl.BaseProcessToolVaadinWidget;
import pl.net.bluesoft.rnd.util.i18n.I18NSource;
import pl.net.bluesoft.rnd.util.vaadin.VaadinUtility;
import pl.net.bluesoft.util.lang.StringUtil;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.logging.Logger;
import static com.vaadin.ui.Alignment.*;
import static pl.net.bluesoft.util.lang.FormatUtil.nvl;
import static pl.net.bluesoft.util.lang.StringUtil.hasText;
@AliasName(name = "ProcessData")
@AperteDoc(humanNameKey = "widget.process_data_block.name", descriptionKey = "widget.process_data_block.description")
@ChildrenAllowed(false)
@WidgetGroup("base-widgets")
public class ProcessDataBlockWidget extends BaseProcessToolVaadinWidget implements ProcessToolDataWidget {
private static final Logger logger = Logger.getLogger(ProcessDataBlockWidget.class.getName());
private static final Resolver resolver = new DefaultResolver();
private WidgetDefinitionLoader definitionLoader = WidgetDefinitionLoader.getInstance();
private ProcessDictionaryRegistry processDictionaryRegistry;
private Map<Property, WidgetElement> boundProperties = new HashMap<Property, WidgetElement>();
private Map<AbstractSelect, WidgetElement> dictContainers = new HashMap<AbstractSelect, WidgetElement>();
private Map<AbstractSelect, WidgetElement> instanceDictContainers = new HashMap<AbstractSelect, WidgetElement>();
private Map<String, ProcessInstanceAttribute> processAttributes = new HashMap<String, ProcessInstanceAttribute>();
protected WidgetsDefinitionElement widgetsDefinitionElement;
private ProcessInstance processInstance;
@AutoWiredProperty(required = true)
@AutoWiredPropertyConfigurator(fieldClass = ProcessDataWidgetsDefinitionEditor.class)
@AperteDoc(
humanNameKey="widget.process_data_block.property.widgetsDefinition.name",
descriptionKey="widget.process_data_block.property.widgetsDefinition.description"
)
private String widgetsDefinition;
public void setDefinitionLoader(WidgetDefinitionLoader definitionLoader) {
this.definitionLoader = definitionLoader;
}
public void setProcessDictionaryRegistry(ProcessDictionaryRegistry processDictionaryRegistry) {
this.processDictionaryRegistry = processDictionaryRegistry;
}
@Override
public void setContext(ProcessStateConfiguration state, ProcessStateWidget configuration, I18NSource i18NSource,
ProcessToolBpmSession bpmSession, Application application, Set<String> permissions, boolean isOwner) {
super.setContext(state, configuration, i18NSource, bpmSession,
application, permissions, isOwner);
ProcessToolContext ctx = ProcessToolContext.Util.getThreadProcessToolContext();
processDictionaryRegistry = ctx.getProcessDictionaryRegistry();
}
private abstract class ComponentEvaluator<T> {
protected T currentComponent;
protected WidgetElement currentElement;
protected ComponentEvaluator(Map<T, WidgetElement> input) {
try {
if (input != null) {
for (Entry<T, WidgetElement> entry : input.entrySet()) {
evaluate(currentComponent = entry.getKey(), currentElement = entry.getValue());
}
}
} catch (Exception e) {
logException(getMessage("processdata.block.error.eval.other")
.replaceFirst("%s", nvl(currentComponent.toString(), "NIL"))
.replaceFirst("%s", nvl(currentElement.getBind(), "NIL")), e);
}
}
public abstract void evaluate(T component, WidgetElement element) throws Exception;
}
@Override
public Collection<String> validateData(final ProcessInstance processInstance) {
final List<String> errors = new ArrayList<String>();
new ComponentEvaluator<Property>(boundProperties) {
@Override
public void evaluate(Property component, WidgetElement element) throws Exception {
if (component instanceof Validatable) {
Validatable validatable = (Validatable) component;
try {
validatable.validate();
} catch (InvalidValueException e) {
errors.add(e.getMessage());
}
}
if (!component.isReadOnly()) {
try {
fetchOrCreateAttribute(element);
} catch (Exception e) {
errors.add(getMessage("processdata.block.error.eval.other").replaceFirst("%s",
component.toString()).replaceFirst("%s", element.getBind()) +
"<br/>" + e.getMessage());
}
}
}
};
return errors;
}
private ProcessInstanceAttribute fetchOrCreateAttribute(WidgetElement element) throws InstantiationException, IllegalAccessException,
ClassNotFoundException, InvocationTargetException, NoSuchMethodException {
int index = element.getBind().indexOf('.');
String attributeName = index == -1 ? element.getBind() : element.getBind().substring(0, index);
ProcessInstanceAttribute attribute = processAttributes.get(attributeName);
if (attribute == null && (hasText(element.getInheritedAttributeClass()) || index == -1)) {
attribute = hasText(element.getInheritedAttributeClass())
? (ProcessInstanceAttribute) getClass().getClassLoader().loadClass(element.getInheritedAttributeClass()).newInstance()
: new ProcessInstanceSimpleAttribute();
attribute.setProcessInstance(processInstance);
attribute.setKey(attributeName);
processAttributes.put(attributeName, attribute);
}
if (index != -1) {
String propertyName = element.getBind().substring(index + 1);
Object bean = attribute;
while (resolver.hasNested(propertyName)) {
String next = resolver.next(propertyName);
Object nestedBean = resolver.isMapped(next) ? PropertyUtils.getMappedProperty(bean, next)
: resolver.isIndexed(next) ? PropertyUtils.getIndexedProperty(bean, next)
: PropertyUtils.getSimpleProperty(bean, next);
if (nestedBean == null) {
Class clazz = PropertyUtils.getPropertyType(bean, next);
PropertyUtils.setProperty(bean, next, nestedBean = clazz.newInstance());
}
bean = nestedBean;
propertyName = resolver.remove(propertyName);
}
}
return attribute;
}
@Override
public void saveData(final ProcessInstance processInstance) {
processAttributes.clear();
for (ProcessInstanceAttribute attribute : processInstance.getProcessAttributes()) {
processAttributes.put(attribute.getKey(), attribute);
}
new ComponentEvaluator<Property>(boundProperties) {
@Override
public void evaluate(Property component, WidgetElement element) throws Exception {
if (!component.isReadOnly()) {
ProcessInstanceAttribute attribute = fetchOrCreateAttribute(element);
if (attribute instanceof ProcessInstanceSimpleAttribute) {
if (element instanceof DateWidgetElement) {
if(component.getValue() != null)
((ProcessInstanceSimpleAttribute) attribute).setValue(
new SimpleDateFormat(((DateWidgetElement) element).getFormat()).format(component.getValue())
);
} else if (component.getValue() != null) {
((ProcessInstanceSimpleAttribute) attribute).setValue(component.getValue().toString());
}
} else {
if (component instanceof FileUploadComponent) {
ProcessInstanceAttachmentAttribute attachment = (ProcessInstanceAttachmentAttribute) component.getValue();
attachment.setProcessState(processInstance.getState());
attachment.setProcessInstance(processInstance);
attachment.setKey(attribute.getKey());
}
PropertyUtils.setProperty(processAttributes, element.getBind(), component.getValue());
}
}
}
};
processInstance.setProcessAttributes(new HashSet<ProcessInstanceAttribute>(processAttributes.values()));
}
@Override
public void loadData(final ProcessInstance processInstance) {
boundProperties.clear();
dictContainers.clear();
if (StringUtil.hasText(widgetsDefinition)) {
widgetsDefinitionElement = (WidgetsDefinitionElement) definitionLoader.unmarshall(widgetsDefinition);
}
this.processInstance = processInstance;
processAttributes.clear();
for (ProcessInstanceAttribute attribute : processInstance.getProcessAttributes()) {
processAttributes.put(attribute.getKey(), attribute);
}
}
private void loadBindings() {
new ComponentEvaluator<Property>(boundProperties) {
@Override
public void evaluate(Property component, WidgetElement element) throws Exception {
Object value = null;
try {
value = PropertyUtils.getProperty(processAttributes, element.getBind());
} catch (NestedNullException e) {
logger.info(e.getMessage());
}
value = value instanceof ProcessInstanceSimpleAttribute ?
((ProcessInstanceSimpleAttribute) value).getValue() : value;
if (value != null) {
boolean readonly = component.isReadOnly();
if (readonly) {
component.setReadOnly(false);
}
// TODO reconsider this approach, perhaps it's easier to check component.getType() and when it returns Object catch possible exception from component.setValue()
if (Date.class.isAssignableFrom(component.getType())) {
Date v = new SimpleDateFormat(((DateWidgetElement) element).getFormat()).parse(String.valueOf(
value));
component.setValue(v);
} else if (String.class.isAssignableFrom(component.getType())) {
component.setValue(nvl(value, ""));
} else if (component instanceof Container &&
component.getType().isAssignableFrom(value.getClass())) {
if (((Container) component).containsId(value)) {
component.setValue(value);
}
}
if (readonly) {
component.setReadOnly(true);
}
}
}
};
}
private void loadProcessInstanceDictionaries() {
new ComponentEvaluator<AbstractSelect>(instanceDictContainers) {
@Override
public void evaluate(AbstractSelect component, WidgetElement element) throws Exception {
AbstractSelectWidgetElement aswe = (AbstractSelectWidgetElement) element;
String dictAttribute = aswe.getDictionaryAttribute();
ProcessInstanceDictionaryAttribute dict = (ProcessInstanceDictionaryAttribute) processInstance.findAttributeByKey(dictAttribute);
if (dict != null) {
int i = 0;
for (Object o : dict.getItems()) {
ProcessInstanceDictionaryItem itemProcess = (ProcessInstanceDictionaryItem) o;
component.addItem(itemProcess.getKey());
component.setItemCaption(itemProcess.getKey(), itemProcess.getValue());
if (element instanceof AbstractSelectWidgetElement) {
AbstractSelectWidgetElement select = (AbstractSelectWidgetElement) element;
if (select.getDefaultSelect() != null && i == select.getDefaultSelect()) {
component.setValue(itemProcess.getKey());
}
}
++i;
}
}
}
};
}
private void loadDictionaries() {
new ComponentEvaluator<AbstractSelect>(dictContainers) {
@Override
public void evaluate(AbstractSelect component, WidgetElement element) throws Exception {
ProcessDictionary dict = processDictionaryRegistry.getSpecificOrDefaultDictionary(
processInstance.getDefinition(), element.getProvider(),
element.getDict(), i18NSource.getLocale().toString());
if (dict != null) {
int i = 0;
for (Object o : dict.items()) {
ProcessDictionaryItem itemProcess = (ProcessDictionaryItem) o;
component.addItem(itemProcess.getKey());
component.setItemCaption(itemProcess.getKey(), getMessage((String) itemProcess.getValue()));
if (element instanceof AbstractSelectWidgetElement) {
AbstractSelectWidgetElement select = (AbstractSelectWidgetElement) element;
if (select.getDefaultSelect() != null && i == select.getDefaultSelect()) {
component.setValue(itemProcess.getKey());
}
}
++i;
}
}
}
};
}
@Override
public void addChild(ProcessToolWidget child) {
throw new IllegalArgumentException("children are not supported in this widget");
}
@Override
public Component render() {
return widgetsDefinitionElement != null ? renderInternal() : new Label(getMessage("processdata.block.nothing.to.render"));
}
private void logException(String message, Exception e) {
logger.severe(message + "<br/>" + e.getMessage());
VaadinUtility.validationNotification(getApplication(), i18NSource, message + "<br/>" + e.getMessage());
}
private Component renderInternal() {
ComponentContainer mainPanel = null;
try {
mainPanel = !hasText(widgetsDefinitionElement.getClassName()) ? new VerticalLayout()
: (ComponentContainer) getClass().getClassLoader().loadClass(widgetsDefinitionElement.getClassName()).newInstance();
} catch (Exception e) {
logException(getMessage("processdata.block.error.load.class").replaceFirst("%s", widgetsDefinitionElement.getClassName()), e);
}
setupWidget(widgetsDefinitionElement, mainPanel);
for (WidgetElement we : widgetsDefinitionElement.getWidgets()) {
processWidgetElement(widgetsDefinitionElement, we, mainPanel);
}
loadDictionaries();
loadProcessInstanceDictionaries();
loadBindings();
return mainPanel;
}
private AbstractComponent processWidgetElement(WidgetElement parent, WidgetElement element, ComponentContainer container) {
AbstractComponent component = null;
if (element instanceof LabelWidgetElement) {
component = createLabelField((LabelWidgetElement) element);
} else if (element instanceof InputWidgetElement) {
component = createInputField((InputWidgetElement) element);
} else if (element instanceof VerticalLayoutWidgetElement) {
component = createVerticalLayout((VerticalLayoutWidgetElement) element);
} else if (element instanceof HorizontalLayoutWidgetElement) {
component = createHorizontalLayout((HorizontalLayoutWidgetElement) element);
} else if (element instanceof AlignElement) {
applyAlignment((AlignElement) element, container);
} else if (element instanceof DateWidgetElement) {
component = createDateField((DateWidgetElement) element);
} else if (element instanceof FormWidgetElement) {
component = createFormField((FormWidgetElement) element);
} else if (element instanceof GridWidgetElement) {
component = createGrid((GridWidgetElement) element);
} else if (element instanceof LinkWidgetElement) {
component = createLink((LinkWidgetElement) element);
} else if (element instanceof ComboboxSelectElementWidget) {
component = createComboSelectField((ComboboxSelectElementWidget) element);
} else if (element instanceof RadioButtonSelectElementWidget) {
component = createRadioButtonSelectField((RadioButtonSelectElementWidget) element);
} else if (element instanceof TextAreaWidgetElement) {
component = createTextAreaField((TextAreaWidgetElement) element);
} else if (element instanceof CheckBoxWidgetElement) {
component = createCheckBoxField((CheckBoxWidgetElement) element);
} else if (element instanceof UploadWidgetElement) {
component = createFileUploadField((UploadWidgetElement) element);
}
if (component != null) {
component.setImmediate(true);
component.setEnabled(hasPermission("EDIT"));
if (component.isReadOnly() || !component.isEnabled()) {
component.setHeight(null);
}
setupWidget(element, component);
container.addComponent(component);
}
element.setParent(parent);
return component;
}
private AbstractComponent createRadioButtonSelectField(RadioButtonSelectElementWidget element) {
OptionGroup radioSelect = new OptionGroup();
radioSelect.setNullSelectionAllowed(false);
radioSelect.setCaption(element.getCaption());
radioSelect.setHtmlContentAllowed(true);
// if(element.getValues().isEmpty())
for (int i = 0; i < element.getValues().size(); i++) {
ItemElement item = element.getValues().get(i);
radioSelect.addItem(item.getKey());
radioSelect.setItemCaption(item.getKey(), item.getValue());
if (element.getDefaultSelect() != null && i == element.getDefaultSelect()) {
radioSelect.setValue(item.getKey());
}
}
if (nvl(element.getRequired(), false)) {
radioSelect.setRequired(true);
if (hasText(element.getCaption())) {
radioSelect.setRequiredError(getMessage("processdata.block.field-required-error") + " " + element.getCaption());
} else {
radioSelect.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
return radioSelect;
}
private AbstractComponent createFileUploadField(UploadWidgetElement element) {
FileUploadComponent upload = new FileUploadComponent(i18NSource);
return upload;
}
private CheckBox createCheckBoxField(CheckBoxWidgetElement we) {
CheckBox cb = new CheckBox();
if (we.getDefaultSelect() != null && we.getDefaultSelect()) {
cb.setValue(we.getDefaultSelect());
}
return cb;
}
private Select createComboSelectField(ComboboxSelectElementWidget swe) {
Select select = new Select();
if (!swe.getValues().isEmpty()) {
for (int i = 0; i < swe.getValues().size(); ++i) {
ItemElement item = swe.getValues().get(i);
select.addItem(item.getKey());
select.setItemCaption(item.getKey(), item.getValue());
if (swe.getDefaultSelect() != null && i == swe.getDefaultSelect()) {
select.setValue(item.getKey());
}
}
}
// else if (swe.getScript() != null) {
// processScriptElement(select, swe.getScript());
// }
if (nvl(swe.getRequired(), false)) {
select.setRequired(true);
if (hasText(swe.getCaption())) {
select.setRequiredError(getMessage("processdata.block.field-required-error") + " " + swe.getCaption());
} else {
select.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
return select;
}
private void processScriptElement(Select select, ScriptElement script) {
throw new RuntimeException("Not implemented yet!");
}
private Form createFormField(FormWidgetElement fwe) {
FormLayout layout = new FormLayout();
processOrderedLayout(fwe, layout);
Form form = new Form(layout);
return form;
}
private AbstractComponent createTextAreaField(TextAreaWidgetElement taw) {
AbstractComponent component;
if (taw.getRich() != null && taw.getRich()) {
RichTextArea rta = new RichTextArea();
if (taw.getVisibleLines() != null) {
rta.setHeight(taw.getVisibleLines() * 2 + 4, Sizeable.UNITS_EM);
}
if (taw.getLimit() != null) {
rta.addValidator(new StringLengthValidator(getMessage("processdata.block.error.text.exceeded").replaceFirst("%s",
"" + taw.getLimit()), 0, taw.getLimit(), true));
}
if (nvl(taw.getRequired(), false)) {
rta.setRequired(true);
if (hasText(taw.getCaption())) {
rta.setRequiredError(getMessage("processdata.block.field-required-error") + " " + taw.getCaption());
} else {
rta.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
if (!hasPermission("EDIT")) {
rta.setReadOnly(true);
rta.setHeight(null);
}
component = rta;
} else {
TextArea ta = new TextArea();
if (taw.getVisibleLines() != null) {
ta.setRows(taw.getVisibleLines());
}
if (taw.getLimit() != null) {
ta.setMaxLength(taw.getLimit());
}
component = ta;
if (nvl(taw.getRequired(), false)) {
ta.setRequired(true);
if (hasText(taw.getCaption())) {
ta.setRequiredError(getMessage("processdata.block.field-required-error") + " " + taw.getCaption());
} else {
ta.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
component = ta;
}
return component;
}
private Link createLink(LinkWidgetElement we) {
Link link = new Link();
link.setTargetName("_blank");
link.setResource(new ExternalResource(we.getUrl()));
return link;
}
private GridLayout createGrid(GridWidgetElement gwe) {
GridLayout grid = new GridLayout();
if (gwe.getCols() != null) {
grid.setColumns(gwe.getCols());
}
if (gwe.getRows() != null) {
grid.setRows(gwe.getRows());
}
processOrderedLayout(gwe, grid);
return grid;
}
private VerticalLayout createVerticalLayout(VerticalLayoutWidgetElement vlw) {
VerticalLayout vl = new VerticalLayout();
vl.setSpacing(true);
processOrderedLayout(vlw, vl);
return vl;
}
private HorizontalLayout createHorizontalLayout(HorizontalLayoutWidgetElement hlw) {
HorizontalLayout hl = new HorizontalLayout();
hl.setSpacing(true);
processOrderedLayout(hlw, hl);
return hl;
}
private void processOrderedLayout(HasWidgetsElement hwe, AbstractLayout al) {
for (WidgetElement we : hwe.getWidgets()) {
Component widget = processWidgetElement(hwe, we, al);
if (widget != null && al instanceof AbstractOrderedLayout) {
AbstractOrderedLayout aol = (AbstractOrderedLayout) al;
aol.setExpandRatio(widget, 1f);
}
}
}
private void applyAlignment(AlignElement ae, ComponentContainer container) {
if (container instanceof AlignmentHandler) {
AlignmentHandler ah = (AlignmentHandler) container;
for (WidgetElement awe : ae.getWidgets()) {
Component widget = processWidgetElement(ae, awe, container);
if (widget != null) {
if (XmlConstants.ALIGN_POS_CENTER_TOP.equals(ae.getPos())) {
ah.setComponentAlignment(widget, TOP_CENTER);
} else if (XmlConstants.ALIGN_POS_LEFT_TOP.equals(ae.getPos())) {
ah.setComponentAlignment(widget, TOP_LEFT);
} else if (XmlConstants.ALIGN_POS_RIGHT_TOP.equals(ae.getPos())) {
ah.setComponentAlignment(widget, TOP_RIGHT);
} else if (XmlConstants.ALIGN_POS_CENTER_MIDDLE.equals(ae.getPos())) {
ah.setComponentAlignment(widget, MIDDLE_CENTER);
} else if (XmlConstants.ALIGN_POS_LEFT_MIDDLE.equals(ae.getPos())) {
ah.setComponentAlignment(widget, MIDDLE_LEFT);
} else if (XmlConstants.ALIGN_POS_RIGHT_MIDDLE.equals(ae.getPos())) {
ah.setComponentAlignment(widget, MIDDLE_RIGHT);
} else if (XmlConstants.ALIGN_POS_CENTER_BOTTOM.equals(ae.getPos())) {
ah.setComponentAlignment(widget, BOTTOM_CENTER);
} else if (XmlConstants.ALIGN_POS_LEFT_BOTTOM.equals(ae.getPos())) {
ah.setComponentAlignment(widget, BOTTOM_LEFT);
} else if (XmlConstants.ALIGN_POS_RIGHT_BOTTOM.equals(ae.getPos())) {
ah.setComponentAlignment(widget, BOTTOM_RIGHT);
}
}
}
}
}
/* private AbstractTextField createInputField(InputWidgetElement iwe) {
AbstractTextField field = iwe.getSecret() != null && iwe.getSecret() ? new PasswordField() : new TextField();
if (iwe.getMaxLength() != null) {
field.setMaxLength(iwe.getMaxLength());
}
if (hasText(iwe.getRegexp()) && hasText(iwe.getRegexp())) {
field.addValidator(new RegexpValidator(OXHelper.replaceXmlEscapeCharacters(iwe.getRegexp()), iwe.getErrorKey() != null ?
iwe.getErrorKey() : getMessage("processdata.block.error.regexp").replaceFirst("%s", iwe.getRegexp())));
}
if (hasText(iwe.getBaseText())) {
field.setValue(getMessage(iwe.getBaseText()));
}
if (hasText(iwe.getPrompt())) {
field.setInputPrompt(getMessage(iwe.getPrompt()));
}
return field;
}*/
private AbstractTextField createInputField(InputWidgetElement iwe) {
AbstractTextField field = iwe.getSecret() != null && iwe.getSecret() ? new PasswordField() : new TextField();
if (iwe.getMaxLength() != null) {
field.setMaxLength(iwe.getMaxLength());
}
if (hasText(iwe.getRegexp()) && hasText(iwe.getRegexp())) {
field.addValidator(new RegexpValidator(WidgetDefinitionLoader.replaceXmlEscapeCharacters(iwe.getRegexp()), iwe.getErrorKey() != null ?
iwe.getErrorKey() : getMessage("processdata.block.error.regexp").replaceFirst("%s", iwe.getRegexp())));
}
if (nvl(iwe.getRequired(), false)) {
field.setRequired(true);
if (hasText(iwe.getCaption())) {
field.setRequiredError(getMessage("processdata.block.field-required-error") + " " + iwe.getCaption());
} else {
field.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
if (hasText(iwe.getBaseText())) {
field.setValue(getMessage(iwe.getBaseText()));
}
if (hasText(iwe.getPrompt())) {
field.setInputPrompt(getMessage(iwe.getPrompt()));
}
return field;
}
private Label createLabelField(LabelWidgetElement lwe) {
Label label = new Label();
if (lwe.getMode() != null) {
label.setContentMode(lwe.getMode());
}
if (hasText(lwe.getText())) {
label.setValue(WidgetDefinitionLoader.removeCDATATag(WidgetDefinitionLoader.replaceXmlEscapeCharacters(lwe.getText())));
}
return label;
}
private DateField createDateField(final DateWidgetElement dwe) {
SimpleDateFormat sdf;
try {
sdf = new SimpleDateFormat(dwe.getFormat());
} catch (Exception e) {
logException(getMessage("processdata.block.error.unparsable.format").replaceFirst("%s", dwe.getFormat()), e);
return null;
}
final PopupDateField field = new PopupDateField();
field.setDateFormat(dwe.getFormat());
field.setResolution(dwe.getShowMinutes() != null && dwe.getShowMinutes() ? DateField.RESOLUTION_MIN : DateField.RESOLUTION_DAY);
if (hasText(dwe.getNotAfter())) {
try {
final Date notAfter = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotAfter()) ? new Date() : sdf.parse(dwe.getNotAfter());
field.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Object value = event.getProperty().getValue();
if (value != null && value instanceof Date) {
if (notAfter.before((Date) value)) {
VaadinUtility.validationNotification(getApplication(), i18NSource,
getMessage("processdata.block.error.date.notafter").replaceFirst("%s", dwe.getNotAfter()));
field.setValue(notAfter);
}
}
}
});
} catch (ParseException e) {
logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotAfter()), e);
}
}
if (hasText(dwe.getNotBefore())) {
try {
final Date notBefore = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotBefore()) ? new Date() : sdf.parse(dwe.getNotBefore());
field.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Object value = event.getProperty().getValue();
if (value != null && value instanceof Date) {
if (notBefore.after((Date) value)) {
VaadinUtility.validationNotification(getApplication(), i18NSource,
- getMessage("processdata.block.error.date.notbefore").replaceFirst("%s", dwe.getNotAfter()));
+ getMessage("processdata.block.error.date.notbefore").replaceFirst("%s", dwe.getNotBefore()));
field.setValue(notBefore);
}
}
}
});
} catch (ParseException e) {
logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotBefore()), e);
}
}
if (nvl(dwe.getRequired(), false)) {
field.setRequired(true);
if (hasText(dwe.getCaption())) {
field.setRequiredError(getMessage("processdata.block.field-required-error") + " " + dwe.getCaption());
} else {
field.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
return field;
}
private void setupWidget(WidgetElement we, Component component) {
if (hasText(we.getCaption())) {
component.setCaption(getMessage(we.getCaption()));
}
if (we.getFullSize() != null && we.getFullSize()) {
component.setSizeFull();
}
if (we.getUndefinedSize() != null && we.getUndefinedSize()) {
component.setSizeUndefined();
}
if (hasText(we.getHeight())) {
component.setHeight(we.getHeight());
}
if (hasText(we.getWidth())) {
component.setWidth(we.getWidth());
}
if (we.getReadonly() != null && we.getReadonly()) {
component.setReadOnly(we.getReadonly());
}
if (hasText(we.getStyle())) {
component.addStyleName(we.getStyle());
}
if (we instanceof HasWidgetsElement && component instanceof SpacingHandler) {
HasWidgetsElement hwe = (HasWidgetsElement) we;
if (hwe.getSpacing() != null && hwe.getSpacing()) {
((SpacingHandler) component).setSpacing(hwe.getSpacing());
}
}
if (hasText(we.getBind()) && component instanceof Property) {
Property property = (Property) component;
boundProperties.put(property, we);
}
if (hasText(we.getDict()) && hasText(we.getProvider()) && component instanceof AbstractSelect) {
AbstractSelect select = (AbstractSelect) component;
dictContainers.put(select, we);
}
if (we instanceof AbstractSelectWidgetElement) {
AbstractSelectWidgetElement aswe = (AbstractSelectWidgetElement) we;
if (!hasText(we.getDict()) && !hasText(we.getProvider()) && hasText(aswe.getDictionaryAttribute())) {
AbstractSelect select = (AbstractSelect) component;
instanceDictContainers.put(select, aswe);
}
}
}
public String getWidgetsDefinition() {
return widgetsDefinition;
}
public void setWidgetsDefinition(String widgetsDefinition) {
this.widgetsDefinition = widgetsDefinition;
}
}
| true | true | private DateField createDateField(final DateWidgetElement dwe) {
SimpleDateFormat sdf;
try {
sdf = new SimpleDateFormat(dwe.getFormat());
} catch (Exception e) {
logException(getMessage("processdata.block.error.unparsable.format").replaceFirst("%s", dwe.getFormat()), e);
return null;
}
final PopupDateField field = new PopupDateField();
field.setDateFormat(dwe.getFormat());
field.setResolution(dwe.getShowMinutes() != null && dwe.getShowMinutes() ? DateField.RESOLUTION_MIN : DateField.RESOLUTION_DAY);
if (hasText(dwe.getNotAfter())) {
try {
final Date notAfter = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotAfter()) ? new Date() : sdf.parse(dwe.getNotAfter());
field.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Object value = event.getProperty().getValue();
if (value != null && value instanceof Date) {
if (notAfter.before((Date) value)) {
VaadinUtility.validationNotification(getApplication(), i18NSource,
getMessage("processdata.block.error.date.notafter").replaceFirst("%s", dwe.getNotAfter()));
field.setValue(notAfter);
}
}
}
});
} catch (ParseException e) {
logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotAfter()), e);
}
}
if (hasText(dwe.getNotBefore())) {
try {
final Date notBefore = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotBefore()) ? new Date() : sdf.parse(dwe.getNotBefore());
field.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Object value = event.getProperty().getValue();
if (value != null && value instanceof Date) {
if (notBefore.after((Date) value)) {
VaadinUtility.validationNotification(getApplication(), i18NSource,
getMessage("processdata.block.error.date.notbefore").replaceFirst("%s", dwe.getNotAfter()));
field.setValue(notBefore);
}
}
}
});
} catch (ParseException e) {
logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotBefore()), e);
}
}
if (nvl(dwe.getRequired(), false)) {
field.setRequired(true);
if (hasText(dwe.getCaption())) {
field.setRequiredError(getMessage("processdata.block.field-required-error") + " " + dwe.getCaption());
} else {
field.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
return field;
}
| private DateField createDateField(final DateWidgetElement dwe) {
SimpleDateFormat sdf;
try {
sdf = new SimpleDateFormat(dwe.getFormat());
} catch (Exception e) {
logException(getMessage("processdata.block.error.unparsable.format").replaceFirst("%s", dwe.getFormat()), e);
return null;
}
final PopupDateField field = new PopupDateField();
field.setDateFormat(dwe.getFormat());
field.setResolution(dwe.getShowMinutes() != null && dwe.getShowMinutes() ? DateField.RESOLUTION_MIN : DateField.RESOLUTION_DAY);
if (hasText(dwe.getNotAfter())) {
try {
final Date notAfter = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotAfter()) ? new Date() : sdf.parse(dwe.getNotAfter());
field.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Object value = event.getProperty().getValue();
if (value != null && value instanceof Date) {
if (notAfter.before((Date) value)) {
VaadinUtility.validationNotification(getApplication(), i18NSource,
getMessage("processdata.block.error.date.notafter").replaceFirst("%s", dwe.getNotAfter()));
field.setValue(notAfter);
}
}
}
});
} catch (ParseException e) {
logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotAfter()), e);
}
}
if (hasText(dwe.getNotBefore())) {
try {
final Date notBefore = XmlConstants.DATE_CURRENT.equalsIgnoreCase(dwe.getNotBefore()) ? new Date() : sdf.parse(dwe.getNotBefore());
field.addListener(new ValueChangeListener() {
@Override
public void valueChange(ValueChangeEvent event) {
Object value = event.getProperty().getValue();
if (value != null && value instanceof Date) {
if (notBefore.after((Date) value)) {
VaadinUtility.validationNotification(getApplication(), i18NSource,
getMessage("processdata.block.error.date.notbefore").replaceFirst("%s", dwe.getNotBefore()));
field.setValue(notBefore);
}
}
}
});
} catch (ParseException e) {
logException(getMessage("processdata.block.error.unparsable.date").replaceFirst("%s", dwe.getNotBefore()), e);
}
}
if (nvl(dwe.getRequired(), false)) {
field.setRequired(true);
if (hasText(dwe.getCaption())) {
field.setRequiredError(getMessage("processdata.block.field-required-error") + " " + dwe.getCaption());
} else {
field.setRequiredError(getMessage("processdata.block.field-required-error"));
}
}
return field;
}
|
diff --git a/beam-meris-preprocessor/src/main/java/org/esa/beam/preprocessor/PreprocessorOp.java b/beam-meris-preprocessor/src/main/java/org/esa/beam/preprocessor/PreprocessorOp.java
index edf681ab9..874cbc257 100644
--- a/beam-meris-preprocessor/src/main/java/org/esa/beam/preprocessor/PreprocessorOp.java
+++ b/beam-meris-preprocessor/src/main/java/org/esa/beam/preprocessor/PreprocessorOp.java
@@ -1,316 +1,320 @@
/*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.beam.preprocessor;
import com.bc.ceres.core.Assert;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.beam.framework.datamodel.Band;
import org.esa.beam.framework.datamodel.Product;
import org.esa.beam.framework.datamodel.ProductData;
import org.esa.beam.framework.datamodel.RasterDataNode;
import org.esa.beam.framework.gpf.Operator;
import org.esa.beam.framework.gpf.OperatorException;
import org.esa.beam.framework.gpf.OperatorSpi;
import org.esa.beam.framework.gpf.Tile;
import org.esa.beam.framework.gpf.annotations.OperatorMetadata;
import org.esa.beam.framework.gpf.annotations.Parameter;
import org.esa.beam.framework.gpf.annotations.SourceProduct;
import org.esa.beam.framework.gpf.annotations.TargetProduct;
import org.esa.beam.preprocessor.equalization.EqualizationAlgorithm;
import org.esa.beam.preprocessor.equalization.ReprocessingVersion;
import org.esa.beam.preprocessor.smilecorr.SmileCorrectionAlgorithm;
import org.esa.beam.preprocessor.smilecorr.SmileCorrectionAuxdata;
import org.esa.beam.util.ProductUtils;
import org.esa.beam.util.math.RsMathUtils;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static org.esa.beam.dataio.envisat.EnvisatConstants.*;
@OperatorMetadata(alias = "Preprocess",
description = "Performs radiometric corrections on MERIS L1b data products.",
authors = "Marc Bouvet (ESTEC), Marco Peters (Brockmann Consult), Marco Zuehlke (Brockmann Consult)," +
"Thomas Storm (Brockmann Consult)",
copyright = "(c) 2010 by Brockmann Consult",
version = "1.0")
public class PreprocessorOp extends Operator {
@Parameter(defaultValue = "true",
label = "Perform SMILE correction",
description = "Whether to perform SMILE correction.")
private boolean doSmile;
@Parameter(defaultValue = "true",
label = "Perform equalization",
description = "Perform removal of detector-to-detector systematic radiometric differences in MERIS L1b data products")
private boolean doEqualization;
@Parameter(label = "Reprocessing version", valueSet = {"AUTO_DETECT", "REPROCESSING_2", "REPROCESSING_3"},
defaultValue = "AUTO_DETECT",
description = "The version of the reprocessing the product comes from. Used only in case that " +
"equalisation is to be performed.")
private ReprocessingVersion reproVersion;
@Parameter(defaultValue = "true",
label = "Perform radiometric calibration",
description = "Whether to perform radiometric calibration.")
private boolean doRadiometricRecalibration;
@Parameter(defaultValue = "true",
label = "Perform radiance-to-reflectance conversion",
description = "Whether to perform radiance-to-reflectance conversion.")
private boolean doRadToRefl;
@SourceProduct(alias = "source", label = "Name", description = "The source product.",
bands = {
MERIS_L1B_FLAGS_DS_NAME, MERIS_DETECTOR_INDEX_DS_NAME,
MERIS_L1B_RADIANCE_1_BAND_NAME,
MERIS_L1B_RADIANCE_2_BAND_NAME,
MERIS_L1B_RADIANCE_3_BAND_NAME,
MERIS_L1B_RADIANCE_4_BAND_NAME,
MERIS_L1B_RADIANCE_5_BAND_NAME,
MERIS_L1B_RADIANCE_6_BAND_NAME,
MERIS_L1B_RADIANCE_7_BAND_NAME,
MERIS_L1B_RADIANCE_8_BAND_NAME,
MERIS_L1B_RADIANCE_9_BAND_NAME,
MERIS_L1B_RADIANCE_10_BAND_NAME,
MERIS_L1B_RADIANCE_11_BAND_NAME,
MERIS_L1B_RADIANCE_12_BAND_NAME,
MERIS_L1B_RADIANCE_13_BAND_NAME,
MERIS_L1B_RADIANCE_14_BAND_NAME,
MERIS_L1B_RADIANCE_15_BAND_NAME
})
private Product sourceProduct;
@TargetProduct(description = "The target product.")
private Product targetProduct;
private static final String UNIT_DL = "dl";
private static final String INVALID_MASK_NAME = "invalid";
private static final String LAND_MASK_NAME = "land";
private EqualizationAlgorithm equalizationAlgorithm;
private SmileCorrectionAlgorithm smileCorrectionAlgorithm;
private HashMap<String, String> bandNameMap;
@Override
public void initialize() throws OperatorException {
initAlgorithms();
validateSourceProduct();
createTargetProduct();
}
@Override
public void computeTile(Band targetBand, Tile targetTile, ProgressMonitor pm) throws OperatorException {
final Rectangle targetRegion = targetTile.getRectangle();
final int spectralIndex = targetBand.getSpectralBandIndex();
final String sourceBandName = bandNameMap.get(targetBand.getName());
final Band sourceBand = sourceProduct.getBand(sourceBandName);
final Tile sourceBandTile = loadSourceTile(sourceBandName, targetRegion);
Tile detectorSourceTile = null;
if (doSmile || doEqualization) {
detectorSourceTile = loadSourceTile(MERIS_DETECTOR_INDEX_DS_NAME, targetRegion);
}
Tile sunZenithTile = null;
if (doRadToRefl) {
sunZenithTile = loadSourceTile(MERIS_SUN_ZENITH_DS_NAME, targetRegion);
}
Tile[] radianceTiles = new Tile[0];
Tile landMaskTile = null;
Tile invalidMaskTile = null;
if (doSmile) {
radianceTiles = loadRequiredRadianceTiles(spectralIndex, targetRegion);
invalidMaskTile = loadSourceTile(INVALID_MASK_NAME, targetRegion);
landMaskTile = loadSourceTile(LAND_MASK_NAME, targetRegion);
}
pm.beginTask("Performing MERIS preprocessing...", targetTile.getHeight());
try {
for (int y = targetTile.getMinY(); y <= targetTile.getMaxY(); y++) {
checkForCancellation(pm);
for (int x = targetTile.getMinX(); x <= targetTile.getMaxX(); x++) {
int detectorIndex = -1;
if (doSmile || doEqualization) {
detectorIndex = detectorSourceTile.getSampleInt(x, y);
}
double sample = sourceBandTile.getSampleDouble(x, y);
if (doSmile && !invalidMaskTile.getSampleBoolean(x, y) && detectorIndex != -1) {
sample = smileCorrectionAlgorithm.correct(x, y, spectralIndex, detectorIndex, radianceTiles,
landMaskTile.getSampleBoolean(x, y));
}
if (doRadToRefl) {
final float solarFlux = sourceBand.getSolarFlux();
final double sunZenithSample = sunZenithTile.getSampleDouble(x, y);
sample = RsMathUtils.radianceToReflectance((float) sample, (float) sunZenithSample, solarFlux);
}
if (doEqualization && detectorIndex != -1) {
sample = equalizationAlgorithm.performEqualization(sample, spectralIndex, detectorIndex);
}
targetTile.setSample(x, y, sample);
}
pm.worked(1);
}
} finally {
pm.done();
}
}
private void createTargetProduct() {
final String productType = String.format("%s_Preprocessed", sourceProduct.getProductType());
final String productDescription = "MERIS L1b Preprocessed";
final String targetBandPrefix;
final String bandDescriptionPrefix;
if (doRadToRefl) {
targetBandPrefix = "reflec";
bandDescriptionPrefix = "Preprocessed TOA reflectance band";
} else {
targetBandPrefix = "radiance";
bandDescriptionPrefix = "Preprocessed TOA radiance band";
}
final int rasterWidth = sourceProduct.getSceneRasterWidth();
final int rasterHeight = sourceProduct.getSceneRasterHeight();
targetProduct = new Product(String.format("%s_Preprocessed", sourceProduct.getName()), productType,
rasterWidth, rasterHeight);
targetProduct.setDescription(productDescription);
ProductUtils.copyMetadata(sourceProduct, targetProduct);
ProductUtils.copyTiePointGrids(sourceProduct, targetProduct);
targetProduct.setAutoGrouping(targetBandPrefix);
bandNameMap = new HashMap<String, String>();
List<String> sourceSpectralBandNames = getSpectralBandNames(sourceProduct);
for (String spectralBandName : sourceSpectralBandNames) {
final Band sourceBand = sourceProduct.getBand(spectralBandName);
final int bandIndex = sourceBand.getSpectralBandIndex() + 1;
final String targetBandName = String.format("%s_%d", targetBandPrefix, bandIndex);
final Band targetBand = targetProduct.addBand(targetBandName, ProductData.TYPE_FLOAT32);
bandNameMap.put(targetBandName, spectralBandName);
targetBand.setDescription(String.format("%s %d", bandDescriptionPrefix, bandIndex));
- targetBand.setUnit(UNIT_DL);
+ if (doRadToRefl) {
+ targetBand.setUnit(UNIT_DL);
+ } else {
+ targetBand.setUnit(sourceBand.getUnit());
+ }
targetBand.setValidPixelExpression(sourceBand.getValidPixelExpression());
ProductUtils.copySpectralBandProperties(sourceBand, targetBand);
}
copyBand(MERIS_DETECTOR_INDEX_DS_NAME);
ProductUtils.copyFlagBands(sourceProduct, targetProduct);
final Band sourceFlagBand = sourceProduct.getBand(MERIS_L1B_FLAGS_DS_NAME);
final Band targetFlagBand = targetProduct.getBand(MERIS_L1B_FLAGS_DS_NAME);
targetFlagBand.setSourceImage(sourceFlagBand.getSourceImage());
ProductUtils.copyGeoCoding(sourceProduct, targetProduct);
targetProduct.setStartTime(sourceProduct.getStartTime());
targetProduct.setEndTime(sourceProduct.getEndTime());
// copy all bands not yet considered
final String[] bandNames = sourceProduct.getBandNames();
for (String bandName : bandNames) {
if (!targetProduct.containsBand(bandName) && !sourceSpectralBandNames.contains(bandName)) {
copyBand(bandName);
}
}
}
private void initAlgorithms() {
if (doSmile) {
try {
smileCorrectionAlgorithm = new SmileCorrectionAlgorithm(SmileCorrectionAuxdata.loadAuxdata(
sourceProduct.getProductType()));
} catch (Exception e) {
throw new OperatorException(e);
}
}
if (doEqualization) {
try {
equalizationAlgorithm = new EqualizationAlgorithm(sourceProduct, reproVersion);
} catch (Exception e) {
throw new OperatorException(e);
}
}
}
private void validateSourceProduct() {
Assert.state(MERIS_L1_TYPE_PATTERN.matcher(sourceProduct.getProductType()).matches(),
"Source product must be of type MERIS L1b.");
final String msgPattern = "Source product must contain '%s'.";
if (doSmile) {
Assert.state(sourceProduct.containsBand(MERIS_DETECTOR_INDEX_DS_NAME),
String.format(msgPattern, MERIS_DETECTOR_INDEX_DS_NAME));
Assert.state(sourceProduct.containsBand(MERIS_L1B_FLAGS_DS_NAME),
String.format(msgPattern, MERIS_L1B_FLAGS_DS_NAME));
}
if (doEqualization) {
Assert.state(sourceProduct.getStartTime() != null, "Source product must have a start time");
Assert.state(sourceProduct.containsBand(MERIS_DETECTOR_INDEX_DS_NAME),
String.format(msgPattern, MERIS_DETECTOR_INDEX_DS_NAME));
}
if (doRadToRefl) {
Assert.state(sourceProduct.containsRasterDataNode(MERIS_SUN_ZENITH_DS_NAME),
String.format(msgPattern, MERIS_SUN_ZENITH_DS_NAME));
}
}
private Tile[] loadRequiredRadianceTiles(int spectralBandIndex, Rectangle targetRectangle) {
final int[] requiredBandIndices = smileCorrectionAlgorithm.computeRequiredBandIndexes(spectralBandIndex);
Tile[] radianceTiles = new Tile[MERIS_L1B_NUM_SPECTRAL_BANDS];
for (int requiredBandIndex : requiredBandIndices) {
final Band band = sourceProduct.getBandAt(requiredBandIndex);
radianceTiles[requiredBandIndex] = getSourceTile(band, targetRectangle, ProgressMonitor.NULL);
}
return radianceTiles;
}
private Tile loadSourceTile(String sourceNodeName, Rectangle rectangle) {
final RasterDataNode sourceNode = sourceProduct.getRasterDataNode(sourceNodeName);
return getSourceTile(sourceNode, rectangle, ProgressMonitor.NULL);
}
private void copyBand(String sourceBandName) {
final Band destBand = ProductUtils.copyBand(sourceBandName, sourceProduct, targetProduct);
Band srcBand = sourceProduct.getBand(sourceBandName);
destBand.setSourceImage(srcBand.getSourceImage());
}
private List<String> getSpectralBandNames(Product sourceProduct) {
final Band[] bands = sourceProduct.getBands();
final List<String> spectralBandNames = new ArrayList<String>(bands.length);
for (Band band : bands) {
if (band.getSpectralBandIndex() != -1) {
spectralBandNames.add(band.getName());
}
}
return spectralBandNames;
}
public static class Spi extends OperatorSpi {
public Spi() {
super(PreprocessorOp.class);
}
}
}
| true | true | private void createTargetProduct() {
final String productType = String.format("%s_Preprocessed", sourceProduct.getProductType());
final String productDescription = "MERIS L1b Preprocessed";
final String targetBandPrefix;
final String bandDescriptionPrefix;
if (doRadToRefl) {
targetBandPrefix = "reflec";
bandDescriptionPrefix = "Preprocessed TOA reflectance band";
} else {
targetBandPrefix = "radiance";
bandDescriptionPrefix = "Preprocessed TOA radiance band";
}
final int rasterWidth = sourceProduct.getSceneRasterWidth();
final int rasterHeight = sourceProduct.getSceneRasterHeight();
targetProduct = new Product(String.format("%s_Preprocessed", sourceProduct.getName()), productType,
rasterWidth, rasterHeight);
targetProduct.setDescription(productDescription);
ProductUtils.copyMetadata(sourceProduct, targetProduct);
ProductUtils.copyTiePointGrids(sourceProduct, targetProduct);
targetProduct.setAutoGrouping(targetBandPrefix);
bandNameMap = new HashMap<String, String>();
List<String> sourceSpectralBandNames = getSpectralBandNames(sourceProduct);
for (String spectralBandName : sourceSpectralBandNames) {
final Band sourceBand = sourceProduct.getBand(spectralBandName);
final int bandIndex = sourceBand.getSpectralBandIndex() + 1;
final String targetBandName = String.format("%s_%d", targetBandPrefix, bandIndex);
final Band targetBand = targetProduct.addBand(targetBandName, ProductData.TYPE_FLOAT32);
bandNameMap.put(targetBandName, spectralBandName);
targetBand.setDescription(String.format("%s %d", bandDescriptionPrefix, bandIndex));
targetBand.setUnit(UNIT_DL);
targetBand.setValidPixelExpression(sourceBand.getValidPixelExpression());
ProductUtils.copySpectralBandProperties(sourceBand, targetBand);
}
copyBand(MERIS_DETECTOR_INDEX_DS_NAME);
ProductUtils.copyFlagBands(sourceProduct, targetProduct);
final Band sourceFlagBand = sourceProduct.getBand(MERIS_L1B_FLAGS_DS_NAME);
final Band targetFlagBand = targetProduct.getBand(MERIS_L1B_FLAGS_DS_NAME);
targetFlagBand.setSourceImage(sourceFlagBand.getSourceImage());
ProductUtils.copyGeoCoding(sourceProduct, targetProduct);
targetProduct.setStartTime(sourceProduct.getStartTime());
targetProduct.setEndTime(sourceProduct.getEndTime());
// copy all bands not yet considered
final String[] bandNames = sourceProduct.getBandNames();
for (String bandName : bandNames) {
if (!targetProduct.containsBand(bandName) && !sourceSpectralBandNames.contains(bandName)) {
copyBand(bandName);
}
}
}
| private void createTargetProduct() {
final String productType = String.format("%s_Preprocessed", sourceProduct.getProductType());
final String productDescription = "MERIS L1b Preprocessed";
final String targetBandPrefix;
final String bandDescriptionPrefix;
if (doRadToRefl) {
targetBandPrefix = "reflec";
bandDescriptionPrefix = "Preprocessed TOA reflectance band";
} else {
targetBandPrefix = "radiance";
bandDescriptionPrefix = "Preprocessed TOA radiance band";
}
final int rasterWidth = sourceProduct.getSceneRasterWidth();
final int rasterHeight = sourceProduct.getSceneRasterHeight();
targetProduct = new Product(String.format("%s_Preprocessed", sourceProduct.getName()), productType,
rasterWidth, rasterHeight);
targetProduct.setDescription(productDescription);
ProductUtils.copyMetadata(sourceProduct, targetProduct);
ProductUtils.copyTiePointGrids(sourceProduct, targetProduct);
targetProduct.setAutoGrouping(targetBandPrefix);
bandNameMap = new HashMap<String, String>();
List<String> sourceSpectralBandNames = getSpectralBandNames(sourceProduct);
for (String spectralBandName : sourceSpectralBandNames) {
final Band sourceBand = sourceProduct.getBand(spectralBandName);
final int bandIndex = sourceBand.getSpectralBandIndex() + 1;
final String targetBandName = String.format("%s_%d", targetBandPrefix, bandIndex);
final Band targetBand = targetProduct.addBand(targetBandName, ProductData.TYPE_FLOAT32);
bandNameMap.put(targetBandName, spectralBandName);
targetBand.setDescription(String.format("%s %d", bandDescriptionPrefix, bandIndex));
if (doRadToRefl) {
targetBand.setUnit(UNIT_DL);
} else {
targetBand.setUnit(sourceBand.getUnit());
}
targetBand.setValidPixelExpression(sourceBand.getValidPixelExpression());
ProductUtils.copySpectralBandProperties(sourceBand, targetBand);
}
copyBand(MERIS_DETECTOR_INDEX_DS_NAME);
ProductUtils.copyFlagBands(sourceProduct, targetProduct);
final Band sourceFlagBand = sourceProduct.getBand(MERIS_L1B_FLAGS_DS_NAME);
final Band targetFlagBand = targetProduct.getBand(MERIS_L1B_FLAGS_DS_NAME);
targetFlagBand.setSourceImage(sourceFlagBand.getSourceImage());
ProductUtils.copyGeoCoding(sourceProduct, targetProduct);
targetProduct.setStartTime(sourceProduct.getStartTime());
targetProduct.setEndTime(sourceProduct.getEndTime());
// copy all bands not yet considered
final String[] bandNames = sourceProduct.getBandNames();
for (String bandName : bandNames) {
if (!targetProduct.containsBand(bandName) && !sourceSpectralBandNames.contains(bandName)) {
copyBand(bandName);
}
}
}
|
diff --git a/examples/DiningPhilosophers/DiningServer.java b/examples/DiningPhilosophers/DiningServer.java
index 0e8cedb..78a5d59 100644
--- a/examples/DiningPhilosophers/DiningServer.java
+++ b/examples/DiningPhilosophers/DiningServer.java
@@ -1,129 +1,129 @@
package examples.DiningPhilosophers;
/**
* A ``table'' at which the dining philosophers eat and think.
* Concrete subclasses implement the takeForks and putForks methods.
*
* @author Stephen J. Hartley
* @version 2005 July
*/
import java.util.HashMap;
import java.lang.management.*;
public abstract class DiningServer {
/**
* Constants for thinking, hungry, and eating states.
*/
protected enum State { THINKING, HUNGRY, EATING }
/**
* Number of chairs at the table (number of philosophers).
*/
protected int numPhils = 0;
/**
* Array of state information, one entry per philosopher
* (thinking, hungry, eating).
*/
protected State[] state = null;
/**
* Constructor.
* @param numPhils The number of dining philosophers.
*/
protected DiningServer(int numPhils) {
this.numPhils = numPhils;
state = new State[numPhils];
for (int i = 0; i < numPhils; i++) state[i] = State.THINKING;
}
/**
* A dining philosopher wants to pick up its forks if available and eat.
* @param name The name of the philosopher.
* @param id The number of the philosopher.
* @param napEat The time the philosopher wants to eat in milliseconds.
* @throws InterruptedException
*/
public void dine(String name, int id, int napEat)
throws InterruptedException {
try {
takeForks(id);
eat(name, napEat);
} finally { // Make sure we return the
putForks(id); // forks if interrupted
}
}
/**
* Compute the identifying number of left neighbor at table.
* @param i Philosopher number.
* @return Right neighbor number.
*/
protected final int left(int i) { return (numPhils + i - 1) % numPhils;}
/**
* Compute the identifying number of right neighbor at table.
* @param i Philosopher number.
* @return Right neighbor number.
*/
protected final int right(int i) { return (i + 1) % numPhils; }
/**
* A philosopher eats to a genteel sufficiency after thinking
* productively, becoming hungry, and taking its forks if available.
* @param name The name of the philosopher.
* @param napEat The time the philosopher wants to eat in milliseconds.
* @throws InterruptedException
*/
private void eat(String name, int napEat) throws InterruptedException {
int napping;
napping = 1 + (int) AgeRandom.random(napEat);
//System.out.println("age=" + AgeRandom.age() + ", " + name
// + " is eating for " + napping + " ms");
//Thread.sleep(napping);
}
/**
* A hungry philosopher attempts to pick up its two forks. If available,
* the philosopher eats, else waits.
* @param i The number of the hungry philosopher.
* @throws InterruptedException
*/
protected abstract void takeForks(int i) throws InterruptedException;
/**
* A philosopher has finished eating. Return its two forks to the table
* and check for hungry neighbors. If a hungry neighbor's two forks
* are now available, nudge the neighbor.
* @param i The number of the philosopher finished eating.
*/
protected abstract void putForks(int i) throws InterruptedException;
/**
* Print the state of the philosophers.
* @param caller The name of the calling method.
*/
protected void printState(String caller) {
// Build a line and use one println() instead of several print()'s
// so that multiple threads' output does not become interleaved.
- StringBuffer line = new StringBuffer();
- line.append(caller);
- for (int i = 0; i < numPhils; i++) {
- line.append(", " + i + " is " + state[i]);
- }
- System.out.println(line);
+ //StringBuffer line = new StringBuffer();
+ //line.append(caller);
+ //for (int i = 0; i < numPhils; i++) {
+ // line.append(", " + i + " is " + state[i]);
+ //}
+ //System.out.println(line);
}
public long getSyncTime() {
return syncTime;
}
protected void setCurrentCpuTime() {
mapThreadCpuTime.put(Thread.currentThread().getId(), threadMXBean.getCurrentThreadCpuTime());
}
protected void addSyncTime() {
syncTime += threadMXBean.getCurrentThreadCpuTime() - mapThreadCpuTime.get(Thread.currentThread().getId());
}
long syncTime = 0;
HashMap<Long, Long> mapThreadCpuTime = new HashMap<Long, Long>();
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
}
| true | true | protected void printState(String caller) {
// Build a line and use one println() instead of several print()'s
// so that multiple threads' output does not become interleaved.
StringBuffer line = new StringBuffer();
line.append(caller);
for (int i = 0; i < numPhils; i++) {
line.append(", " + i + " is " + state[i]);
}
System.out.println(line);
}
| protected void printState(String caller) {
// Build a line and use one println() instead of several print()'s
// so that multiple threads' output does not become interleaved.
//StringBuffer line = new StringBuffer();
//line.append(caller);
//for (int i = 0; i < numPhils; i++) {
// line.append(", " + i + " is " + state[i]);
//}
//System.out.println(line);
}
|
diff --git a/src/gov/nih/nci/eagle/web/struts/EpiAction.java b/src/gov/nih/nci/eagle/web/struts/EpiAction.java
index 02090a0..e18db85 100755
--- a/src/gov/nih/nci/eagle/web/struts/EpiAction.java
+++ b/src/gov/nih/nci/eagle/web/struts/EpiAction.java
@@ -1,177 +1,177 @@
package gov.nih.nci.eagle.web.struts;
import gov.nih.nci.caintegrator.application.cache.PresentationCacheManager;
import gov.nih.nci.caintegrator.application.lists.ListType;
import gov.nih.nci.caintegrator.application.lists.UserList;
import gov.nih.nci.caintegrator.application.lists.UserListBeanHelper;
import gov.nih.nci.caintegrator.exceptions.FindingsQueryException;
import gov.nih.nci.caintegrator.service.task.Task;
import gov.nih.nci.caintegrator.studyQueryService.FindingsManager;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.EPIQueryDTO;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.EducationLevel;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.ExposureLevel;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.Gender;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.MaritalStatus;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.Relative;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.Religion;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.ResidentialArea;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.SmokingStatus;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.TobaccoType;
import gov.nih.nci.caintegrator.studyQueryService.dto.epi.SmokingExposure;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.util.LabelValueBean;
/**
* all instance variables (objects) in this action are injected by the Spring
* container (application-context-services.xml). The struts action itself is
* managed by spring by use of the
* org.springframework.web.struts.DelegatingActionProxy class. The action path
* can then be referenced by Spring in application-context-struts.xml) All
* struts and spring config files can be found in the WEB-INF directory.
*
* @author landyr
*/
public class EpiAction extends DispatchAction {
private FindingsManager findingsManager;
private PresentationCacheManager presentationCacheManager;
public ActionForward submit(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException {
EPIQueryDTO dto = new EPIQueryDTO();
dto.setQueryName(((EpiForm)form).getQueryName());
try {
Task task = findingsManager.submitQuery(dto);
presentationCacheManager.addNonPersistableToSessionCache(request
.getSession().getId(), task.getId(), task);
} catch (FindingsQueryException e) {
ActionErrors errors = new ActionErrors();
errors.add("queryErrors", new ActionMessage(
"caintegrator.error.query"));
saveMessages(request, errors);
return (mapping.findForward("failure"));
}
return (mapping.findForward("success"));
}
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
EpiForm eform = (EpiForm) form;
//set the group names
UserListBeanHelper helper = new UserListBeanHelper(request.getSession());
List<UserList> patientLists = helper.getLists(ListType.PatientDID);
List<LabelValueBean> lvbeans = new ArrayList<LabelValueBean>();
for(UserList patientList: patientLists){
//sampleGroups.add(new LabelValueBean(patientList.getName(),patientList.getClass().getCanonicalName() + "#" + patientList.getName()));
lvbeans.add(new LabelValueBean(patientList.getName(),patientList.getName()));
}
eform.setExistingGroups(lvbeans);
//set the smoking status
lvbeans = new ArrayList<LabelValueBean>();
for(SmokingStatus s : SmokingStatus.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokingStatus(lvbeans);
//set the gender
lvbeans = new ArrayList<LabelValueBean>();
for(Gender s : Gender.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingGender(lvbeans);
//set the educationLevel
lvbeans = new ArrayList<LabelValueBean>();
for(EducationLevel s : EducationLevel.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingEducationLevel(lvbeans);
//set the residentialArea
lvbeans = new ArrayList<LabelValueBean>();
for(ResidentialArea s : ResidentialArea.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingResidentialArea(lvbeans);
//set the maritalStatus
lvbeans = new ArrayList<LabelValueBean>();
for(MaritalStatus s : MaritalStatus.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingMaritalStatus(lvbeans);
//set the religion
lvbeans = new ArrayList<LabelValueBean>();
for(Religion s : Religion.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingReligion(lvbeans);
//set the relatives
lvbeans = new ArrayList<LabelValueBean>();
for(Relative s : Relative.values()) {
- lvbeans.add(new LabelValueBean(s.getValue(), s.toString()));
+ lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingRelatives(lvbeans);
//set the smokiness
lvbeans = new ArrayList<LabelValueBean>();
for(ExposureLevel s : ExposureLevel.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokiness(lvbeans);
//set the tobacco type
lvbeans = new ArrayList<LabelValueBean>();
for(TobaccoType s : TobaccoType.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingTobaccoType(lvbeans);
//set the smokingAreas
lvbeans = new ArrayList<LabelValueBean>();
for(SmokingExposure s : SmokingExposure.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokingAreas(lvbeans);
return mapping.findForward("success");
}
public FindingsManager getFindingsManager() {
return findingsManager;
}
public void setFindingsManager(FindingsManager findingsManager) {
this.findingsManager = findingsManager;
}
public PresentationCacheManager getPresentationCacheManager() {
return presentationCacheManager;
}
public void setPresentationCacheManager(
PresentationCacheManager presentationCacheManager) {
this.presentationCacheManager = presentationCacheManager;
}
}
| true | true | public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
EpiForm eform = (EpiForm) form;
//set the group names
UserListBeanHelper helper = new UserListBeanHelper(request.getSession());
List<UserList> patientLists = helper.getLists(ListType.PatientDID);
List<LabelValueBean> lvbeans = new ArrayList<LabelValueBean>();
for(UserList patientList: patientLists){
//sampleGroups.add(new LabelValueBean(patientList.getName(),patientList.getClass().getCanonicalName() + "#" + patientList.getName()));
lvbeans.add(new LabelValueBean(patientList.getName(),patientList.getName()));
}
eform.setExistingGroups(lvbeans);
//set the smoking status
lvbeans = new ArrayList<LabelValueBean>();
for(SmokingStatus s : SmokingStatus.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokingStatus(lvbeans);
//set the gender
lvbeans = new ArrayList<LabelValueBean>();
for(Gender s : Gender.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingGender(lvbeans);
//set the educationLevel
lvbeans = new ArrayList<LabelValueBean>();
for(EducationLevel s : EducationLevel.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingEducationLevel(lvbeans);
//set the residentialArea
lvbeans = new ArrayList<LabelValueBean>();
for(ResidentialArea s : ResidentialArea.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingResidentialArea(lvbeans);
//set the maritalStatus
lvbeans = new ArrayList<LabelValueBean>();
for(MaritalStatus s : MaritalStatus.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingMaritalStatus(lvbeans);
//set the religion
lvbeans = new ArrayList<LabelValueBean>();
for(Religion s : Religion.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingReligion(lvbeans);
//set the relatives
lvbeans = new ArrayList<LabelValueBean>();
for(Relative s : Relative.values()) {
lvbeans.add(new LabelValueBean(s.getValue(), s.toString()));
}
eform.setExistingRelatives(lvbeans);
//set the smokiness
lvbeans = new ArrayList<LabelValueBean>();
for(ExposureLevel s : ExposureLevel.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokiness(lvbeans);
//set the tobacco type
lvbeans = new ArrayList<LabelValueBean>();
for(TobaccoType s : TobaccoType.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingTobaccoType(lvbeans);
//set the smokingAreas
lvbeans = new ArrayList<LabelValueBean>();
for(SmokingExposure s : SmokingExposure.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokingAreas(lvbeans);
return mapping.findForward("success");
}
| public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
EpiForm eform = (EpiForm) form;
//set the group names
UserListBeanHelper helper = new UserListBeanHelper(request.getSession());
List<UserList> patientLists = helper.getLists(ListType.PatientDID);
List<LabelValueBean> lvbeans = new ArrayList<LabelValueBean>();
for(UserList patientList: patientLists){
//sampleGroups.add(new LabelValueBean(patientList.getName(),patientList.getClass().getCanonicalName() + "#" + patientList.getName()));
lvbeans.add(new LabelValueBean(patientList.getName(),patientList.getName()));
}
eform.setExistingGroups(lvbeans);
//set the smoking status
lvbeans = new ArrayList<LabelValueBean>();
for(SmokingStatus s : SmokingStatus.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokingStatus(lvbeans);
//set the gender
lvbeans = new ArrayList<LabelValueBean>();
for(Gender s : Gender.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingGender(lvbeans);
//set the educationLevel
lvbeans = new ArrayList<LabelValueBean>();
for(EducationLevel s : EducationLevel.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingEducationLevel(lvbeans);
//set the residentialArea
lvbeans = new ArrayList<LabelValueBean>();
for(ResidentialArea s : ResidentialArea.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingResidentialArea(lvbeans);
//set the maritalStatus
lvbeans = new ArrayList<LabelValueBean>();
for(MaritalStatus s : MaritalStatus.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingMaritalStatus(lvbeans);
//set the religion
lvbeans = new ArrayList<LabelValueBean>();
for(Religion s : Religion.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingReligion(lvbeans);
//set the relatives
lvbeans = new ArrayList<LabelValueBean>();
for(Relative s : Relative.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingRelatives(lvbeans);
//set the smokiness
lvbeans = new ArrayList<LabelValueBean>();
for(ExposureLevel s : ExposureLevel.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokiness(lvbeans);
//set the tobacco type
lvbeans = new ArrayList<LabelValueBean>();
for(TobaccoType s : TobaccoType.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingTobaccoType(lvbeans);
//set the smokingAreas
lvbeans = new ArrayList<LabelValueBean>();
for(SmokingExposure s : SmokingExposure.values()) {
lvbeans.add(new LabelValueBean(s.getName(), s.toString()));
}
eform.setExistingSmokingAreas(lvbeans);
return mapping.findForward("success");
}
|
diff --git a/src/com/google/videoeditor/widgets/PlayheadView.java b/src/com/google/videoeditor/widgets/PlayheadView.java
index 16d3172..30eb822 100755
--- a/src/com/google/videoeditor/widgets/PlayheadView.java
+++ b/src/com/google/videoeditor/widgets/PlayheadView.java
@@ -1,196 +1,197 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.videoeditor.widgets;
import com.google.videoeditor.R;
import com.google.videoeditor.service.VideoEditorProject;
import com.google.videoeditor.util.StringUtils;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
/**
* The view which displays the scroll position
*/
public class PlayheadView extends View {
// Instance variables
private final Paint mLinePaint;
private final Paint mTextPaint;
private final int mTicksHeight;
private final int mScreenWidth;
private final ScrollViewListener mScrollListener;
private int mScrollX;
private VideoEditorProject mProject;
/*
* {@inheritDoc}
*/
public PlayheadView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources resources = context.getResources();
// Prepare the Paint used to draw the tick marks
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.playhead_tick_color));
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);
// Prepare the Paint used to draw the text
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(resources.getColor(R.color.playhead_tick_color));
mTextPaint.setTextSize(18);
// The ticks height
mTicksHeight = (int)resources.getDimension(R.dimen.playhead_tick_height);
// Get the screen width
final Display display = ((WindowManager)context.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScreenWidth = metrics.widthPixels;
// Listen to scroll events and repaint this view as needed
mScrollListener = new ScrollViewListener() {
/*
* {@inheritDoc}
*/
public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
+ invalidate();
}
/*
* {@inheritDoc}
*/
public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
};
}
/*
* {@inheritDoc}
*/
public PlayheadView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
/*
* {@inheritDoc}
*/
public PlayheadView(Context context) {
this(context, null, 0);
}
/*
* {@inheritDoc}
*/
@Override
protected void onAttachedToWindow() {
final TimelineHorizontalScrollView scrollView =
(TimelineHorizontalScrollView)((View)getParent()).getParent();
mScrollX = scrollView.getScrollX();
scrollView.addScrollListener(mScrollListener);
}
/*
* {@inheritDoc}
*/
@Override
protected void onDetachedFromWindow() {
final TimelineHorizontalScrollView scrollView =
(TimelineHorizontalScrollView)((View)getParent()).getParent();
scrollView.removeScrollListener(mScrollListener);
}
/**
* @param project The project
*/
public void setProject(VideoEditorProject project) {
mProject = project;
}
/*
* {@inheritDoc}
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mProject == null) {
return;
}
final long durationMs = mProject.computeDuration();
final long durationSec = durationMs / 1000;
if (durationMs == 0 || durationSec == 0) {
final String timeText = StringUtils.getSimpleTimestampAsString(getContext(), 0);
canvas.drawText(timeText, (getWidth() / 2) - 35, 28, mTextPaint);
return;
}
final int width = getWidth() - mScreenWidth;
// Compute the number of pixels per second
final int pixelsPerSec = (int)(width / durationSec);
// Compute the distance between ticks
final long tickMs;
if (pixelsPerSec < 4) {
tickMs = 240000;
} else if (pixelsPerSec < 6) {
tickMs = 120000;
} else if (pixelsPerSec < 10) {
tickMs = 60000;
} else if (pixelsPerSec < 50) {
tickMs = 10000;
} else if (pixelsPerSec < 200) {
tickMs = 5000;
} else {
tickMs = 1000;
}
final float spacing = ((float)(width * tickMs) / (float)durationMs);
final float startX = Math.max(mScrollX - (((mScrollX - (mScreenWidth / 2)) % spacing)),
mScreenWidth / 2);
float startMs = ((tickMs * (startX - (mScreenWidth / 2))) / spacing);
startMs = Math.round(startMs);
startMs -= (startMs % tickMs);
final float endX = Math.min(mScrollX + mScreenWidth, getWidth() - (mScreenWidth / 2));
for (float i = startX; i <= endX; i += spacing, startMs += tickMs) {
final String timeText = StringUtils.getSimpleTimestampAsString(getContext(),
(long)startMs);
canvas.drawText(timeText, i - 35, 28, mTextPaint);
canvas.drawLine(i, 0, i, mTicksHeight, mLinePaint);
}
}
}
| true | true | public PlayheadView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources resources = context.getResources();
// Prepare the Paint used to draw the tick marks
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.playhead_tick_color));
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);
// Prepare the Paint used to draw the text
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(resources.getColor(R.color.playhead_tick_color));
mTextPaint.setTextSize(18);
// The ticks height
mTicksHeight = (int)resources.getDimension(R.dimen.playhead_tick_height);
// Get the screen width
final Display display = ((WindowManager)context.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScreenWidth = metrics.widthPixels;
// Listen to scroll events and repaint this view as needed
mScrollListener = new ScrollViewListener() {
/*
* {@inheritDoc}
*/
public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
}
/*
* {@inheritDoc}
*/
public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
};
}
| public PlayheadView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final Resources resources = context.getResources();
// Prepare the Paint used to draw the tick marks
mLinePaint = new Paint();
mLinePaint.setColor(resources.getColor(R.color.playhead_tick_color));
mLinePaint.setStrokeWidth(2);
mLinePaint.setStyle(Paint.Style.STROKE);
// Prepare the Paint used to draw the text
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setColor(resources.getColor(R.color.playhead_tick_color));
mTextPaint.setTextSize(18);
// The ticks height
mTicksHeight = (int)resources.getDimension(R.dimen.playhead_tick_height);
// Get the screen width
final Display display = ((WindowManager)context.getSystemService(
Context.WINDOW_SERVICE)).getDefaultDisplay();
final DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
mScreenWidth = metrics.widthPixels;
// Listen to scroll events and repaint this view as needed
mScrollListener = new ScrollViewListener() {
/*
* {@inheritDoc}
*/
public void onScrollBegin(View view, int scrollX, int scrollY, boolean appScroll) {
}
/*
* {@inheritDoc}
*/
public void onScrollProgress(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
/*
* {@inheritDoc}
*/
public void onScrollEnd(View view, int scrollX, int scrollY, boolean appScroll) {
mScrollX = scrollX;
invalidate();
}
};
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/JavaBreakpointTypeChange.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/JavaBreakpointTypeChange.java
index d9fe1a22b..961c7b318 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/JavaBreakpointTypeChange.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/core/refactoring/JavaBreakpointTypeChange.java
@@ -1,450 +1,453 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.internal.debug.core.refactoring;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.model.IBreakpoint;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IPackageFragment;
import org.eclipse.jdt.core.IPackageFragmentRoot;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.debug.core.IJavaBreakpoint;
import org.eclipse.jdt.debug.core.IJavaClassPrepareBreakpoint;
import org.eclipse.jdt.debug.core.IJavaExceptionBreakpoint;
import org.eclipse.jdt.debug.core.IJavaLineBreakpoint;
import org.eclipse.jdt.debug.core.IJavaMethodBreakpoint;
import org.eclipse.jdt.debug.core.IJavaWatchpoint;
import org.eclipse.jdt.debug.core.JDIDebugModel;
import org.eclipse.jdt.internal.debug.ui.BreakpointUtils;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.NullChange;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
/**
* Abtract change to update a breakpoint when a IType is moved or renamed.
*/
public abstract class JavaBreakpointTypeChange extends Change {
public static final int TYPE_RENAME= 1;
public static final int TYPE_MOVE= 2;
public static final int PROJECT_RENAME= 3;
public static final int PACKAGE_RENAME= 4;
public static final int PACKAGE_MOVE= 5;
private IJavaBreakpoint fBreakpoint;
private Object fChangedElement;
private Object fArgument;
private int fChangeType;
private IType fDeclaringType;
private boolean fIsEnable;
private Map fAttributes;
private int fHitCount;
/**
* Create changes for each breakpoint which needs to be updated for this IType rename.
*/
public static Change createChangesForTypeRename(IType type, String newName) throws CoreException {
return createChangesForTypeChange(type, newName, TYPE_RENAME);
}
/**
* Create changes for each breakpoint which needs to be updated for this IType move.
*/
public static Change createChangesForTypeMove(IType type, Object destination) throws CoreException {
return createChangesForTypeChange(type, destination, TYPE_MOVE);
}
/**
* Create a change for each breakpoint which needs to be updated for this IJavaProject rename.
*/
public static Change createChangesForProjectRename(IJavaProject project, String newName) throws CoreException {
List changes= new ArrayList();
IBreakpoint[] breakpoints= DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(JDIDebugModel.getPluginIdentifier());
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaBreakpoint) {
IJavaBreakpoint javaBreakpoint= (IJavaBreakpoint) breakpoint;
IType breakpointType= BreakpointUtils.getType(javaBreakpoint);
if (breakpointType != null && project.equals(breakpointType.getJavaProject())) {
changes.add(createChange(javaBreakpoint, null, newName, PROJECT_RENAME));
}
}
}
return JDTDebugRefactoringUtil.createChangeFromList(changes, RefactoringMessages.getString("JavaBreakpointTypeChange.0")); //$NON-NLS-1$
}
/**
* Create a change for each breakpoint which needs to be updated for this IPackageFragment rename.
*/
public static Change createChangesForPackageRename(IPackageFragment packageFragment, String newName) throws CoreException {
return createChangesForPackageChange(packageFragment, newName, PACKAGE_RENAME);
}
/**
* Create a change for each breakponit which needs to be updated for this IPackageFragment move.
*/
public static Change createChangesForPackageMove(IPackageFragment packageFragment, IPackageFragmentRoot destination) throws CoreException {
return createChangesForPackageChange(packageFragment, destination, PACKAGE_MOVE);
}
/**
* Create changes for each breakpoint which need to be updated for this IType change.
*/
private static Change createChangesForTypeChange(IType changedType, Object argument, int changeType) throws CoreException {
List changes= new ArrayList();
IBreakpoint[] breakpoints= DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(JDIDebugModel.getPluginIdentifier());
String typeName= changedType.getFullyQualifiedName();
for (int i= 0; i < breakpoints.length; i++) {
// for each breakpoint
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaBreakpoint) {
IJavaBreakpoint javaBreakpoint= (IJavaBreakpoint) breakpoint;
IType breakpointType= BreakpointUtils.getType(javaBreakpoint);
// check the name of the type where the breakpoint is installed
if (breakpointType != null && javaBreakpoint.getTypeName().startsWith(typeName)) {
// if it matcheds, check the type
if (changedType.equals(breakpointType)) {
changes.add(createChange(javaBreakpoint, changedType, argument, changeType));
} else {
// if it's not the type, check the inner types
Change change= createChangesForOuterTypeChange(javaBreakpoint, changedType, changedType, argument, changeType);
if (change != null) {
changes.add(change);
}
}
}
}
}
return JDTDebugRefactoringUtil.createChangeFromList(changes, RefactoringMessages.getString("JavaBreakpointTypeChange.0")); //$NON-NLS-1$
}
private static Change createChangesForOuterTypeChange(IJavaBreakpoint javaBreakpoint, IType type, IType changedType, Object argument, int changeType) throws CoreException {
IType[] innerTypes= type.getTypes();
String breakpointTypeName= javaBreakpoint.getTypeName();
IType breakpointType= BreakpointUtils.getType(javaBreakpoint);
for (int i= 0; i < innerTypes.length; i++) {
IType innerType= innerTypes[i];
// check the name of the type where the breakpoint is installed
if (breakpointTypeName.startsWith(innerType.getFullyQualifiedName())) {
// if it matcheds, check the type
if (innerType.equals(breakpointType)) {
return createChange(javaBreakpoint, changedType, argument, changeType);
}
// if it's not the type, check the inner types
return createChangesForOuterTypeChange(javaBreakpoint, innerType, changedType, argument, changeType);
}
}
return null;
}
/**
* Create a change for each breakpoint which needs to be updated for this IPackageFragment change.
*/
private static Change createChangesForPackageChange(IPackageFragment packageFragment, Object argument, int changeType) throws CoreException {
List changes= new ArrayList();
IBreakpoint[] breakpoints= DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(JDIDebugModel.getPluginIdentifier());
for (int i= 0; i < breakpoints.length; i++) {
IBreakpoint breakpoint= breakpoints[i];
if (breakpoint instanceof IJavaBreakpoint) {
IJavaBreakpoint javaBreakpoint= (IJavaBreakpoint) breakpoint;
IType breakpointType= BreakpointUtils.getType(javaBreakpoint);
if (breakpointType != null && packageFragment.equals(breakpointType.getPackageFragment())) {
changes.add(createChange(javaBreakpoint, packageFragment, argument, changeType));
}
}
}
return JDTDebugRefactoringUtil.createChangeFromList(changes, RefactoringMessages.getString("JavaBreakpointTypeChange.0")); //$NON-NLS-1$
}
/**
* Create a change according to type of the breakpoint.
*/
private static Change createChange(IJavaBreakpoint javaBreakpoint, Object changedElement, Object argument, int changeType) throws CoreException {
if (javaBreakpoint instanceof IJavaClassPrepareBreakpoint) {
return new JavaClassPrepareBreakpointTypeChange((IJavaClassPrepareBreakpoint) javaBreakpoint, changedElement, argument, changeType);
} else if (javaBreakpoint instanceof IJavaExceptionBreakpoint) {
return new JavaExceptionBreakpointTypeChange((IJavaExceptionBreakpoint) javaBreakpoint, changedElement, argument, changeType);
} else if (javaBreakpoint instanceof IJavaMethodBreakpoint) {
return new JavaMethodBreakpointTypeChange((IJavaMethodBreakpoint) javaBreakpoint, changedElement, argument, changeType);
} else if (javaBreakpoint instanceof IJavaWatchpoint) {
return new JavaWatchpointTypeChange((IJavaWatchpoint) javaBreakpoint, changedElement, argument, changeType);
} else if (javaBreakpoint instanceof IJavaLineBreakpoint) {
return new JavaLineBreakpointTypeChange((IJavaLineBreakpoint) javaBreakpoint, changedElement, argument, changeType);
} else {
return null;
}
}
/**
* JavaBreakpointTypeChange constructor.
*/
protected JavaBreakpointTypeChange(IJavaBreakpoint breakpoint, Object changedElement, Object argument, int changeType) throws CoreException {
fBreakpoint= breakpoint;
fChangedElement= changedElement;
fArgument= argument;
fChangeType= changeType;
fDeclaringType= BreakpointUtils.getType(breakpoint);
fAttributes= breakpoint.getMarker().getAttributes();
fIsEnable= breakpoint.isEnabled();
fHitCount= breakpoint.getHitCount();
}
/* (non-Javadoc)
* @see org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.eclipse.core.runtime.IProgressMonitor)
*/
public void initializeValidationData(IProgressMonitor pm) {
}
/* (non-Javadoc)
* @see org.eclipse.ltk.core.refactoring.Change#isValid(org.eclipse.core.runtime.IProgressMonitor)
*/
public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException {
RefactoringStatus status= new RefactoringStatus();
if (!fBreakpoint.isRegistered()) {
status.addFatalError(getErrorMessageNoMoreExists());
}
return status;
}
/* (non-Javadoc)
* @see org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime.IProgressMonitor)
*/
public Change perform(IProgressMonitor pm) throws CoreException {
switch (fChangeType) {
case TYPE_RENAME:
return performTypeRename();
case TYPE_MOVE:
return performTypeMove();
case PROJECT_RENAME:
return performProjectRename();
case PACKAGE_RENAME:
return performPackageRename();
case PACKAGE_MOVE:
return performPackageMove();
}
return null;
}
private Change performTypeRename() throws CoreException {
// Get the new type and the new 'changed' type then call the code specific to this type
// of breakpoint.
IType changedType= getChangedType();
String oldChangedTypeName= changedType.getFullyQualifiedName();
String newChangedTypeName;
IType parent= changedType.getDeclaringType();
if (parent == null) {
newChangedTypeName= changedType.getPackageFragment().getElementName() + '.' + getNewName();
} else {
newChangedTypeName= parent.getFullyQualifiedName() + '$' + getNewName();
}
IType newChangedType;
IType newType;
IJavaProject project= fDeclaringType.getJavaProject();
if (changedType == fDeclaringType) {
newType= project.findType(newChangedTypeName);
newChangedType= newType;
} else {
String typeNameSuffix= fDeclaringType.getFullyQualifiedName().substring(oldChangedTypeName.length());
String newTypeName= newChangedTypeName + typeNameSuffix;
newType= project.findType(newTypeName);
newChangedType= project.findType(newChangedTypeName);
}
/*return*/ performChange(newType, newChangedType, changedType.getElementName(), TYPE_RENAME);
return new NullChange();
}
private Change performTypeMove() throws CoreException {
// Get the new type and the new 'changed' type then call the code specific to this type
// of breakpoint.
IType changedType= getChangedType();
Object destination= getDestination();
String newChangedTypeName;
+ IJavaProject project;
if (destination instanceof IPackageFragment) {
IPackageFragment packageDestination= (IPackageFragment) destination;
+ project= packageDestination.getJavaProject();
if (packageDestination.isDefaultPackage()) {
newChangedTypeName= changedType.getElementName();
} else {
newChangedTypeName= ((IPackageFragment)destination).getElementName() + '.' + changedType.getElementName();
}
} else {
- newChangedTypeName= ((IType)destination).getFullyQualifiedName() + '$' + changedType.getElementName();
+ IType type = (IType)destination;
+ newChangedTypeName= (type).getFullyQualifiedName() + '$' + changedType.getElementName();
+ project= type.getJavaProject();
}
IType newChangedType;
IType newType;
- IJavaProject project= fDeclaringType.getJavaProject();
if (changedType == fDeclaringType) {
newType= project.findType(newChangedTypeName);
newChangedType= newType;
} else {
String oldChangedTypeName= changedType.getFullyQualifiedName();
String typeNameSuffix= fDeclaringType.getFullyQualifiedName().substring(oldChangedTypeName.length());
String newTypeName= newChangedTypeName + typeNameSuffix;
newType= project.findType(newTypeName);
newChangedType= project.findType(newChangedTypeName);
}
Object oldDestination= changedType.getDeclaringType();
if (oldDestination == null) {
oldDestination= changedType.getPackageFragment();
}
/*return*/ performChange(newType, newChangedType, oldDestination, TYPE_MOVE);
return new NullChange();
}
private Change performProjectRename() throws CoreException {
// Get the new type, then call the code specific to this type of breakpoint.
IJavaProject project= JavaCore.create(ResourcesPlugin.getWorkspace().getRoot().getProject(getNewName()));
IType newType= project.findType(fDeclaringType.getFullyQualifiedName());
/*return*/ performChange(newType, null, fDeclaringType.getJavaProject().getElementName(), PROJECT_RENAME);
return new NullChange();
}
private Change performPackageRename() throws CoreException {
// Get the new type and the new package fragment, then call the code specific
// to this type of breakpoint.
IPackageFragment changedPackage= getChangePackage();
IJavaProject project= fDeclaringType.getJavaProject();
String newTypeName= getNewName() + fDeclaringType.getFullyQualifiedName().substring(changedPackage.getElementName().length());
IType newType= project.findType(newTypeName);
/*return*/ performChange(newType, newType.getPackageFragment(), changedPackage.getElementName(), PACKAGE_RENAME);
return new NullChange();
}
private Change performPackageMove() throws CoreException {
IPackageFragmentRoot destination= getPackageRootDestination();
IPackageFragment changedPackage= getChangePackage();
IJavaProject project= destination.getJavaProject();
IType newType= project.findType(fDeclaringType.getFullyQualifiedName());
/*return*/ performChange(newType, newType.getPackageFragment(), changedPackage.getParent(), PROJECT_RENAME);
return new NullChange();
}
/* (non-Javadoc)
* @see org.eclipse.ltk.core.refactoring.Change#getModifiedElement()
*/
public Object getModifiedElement() {
return getBreakpoint();
}
/**
* Return the breakpoint modified in this change.
*/
public IJavaBreakpoint getBreakpoint() {
return fBreakpoint;
}
/**
* Return the new name of the changed type for a IType, IJavaProject
* or IPackageFragment rename change.
*/
public String getNewName() {
if (fChangeType == TYPE_RENAME || fChangeType == PROJECT_RENAME || fChangeType == PACKAGE_RENAME) {
return (String)fArgument;
}
return null;
}
/**
* Return the destination for a IType move change.
*/
private Object getDestination() {
if (fChangeType == TYPE_MOVE) {
return fArgument;
}
return null;
}
/**
* Return the destination for a IPackageFragment move change.
*/
private IPackageFragmentRoot getPackageRootDestination() {
if (fChangeType == PACKAGE_MOVE) {
return (IPackageFragmentRoot)fArgument;
}
return null;
}
/**
* Return the original declaring type of the breakpoint.
*/
public IType getDeclaringType() {
return fDeclaringType;
}
/**
* Return the type modified.
*/
public IType getChangedType() {
if (fChangeType == TYPE_RENAME || fChangeType == TYPE_MOVE) {
return (IType) fChangedElement;
}
return null;
}
/**
* Return the package modified.
*/
public IPackageFragment getChangePackage() {
if (fChangeType == PACKAGE_RENAME || fChangeType == PACKAGE_MOVE) {
return (IPackageFragment) fChangedElement;
}
return null;
}
/**
* Return the enable state of the breakpoint.
*/
public boolean getEnable() {
return fIsEnable;
}
/**
* Return the attributes map of the breakpoint.
*/
public Map getAttributes() {
return fAttributes;
}
/**
* Return the hit count of the breakpoint.
*/
public int getHitCount() {
return fHitCount;
}
/**
* Return the message to use if the breakpoint no more exists (used in #isValid()).
*/
public abstract String getErrorMessageNoMoreExists();
/**
* Perform the real modifications.
* @return the undo change.
*/
public abstract Change performChange(IType newType, Object undoChangedElement, Object undoArgument, int changeType) throws CoreException;
}
| false | true | private Change performTypeMove() throws CoreException {
// Get the new type and the new 'changed' type then call the code specific to this type
// of breakpoint.
IType changedType= getChangedType();
Object destination= getDestination();
String newChangedTypeName;
if (destination instanceof IPackageFragment) {
IPackageFragment packageDestination= (IPackageFragment) destination;
if (packageDestination.isDefaultPackage()) {
newChangedTypeName= changedType.getElementName();
} else {
newChangedTypeName= ((IPackageFragment)destination).getElementName() + '.' + changedType.getElementName();
}
} else {
newChangedTypeName= ((IType)destination).getFullyQualifiedName() + '$' + changedType.getElementName();
}
IType newChangedType;
IType newType;
IJavaProject project= fDeclaringType.getJavaProject();
if (changedType == fDeclaringType) {
newType= project.findType(newChangedTypeName);
newChangedType= newType;
} else {
String oldChangedTypeName= changedType.getFullyQualifiedName();
String typeNameSuffix= fDeclaringType.getFullyQualifiedName().substring(oldChangedTypeName.length());
String newTypeName= newChangedTypeName + typeNameSuffix;
newType= project.findType(newTypeName);
newChangedType= project.findType(newChangedTypeName);
}
Object oldDestination= changedType.getDeclaringType();
if (oldDestination == null) {
oldDestination= changedType.getPackageFragment();
}
/*return*/ performChange(newType, newChangedType, oldDestination, TYPE_MOVE);
return new NullChange();
}
| private Change performTypeMove() throws CoreException {
// Get the new type and the new 'changed' type then call the code specific to this type
// of breakpoint.
IType changedType= getChangedType();
Object destination= getDestination();
String newChangedTypeName;
IJavaProject project;
if (destination instanceof IPackageFragment) {
IPackageFragment packageDestination= (IPackageFragment) destination;
project= packageDestination.getJavaProject();
if (packageDestination.isDefaultPackage()) {
newChangedTypeName= changedType.getElementName();
} else {
newChangedTypeName= ((IPackageFragment)destination).getElementName() + '.' + changedType.getElementName();
}
} else {
IType type = (IType)destination;
newChangedTypeName= (type).getFullyQualifiedName() + '$' + changedType.getElementName();
project= type.getJavaProject();
}
IType newChangedType;
IType newType;
if (changedType == fDeclaringType) {
newType= project.findType(newChangedTypeName);
newChangedType= newType;
} else {
String oldChangedTypeName= changedType.getFullyQualifiedName();
String typeNameSuffix= fDeclaringType.getFullyQualifiedName().substring(oldChangedTypeName.length());
String newTypeName= newChangedTypeName + typeNameSuffix;
newType= project.findType(newTypeName);
newChangedType= project.findType(newChangedTypeName);
}
Object oldDestination= changedType.getDeclaringType();
if (oldDestination == null) {
oldDestination= changedType.getPackageFragment();
}
/*return*/ performChange(newType, newChangedType, oldDestination, TYPE_MOVE);
return new NullChange();
}
|
diff --git a/chips/src/com/android/ex/chips/RecipientAlternatesAdapter.java b/chips/src/com/android/ex/chips/RecipientAlternatesAdapter.java
index 39257fa..e3ef6cd 100644
--- a/chips/src/com/android/ex/chips/RecipientAlternatesAdapter.java
+++ b/chips/src/com/android/ex/chips/RecipientAlternatesAdapter.java
@@ -1,298 +1,298 @@
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ex.chips;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.text.util.Rfc822Token;
import android.text.util.Rfc822Tokenizer;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.ex.chips.Queries.Query;
import java.util.HashMap;
import java.util.HashSet;
/**
* RecipientAlternatesAdapter backs the RecipientEditTextView for managing contacts
* queried by email or by phone number.
*/
public class RecipientAlternatesAdapter extends CursorAdapter {
static final int MAX_LOOKUPS = 50;
private final LayoutInflater mLayoutInflater;
private final long mCurrentId;
private int mCheckedItemPosition = -1;
private OnCheckedItemChangedListener mCheckedItemChangedListener;
private static final String TAG = "RecipAlternates";
public static final int QUERY_TYPE_EMAIL = 0;
public static final int QUERY_TYPE_PHONE = 1;
private Query mQuery;
public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context,
String[] inAddresses) {
return getMatchingRecipients(context, inAddresses, QUERY_TYPE_EMAIL);
}
/**
* Get a HashMap of address to RecipientEntry that contains all contact
* information for a contact with the provided address, if one exists. This
* may block the UI, so run it in an async task.
*
* @param context Context.
* @param inAddresses Array of addresses on which to perform the lookup.
* @return HashMap<String,RecipientEntry>
*/
public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context,
String[] inAddresses, int addressType) {
Queries.Query query;
if (addressType == QUERY_TYPE_EMAIL) {
query = Queries.EMAIL;
} else {
query = Queries.PHONE;
}
int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.length);
String[] addresses = new String[addressesSize];
StringBuilder bindString = new StringBuilder();
// Create the "?" string and set up arguments.
for (int i = 0; i < addressesSize; i++) {
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses[i].toLowerCase());
addresses[i] = (tokens.length > 0 ? tokens[0].getAddress() : inAddresses[i]);
bindString.append("?");
if (i < addressesSize - 1) {
bindString.append(",");
}
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Doing reverse lookup for " + addresses.toString());
}
HashMap<String, RecipientEntry> recipientEntries = new HashMap<String, RecipientEntry>();
Cursor c = context.getContentResolver().query(
- query.getContentUri(), query.getProjection(),
- Queries.Query.DESTINATION + " IN (" + bindString.toString() + ")",
- addresses,
- null);
+ query.getContentUri(),
+ query.getProjection(),
+ query.getProjection()[Queries.Query.DESTINATION] + " IN (" + bindString.toString()
+ + ")", addresses, null);
if (c != null) {
try {
if (c.moveToFirst()) {
do {
String address = c.getString(Queries.Query.DESTINATION);
recipientEntries.put(address, RecipientEntry.constructTopLevelEntry(
c.getString(Queries.Query.NAME),
c.getInt(Queries.Query.DISPLAY_NAME_SOURCE),
c.getString(Queries.Query.DESTINATION),
c.getInt(Queries.Query.DESTINATION_TYPE),
c.getString(Queries.Query.DESTINATION_LABEL),
c.getLong(Queries.Query.CONTACT_ID),
c.getLong(Queries.Query.DATA_ID),
c.getString(Queries.Query.PHOTO_THUMBNAIL_URI)));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Received reverse look up information for " + address
+ " RESULTS: "
+ " NAME : " + c.getString(Queries.Query.NAME)
+ " CONTACT ID : " + c.getLong(Queries.Query.CONTACT_ID)
+ " ADDRESS :" + c.getString(Queries.Query.DESTINATION));
}
} while (c.moveToNext());
}
} finally {
c.close();
}
}
return recipientEntries;
}
public RecipientAlternatesAdapter(Context context, long contactId, long currentId, int viewId,
OnCheckedItemChangedListener listener) {
this(context, contactId, currentId, viewId, QUERY_TYPE_EMAIL, listener);
}
public RecipientAlternatesAdapter(Context context, long contactId, long currentId, int viewId,
int queryMode, OnCheckedItemChangedListener listener) {
super(context, getCursorForConstruction(context, contactId, queryMode), 0);
mLayoutInflater = LayoutInflater.from(context);
mCurrentId = currentId;
mCheckedItemChangedListener = listener;
if (queryMode == QUERY_TYPE_EMAIL) {
mQuery = Queries.EMAIL;
} else if (queryMode == QUERY_TYPE_PHONE) {
mQuery = Queries.PHONE;
} else {
mQuery = Queries.EMAIL;
Log.e(TAG, "Unsupported query type: " + queryMode);
}
}
private static Cursor getCursorForConstruction(Context context, long contactId, int queryType) {
final Cursor cursor;
if (queryType == QUERY_TYPE_EMAIL) {
cursor = context.getContentResolver().query(
Queries.EMAIL.getContentUri(),
Queries.EMAIL.getProjection(),
Queries.EMAIL.getProjection()[Queries.Query.CONTACT_ID] + " =?", new String[] {
String.valueOf(contactId)
}, null);
} else {
cursor = context.getContentResolver().query(
Queries.PHONE.getContentUri(),
Queries.PHONE.getProjection(),
Queries.PHONE.getProjection()[Queries.Query.CONTACT_ID] + " =?", new String[] {
String.valueOf(contactId)
}, null);
}
return removeDuplicateDestinations(cursor);
}
/**
* @return a new cursor based on the given cursor with all duplicate destinations removed.
*
* It's only intended to use for the alternate list, so...
* - This method ignores all other fields and dedupe solely on the destination. Normally,
* if a cursor contains multiple contacts and they have the same destination, we'd still want
* to show both.
* - This method creates a MatrixCursor, so all data will be kept in memory. We wouldn't want
* to do this if the original cursor is large, but it's okay here because the alternate list
* won't be that big.
*/
// Visible for testing
/* package */ static Cursor removeDuplicateDestinations(Cursor original) {
final MatrixCursor result = new MatrixCursor(
original.getColumnNames(), original.getCount());
final HashSet<String> destinationsSeen = new HashSet<String>();
original.moveToPosition(-1);
while (original.moveToNext()) {
final String destination = original.getString(Query.DESTINATION);
if (destinationsSeen.contains(destination)) {
continue;
}
destinationsSeen.add(destination);
result.addRow(new Object[] {
original.getString(Query.NAME),
original.getString(Query.DESTINATION),
original.getInt(Query.DESTINATION_TYPE),
original.getString(Query.DESTINATION_LABEL),
original.getLong(Query.CONTACT_ID),
original.getLong(Query.DATA_ID),
original.getString(Query.PHOTO_THUMBNAIL_URI),
original.getInt(Query.DISPLAY_NAME_SOURCE)
});
}
return result;
}
@Override
public long getItemId(int position) {
Cursor c = getCursor();
if (c.moveToPosition(position)) {
c.getLong(Queries.Query.DATA_ID);
}
return -1;
}
public RecipientEntry getRecipientEntry(int position) {
Cursor c = getCursor();
c.moveToPosition(position);
return RecipientEntry.constructTopLevelEntry(
c.getString(Queries.Query.NAME),
c.getInt(Queries.Query.DISPLAY_NAME_SOURCE),
c.getString(Queries.Query.DESTINATION),
c.getInt(Queries.Query.DESTINATION_TYPE),
c.getString(Queries.Query.DESTINATION_LABEL),
c.getLong(Queries.Query.CONTACT_ID),
c.getLong(Queries.Query.DATA_ID),
c.getString(Queries.Query.PHOTO_THUMBNAIL_URI));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Cursor cursor = getCursor();
cursor.moveToPosition(position);
if (convertView == null) {
convertView = newView();
}
if (cursor.getLong(Queries.Query.DATA_ID) == mCurrentId) {
mCheckedItemPosition = position;
if (mCheckedItemChangedListener != null) {
mCheckedItemChangedListener.onCheckedItemChanged(mCheckedItemPosition);
}
}
bindView(convertView, convertView.getContext(), cursor);
return convertView;
}
// TODO: this is VERY similar to the BaseRecipientAdapter. Can we combine
// somehow?
@Override
public void bindView(View view, Context context, Cursor cursor) {
int position = cursor.getPosition();
TextView display = (TextView) view.findViewById(android.R.id.title);
ImageView imageView = (ImageView) view.findViewById(android.R.id.icon);
RecipientEntry entry = getRecipientEntry(position);
if (position == 0) {
display.setText(cursor.getString(Queries.Query.NAME));
display.setVisibility(View.VISIBLE);
// TODO: see if this needs to be done outside the main thread
// as it may be too slow to get immediately.
imageView.setImageURI(entry.getPhotoThumbnailUri());
imageView.setVisibility(View.VISIBLE);
} else {
display.setVisibility(View.GONE);
imageView.setVisibility(View.GONE);
}
TextView destination = (TextView) view.findViewById(android.R.id.text1);
destination.setText(cursor.getString(Queries.Query.DESTINATION));
TextView destinationType = (TextView) view.findViewById(android.R.id.text2);
if (destinationType != null) {
destinationType.setText(mQuery.getTypeLabel(context.getResources(),
cursor.getInt(Queries.Query.DESTINATION_TYPE),
cursor.getString(Queries.Query.DESTINATION_LABEL)).toString().toUpperCase());
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return newView();
}
private View newView() {
return mLayoutInflater.inflate(R.layout.chips_recipient_dropdown_item, null);
}
/*package*/ static interface OnCheckedItemChangedListener {
public void onCheckedItemChanged(int position);
}
}
| true | true | public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context,
String[] inAddresses, int addressType) {
Queries.Query query;
if (addressType == QUERY_TYPE_EMAIL) {
query = Queries.EMAIL;
} else {
query = Queries.PHONE;
}
int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.length);
String[] addresses = new String[addressesSize];
StringBuilder bindString = new StringBuilder();
// Create the "?" string and set up arguments.
for (int i = 0; i < addressesSize; i++) {
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses[i].toLowerCase());
addresses[i] = (tokens.length > 0 ? tokens[0].getAddress() : inAddresses[i]);
bindString.append("?");
if (i < addressesSize - 1) {
bindString.append(",");
}
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Doing reverse lookup for " + addresses.toString());
}
HashMap<String, RecipientEntry> recipientEntries = new HashMap<String, RecipientEntry>();
Cursor c = context.getContentResolver().query(
query.getContentUri(), query.getProjection(),
Queries.Query.DESTINATION + " IN (" + bindString.toString() + ")",
addresses,
null);
if (c != null) {
try {
if (c.moveToFirst()) {
do {
String address = c.getString(Queries.Query.DESTINATION);
recipientEntries.put(address, RecipientEntry.constructTopLevelEntry(
c.getString(Queries.Query.NAME),
c.getInt(Queries.Query.DISPLAY_NAME_SOURCE),
c.getString(Queries.Query.DESTINATION),
c.getInt(Queries.Query.DESTINATION_TYPE),
c.getString(Queries.Query.DESTINATION_LABEL),
c.getLong(Queries.Query.CONTACT_ID),
c.getLong(Queries.Query.DATA_ID),
c.getString(Queries.Query.PHOTO_THUMBNAIL_URI)));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Received reverse look up information for " + address
+ " RESULTS: "
+ " NAME : " + c.getString(Queries.Query.NAME)
+ " CONTACT ID : " + c.getLong(Queries.Query.CONTACT_ID)
+ " ADDRESS :" + c.getString(Queries.Query.DESTINATION));
}
} while (c.moveToNext());
}
} finally {
c.close();
}
}
return recipientEntries;
}
| public static HashMap<String, RecipientEntry> getMatchingRecipients(Context context,
String[] inAddresses, int addressType) {
Queries.Query query;
if (addressType == QUERY_TYPE_EMAIL) {
query = Queries.EMAIL;
} else {
query = Queries.PHONE;
}
int addressesSize = Math.min(MAX_LOOKUPS, inAddresses.length);
String[] addresses = new String[addressesSize];
StringBuilder bindString = new StringBuilder();
// Create the "?" string and set up arguments.
for (int i = 0; i < addressesSize; i++) {
Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(inAddresses[i].toLowerCase());
addresses[i] = (tokens.length > 0 ? tokens[0].getAddress() : inAddresses[i]);
bindString.append("?");
if (i < addressesSize - 1) {
bindString.append(",");
}
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Doing reverse lookup for " + addresses.toString());
}
HashMap<String, RecipientEntry> recipientEntries = new HashMap<String, RecipientEntry>();
Cursor c = context.getContentResolver().query(
query.getContentUri(),
query.getProjection(),
query.getProjection()[Queries.Query.DESTINATION] + " IN (" + bindString.toString()
+ ")", addresses, null);
if (c != null) {
try {
if (c.moveToFirst()) {
do {
String address = c.getString(Queries.Query.DESTINATION);
recipientEntries.put(address, RecipientEntry.constructTopLevelEntry(
c.getString(Queries.Query.NAME),
c.getInt(Queries.Query.DISPLAY_NAME_SOURCE),
c.getString(Queries.Query.DESTINATION),
c.getInt(Queries.Query.DESTINATION_TYPE),
c.getString(Queries.Query.DESTINATION_LABEL),
c.getLong(Queries.Query.CONTACT_ID),
c.getLong(Queries.Query.DATA_ID),
c.getString(Queries.Query.PHOTO_THUMBNAIL_URI)));
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Received reverse look up information for " + address
+ " RESULTS: "
+ " NAME : " + c.getString(Queries.Query.NAME)
+ " CONTACT ID : " + c.getLong(Queries.Query.CONTACT_ID)
+ " ADDRESS :" + c.getString(Queries.Query.DESTINATION));
}
} while (c.moveToNext());
}
} finally {
c.close();
}
}
return recipientEntries;
}
|
diff --git a/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java b/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java
index 06e4c425e..95b554bf4 100644
--- a/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java
+++ b/closure/closure-compiler/src/com/google/javascript/jscomp/DefaultPassConfig.java
@@ -1,1834 +1,1834 @@
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.io.Files;
import com.google.javascript.jscomp.NodeTraversal.Callback;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Pass factories and meta-data for native JSCompiler passes.
*
* @author [email protected] (Nick Santos)
*/
// TODO(nicksantos): This needs state for a variety of reasons. Some of it
// is to satisfy the existing API. Some of it is because passes really do
// need to share state in non-trivial ways. This should be audited and
// cleaned up.
public class DefaultPassConfig extends PassConfig {
/* For the --mark-as-compiled pass */
private static final String COMPILED_CONSTANT_NAME = "COMPILED";
/* Constant name for Closure's locale */
private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE";
// Compiler errors when invalid combinations of passes are run.
static final DiagnosticType TIGHTEN_TYPES_WITHOUT_TYPE_CHECK =
DiagnosticType.error("JSC_TIGHTEN_TYPES_WITHOUT_TYPE_CHECK",
"TightenTypes requires type checking. Please use --check_types.");
static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR =
DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR",
"Rename prototypes and inline variables cannot be used together");
// Miscellaneous errors.
static final DiagnosticType REPORT_PATH_IO_ERROR =
DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR",
"Error writing compiler report to {0}");
private static final DiagnosticType INPUT_MAP_PROP_PARSE =
DiagnosticType.error("JSC_INPUT_MAP_PROP_PARSE",
"Input property map parse error: {0}");
private static final DiagnosticType INPUT_MAP_VAR_PARSE =
DiagnosticType.error("JSC_INPUT_MAP_VAR_PARSE",
"Input variable map parse error: {0}");
/**
* A global namespace to share across checking passes.
* TODO(nicksantos): This is a hack until I can get the namespace into
* the symbol table.
*/
private GlobalNamespace namespaceForChecks = null;
/**
* A type-tightener to share across optimization passes.
*/
private TightenTypes tightenTypes = null;
/** Names exported by goog.exportSymbol. */
private Set<String> exportedNames = null;
/**
* Ids for cross-module method stubbing, so that each method has
* a unique id.
*/
private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator =
new CrossModuleMethodMotion.IdGenerator();
/**
* Keys are arguments passed to getCssName() found during compilation; values
* are the number of times the key appeared as an argument to getCssName().
*/
private Map<String, Integer> cssNames = null;
/** The variable renaming map */
private VariableMap variableMap = null;
/** The property renaming map */
private VariableMap propertyMap = null;
/** The naming map for anonymous functions */
private VariableMap anonymousFunctionNameMap = null;
/** Fully qualified function names and globally unique ids */
private FunctionNames functionNames = null;
public DefaultPassConfig(CompilerOptions options) {
super(options);
}
@Override
State getIntermediateState() {
return new State(
cssNames == null ? null : Maps.newHashMap(cssNames),
exportedNames == null ? null :
Collections.unmodifiableSet(exportedNames),
crossModuleIdGenerator, variableMap, propertyMap,
anonymousFunctionNameMap, functionNames);
}
@Override
void setIntermediateState(State state) {
this.cssNames = state.cssNames == null ? null :
Maps.newHashMap(state.cssNames);
this.exportedNames = state.exportedNames == null ? null :
Sets.newHashSet(state.exportedNames);
this.crossModuleIdGenerator = state.crossModuleIdGenerator;
this.variableMap = state.variableMap;
this.propertyMap = state.propertyMap;
this.anonymousFunctionNameMap = state.anonymousFunctionNameMap;
this.functionNames = state.functionNames;
}
@Override
protected List<PassFactory> getChecks() {
List<PassFactory> checks = Lists.newArrayList();
if (options.nameAnonymousFunctionsOnly) {
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.MAPPED) {
checks.add(nameMappedAnonymousFunctions);
} else if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.UNMAPPED) {
checks.add(nameUnmappedAnonymousFunctions);
}
return checks;
}
if (options.checkSuspiciousCode) {
checks.add(suspiciousCode);
}
if (options.checkControlStructures) {
checks.add(checkControlStructures);
}
if (options.checkRequires.isOn()) {
checks.add(checkRequires);
}
if (options.checkProvides.isOn()) {
checks.add(checkProvides);
}
// The following passes are more like "preprocessor" passes.
// It's important that they run before most checking passes.
// Perhaps this method should be renamed?
if (options.generateExports) {
checks.add(generateExports);
}
if (options.exportTestFunctions) {
checks.add(exportTestFunctions);
}
if (options.closurePass) {
checks.add(closurePrimitives.makeOneTimePass());
}
if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) {
checks.add(closureCheckGetCssName);
}
if (options.closurePass) {
checks.add(closureReplaceGetCssName);
}
if (options.syntheticBlockStartMarker != null) {
// This pass must run before the first fold constants pass.
checks.add(createSyntheticBlocks);
}
// All passes must run the variable check. This synthesizes
// variables later so that the compiler doesn't crash. It also
// checks the externs file for validity. If you don't want to warn
// about missing variable declarations, we shut that specific
// error off.
WarningsGuard warningsGuard = options.getWarningsGuard();
if (!options.checkSymbols &&
(warningsGuard == null || !warningsGuard.disables(
DiagnosticGroups.CHECK_VARIABLES))) {
options.setWarningLevel(DiagnosticGroups.CHECK_VARIABLES,
CheckLevel.OFF);
}
checks.add(checkVars);
if (options.checkShadowVars.isOn()) {
checks.add(checkShadowVars);
}
if (options.aggressiveVarCheck.isOn()) {
checks.add(checkVariableReferences);
}
// This pass should run before types are assigned.
if (options.processObjectPropertyString) {
checks.add(objectPropertyStringPreprocess);
}
// DiagnosticGroups override the plain checkTypes option.
if (options.enables(DiagnosticGroups.CHECK_TYPES)) {
options.checkTypes = true;
} else if (options.disables(DiagnosticGroups.CHECK_TYPES)) {
options.checkTypes = false;
}
// Type-checking already does more accurate method arity checking, so don't
// do legacy method arity checking unless checkTypes is OFF.
if (options.checkTypes) {
checks.add(resolveTypes.makeOneTimePass());
checks.add(inferTypes.makeOneTimePass());
checks.add(checkTypes.makeOneTimePass());
} else {
if (options.checkFunctions.isOn()) {
checks.add(checkFunctions);
}
if (options.checkMethods.isOn()) {
checks.add(checkMethods);
}
}
if (options.checkUnreachableCode.isOn() ||
(options.checkTypes && options.checkMissingReturn.isOn())) {
checks.add(checkControlFlow);
}
// CheckAccessControls only works if check types is on.
if (options.enables(DiagnosticGroups.ACCESS_CONTROLS)
&& options.checkTypes) {
checks.add(checkAccessControls);
}
if (options.checkGlobalNamesLevel.isOn()) {
checks.add(checkGlobalNames);
}
if (options.checkUndefinedProperties.isOn() ||
options.checkUnusedPropertiesEarly) {
checks.add(checkSuspiciousProperties);
}
if (options.checkCaja || options.checkEs5Strict) {
checks.add(checkStrictMode);
}
// Defines in code always need to be processed.
checks.add(processDefines);
if (options.instrumentationTemplate != null ||
options.recordFunctionInformation) {
checks.add(computeFunctionNames);
}
assertAllOneTimePasses(checks);
return checks;
}
@Override
protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = Lists.newArrayList();
// TODO(nicksantos): The order of these passes makes no sense, and needs
// to be re-arranged.
if (options.runtimeTypeCheck) {
passes.add(runtimeTypeCheck);
}
passes.add(createEmptyPass("beforeStandardOptimizations"));
if (!options.idGenerators.isEmpty()) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Remove all parameters that are constants or unused.
if (options.optimizeParameters) {
passes.add(removeUselessParameters);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass && options.removeAbstractMethods) {
passes.add(removeAbstractMethods);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
// Tighten types based on actual usage.
if (options.tightenTypes) {
passes.add(tightenTypesBuilder);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguateProperties) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
// Constant checking must be done after property collapsing because
// property collapsing can introduce new constants (e.g. enum values).
if (options.inlineConstantVars) {
passes.add(checkConsts);
}
// The Caja library adds properties to Object.prototype, which breaks
// most for-in loops. This adds a check to each loop that skips
// any property matching /___$/.
if (options.ignoreCajaProperties) {
passes.add(ignoreCajaProperties);
}
assertAllOneTimePasses(passes);
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Method devirtualization benefits from property disambiguiation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass("beforeMainOptimizations"));
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.flowSensitiveInlineVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars) {
passes.add(removeUnusedVars);
}
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
//
// Extracting prototype properties screws up the heuristic renaming
// policies, so never run it when those policies are requested.
if (options.extractPrototypeMemberDeclarations &&
(options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC &&
options.propertyRenaming !=
PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.coalesceVariableNames) {
passes.add(coalesceVariableNames);
}
if (options.ambiguateProperties &&
(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming != PropertyRenamingPolicy.OFF) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
if (options.aliasExternals) {
passes.add(aliasExternals);
}
if (options.aliasKeywords) {
passes.add(aliasKeywords);
}
if (options.collapseVariableDeclarations) {
passes.add(collapseVariableDeclarations);
}
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
- // local variables ("$$1") or constants ("$$constant").
+ // local variables ("$$1").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
// Safety check
if (options.checkSymbols) {
passes.add(sanityCheckVars);
}
return passes;
}
/** Creates the passes for the main optimization loop. */
private List<PassFactory> getMainOptimizationLoop() {
List<PassFactory> passes = Lists.newArrayList();
if (options.inlineGetters) {
passes.add(inlineGetters);
}
passes.addAll(getCodeRemovingPasses());
if (options.inlineFunctions || options.inlineLocalFunctions) {
passes.add(inlineFunctions);
}
if (options.removeUnusedVars) {
if (options.deadAssignmentElimination) {
passes.add(deadAssignmentsElimination);
}
passes.add(removeUnusedVars);
}
assertAllLoopablePasses(passes);
return passes;
}
/** Creates several passes aimed at removing code. */
private List<PassFactory> getCodeRemovingPasses() {
List<PassFactory> passes = Lists.newArrayList();
if (options.inlineVariables || options.inlineLocalVariables) {
passes.add(inlineVariables);
} else if (options.inlineConstantVars) {
passes.add(inlineConstants);
}
if (options.removeConstantExpressions) {
passes.add(removeConstantExpressions);
}
if (options.foldConstants) {
// These used to be one pass.
passes.add(minimizeExitPoints);
passes.add(foldConstants);
}
if (options.removeDeadCode) {
passes.add(removeUnreachableCode);
}
if (options.removeUnusedPrototypeProperties) {
passes.add(removeUnusedPrototypeProperties);
}
assertAllLoopablePasses(passes);
return passes;
}
/**
* Checks for code that is probably wrong (such as stray expressions).
*/
// TODO(bolinfest): Write a CompilerPass for this.
final PassFactory suspiciousCode =
new PassFactory("suspiciousCode", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
List<Callback> sharedCallbacks = Lists.newArrayList();
sharedCallbacks.add(new CheckAccidentalSemicolon(CheckLevel.WARNING));
sharedCallbacks.add(new CheckSideEffects(CheckLevel.WARNING));
if (options.checkGlobalThisLevel.isOn()) {
sharedCallbacks.add(
new CheckGlobalThis(compiler, options.checkGlobalThisLevel));
}
return combineChecks(compiler, sharedCallbacks);
}
};
/** Verify that all the passes are one-time passes. */
private void assertAllOneTimePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
Preconditions.checkState(pass.isOneTimePass());
}
}
/** Verify that all the passes are multi-run passes. */
private void assertAllLoopablePasses(List<PassFactory> passes) {
for (PassFactory pass : passes) {
Preconditions.checkState(!pass.isOneTimePass());
}
}
/** Checks for validity of the control structures. */
private final PassFactory checkControlStructures =
new PassFactory("checkControlStructures", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ControlStructureCheck(compiler);
}
};
/** Checks that all constructed classes are goog.require()d. */
private final PassFactory checkRequires =
new PassFactory("checkRequires", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CheckRequiresForConstructors(compiler, options.checkRequires);
}
};
/** Makes sure @constructor is paired with goog.provides(). */
private final PassFactory checkProvides =
new PassFactory("checkProvides", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CheckProvides(compiler, options.checkProvides);
}
};
private static final DiagnosticType GENERATE_EXPORTS_ERROR =
DiagnosticType.error(
"JSC_GENERATE_EXPORTS_ERROR",
"Exports can only be generated if export symbol/property " +
"functions are set.");
/** Generates exports for @export annotations. */
private final PassFactory generateExports =
new PassFactory("generateExports", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null &&
convention.getExportPropertyFunction() != null) {
return new GenerateExports(compiler,
convention.getExportSymbolFunction(),
convention.getExportPropertyFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
};
/** Generates exports for functions associated with JSUnit. */
private final PassFactory exportTestFunctions =
new PassFactory("exportTestFunctions", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
CodingConvention convention = compiler.getCodingConvention();
if (convention.getExportSymbolFunction() != null) {
return new ExportTestFunctions(compiler,
convention.getExportSymbolFunction());
} else {
return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR);
}
}
};
/** Raw exports processing pass. */
final PassFactory gatherRawExports =
new PassFactory("gatherRawExports", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
final GatherRawExports pass = new GatherRawExports(
compiler);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
if (exportedNames == null) {
exportedNames = Sets.newHashSet();
}
exportedNames.addAll(pass.getExportedVariableNames());
}
};
}
};
/** Closure pre-processing pass. */
@SuppressWarnings("deprecation")
final PassFactory closurePrimitives =
new PassFactory("processProvidesAndRequires", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
final ProcessClosurePrimitives pass = new ProcessClosurePrimitives(
compiler,
options.brokenClosureRequiresLevel,
options.rewriteNewDateGoogNow);
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
pass.process(externs, root);
exportedNames = pass.getExportedVariableNames();
}
};
}
};
/** Checks that CSS class names are wrapped in goog.getCssName */
private final PassFactory closureCheckGetCssName =
new PassFactory("checkMissingGetCssName", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
String blacklist = options.checkMissingGetCssNameBlacklist;
Preconditions.checkState(blacklist != null && !blacklist.isEmpty(),
"Not checking use of goog.getCssName because of empty blacklist.");
return new CheckMissingGetCssName(
compiler, options.checkMissingGetCssNameLevel, blacklist);
}
};
/**
* Processes goog.getCssName. The cssRenamingMap is used to lookup
* replacement values for the classnames. If null, the raw class names are
* inlined.
*/
private final PassFactory closureReplaceGetCssName =
new PassFactory("renameCssNames", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
Map<String, Integer> newCssNames = null;
if (options.gatherCssNames) {
newCssNames = Maps.newHashMap();
}
(new ReplaceCssNames(compiler, newCssNames)).process(
externs, jsRoot);
cssNames = newCssNames;
}
};
}
};
/**
* Creates synthetic blocks to prevent FoldConstants from moving code
* past markers in the source.
*/
private final PassFactory createSyntheticBlocks =
new PassFactory("createSyntheticBlocks", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CreateSyntheticBlocks(compiler,
options.syntheticBlockStartMarker,
options.syntheticBlockEndMarker);
}
};
/** Local constant folding */
static final PassFactory foldConstants =
new PassFactory("foldConstants", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new FoldConstants(compiler);
}
};
/** Checks that all variables are defined. */
private final PassFactory checkVars =
new PassFactory("checkVars", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new VarCheck(compiler);
}
};
/** Checks that no vars are illegally shadowed. */
private final PassFactory checkShadowVars =
new PassFactory("variableShadowDeclarationCheck", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new VariableShadowDeclarationCheck(
compiler, options.checkShadowVars);
}
};
/** Checks that references to variables look reasonable. */
private final PassFactory checkVariableReferences =
new PassFactory("checkVariableReferences", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new VariableReferenceCheck(
compiler, options.aggressiveVarCheck);
}
};
/** Pre-process goog.testing.ObjectPropertyString. */
private final PassFactory objectPropertyStringPreprocess =
new PassFactory("ObjectPropertyStringPreprocess", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ObjectPropertyStringPreprocess(compiler);
}
};
/** Checks number of args passed to functions. */
private final PassFactory checkFunctions =
new PassFactory("checkFunctions", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new FunctionCheck(compiler, options.checkFunctions);
}
};
/** Checks number of args passed to methods. */
private final PassFactory checkMethods =
new PassFactory("checkMethods", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new MethodCheck(compiler, options.checkMethods);
}
};
/** Creates a typed scope and adds types to the type registry. */
final PassFactory resolveTypes =
new PassFactory("resolveTypes", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new GlobalTypeResolver(compiler);
}
};
/** Rusn type inference. */
private final PassFactory inferTypes =
new PassFactory("inferTypes", false) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(typedScopeCreator);
makeTypeInference(compiler).process(externs, root);
}
};
}
};
/** Checks type usage */
private final PassFactory checkTypes =
new PassFactory("checkTypes", false) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
Preconditions.checkNotNull(topScope);
Preconditions.checkNotNull(typedScopeCreator);
TypeCheck check = makeTypeCheck(compiler);
check.process(externs, root);
compiler.getErrorManager().setTypedPercent(check.getTypedPercent());
}
};
}
};
/**
* Checks possible execution paths of the program for problems: missing return
* statements and dead code.
*/
private final PassFactory checkControlFlow =
new PassFactory("checkControlFlow", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
List<Callback> callbacks = Lists.newArrayList();
if (options.checkUnreachableCode.isOn()) {
callbacks.add(
new CheckUnreachableCode(compiler, options.checkUnreachableCode));
}
if (options.checkMissingReturn.isOn() && options.checkTypes) {
callbacks.add(
new CheckMissingReturn(compiler, options.checkMissingReturn));
}
return combineChecks(compiler, callbacks);
}
};
/** Checks access controls. Depends on type-inference. */
private final PassFactory checkAccessControls =
new PassFactory("checkAccessControls", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CheckAccessControls(compiler);
}
};
/** Executes the given callbacks with a {@link CombinedCompilerPass}. */
private static CompilerPass combineChecks(AbstractCompiler compiler,
List<Callback> callbacks) {
Preconditions.checkArgument(callbacks.size() > 0);
Callback[] array = callbacks.toArray(new Callback[callbacks.size()]);
return new CombinedCompilerPass(compiler, array);
}
/** A compiler pass that resolves types in the global scope. */
private class GlobalTypeResolver implements CompilerPass {
private final AbstractCompiler compiler;
GlobalTypeResolver(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
if (topScope == null) {
typedScopeCreator =
new MemoizedScopeCreator(new TypedScopeCreator(compiler));
topScope = typedScopeCreator.createScope(root.getParent(), null);
} else {
compiler.getTypeRegistry().resolveTypesInScope(topScope);
}
}
}
/** Checks global name usage. */
private final PassFactory checkGlobalNames =
new PassFactory("Check names", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
// Create a global namespace for analysis by check passes.
// Note that this class does all heavy computation lazily,
// so it's OK to create it here.
namespaceForChecks = new GlobalNamespace(compiler, jsRoot);
new CheckGlobalNames(compiler, options.checkGlobalNamesLevel)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
}
};
}
};
/** Checks for properties that are not read or written */
private final PassFactory checkSuspiciousProperties =
new PassFactory("checkSuspiciousProperties", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new SuspiciousPropertiesCheck(
compiler,
options.checkUndefinedProperties,
options.checkUnusedPropertiesEarly ?
CheckLevel.WARNING : CheckLevel.OFF);
}
};
/** Checks that the code is ES5 or Caja compliant. */
private final PassFactory checkStrictMode =
new PassFactory("checkStrictMode", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new StrictModeCheck(compiler,
!options.checkSymbols, // don't check variables twice
!options.checkCaja); // disable eval check if not Caja
}
};
/** Override @define-annotated constants. */
final PassFactory processDefines =
new PassFactory("processDefines", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node jsRoot) {
Map<String, Node> replacements = getAdditionalReplacements(options);
replacements.putAll(options.getDefineReplacements());
new ProcessDefines(compiler, replacements)
.injectNamespace(namespaceForChecks).process(externs, jsRoot);
// Kill the namespace in the other class
// so that it can be garbage collected after all passes
// are through with it.
namespaceForChecks = null;
}
};
}
};
/** Checks that all constants are not modified */
private final PassFactory checkConsts =
new PassFactory("checkConsts", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ConstCheck(compiler);
}
};
/** Computes the names of functions for later analysis. */
private final PassFactory computeFunctionNames =
new PassFactory("computeFunctionNames", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return ((functionNames = new FunctionNames(compiler)));
}
};
/** Skips Caja-private properties in for-in loops */
private final PassFactory ignoreCajaProperties =
new PassFactory("ignoreCajaProperties", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new IgnoreCajaProperties(compiler);
}
};
/** Inserts runtime type assertions for debugging. */
private final PassFactory runtimeTypeCheck =
new PassFactory("runtimeTypeCheck", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new RuntimeTypeCheck(compiler,
options.runtimeTypeCheckLogFunction);
}
};
/** Generates unique ids. */
private final PassFactory replaceIdGenerators =
new PassFactory("replaceIdGenerators", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ReplaceIdGenerators(compiler, options.idGenerators);
}
};
/** Optimizes the "arguments" array. */
private final PassFactory optimizeArgumentsArray =
new PassFactory("optimizeArgumentsArray", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new OptimizeArgumentsArray(compiler);
}
};
/** Removes unused or constant formal parameters. */
private final PassFactory removeUselessParameters =
new PassFactory("optimizeParameters", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
NameReferenceGraphConstruction c =
new NameReferenceGraphConstruction(compiler);
c.process(externs, root);
(new OptimizeParameters(compiler, c.getNameReferenceGraph())).process(
externs, root);
}
};
}
};
/** Remove variables set to goog.abstractMethod. */
private final PassFactory removeAbstractMethods =
new PassFactory("removeAbstractMethods", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new GoogleCodeRemoval(compiler);
}
};
/** Collapses names in the global scope. */
private final PassFactory collapseProperties =
new PassFactory("collapseProperties", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CollapseProperties(
compiler, options.collapsePropertiesOnExternTypes,
!isInliningForbidden());
}
};
/**
* Try to infer the actual types, which may be narrower
* than the declared types.
*/
private final PassFactory tightenTypesBuilder =
new PassFactory("tightenTypes", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
if (!options.checkTypes) {
return new ErrorPass(compiler, TIGHTEN_TYPES_WITHOUT_TYPE_CHECK);
}
tightenTypes = new TightenTypes(compiler);
return tightenTypes;
}
};
/** Devirtualize property names based on type information. */
private final PassFactory disambiguateProperties =
new PassFactory("disambiguateProperties", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
if (tightenTypes == null) {
return DisambiguateProperties.forJSTypeSystem(compiler);
} else {
return DisambiguateProperties.forConcreteTypeSystem(
compiler, tightenTypes);
}
}
};
/**
* Chain calls to functions that return this.
*/
private final PassFactory chainCalls =
new PassFactory("chainCalls", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ChainCalls(compiler);
}
};
/**
* Rewrite instance methods as static methods, to make them easier
* to inline.
*/
private final PassFactory devirtualizePrototypeMethods =
new PassFactory("devirtualizePrototypeMethods", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new DevirtualizePrototypeMethods(compiler);
}
};
/**
* Look for function calls that are pure, and annotate them
* that way.
*/
private final PassFactory markPureFunctions =
new PassFactory("markPureFunctions", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new PureFunctionMarker(
compiler, options.debugFunctionSideEffectsPath, false);
}
};
/**
* Look for function calls that have no side effects, and annotate them
* that way.
*/
private final PassFactory markNoSideEffectCalls =
new PassFactory("markNoSideEffectCalls", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new MarkNoSideEffectCalls(compiler);
}
};
/** Inlines variables heuristically. */
private final PassFactory inlineVariables =
new PassFactory("inlineVariables", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
if (isInliningForbidden()) {
// In old renaming schemes, inlining a variable can change whether
// or not a property is renamed. This is bad, and those old renaming
// schemes need to die.
return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR);
} else {
InlineVariables.Mode mode;
if (options.inlineVariables) {
mode = InlineVariables.Mode.ALL;
} else if (options.inlineLocalVariables) {
mode = InlineVariables.Mode.LOCALS_ONLY;
} else {
throw new IllegalStateException("No variable inlining option set.");
}
return new InlineVariables(compiler, mode, true);
}
}
};
/** Inlines variables that are marked as constants. */
private final PassFactory inlineConstants =
new PassFactory("inlineConstants", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new InlineVariables(
compiler, InlineVariables.Mode.CONSTANTS_ONLY, true);
}
};
/**
* Simplify expressions by removing the parts that have no side effects.
*/
private final PassFactory removeConstantExpressions =
new PassFactory("removeConstantExpressions", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new RemoveConstantExpressions(compiler);
}
};
/**
* Perform local control flow optimizations.
*/
private final PassFactory minimizeExitPoints =
new PassFactory("minimizeExitPoints", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new MinimizeExitPoints(compiler);
}
};
/**
* Use data flow analysis to remove dead branches.
*/
private final PassFactory removeUnreachableCode =
new PassFactory("removeUnreachableCode", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new UnreachableCodeElimination(compiler, true);
}
};
/**
* Remove prototype properties that do not appear to be used.
*/
private final PassFactory removeUnusedPrototypeProperties =
new PassFactory("removeUnusedPrototypeProperties", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new RemoveUnusedPrototypeProperties(
compiler, options.removeUnusedPrototypePropertiesInExterns,
!options.removeUnusedVars);
}
};
/**
* Process smart name processing - removes unused classes and does referencing
* starting with minimum set of names.
*/
private final PassFactory smartNamePass =
new PassFactory("smartNamePass", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override
public void process(Node externs, Node root) {
NameAnalyzer na = new NameAnalyzer(compiler, false);
na.process(externs, root);
String reportPath = options.reportPath;
if (reportPath != null) {
try {
Files.write(na.getHtmlReport(), new File(reportPath),
Charsets.UTF_8);
} catch (IOException e) {
compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath));
}
}
if (options.smartNameRemoval) {
na.removeUnreferenced();
}
}
};
}
};
/** Inlines simple methods, like getters */
private PassFactory inlineGetters =
new PassFactory("inlineGetters", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new InlineGetters(compiler);
}
};
/** Kills dead assignments. */
private PassFactory deadAssignmentsElimination =
new PassFactory("deadAssignmentsElimination", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new DeadAssignmentsElimination(compiler);
}
};
/** Inlines function calls. */
private PassFactory inlineFunctions =
new PassFactory("inlineFunctions", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
boolean enableBlockInlining = !isInliningForbidden();
return new InlineFunctions(
compiler,
compiler.getUniqueNameIdSupplier(),
options.inlineFunctions,
options.inlineLocalFunctions,
options.inlineAnonymousFunctionExpressions,
enableBlockInlining,
options.decomposeExpressions);
}
};
/** Removes variables that are never used. */
private PassFactory removeUnusedVars =
new PassFactory("removeUnusedVars", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
return new RemoveUnusedVars(
compiler,
options.removeUnusedVarsInGlobalScope,
preserveAnonymousFunctionNames);
}
};
/**
* Move global symbols to a deeper common module
*/
private PassFactory crossModuleCodeMotion =
new PassFactory("crossModuleCodeMotion", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CrossModuleCodeMotion(compiler, compiler.getModuleGraph());
}
};
/**
* Move methods to a deeper common module
*/
private PassFactory crossModuleMethodMotion =
new PassFactory("crossModuleMethodMotion", false) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CrossModuleMethodMotion(
compiler, crossModuleIdGenerator,
// Only move properties in externs if we're not treating
// them as exports.
options.removeUnusedPrototypePropertiesInExterns);
}
};
/** A data-flow based variable inliner. */
private final PassFactory flowSensitiveInlineVariables =
new PassFactory("flowSensitiveInlineVariables", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new FlowSensitiveInlineVariables(compiler);
}
};
/** Uses register-allocation algorithms to use fewer variables. */
private final PassFactory coalesceVariableNames =
new PassFactory("coalesceVariableNames", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CoalesceVariableNames(compiler, options.generatePseudoNames);
}
};
/**
* Some simple, local collapses (e.g., {@code var x; var y;} becomes
* {@code var x,y;}.
*/
private final PassFactory collapseVariableDeclarations =
new PassFactory("collapseVariableDeclarations", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
compiler.setUnnormalized();
return new CollapseVariableDeclarations(compiler);
}
};
/**
* Extracts common sub-expressions.
*/
private final PassFactory extractPrototypeMemberDeclarations =
new PassFactory("extractPrototypeMemberDeclarations", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ExtractPrototypeMemberDeclarations(compiler);
}
};
/** Rewrites common function definitions to be more compact. */
private final PassFactory rewriteFunctionExpressions =
new PassFactory("rewriteFunctionExpressions", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new FunctionRewriter(compiler);
}
};
/** Collapses functions to not use the VAR keyword. */
private final PassFactory collapseAnonymousFunctions =
new PassFactory("collapseAnonymousFunctions", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new CollapseAnonymousFunctions(compiler);
}
};
/** Moves function declarations to the top, to simulate actual hoisting. */
private final PassFactory moveFunctionDeclarations =
new PassFactory("moveFunctionDeclarations", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new MoveFunctionDeclarations(compiler);
}
};
private final PassFactory nameUnmappedAnonymousFunctions =
new PassFactory("nameAnonymousFunctions", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new NameAnonymousFunctions(compiler);
}
};
private final PassFactory nameMappedAnonymousFunctions =
new PassFactory("nameAnonymousFunctions", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
NameAnonymousFunctionsMapped naf =
new NameAnonymousFunctionsMapped(compiler);
naf.process(externs, root);
anonymousFunctionNameMap = naf.getFunctionMap();
}
};
}
};
/** Alias external symbols. */
private final PassFactory aliasExternals =
new PassFactory("aliasExternals", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new AliasExternals(compiler, compiler.getModuleGraph(),
options.unaliasableGlobals, options.aliasableGlobals);
}
};
/**
* Alias string literals with global variables, to avoid creating lots of
* transient objects.
*/
private final PassFactory aliasStrings =
new PassFactory("aliasStrings", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new AliasStrings(
compiler,
compiler.getModuleGraph(),
options.aliasAllStrings ? null : options.aliasableStrings,
options.aliasStringsBlacklist,
options.outputJsStringUsage);
}
};
/** Aliases common keywords (true, false) */
private final PassFactory aliasKeywords =
new PassFactory("aliasKeywords", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new AliasKeywords(compiler);
}
};
/** Handling for the ObjectPropertyString primitive. */
private final PassFactory objectPropertyStringPostprocess =
new PassFactory("ObjectPropertyStringPostprocess", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ObjectPropertyStringPostprocess(compiler);
}
};
/**
* Renames properties so that the two properties that never appear on
* the same object get the same name.
*/
private final PassFactory ambiguateProperties =
new PassFactory("ambiguateProperties", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new AmbiguateProperties(
compiler, options.anonymousFunctionNaming.getReservedCharacters());
}
};
/** Denormalize the AST for code generation. */
private final PassFactory denormalize =
new PassFactory("denormalize", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
compiler.setUnnormalized();
return new Denormalize(compiler);
}
};
/** Inverting name normalization. */
private final PassFactory invertContextualRenaming =
new PassFactory("invertNames", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler);
}
};
/**
* Renames properties.
*/
private final PassFactory renameProperties =
new PassFactory("renameProperties", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
VariableMap map = null;
if (options.inputPropertyMapSerialized != null) {
try {
map = VariableMap.fromBytes(options.inputPropertyMapSerialized);
} catch (ParseException e) {
return new ErrorPass(compiler,
JSError.make(INPUT_MAP_PROP_PARSE, e.getMessage()));
}
}
final VariableMap prevPropertyMap = map;
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
propertyMap = runPropertyRenaming(
compiler, prevPropertyMap, externs, root);
}
};
}
};
private VariableMap runPropertyRenaming(
AbstractCompiler compiler, VariableMap prevPropertyMap,
Node externs, Node root) {
char[] reservedChars =
options.anonymousFunctionNaming.getReservedCharacters();
switch (options.propertyRenaming) {
case HEURISTIC:
RenamePrototypes rproto = new RenamePrototypes(compiler, false,
reservedChars, prevPropertyMap);
rproto.process(externs, root);
return rproto.getPropertyMap();
case AGGRESSIVE_HEURISTIC:
RenamePrototypes rproto2 = new RenamePrototypes(compiler, true,
reservedChars, prevPropertyMap);
rproto2.process(externs, root);
return rproto2.getPropertyMap();
case ALL_UNQUOTED:
RenameProperties rprop = new RenameProperties(
compiler, options.generatePseudoNames, prevPropertyMap,
reservedChars);
rprop.process(externs, root);
return rprop.getPropertyMap();
default:
throw new IllegalStateException(
"Unrecognized property renaming policy");
}
}
/** Renames variables. */
private final PassFactory renameVars =
new PassFactory("renameVars", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
VariableMap map = null;
if (options.inputVariableMapSerialized != null) {
try {
map = VariableMap.fromBytes(options.inputVariableMapSerialized);
} catch (ParseException e) {
return new ErrorPass(compiler,
JSError.make(INPUT_MAP_VAR_PARSE, e.getMessage()));
}
}
final VariableMap prevVariableMap = map;
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
variableMap = runVariableRenaming(
compiler, prevVariableMap, externs, root);
}
};
}
};
private VariableMap runVariableRenaming(
AbstractCompiler compiler, VariableMap prevVariableMap,
Node externs, Node root) {
char[] reservedChars =
options.anonymousFunctionNaming.getReservedCharacters();
boolean preserveAnonymousFunctionNames =
options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF;
RenameVars rn = new RenameVars(
compiler,
options.renamePrefix,
options.variableRenaming == VariableRenamingPolicy.LOCAL,
preserveAnonymousFunctionNames,
options.generatePseudoNames,
prevVariableMap,
reservedChars,
exportedNames);
rn.process(externs, root);
return rn.getVariableMap();
}
/** Renames labels */
private final PassFactory renameLabels =
new PassFactory("renameLabels", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new RenameLabels(compiler);
}
};
/** Convert bracket access to dot access */
private final PassFactory convertToDottedProperties =
new PassFactory("convertToDottedProperties", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new ConvertToDottedProperties(compiler);
}
};
/** Checks that all variables are defined. */
private final PassFactory sanityCheckVars =
new PassFactory("sanityCheckVars", true) {
@Override
protected CompilerPass createInternal(AbstractCompiler compiler) {
return new VarCheck(compiler, true);
}
};
/** Adds instrumentations according to an instrumentation template. */
private final PassFactory instrumentFunctions =
new PassFactory("instrumentFunctions", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
try {
FileReader templateFile =
new FileReader(options.instrumentationTemplate);
(new InstrumentFunctions(
compiler, functionNames,
options.instrumentationTemplate,
options.appNameStr,
templateFile)).process(externs, root);
} catch (IOException e) {
compiler.report(
JSError.make(AbstractCompiler.READ_ERROR,
options.instrumentationTemplate));
}
}
};
}
};
/**
* Create a no-op pass that can only run once. Used to break up loops.
*/
private static PassFactory createEmptyPass(String name) {
return new PassFactory(name, true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return runInSerial();
}
};
}
/**
* Runs custom passes that are designated to run at a particular time.
*/
private PassFactory getCustomPasses(
final CustomPassExecutionTime executionTime) {
return new PassFactory("runCustomPasses", true) {
@Override
protected CompilerPass createInternal(final AbstractCompiler compiler) {
return runInSerial(options.customPasses.get(executionTime));
}
};
}
/**
* All inlining is forbidden in heuristic renaming mode, because inlining
* will ruin the invariants that it depends on.
*/
private boolean isInliningForbidden() {
return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC ||
options.propertyRenaming ==
PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC;
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(final CompilerPass ... passes) {
return runInSerial(Lists.newArrayList(passes));
}
/** Create a compiler pass that runs the given passes in serial. */
private static CompilerPass runInSerial(
final Collection<CompilerPass> passes) {
return new CompilerPass() {
@Override public void process(Node externs, Node root) {
for (CompilerPass pass : passes) {
pass.process(externs, root);
}
}
};
}
@VisibleForTesting
static Map<String, Node> getAdditionalReplacements(
CompilerOptions options) {
Map<String, Node> additionalReplacements = Maps.newHashMap();
if (options.markAsCompiled || options.closurePass) {
additionalReplacements.put(COMPILED_CONSTANT_NAME, new Node(Token.TRUE));
}
if (options.closurePass && options.locale != null) {
additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME,
Node.newString(options.locale));
}
return additionalReplacements;
}
/** A compiler pass that marks pure functions. */
private static class PureFunctionMarker implements CompilerPass {
private final AbstractCompiler compiler;
private final String reportPath;
private final boolean useNameReferenceGraph;
PureFunctionMarker(AbstractCompiler compiler, String reportPath,
boolean useNameReferenceGraph) {
this.compiler = compiler;
this.reportPath = reportPath;
this.useNameReferenceGraph = useNameReferenceGraph;
}
@Override
public void process(Node externs, Node root) {
DefinitionProvider definitionProvider = null;
if (useNameReferenceGraph) {
NameReferenceGraphConstruction graphBuilder =
new NameReferenceGraphConstruction(compiler);
graphBuilder.process(externs, root);
definitionProvider = graphBuilder.getNameReferenceGraph();
} else {
SimpleDefinitionFinder defFinder = new SimpleDefinitionFinder(compiler);
defFinder.process(externs, root);
definitionProvider = defFinder;
}
PureFunctionIdentifier pureFunctionIdentifier =
new PureFunctionIdentifier(compiler, definitionProvider);
pureFunctionIdentifier.process(externs, root);
if (reportPath != null) {
try {
Files.write(pureFunctionIdentifier.getDebugReport(),
new File(reportPath),
Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
| true | true | protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = Lists.newArrayList();
// TODO(nicksantos): The order of these passes makes no sense, and needs
// to be re-arranged.
if (options.runtimeTypeCheck) {
passes.add(runtimeTypeCheck);
}
passes.add(createEmptyPass("beforeStandardOptimizations"));
if (!options.idGenerators.isEmpty()) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Remove all parameters that are constants or unused.
if (options.optimizeParameters) {
passes.add(removeUselessParameters);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass && options.removeAbstractMethods) {
passes.add(removeAbstractMethods);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
// Tighten types based on actual usage.
if (options.tightenTypes) {
passes.add(tightenTypesBuilder);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguateProperties) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
// Constant checking must be done after property collapsing because
// property collapsing can introduce new constants (e.g. enum values).
if (options.inlineConstantVars) {
passes.add(checkConsts);
}
// The Caja library adds properties to Object.prototype, which breaks
// most for-in loops. This adds a check to each loop that skips
// any property matching /___$/.
if (options.ignoreCajaProperties) {
passes.add(ignoreCajaProperties);
}
assertAllOneTimePasses(passes);
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Method devirtualization benefits from property disambiguiation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass("beforeMainOptimizations"));
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.flowSensitiveInlineVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars) {
passes.add(removeUnusedVars);
}
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
//
// Extracting prototype properties screws up the heuristic renaming
// policies, so never run it when those policies are requested.
if (options.extractPrototypeMemberDeclarations &&
(options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC &&
options.propertyRenaming !=
PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.coalesceVariableNames) {
passes.add(coalesceVariableNames);
}
if (options.ambiguateProperties &&
(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming != PropertyRenamingPolicy.OFF) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
if (options.aliasExternals) {
passes.add(aliasExternals);
}
if (options.aliasKeywords) {
passes.add(aliasKeywords);
}
if (options.collapseVariableDeclarations) {
passes.add(collapseVariableDeclarations);
}
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
// local variables ("$$1") or constants ("$$constant").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
// Safety check
if (options.checkSymbols) {
passes.add(sanityCheckVars);
}
return passes;
}
| protected List<PassFactory> getOptimizations() {
List<PassFactory> passes = Lists.newArrayList();
// TODO(nicksantos): The order of these passes makes no sense, and needs
// to be re-arranged.
if (options.runtimeTypeCheck) {
passes.add(runtimeTypeCheck);
}
passes.add(createEmptyPass("beforeStandardOptimizations"));
if (!options.idGenerators.isEmpty()) {
passes.add(replaceIdGenerators);
}
// Optimizes references to the arguments variable.
if (options.optimizeArgumentsArray) {
passes.add(optimizeArgumentsArray);
}
// Remove all parameters that are constants or unused.
if (options.optimizeParameters) {
passes.add(removeUselessParameters);
}
// Abstract method removal works best on minimally modified code, and also
// only needs to run once.
if (options.closurePass && options.removeAbstractMethods) {
passes.add(removeAbstractMethods);
}
// Collapsing properties can undo constant inlining, so we do this before
// the main optimization loop.
if (options.collapseProperties) {
passes.add(collapseProperties);
}
// Tighten types based on actual usage.
if (options.tightenTypes) {
passes.add(tightenTypesBuilder);
}
// Property disambiguation should only run once and needs to be done
// soon after type checking, both so that it can make use of type
// information and so that other passes can take advantage of the renamed
// properties.
if (options.disambiguateProperties) {
passes.add(disambiguateProperties);
}
if (options.computeFunctionSideEffects) {
passes.add(markPureFunctions);
} else if (options.markNoSideEffectCalls) {
// TODO(user) The properties that this pass adds to CALL and NEW
// AST nodes increase the AST's in-memory size. Given that we are
// already running close to our memory limits, we could run into
// trouble if we end up using the @nosideeffects annotation a lot
// or compute @nosideeffects annotations by looking at function
// bodies. It should be easy to propagate @nosideeffects
// annotations as part of passes that depend on this property and
// store the result outside the AST (which would allow garbage
// collection once the pass is done).
passes.add(markNoSideEffectCalls);
}
if (options.chainCalls) {
passes.add(chainCalls);
}
// Constant checking must be done after property collapsing because
// property collapsing can introduce new constants (e.g. enum values).
if (options.inlineConstantVars) {
passes.add(checkConsts);
}
// The Caja library adds properties to Object.prototype, which breaks
// most for-in loops. This adds a check to each loop that skips
// any property matching /___$/.
if (options.ignoreCajaProperties) {
passes.add(ignoreCajaProperties);
}
assertAllOneTimePasses(passes);
if (options.smartNameRemoval || options.reportPath != null) {
passes.addAll(getCodeRemovingPasses());
passes.add(smartNamePass);
}
// TODO(user): This forces a first crack at crossModuleCodeMotion
// before devirtualization. Once certain functions are devirtualized,
// it confuses crossModuleCodeMotion ability to recognized that
// it is recursive.
// TODO(user): This is meant for a temporary quick win.
// In the future, we might want to improve our analysis in
// CrossModuleCodeMotion so we don't need to do this.
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
// Method devirtualization benefits from property disambiguiation so
// it should run after that pass but before passes that do
// optimizations based on global names (like cross module code motion
// and inline functions). Smart Name Removal does better if run before
// this pass.
if (options.devirtualizePrototypeMethods) {
passes.add(devirtualizePrototypeMethods);
}
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP));
}
passes.add(createEmptyPass("beforeMainOptimizations"));
passes.addAll(getMainOptimizationLoop());
passes.add(createEmptyPass("beforeModuleMotion"));
if (options.crossModuleCodeMotion) {
passes.add(crossModuleCodeMotion);
}
if (options.crossModuleMethodMotion) {
passes.add(crossModuleMethodMotion);
}
passes.add(createEmptyPass("afterModuleMotion"));
// Some optimizations belong outside the loop because running them more
// than once would either have no benefit or be incorrect.
if (options.customPasses != null) {
passes.add(getCustomPasses(
CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP));
}
if (options.flowSensitiveInlineVariables) {
passes.add(flowSensitiveInlineVariables);
// After inlining some of the variable uses, some variables are unused.
// Re-run remove unused vars to clean it up.
if (options.removeUnusedVars) {
passes.add(removeUnusedVars);
}
}
if (options.collapseAnonymousFunctions) {
passes.add(collapseAnonymousFunctions);
}
// Move functions before extracting prototype member declarations.
if (options.moveFunctionDeclarations) {
passes.add(moveFunctionDeclarations);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.MAPPED) {
passes.add(nameMappedAnonymousFunctions);
}
// The mapped name anonymous function pass makes use of information that
// the extract prototype member declarations pass removes so the former
// happens before the latter.
//
// Extracting prototype properties screws up the heuristic renaming
// policies, so never run it when those policies are requested.
if (options.extractPrototypeMemberDeclarations &&
(options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC &&
options.propertyRenaming !=
PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) {
passes.add(extractPrototypeMemberDeclarations);
}
if (options.coalesceVariableNames) {
passes.add(coalesceVariableNames);
}
if (options.ambiguateProperties &&
(options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) {
passes.add(ambiguateProperties);
}
if (options.propertyRenaming != PropertyRenamingPolicy.OFF) {
passes.add(renameProperties);
}
// Reserve global names added to the "windows" object.
if (options.reserveRawExports) {
passes.add(gatherRawExports);
}
// This comes after property renaming because quoted property names must
// not be renamed.
if (options.convertToDottedProperties) {
passes.add(convertToDottedProperties);
}
// Property renaming must happen before this pass runs since this
// pass may convert dotted properties into quoted properties. It
// is beneficial to run before alias strings, alias keywords and
// variable renaming.
if (options.rewriteFunctionExpressions) {
passes.add(rewriteFunctionExpressions);
}
// This comes after converting quoted property accesses to dotted property
// accesses in order to avoid aliasing property names.
if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) {
passes.add(aliasStrings);
}
if (options.aliasExternals) {
passes.add(aliasExternals);
}
if (options.aliasKeywords) {
passes.add(aliasKeywords);
}
if (options.collapseVariableDeclarations) {
passes.add(collapseVariableDeclarations);
}
passes.add(denormalize);
if (options.instrumentationTemplate != null) {
passes.add(instrumentFunctions);
}
if (options.variableRenaming != VariableRenamingPolicy.ALL) {
// If we're leaving some (or all) variables with their old names,
// then we need to undo any of the markers we added for distinguishing
// local variables ("$$1").
passes.add(invertContextualRenaming);
}
if (options.variableRenaming != VariableRenamingPolicy.OFF) {
passes.add(renameVars);
}
// This pass should run after names stop changing.
if (options.processObjectPropertyString) {
passes.add(objectPropertyStringPostprocess);
}
if (options.labelRenaming) {
passes.add(renameLabels);
}
if (options.anonymousFunctionNaming ==
AnonymousFunctionNamingPolicy.UNMAPPED) {
passes.add(nameUnmappedAnonymousFunctions);
}
// Safety check
if (options.checkSymbols) {
passes.add(sanityCheckVars);
}
return passes;
}
|
diff --git a/bpel-dd/src/main/java/com/fs/pxe/bpel/dd/EndpointEnhancer.java b/bpel-dd/src/main/java/com/fs/pxe/bpel/dd/EndpointEnhancer.java
index ef986b10..c26d606e 100644
--- a/bpel-dd/src/main/java/com/fs/pxe/bpel/dd/EndpointEnhancer.java
+++ b/bpel-dd/src/main/java/com/fs/pxe/bpel/dd/EndpointEnhancer.java
@@ -1,157 +1,158 @@
package com.fs.pxe.bpel.dd;
import com.fs.pxe.bpel.o.OPartnerLink;
import com.fs.pxe.bpel.o.OProcess;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import javax.wsdl.*;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.UnknownExtensibilityElement;
import javax.wsdl.extensions.soap.SOAPAddress;
import javax.xml.namespace.QName;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Enhance a deployment descriptor by adding endpoint references
* if they are defined in a related WSDL document (from the
* <code>soap:address</code> element).
*/
public class EndpointEnhancer implements DDEnhancer {
private static final Log __log = LogFactory.getLog(DDHandler.class);
public boolean enhance(TDeploymentDescriptor dd, OProcess oprocess, Definition[] wsdlDefs)
throws DDException {
// Creating endpoints from WSDL SOAP address if none are specified
boolean updated = false;
for (OPartnerLink plink : oprocess.getAllPartnerLinks()) {
__log.debug("Analyzing partner link " + plink.getName());
if (plink.hasPartnerRole() && plink.initializePartnerRole) {
URL soapUrl = resolveServiceURL(wsdlDefs, plink.partnerRolePortType);
__log.debug("Resolved service url: " + soapUrl);
updated = declareEndpoint(dd, plink, soapUrl, false) || updated;
}
// If my role is never used in assignment, no need to declare it.
if (plink.hasMyRole()) {
URL soapUrl = resolveServiceURL(wsdlDefs, plink.myRolePortType);
updated = declareEndpoint(dd, plink, soapUrl, true) || updated;
}
}
return updated;
}
/**
* Reads WSDL description to establish a default endpoint address using
* the soap:address element.
* @param wsdlDefs
* @param pType
* @return
* @throws DDException
*/
private URL resolveServiceURL(Definition[] wsdlDefs, PortType pType) throws DDException {
QName portTypeQName = pType.getQName();
Binding wsdlBinding = null;
for (Definition def : wsdlDefs) {
for (Object obinding : def.getBindings().values()) {
Binding binding = (Binding) obinding;
if (binding.getPortType().getQName().getLocalPart().equals(portTypeQName.getLocalPart())
&& binding.getPortType().getQName().getNamespaceURI().equals(portTypeQName.getNamespaceURI())) {
wsdlBinding = binding;
}
}
}
if (wsdlBinding == null) {
- throw new DDException(
- "Couldn't find binding for portType with namespace " + portTypeQName.getNamespaceURI() +
- " and name " + portTypeQName.getLocalPart() + " in WSDL definition.");
+ __log.warn("No binding for portType with namespace " + portTypeQName.getNamespaceURI() +
+ " and name " + portTypeQName.getLocalPart() + " in WSDL definition.");
+ return null;
}
Port wsdlPort = null;
for (Definition def : wsdlDefs) {
for (Object oservice : def.getServices().values()) {
Service service = (Service) oservice;
for (Object oport : service.getPorts().values()) {
Port port = (Port) oport;
if (port.getBinding().getQName().equals(wsdlBinding.getQName())) {
wsdlPort = port;
}
}
}
}
if (wsdlPort == null) {
- throw new DDException(
- "Couldn't find port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
- " and name " + wsdlBinding.getQName().getLocalPart() + " in WSDL definition.");
+ __log.warn("No port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
+ " and name " + wsdlBinding.getQName().getLocalPart() + " in WSDL definition.");
+ return null;
}
String soapURIStr = null;
SOAPAddress wsdlSoapAddress = null;
for (Object oextElmt : wsdlPort.getExtensibilityElements()) {
ExtensibilityElement extElmt = (ExtensibilityElement) oextElmt;
if (extElmt instanceof UnknownExtensibilityElement)
if ((((UnknownExtensibilityElement)extElmt).getElement()).hasAttribute("location"))
soapURIStr = ((UnknownExtensibilityElement)extElmt).getElement().getAttribute("location");
if (extElmt instanceof SOAPAddress) wsdlSoapAddress = (SOAPAddress)extElmt;
}
if (wsdlSoapAddress == null && soapURIStr == null) {
- throw new DDException(
- "Couldn't find port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
+ __log.warn("No port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
" and name " + wsdlBinding.getQName().getLocalPart() + " in WSDL definition.");
+ return null;
}
if (soapURIStr == null) soapURIStr = wsdlSoapAddress.getLocationURI();
if (soapURIStr == null || "".equals(soapURIStr)) {
- throw new DDException(
- "Couldn't find SOAP address for port " + wsdlPort.getName() + " in WSDL definition.");
+ __log.warn("No SOAP address for port " + wsdlPort.getName() + " in WSDL definition.");
+ return null;
}
URL portURL;
try {
portURL = new URL(soapURIStr);
} catch (MalformedURLException e) {
- throw new DDException("SOAP address URL " + soapURIStr + " is invalid (not a valid URL).");
+ __log.warn("SOAP address URL " + soapURIStr + " is invalid (not a valid URL).");
+ return null;
}
return portURL;
}
private boolean declareEndpoint(TDeploymentDescriptor dd, OPartnerLink plink,
URL soapUrl, boolean myRole) {
boolean updated = false;
TDeploymentDescriptor.EndpointRefs eprs = dd.getEndpointRefs();
if (eprs == null) eprs = dd.addNewEndpointRefs();
TDeploymentDescriptor.EndpointRefs.EndpointRef foundEpr = null;
for (TDeploymentDescriptor.EndpointRefs.EndpointRef epr : eprs.getEndpointRefList()) {
if (epr.getPartnerLinkName().equals(plink.getName()) && epr.getPartnerLinkRole().equals(TRoles.PARTNER_ROLE)
&& !myRole) {
foundEpr = epr;
}
if (epr.getPartnerLinkName().equals(plink.getName()) && epr.getPartnerLinkRole().equals(TRoles.MY_ROLE)
&& myRole) {
foundEpr = epr;
}
}
if (__log.isDebugEnabled()) {
if (foundEpr == null) __log.debug("No EPR declared in the deployment descriptor for " + plink.getName() +
" (myRole=" + myRole + "), creating one.");
else __log.debug("An EPR is already declared in the deployment descriptor for " + plink.getName() +
" (myRole=" + myRole + ").");
}
if (foundEpr == null) {
updated = true;
TDeploymentDescriptor.EndpointRefs.EndpointRef epr = eprs.addNewEndpointRef();
epr.setPartnerLinkName(plink.name);
if (myRole) epr.setPartnerLinkRole(TRoles.MY_ROLE);
else epr.setPartnerLinkRole(TRoles.PARTNER_ROLE);
Node eprNode = epr.getDomNode();
Element addrElmt = eprNode.getOwnerDocument()
.createElementNS("http://schemas.xmlsoap.org/wsdl/soap/", "address");
addrElmt.setAttribute("location", soapUrl.toExternalForm());
eprNode.appendChild(addrElmt);
}
return updated;
}
}
| false | true | private URL resolveServiceURL(Definition[] wsdlDefs, PortType pType) throws DDException {
QName portTypeQName = pType.getQName();
Binding wsdlBinding = null;
for (Definition def : wsdlDefs) {
for (Object obinding : def.getBindings().values()) {
Binding binding = (Binding) obinding;
if (binding.getPortType().getQName().getLocalPart().equals(portTypeQName.getLocalPart())
&& binding.getPortType().getQName().getNamespaceURI().equals(portTypeQName.getNamespaceURI())) {
wsdlBinding = binding;
}
}
}
if (wsdlBinding == null) {
throw new DDException(
"Couldn't find binding for portType with namespace " + portTypeQName.getNamespaceURI() +
" and name " + portTypeQName.getLocalPart() + " in WSDL definition.");
}
Port wsdlPort = null;
for (Definition def : wsdlDefs) {
for (Object oservice : def.getServices().values()) {
Service service = (Service) oservice;
for (Object oport : service.getPorts().values()) {
Port port = (Port) oport;
if (port.getBinding().getQName().equals(wsdlBinding.getQName())) {
wsdlPort = port;
}
}
}
}
if (wsdlPort == null) {
throw new DDException(
"Couldn't find port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
" and name " + wsdlBinding.getQName().getLocalPart() + " in WSDL definition.");
}
String soapURIStr = null;
SOAPAddress wsdlSoapAddress = null;
for (Object oextElmt : wsdlPort.getExtensibilityElements()) {
ExtensibilityElement extElmt = (ExtensibilityElement) oextElmt;
if (extElmt instanceof UnknownExtensibilityElement)
if ((((UnknownExtensibilityElement)extElmt).getElement()).hasAttribute("location"))
soapURIStr = ((UnknownExtensibilityElement)extElmt).getElement().getAttribute("location");
if (extElmt instanceof SOAPAddress) wsdlSoapAddress = (SOAPAddress)extElmt;
}
if (wsdlSoapAddress == null && soapURIStr == null) {
throw new DDException(
"Couldn't find port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
" and name " + wsdlBinding.getQName().getLocalPart() + " in WSDL definition.");
}
if (soapURIStr == null) soapURIStr = wsdlSoapAddress.getLocationURI();
if (soapURIStr == null || "".equals(soapURIStr)) {
throw new DDException(
"Couldn't find SOAP address for port " + wsdlPort.getName() + " in WSDL definition.");
}
URL portURL;
try {
portURL = new URL(soapURIStr);
} catch (MalformedURLException e) {
throw new DDException("SOAP address URL " + soapURIStr + " is invalid (not a valid URL).");
}
return portURL;
}
| private URL resolveServiceURL(Definition[] wsdlDefs, PortType pType) throws DDException {
QName portTypeQName = pType.getQName();
Binding wsdlBinding = null;
for (Definition def : wsdlDefs) {
for (Object obinding : def.getBindings().values()) {
Binding binding = (Binding) obinding;
if (binding.getPortType().getQName().getLocalPart().equals(portTypeQName.getLocalPart())
&& binding.getPortType().getQName().getNamespaceURI().equals(portTypeQName.getNamespaceURI())) {
wsdlBinding = binding;
}
}
}
if (wsdlBinding == null) {
__log.warn("No binding for portType with namespace " + portTypeQName.getNamespaceURI() +
" and name " + portTypeQName.getLocalPart() + " in WSDL definition.");
return null;
}
Port wsdlPort = null;
for (Definition def : wsdlDefs) {
for (Object oservice : def.getServices().values()) {
Service service = (Service) oservice;
for (Object oport : service.getPorts().values()) {
Port port = (Port) oport;
if (port.getBinding().getQName().equals(wsdlBinding.getQName())) {
wsdlPort = port;
}
}
}
}
if (wsdlPort == null) {
__log.warn("No port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
" and name " + wsdlBinding.getQName().getLocalPart() + " in WSDL definition.");
return null;
}
String soapURIStr = null;
SOAPAddress wsdlSoapAddress = null;
for (Object oextElmt : wsdlPort.getExtensibilityElements()) {
ExtensibilityElement extElmt = (ExtensibilityElement) oextElmt;
if (extElmt instanceof UnknownExtensibilityElement)
if ((((UnknownExtensibilityElement)extElmt).getElement()).hasAttribute("location"))
soapURIStr = ((UnknownExtensibilityElement)extElmt).getElement().getAttribute("location");
if (extElmt instanceof SOAPAddress) wsdlSoapAddress = (SOAPAddress)extElmt;
}
if (wsdlSoapAddress == null && soapURIStr == null) {
__log.warn("No port for binding with namespace " + wsdlBinding.getQName().getNamespaceURI() +
" and name " + wsdlBinding.getQName().getLocalPart() + " in WSDL definition.");
return null;
}
if (soapURIStr == null) soapURIStr = wsdlSoapAddress.getLocationURI();
if (soapURIStr == null || "".equals(soapURIStr)) {
__log.warn("No SOAP address for port " + wsdlPort.getName() + " in WSDL definition.");
return null;
}
URL portURL;
try {
portURL = new URL(soapURIStr);
} catch (MalformedURLException e) {
__log.warn("SOAP address URL " + soapURIStr + " is invalid (not a valid URL).");
return null;
}
return portURL;
}
|
diff --git a/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java b/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
index b928110..6da41fa 100644
--- a/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
+++ b/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
@@ -1,568 +1,568 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.handler.component;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.util.BytesRef;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.request.SimpleFacets;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.FieldType;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.DocSet;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.util.NamedListHelper;
import org.apache.solr.util.PivotListEntry;
/**
* This is thread safe
*
* @since solr 4.0
*/
public class PivotFacetHelper {
protected NamedListHelper namedListHelper = NamedListHelper.INSTANCE;
protected Comparator<NamedList<Object>> namedListCountComparator = new PivotNamedListCountComparator();
/**
* Designed to be overridden by subclasses that provide different faceting
* implementations. TODO: Currently this is returning a SimpleFacets object,
* but those capabilities would be better as an extracted abstract class or
* interface.
*/
protected SimpleFacets getFacetImplementation(SolrQueryRequest req,
DocSet docs, SolrParams params) {
return new SimpleFacets(req, docs, params);
}
public SimpleOrderedMap<List<NamedList<Object>>> process(ResponseBuilder rb,
SolrParams params, String[] pivots) throws IOException {
if (!rb.doFacets || pivots == null) return null;
int minMatch = params.getInt(FacetParams.FACET_PIVOT_MINCOUNT, 1);
boolean distinct = params.getBool( FacetParams.FACET_PIVOT_DISTINCT, false); // distinct pivot?
boolean showDistinctCounts = params.getBool( FacetParams.FACET_PIVOT_DISTINCT, false);
if (showDistinctCounts) {
// force values in facet query to default values when facet.pivot.distinct = true
// facet.mincount = 1 ---- distinct count makes no sense if we filter out valid terms
// facet.limit = -1 ---- distinct count makes no sense if we limit terms
ModifiableSolrParams v = new ModifiableSolrParams(rb.req.getParams());
v.set("facet.mincount", 1);
v.set("facet.limit", -1);
params = v;
rb.req.setParams(params);
}
SimpleOrderedMap<List<NamedList<Object>>> pivotResponse = new SimpleOrderedMap<List<NamedList<Object>>>();
for (String pivot : pivots) {
String[] fields = pivot.split(","); // only support two levels for now
int depth = fields.length;
if (fields.length < 1) {
throw new SolrException(ErrorCode.BAD_REQUEST,
"Pivot Facet needs at least one field: " + pivot);
}
DocSet docs = rb.getResults().docSet;
String field = fields[0];
Deque<String> fnames = new LinkedList<String>();
for (int i = fields.length - 1; i > 1; i--) {
fnames.push(fields[i]);
}
SimpleFacets sf = getFacetImplementation(rb.req, rb.getResults().docSet, params);
NamedList<Integer> superFacets = sf.getTermCounts(field);
if(fields.length > 1) {
String subField = fields[1];
pivotResponse.add(pivot,
doPivots(superFacets, field, subField, fnames, rb, docs, minMatch, distinct, depth, depth));
}
else {
pivotResponse.add(pivot,
doPivots(superFacets,field,null,fnames,rb,docs, minMatch, distinct, depth, depth));
}
}
return pivotResponse;
}
/**
* Recursive function to do all the pivots
*/
protected List<NamedList<Object>> doPivots( NamedList<Integer> superFacets, String field, String subField, Deque<String> fnames, ResponseBuilder rb, DocSet docs, int minMatch, boolean distinct, int maxDepth, int depth) throws IOException
{
SolrIndexSearcher searcher = rb.req.getSearcher();
// TODO: optimize to avoid converting to an external string and then having to convert back to internal below
SchemaField sfield = searcher.getSchema().getField(field);
FieldType ftype = sfield.getType();
String nextField = fnames.poll();
// when distinct and no subs, dont bother
if (subField == null && distinct == true) {
return new ArrayList<NamedList<Object>>();
}
Query baseQuery = rb.getQuery();
List<NamedList<Object>> values = new ArrayList<NamedList<Object>>( superFacets.size() );
for (Map.Entry<String, Integer> kv : superFacets) {
// Only sub-facet if parent facet has positive count - still may not be any values for the sub-field though
if (kv.getValue() >= minMatch ) {
// don't reuse the same BytesRef each time since we will be constructing Term
// objects that will most likely be cached.
BytesRef termval = new BytesRef();
ftype.readableToIndexed(kv.getKey(), termval);
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<Object>();
pivot.add("field", field );
pivot.add("value", ftype.toObject(sfield, termval) );
pivot.add("count", kv.getValue() );
// only due stats
DocSet subset = null;
SimpleFacets sf = null;
if (maxDepth != depth) {
Query query = new TermQuery(new Term(field, termval));
subset = searcher.getDocSet(query, docs);
sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Object> subFieldStats = sf.getFacetPercentileCounts();
- if (subFieldStats != null && subFieldStats.size() > 0) {
+ // if (subFieldStats != null && subFieldStats.size() > 0) {
pivot.add( "statistics", subFieldStats);
- }
+ // }
}
if( subField == null) {
if (distinct == false) {
values.add( pivot );
}
}
else {
if (sf == null) {
Query query = new TermQuery(new Term(field, termval));
subset = searcher.getDocSet(query, docs);
sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Object> subFieldStats = sf.getFacetPercentileCounts();
- if (subFieldStats != null && subFieldStats.size() > 0) {
+ // if (subFieldStats != null && subFieldStats.size() > 0) {
pivot.add( "statistics", subFieldStats);
- }
+ // }
}
NamedList<Integer> nl = sf.getTermCounts(subField);
if (distinct) {
pivot.add("distinct", nl.size());
if (depth > 1) {
List<NamedList<Object>> list = doPivots( nl, subField, nextField, fnames, rb, subset, minMatch, distinct, maxDepth, depth-1 );
- if (list.size() > 0) {
+ // if (list.size() > 0) {
pivot.add( "pivot", list);
- }
+ // }
values.add( pivot );
}
} else {
if (nl.size() >= minMatch) {
List<NamedList<Object>> list = doPivots( nl, subField, nextField, fnames, rb, subset, minMatch, distinct, maxDepth, depth-1 );
- if (list.size() > 0) {
+ // if (list.size() > 0) {
pivot.add( "pivot", list);
- }
+ // }
values.add( pivot );
}
}
}
}
}
// put the field back on the list
fnames.push( nextField );
return values;
}
private void mergeValueToMap(Map<Object,NamedList<Object>> polecatCounts,
String field, Object value, Integer count,
List<NamedList<Object>> subPivot, int pivotsDone, int numberOfPivots) {
if (polecatCounts.containsKey(value)) {
polecatCounts.put(
value,
mergePivots(polecatCounts.get(value), count, subPivot, pivotsDone,
numberOfPivots));
} else {
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<Object>();
pivot.add(PivotListEntry.FIELD.getName(), field);
pivot.add(PivotListEntry.VALUE.getName(), value);
pivot.add(PivotListEntry.COUNT.getName(), count);
if (subPivot != null) {
pivot.add(PivotListEntry.PIVOT.getName(),
convertPivotsToMaps(subPivot, pivotsDone, numberOfPivots));
}
polecatCounts.put(value, pivot);
}
}
private NamedList<Object> mergePivots(NamedList<Object> existingNamedList,
Integer countToMerge, List<NamedList<Object>> pivotToMergeList,
int pivotsDone, int numberOfPivots) {
if (countToMerge != null) {
// Cast here, but as we're only putting Integers in above it should be
// fine
existingNamedList.setVal(
PivotListEntry.COUNT.getIndex(),
((Integer) namedListHelper.getFromPivotList(PivotListEntry.COUNT,
existingNamedList)) + countToMerge);
}
if (pivotToMergeList != null) {
Object existingPivotObj = namedListHelper.getFromPivotList(
PivotListEntry.PIVOT, existingNamedList);
if (existingPivotObj instanceof Map) {
for (NamedList<Object> pivotToMerge : pivotToMergeList) {
String nextFieldToMerge = (String) namedListHelper.getFromPivotList(
PivotListEntry.FIELD, pivotToMerge);
Object nextValueToMerge = namedListHelper.getFromPivotList(
PivotListEntry.VALUE, pivotToMerge);
Integer nextCountToMerge = (Integer) namedListHelper
.getFromPivotList(PivotListEntry.COUNT, pivotToMerge);
Object nextPivotToMergeListObj = namedListHelper.getFromPivotList(
PivotListEntry.PIVOT, pivotToMerge);
List nextPivotToMergeList = null;
if (nextPivotToMergeListObj instanceof List) {
nextPivotToMergeList = (List) nextPivotToMergeListObj;
}
mergeValueToMap((Map) existingPivotObj, nextFieldToMerge,
nextValueToMerge, nextCountToMerge, nextPivotToMergeList,
pivotsDone++, numberOfPivots);
}
} else {
existingNamedList.add(
PivotListEntry.PIVOT.getName(),
convertPivotsToMaps(pivotToMergeList, pivotsDone + 1,
numberOfPivots));
}
}
return existingNamedList;
}
public Map<Object,NamedList<Object>> convertPivotsToMaps(
List<NamedList<Object>> pivots, int pivotsDone, int numberOfPivots) {
return convertPivotsToMaps(pivots, pivotsDone, numberOfPivots, null);
}
public Map<Object,NamedList<Object>> convertPivotsToMaps(
List<NamedList<Object>> pivots, int pivotsDone, int numberOfPivots,
Map<Integer,Map<Object,Integer>> fieldCounts) {
Map<Object,NamedList<Object>> pivotMap = new HashMap<Object,NamedList<Object>>();
boolean countFields = (fieldCounts != null);
Map<Object,Integer> thisFieldCountMap = null;
if (countFields) {
thisFieldCountMap = getFieldCountMap(fieldCounts, pivotsDone);
}
for (NamedList<Object> pivot : pivots) {
Object valueObj = namedListHelper.getFromPivotList(PivotListEntry.VALUE,
pivot);
pivotMap.put(valueObj, pivot);
if (countFields) {
Object countObj = namedListHelper.getFromPivotList(
PivotListEntry.COUNT, pivot);
int count = 0;
if (countObj instanceof Integer) {
count = (Integer) countObj;
}
addFieldCounts(valueObj, count, thisFieldCountMap);
}
if (pivotsDone < numberOfPivots) {
Integer pivotIdx = pivot.indexOf(PivotListEntry.PIVOT.getName(), 0);
if (pivotIdx > -1) {
Object pivotObj = pivot.getVal(pivotIdx);
if (pivotObj instanceof List) {
pivot.setVal(
pivotIdx,
convertPivotsToMaps((List) pivotObj, pivotsDone + 1,
numberOfPivots, fieldCounts));
}
}
}
}
return pivotMap;
}
public List<NamedList<Object>> convertPivotMapToList(
Map<Object,NamedList<Object>> pivotMap, int numberOfPivots) {
return convertPivotMapToList(pivotMap, new InternalPivotLimitInfo(), 0,
numberOfPivots, false);
}
private List<NamedList<Object>> convertPivotMapToList(
Map<Object,NamedList<Object>> pivotMap,
InternalPivotLimitInfo pivotLimitInfo, int currentPivot,
int numberOfPivots, boolean sortByCount) {
List<NamedList<Object>> pivots = new ArrayList<NamedList<Object>>();
currentPivot++;
List<Object> fieldLimits = null;
InternalPivotLimitInfo nextPivotLimitInfo = new InternalPivotLimitInfo(
pivotLimitInfo);
if (pivotLimitInfo.combinedPivotLimit
&& pivotLimitInfo.fieldLimitsList.size() > 0) {
fieldLimits = pivotLimitInfo.fieldLimitsList.get(0);
nextPivotLimitInfo.fieldLimitsList = pivotLimitInfo.fieldLimitsList
.subList(1, pivotLimitInfo.fieldLimitsList.size());
}
for (Entry<Object,NamedList<Object>> pivot : pivotMap.entrySet()) {
if (pivotLimitInfo.limit == 0 || !pivotLimitInfo.combinedPivotLimit
|| fieldLimits == null || fieldLimits.contains(pivot.getKey())) {
pivots.add(pivot.getValue());
convertPivotEntryToListType(pivot.getValue(), nextPivotLimitInfo,
currentPivot, numberOfPivots, sortByCount);
}
}
if (sortByCount) {
Collections.sort(pivots, namedListCountComparator);
}
if (!pivotLimitInfo.combinedPivotLimit && pivotLimitInfo.limit > 0
&& pivots.size() > pivotLimitInfo.limit) {
pivots = new ArrayList<NamedList<Object>>(pivots.subList(0,
pivotLimitInfo.limit));
}
return pivots;
}
public SimpleOrderedMap<List<NamedList<Object>>> convertPivotMapsToList(
SimpleOrderedMap<Map<Object,NamedList<Object>>> pivotValues,
PivotLimitInfo pivotLimitInfo, boolean sortByCount) {
SimpleOrderedMap<List<NamedList<Object>>> pivotsLists = new SimpleOrderedMap<List<NamedList<Object>>>();
for (Entry<String,Map<Object,NamedList<Object>>> pivotMapEntry : pivotValues) {
String pivotName = pivotMapEntry.getKey();
Integer numberOfPivots = 1 + StringUtils.countMatches(pivotName, ",");
InternalPivotLimitInfo internalPivotLimitInfo = new InternalPivotLimitInfo(
pivotLimitInfo, pivotName);
pivotsLists.add(
pivotName,
convertPivotMapToList(pivotMapEntry.getValue(),
internalPivotLimitInfo, 0, numberOfPivots, sortByCount));
}
return pivotsLists;
}
private void convertPivotEntryToListType(NamedList<Object> pivotEntry,
InternalPivotLimitInfo pivotLimitInfo, int pivotsDone,
int numberOfPivots, boolean sortByCount) {
if (pivotsDone < numberOfPivots) {
int pivotIdx = pivotEntry.indexOf(PivotListEntry.PIVOT.getName(), 0);
if (pivotIdx > -1) {
Object subPivotObj = pivotEntry.getVal(pivotIdx);
if (subPivotObj instanceof Map) {
Map<Object,NamedList<Object>> subPivotMap = (Map) subPivotObj;
pivotEntry.setVal(
pivotIdx,
convertPivotMapToList(subPivotMap, pivotLimitInfo, pivotsDone,
numberOfPivots, sortByCount));
}
}
}
}
public Map<Object,Integer> getFieldCountMap(
Map<Integer,Map<Object,Integer>> fieldCounts, int pivotNumber) {
Map<Object,Integer> fieldCountMap = fieldCounts.get(pivotNumber);
if (fieldCountMap == null) {
fieldCountMap = new HashMap<Object,Integer>();
fieldCounts.put(pivotNumber, fieldCountMap);
}
return fieldCountMap;
}
public void addFieldCounts(Object name, int count,
Map<Object,Integer> thisFieldCountMap) {
Integer existingFieldCount = thisFieldCountMap.get(name);
if (existingFieldCount == null) {
thisFieldCountMap.put(name, count);
} else {
thisFieldCountMap.put(name, existingFieldCount + count);
}
}
public static class PivotLimitInfo {
public SimpleOrderedMap<List<List<Object>>> fieldLimitsMap = null;
public int limit = 0;
public boolean combinedPivotLimit = false;
}
private static class InternalPivotLimitInfo {
public List<List<Object>> fieldLimitsList = null;
public int limit = 0;
public boolean combinedPivotLimit = false;
private InternalPivotLimitInfo() {}
private InternalPivotLimitInfo(PivotLimitInfo pivotLimitInfo,
String pivotName) {
this.limit = pivotLimitInfo.limit;
this.combinedPivotLimit = pivotLimitInfo.combinedPivotLimit;
if (pivotLimitInfo.fieldLimitsMap != null) {
this.fieldLimitsList = pivotLimitInfo.fieldLimitsMap.get(pivotName);
}
}
private InternalPivotLimitInfo(InternalPivotLimitInfo pivotLimitInfo) {
this.fieldLimitsList = pivotLimitInfo.fieldLimitsList;
this.limit = pivotLimitInfo.limit;
this.combinedPivotLimit = pivotLimitInfo.combinedPivotLimit;
}
}
// TODO: This is code from various patches to support distributed search.
// Some parts may be helpful for whoever implements distributed search.
//
// @Override
// public int distributedProcess(ResponseBuilder rb) throws IOException {
// if (!rb.doFacets) {
// return ResponseBuilder.STAGE_DONE;
// }
//
// if (rb.stage == ResponseBuilder.STAGE_GET_FIELDS) {
// SolrParams params = rb.req.getParams();
// String[] pivots = params.getParams(FacetParams.FACET_PIVOT);
// for ( ShardRequest sreq : rb.outgoing ) {
// if (( sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS ) != 0
// && sreq.shards != null && sreq.shards.length == 1 ) {
// sreq.params.set( FacetParams.FACET, "true" );
// sreq.params.set( FacetParams.FACET_PIVOT, pivots );
// sreq.params.set( FacetParams.FACET_PIVOT_MINCOUNT, 1 ); // keep this at 1 regardless so that it accumulates everything
// }
// }
// }
// return ResponseBuilder.STAGE_DONE;
// }
//
// @Override
// public void handleResponses(ResponseBuilder rb, ShardRequest sreq) {
// if (!rb.doFacets) return;
//
//
// if ((sreq.purpose & ShardRequest.PURPOSE_GET_FACETS)!=0) {
// SimpleOrderedMap<List<NamedList<Object>>> tf = rb._pivots;
// if ( null == tf ) {
// tf = new SimpleOrderedMap<List<NamedList<Object>>>();
// rb._pivots = tf;
// }
// for (ShardResponse srsp: sreq.responses) {
// int shardNum = rb.getShardNum(srsp.getShard());
//
// NamedList facet_counts = (NamedList)srsp.getSolrResponse().getResponse().get("facet_counts");
//
// // handle facet trees from shards
// SimpleOrderedMap<List<NamedList<Object>>> shard_pivots =
// (SimpleOrderedMap<List<NamedList<Object>>>)facet_counts.get( PIVOT_KEY );
//
// if ( shard_pivots != null ) {
// for (int j=0; j< shard_pivots.size(); j++) {
// // TODO -- accumulate the results from each shard
// // The following code worked to accumulate facets for an previous
// // two level patch... it is here for reference till someone can upgrade
// /**
// String shard_tree_name = (String) shard_pivots.getName( j );
// SimpleOrderedMap<NamedList> shard_tree = (SimpleOrderedMap<NamedList>)shard_pivots.getVal( j );
// SimpleOrderedMap<NamedList> facet_tree = tf.get( shard_tree_name );
// if ( null == facet_tree) {
// facet_tree = new SimpleOrderedMap<NamedList>();
// tf.add( shard_tree_name, facet_tree );
// }
//
// for( int o = 0; o < shard_tree.size() ; o++ ) {
// String shard_outer = (String) shard_tree.getName( o );
// NamedList shard_innerList = (NamedList) shard_tree.getVal( o );
// NamedList tree_innerList = (NamedList) facet_tree.get( shard_outer );
// if ( null == tree_innerList ) {
// tree_innerList = new NamedList();
// facet_tree.add( shard_outer, tree_innerList );
// }
//
// for ( int i = 0 ; i < shard_innerList.size() ; i++ ) {
// String shard_term = (String) shard_innerList.getName( i );
// long shard_count = ((Number) shard_innerList.getVal(i)).longValue();
// int tree_idx = tree_innerList.indexOf( shard_term, 0 );
//
// if ( -1 == tree_idx ) {
// tree_innerList.add( shard_term, shard_count );
// } else {
// long tree_count = ((Number) tree_innerList.getVal( tree_idx )).longValue();
// tree_innerList.setVal( tree_idx, shard_count + tree_count );
// }
// } // innerList loop
// } // outer loop
// **/
// } // each tree loop
// }
// }
// }
// return ;
// }
//
// @Override
// public void finishStage(ResponseBuilder rb) {
// if (!rb.doFacets || rb.stage != ResponseBuilder.STAGE_GET_FIELDS) return;
// // wait until STAGE_GET_FIELDS
// // so that "result" is already stored in the response (for aesthetics)
//
// SimpleOrderedMap<List<NamedList<Object>>> tf = rb._pivots;
//
// // get 'facet_counts' from the response
// NamedList facetCounts = (NamedList) rb.rsp.getValues().get("facet_counts");
// if (facetCounts == null) {
// facetCounts = new NamedList();
// rb.rsp.add("facet_counts", facetCounts);
// }
// facetCounts.add( PIVOT_KEY, tf );
// rb._pivots = null;
// }
//
// public String getDescription() {
// return "Handle Pivot (multi-level) Faceting";
// }
//
// public String getSource() {
// return "$URL: http://svn.apache.org/repos/asf/lucene/dev/branches/branch_4x/solr/core/src/java/org/apache/solr/handler/component/PivotFacetHelper.java $";
// }
}
| false | true | protected List<NamedList<Object>> doPivots( NamedList<Integer> superFacets, String field, String subField, Deque<String> fnames, ResponseBuilder rb, DocSet docs, int minMatch, boolean distinct, int maxDepth, int depth) throws IOException
{
SolrIndexSearcher searcher = rb.req.getSearcher();
// TODO: optimize to avoid converting to an external string and then having to convert back to internal below
SchemaField sfield = searcher.getSchema().getField(field);
FieldType ftype = sfield.getType();
String nextField = fnames.poll();
// when distinct and no subs, dont bother
if (subField == null && distinct == true) {
return new ArrayList<NamedList<Object>>();
}
Query baseQuery = rb.getQuery();
List<NamedList<Object>> values = new ArrayList<NamedList<Object>>( superFacets.size() );
for (Map.Entry<String, Integer> kv : superFacets) {
// Only sub-facet if parent facet has positive count - still may not be any values for the sub-field though
if (kv.getValue() >= minMatch ) {
// don't reuse the same BytesRef each time since we will be constructing Term
// objects that will most likely be cached.
BytesRef termval = new BytesRef();
ftype.readableToIndexed(kv.getKey(), termval);
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<Object>();
pivot.add("field", field );
pivot.add("value", ftype.toObject(sfield, termval) );
pivot.add("count", kv.getValue() );
// only due stats
DocSet subset = null;
SimpleFacets sf = null;
if (maxDepth != depth) {
Query query = new TermQuery(new Term(field, termval));
subset = searcher.getDocSet(query, docs);
sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Object> subFieldStats = sf.getFacetPercentileCounts();
if (subFieldStats != null && subFieldStats.size() > 0) {
pivot.add( "statistics", subFieldStats);
}
}
if( subField == null) {
if (distinct == false) {
values.add( pivot );
}
}
else {
if (sf == null) {
Query query = new TermQuery(new Term(field, termval));
subset = searcher.getDocSet(query, docs);
sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Object> subFieldStats = sf.getFacetPercentileCounts();
if (subFieldStats != null && subFieldStats.size() > 0) {
pivot.add( "statistics", subFieldStats);
}
}
NamedList<Integer> nl = sf.getTermCounts(subField);
if (distinct) {
pivot.add("distinct", nl.size());
if (depth > 1) {
List<NamedList<Object>> list = doPivots( nl, subField, nextField, fnames, rb, subset, minMatch, distinct, maxDepth, depth-1 );
if (list.size() > 0) {
pivot.add( "pivot", list);
}
values.add( pivot );
}
} else {
if (nl.size() >= minMatch) {
List<NamedList<Object>> list = doPivots( nl, subField, nextField, fnames, rb, subset, minMatch, distinct, maxDepth, depth-1 );
if (list.size() > 0) {
pivot.add( "pivot", list);
}
values.add( pivot );
}
}
}
}
}
// put the field back on the list
fnames.push( nextField );
return values;
}
| protected List<NamedList<Object>> doPivots( NamedList<Integer> superFacets, String field, String subField, Deque<String> fnames, ResponseBuilder rb, DocSet docs, int minMatch, boolean distinct, int maxDepth, int depth) throws IOException
{
SolrIndexSearcher searcher = rb.req.getSearcher();
// TODO: optimize to avoid converting to an external string and then having to convert back to internal below
SchemaField sfield = searcher.getSchema().getField(field);
FieldType ftype = sfield.getType();
String nextField = fnames.poll();
// when distinct and no subs, dont bother
if (subField == null && distinct == true) {
return new ArrayList<NamedList<Object>>();
}
Query baseQuery = rb.getQuery();
List<NamedList<Object>> values = new ArrayList<NamedList<Object>>( superFacets.size() );
for (Map.Entry<String, Integer> kv : superFacets) {
// Only sub-facet if parent facet has positive count - still may not be any values for the sub-field though
if (kv.getValue() >= minMatch ) {
// don't reuse the same BytesRef each time since we will be constructing Term
// objects that will most likely be cached.
BytesRef termval = new BytesRef();
ftype.readableToIndexed(kv.getKey(), termval);
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<Object>();
pivot.add("field", field );
pivot.add("value", ftype.toObject(sfield, termval) );
pivot.add("count", kv.getValue() );
// only due stats
DocSet subset = null;
SimpleFacets sf = null;
if (maxDepth != depth) {
Query query = new TermQuery(new Term(field, termval));
subset = searcher.getDocSet(query, docs);
sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Object> subFieldStats = sf.getFacetPercentileCounts();
// if (subFieldStats != null && subFieldStats.size() > 0) {
pivot.add( "statistics", subFieldStats);
// }
}
if( subField == null) {
if (distinct == false) {
values.add( pivot );
}
}
else {
if (sf == null) {
Query query = new TermQuery(new Term(field, termval));
subset = searcher.getDocSet(query, docs);
sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Object> subFieldStats = sf.getFacetPercentileCounts();
// if (subFieldStats != null && subFieldStats.size() > 0) {
pivot.add( "statistics", subFieldStats);
// }
}
NamedList<Integer> nl = sf.getTermCounts(subField);
if (distinct) {
pivot.add("distinct", nl.size());
if (depth > 1) {
List<NamedList<Object>> list = doPivots( nl, subField, nextField, fnames, rb, subset, minMatch, distinct, maxDepth, depth-1 );
// if (list.size() > 0) {
pivot.add( "pivot", list);
// }
values.add( pivot );
}
} else {
if (nl.size() >= minMatch) {
List<NamedList<Object>> list = doPivots( nl, subField, nextField, fnames, rb, subset, minMatch, distinct, maxDepth, depth-1 );
// if (list.size() > 0) {
pivot.add( "pivot", list);
// }
values.add( pivot );
}
}
}
}
}
// put the field back on the list
fnames.push( nextField );
return values;
}
|
diff --git a/src/main/org/codehaus/groovy/ast/ClassNode.java b/src/main/org/codehaus/groovy/ast/ClassNode.java
index bd9c7670b..159ea12d4 100644
--- a/src/main/org/codehaus/groovy/ast/ClassNode.java
+++ b/src/main/org/codehaus/groovy/ast/ClassNode.java
@@ -1,689 +1,689 @@
/*
* $Id$
*
* Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided that the
* following conditions are met:
* 1. Redistributions of source code must retain copyright statements and
* notices. Redistributions must also contain a copy of this document.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name "groovy" must not be used to endorse or promote products
* derived from this Software without prior written permission of The Codehaus.
* For written permission, please contact [email protected].
* 4. Products derived from this Software may not be called "groovy" nor may
* "groovy" appear in their names without prior written permission of The
* Codehaus. "groovy" is a registered trademark of The Codehaus.
* 5. Due credit should be given to The Codehaus - http://groovy.codehaus.org/
*
* THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS ``AS IS'' AND ANY
* EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
*/
package org.codehaus.groovy.ast;
import groovy.lang.GroovyObject;
import groovy.lang.Script;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.objectweb.asm.Constants;
/**
* Represents a class declaration
*
* @author <a href="mailto:[email protected]">James Strachan</a>
* @version $Revision$
*/
public class ClassNode extends MetadataNode implements Constants {
private Logger log = Logger.getLogger(getClass().getName());
private String name;
private int modifiers;
private String superClass;
private String[] interfaces;
private MixinNode[] mixins;
private List constructors = new ArrayList();
private List methods = new ArrayList();
private List fields = new ArrayList();
private List properties = new ArrayList();
private Map fieldIndex = new HashMap();
private ModuleNode module;
private boolean staticClass = false;
private boolean scriptBody = false;
private boolean script;
private ClassNode superClassNode;
/**
* @param name
* is the full name of the class
* @param modifiers
* the modifiers,
* @see org.objectweb.asm.Constants
* @param superClass
* the base class name - use "java.lang.Object" if no direct
* base class
*/
public ClassNode(String name, int modifiers, String superClass) {
this(name, modifiers, superClass, EMPTY_STRING_ARRAY, MixinNode.EMPTY_ARRAY);
}
/**
* @param name
* is the full name of the class
* @param modifiers
* the modifiers,
* @see org.objectweb.asm.Constants
* @param superClass
* the base class name - use "java.lang.Object" if no direct
* base class
*/
public ClassNode(String name, int modifiers, String superClass, String[] interfaces, MixinNode[] mixins) {
this.name = name;
this.modifiers = modifiers;
this.superClass = superClass;
this.interfaces = interfaces;
this.mixins = mixins;
}
public String getSuperClass() {
return superClass;
}
public List getFields() {
return fields;
}
public String[] getInterfaces() {
return interfaces;
}
public MixinNode[] getMixins() {
return mixins;
}
public List getMethods() {
return methods;
}
public String getName() {
return name;
}
public int getModifiers() {
return modifiers;
}
public List getProperties() {
return properties;
}
public List getConstructors() {
return constructors;
}
public ModuleNode getModule() {
return module;
}
public void setModule(ModuleNode module) {
this.module = module;
}
public void addField(FieldNode node) {
fields.add(node);
fieldIndex.put(node.getName(), node);
}
public void addProperty(PropertyNode node) {
FieldNode field = node.getField();
addField(field);
properties.add(node);
}
public PropertyNode addProperty(
String name,
int modifiers,
String type,
Expression initialValueExpression,
Statement getterBlock,
Statement setterBlock) {
PropertyNode node =
new PropertyNode(name, modifiers, type, getName(), initialValueExpression, getterBlock, setterBlock);
addProperty(node);
return node;
}
public void addConstructor(ConstructorNode node) {
constructors.add(node);
}
public ConstructorNode addConstructor(int modifiers, Parameter[] parameters, Statement code) {
ConstructorNode node = new ConstructorNode(modifiers, parameters, code);
addConstructor(node);
return node;
}
public void addMethod(MethodNode node) {
methods.add(node);
}
/**
* IF a method with the given name and parameters is already defined then it is returned
* otherwise the given method is added to this node. This method is useful for
* default method adding like getProperty() or invokeMethod() where there may already
* be a method defined in a class and so the default implementations should not be added
* if already present.
*/
public MethodNode addMethod(
String name,
int modifiers,
String returnType,
Parameter[] parameters,
Statement code) {
MethodNode other = getMethod(name, parameters);
// lets not add duplicate methods
if (other != null) {
return other;
}
MethodNode node = new MethodNode(name, modifiers, returnType, parameters, code);
addMethod(node);
return node;
}
/**
* Adds a synthetic method as part of the compilation process
*/
public MethodNode addSyntheticMethod(
String name,
int modifiers,
String returnType,
Parameter[] parameters,
Statement code) {
MethodNode answer = addMethod(name, modifiers, returnType, parameters, code);
answer.setSynthetic(true);
return answer;
}
public FieldNode addField(String name, int modifiers, String type, Expression initialValue) {
FieldNode node = new FieldNode(name, modifiers, type, getName(), initialValue);
addField(node);
return node;
}
public void addInterface(String name) {
// lets check if it already implements an interface
boolean skip = false;
for (int i = 0; i < interfaces.length; i++) {
if (name.equals(interfaces[i])) {
skip = true;
}
}
if (!skip) {
String[] newInterfaces = new String[interfaces.length + 1];
System.arraycopy(interfaces, 0, newInterfaces, 0, interfaces.length);
newInterfaces[interfaces.length] = name;
interfaces = newInterfaces;
}
}
public void addMixin(MixinNode mixin) {
// lets check if it already uses a mixin
boolean skip = false;
String name = mixin.getName();
for (int i = 0; i < mixins.length; i++) {
if (name.equals(mixins[i].getName())) {
skip = true;
}
}
if (!skip) {
MixinNode[] newMixins = new MixinNode[mixins.length + 1];
System.arraycopy(mixins, 0, newMixins, 0, mixins.length);
newMixins[mixins.length] = mixin;
mixins = newMixins;
}
}
public FieldNode getField(String name) {
return (FieldNode) fieldIndex.get(name);
}
/**
* @return the field node on the outer class or null if this is not an
* inner class
*/
public FieldNode getOuterField(String name) {
return null;
}
/**
* Helper method to avoid casting to inner class
*
* @return
*/
public ClassNode getOuterClass() {
return null;
}
public void addStaticInitializerStatements(List staticStatements) {
MethodNode method = getMethod("<clinit>");
if (method == null) {
method =
addMethod("<clinit>", ACC_PUBLIC | ACC_STATIC, "void", Parameter.EMPTY_ARRAY, new BlockStatement());
}
BlockStatement block = null;
Statement statement = method.getCode();
if (statement == null) {
block = new BlockStatement();
}
else if (statement instanceof BlockStatement) {
block = (BlockStatement) statement;
}
else {
block = new BlockStatement();
block.addStatement(statement);
}
block.addStatements(staticStatements);
}
public MethodNode getMethod(String name) {
for (Iterator iter = methods.iterator(); iter.hasNext();) {
MethodNode method = (MethodNode) iter.next();
if (name.equals(method.getName())) {
return method;
}
}
return null;
}
/**
* @return the method matching the given name and parameters or null
*/
public MethodNode getMethod(String name, Parameter[] parameters) {
for (Iterator iter = methods.iterator(); iter.hasNext();) {
MethodNode method = (MethodNode) iter.next();
if (name.equals(method.getName()) && parametersEqual(method.getParameters(), parameters)) {
return method;
}
}
return null;
}
/**
* @return true if this node is derived from the given class node
*/
public boolean isDerivedFrom(String name) {
ClassNode node = getSuperClassNode();
while (node != null) {
if (name.equals(node.getName())) {
return true;
}
node = node.getSuperClassNode();
}
return false;
}
/**
* @return true if this class is derived from a groovy object
* i.e. it implements GroovyObject
*/
public boolean isDerivedFromGroovyObject() {
return implementsInteface(GroovyObject.class.getName());
}
/**
* @param name the fully qualified name of the interface
* @return true if this class or any base class implements the given interface
*/
public boolean implementsInteface(String name) {
ClassNode node = this;
do {
if (node.declaresInterface(name)) {
return true;
}
node = node.getSuperClassNode();
}
while (node != null);
return false;
}
/**
* @param name the fully qualified name of the interface
* @return true if this class declares that it implements the given interface
*/
public boolean declaresInterface(String name) {
int size = interfaces.length;
for (int i = 0; i < size; i++ ) {
if (name.equals(interfaces[i])) {
return true;
}
}
return false;
}
/**
* @return the ClassNode of the super class of this type
*/
public ClassNode getSuperClassNode() {
if (superClassNode == null && !superClass.equals("java.lang.Object")) {
// lets try find the class in the compile unit
superClassNode = findClassNode(superClass);
}
return superClassNode;
}
/**
* Attempts to lookup the fully qualified class name in the compile unit or classpath
*
* @param type fully qulified type name
* @return the ClassNode for this type or null if it could not be found
*/
public ClassNode findClassNode(String type) {
ClassNode answer = null;
CompileUnit compileUnit = getCompileUnit();
if (compileUnit != null) {
answer = compileUnit.getClass(type);
if (answer == null) {
Class theClass;
try {
theClass = compileUnit.loadClass(type);
answer = createClassNode(theClass);
}
catch (ClassNotFoundException e) {
// lets ignore class not found exceptions
log.warning("Cannot find class: " + type + " due to: " + e);
}
}
}
return answer;
}
protected ClassNode createClassNode(Class theClass) {
Class[] interfaces = theClass.getInterfaces();
int size = interfaces.length;
String[] interfaceNames = new String[size];
for (int i = 0; i < size; i++) {
interfaceNames[i] = interfaces[i].getName();
}
ClassNode answer =
new ClassNode(
theClass.getName(),
theClass.getModifiers(),
theClass.getSuperclass().getName(),
interfaceNames,
MixinNode.EMPTY_ARRAY);
return answer;
}
/**
* Tries to create a Class node for the given type name
*
* @param type
* @return
*/
/*
public ClassNode resolveClass(String type) {
if (type != null) {
if (getNameWithoutPackage().equals(type)) {
return this;
}
for (int i = 0; i < 2; i++) {
CompileUnit compileUnit = getCompileUnit();
if (compileUnit != null) {
ClassNode classNode = compileUnit.getClass(type);
if (classNode != null) {
return classNode;
}
try {
Class theClass = compileUnit.loadClass(type);
return createClassNode(theClass);
}
catch (Throwable e) {
// fall through
}
}
// lets try class in same package
String packageName = getPackageName();
if (packageName == null || packageName.length() <= 0) {
break;
}
type = packageName + "." + type;
}
}
return null;
}
*/
public String resolveClassName(String type) {
String answer = null;
if (type != null) {
- if (getNameWithoutPackage().equals(type)) {
+ if (getName().equals(type) || getNameWithoutPackage().equals(type)) {
return getName();
}
answer = tryResolveClassFromCompileUnit(type);
if (answer == null) {
// lets try class in same package
String packageName = getPackageName();
if (packageName != null && packageName.length() > 0) {
answer = tryResolveClassFromCompileUnit(packageName + "." + type);
}
}
if (answer == null) {
// lets try use the packages imported in the module
if (module != null) {
//System.out.println("Looking up inside the imported packages: " + module.getImportPackages());
for (Iterator iter = module.getImportPackages().iterator(); iter.hasNext(); ) {
String packageName = (String) iter.next();
answer = tryResolveClassFromCompileUnit(packageName + type);
if (answer != null) {
return answer;
}
}
}
}
}
return answer;
}
/**
* @param type
* @return
*/
protected String tryResolveClassFromCompileUnit(String type) {
CompileUnit compileUnit = getCompileUnit();
if (compileUnit != null) {
if (compileUnit.getClass(type) != null) {
return type;
}
try {
compileUnit.loadClass(type);
return type;
}
catch (Throwable e) {
// fall through
}
}
return null;
}
public CompileUnit getCompileUnit() {
return (module != null) ? module.getUnit() : null;
}
/**
* @return true if the two arrays are of the same size and have the same contents
*/
protected boolean parametersEqual(Parameter[] a, Parameter[] b) {
if (a.length == b.length) {
boolean answer = true;
for (int i = 0; i < a.length; i++) {
if (!a[i].getType().equals(b[i].getType())) {
answer = false;
break;
}
}
return answer;
}
return false;
}
/**
* @return the name of the class for the given identifier if it is a class
* otherwise return null
*/
public String getClassNameForExpression(String identifier) {
// lets see if it really is a class name
String className = null;
if (module != null) {
className = module.getImport(identifier);
if (className == null) {
if (module.getUnit().getClass(identifier) != null) {
className = identifier;
}
else {
// lets prepend the package name to see if its in our
// package
String packageName = getPackageName();
if (packageName != null) {
String guessName = packageName + "." + identifier;
if (module.getUnit().getClass(guessName) != null) {
className = guessName;
}
else if (guessName.equals(name)) {
className = name;
}
}
}
}
}
else {
System.out.println("No module for class: " + getName());
}
return className;
}
/**
* @return the package name of this class
*/
public String getPackageName() {
int idx = name.lastIndexOf('.');
if (idx > 0) {
return name.substring(0, idx);
}
return null;
}
public String getNameWithoutPackage() {
int idx = name.lastIndexOf('.');
if (idx > 0) {
return name.substring(idx + 1);
}
return name;
}
public void visitContents(GroovyClassVisitor visitor) {
// now lets visit the contents of the class
for (Iterator iter = getProperties().iterator(); iter.hasNext();) {
visitor.visitProperty((PropertyNode) iter.next());
}
for (Iterator iter = getFields().iterator(); iter.hasNext();) {
visitor.visitField((FieldNode) iter.next());
}
for (Iterator iter = getConstructors().iterator(); iter.hasNext();) {
visitor.visitConstructor((ConstructorNode) iter.next());
}
for (Iterator iter = getMethods().iterator(); iter.hasNext();) {
visitor.visitMethod((MethodNode) iter.next());
}
}
public MethodNode getGetterMethod(String getterName) {
for (Iterator iter = methods.iterator(); iter.hasNext();) {
MethodNode method = (MethodNode) iter.next();
if (getterName.equals(method.getName())
&& !"void".equals(method.getReturnType())
&& method.getParameters().length == 0) {
return method;
}
}
return null;
}
public MethodNode getSetterMethod(String getterName) {
for (Iterator iter = methods.iterator(); iter.hasNext();) {
MethodNode method = (MethodNode) iter.next();
if (getterName.equals(method.getName())
&& "void".equals(method.getReturnType())
&& method.getParameters().length == 1) {
return method;
}
}
return null;
}
/**
* Is this class delcared in a static method (such as a closure / inner class declared in a static method)
* @return
*/
public boolean isStaticClass() {
return staticClass;
}
public void setStaticClass(boolean staticClass) {
this.staticClass = staticClass;
}
/**
* @return Returns true if this inner class or closure was declared inside a script body
*/
public boolean isScriptBody() {
return scriptBody;
}
public void setScriptBody(boolean scriptBody) {
this.scriptBody = scriptBody;
}
public boolean isScript() {
return script | isDerivedFrom(Script.class.getName());
}
public void setScript(boolean script) {
this.script = script;
}
public String toString() {
return super.toString() + "[name: " + name + "]";
}
}
| true | true | public String resolveClassName(String type) {
String answer = null;
if (type != null) {
if (getNameWithoutPackage().equals(type)) {
return getName();
}
answer = tryResolveClassFromCompileUnit(type);
if (answer == null) {
// lets try class in same package
String packageName = getPackageName();
if (packageName != null && packageName.length() > 0) {
answer = tryResolveClassFromCompileUnit(packageName + "." + type);
}
}
if (answer == null) {
// lets try use the packages imported in the module
if (module != null) {
//System.out.println("Looking up inside the imported packages: " + module.getImportPackages());
for (Iterator iter = module.getImportPackages().iterator(); iter.hasNext(); ) {
String packageName = (String) iter.next();
answer = tryResolveClassFromCompileUnit(packageName + type);
if (answer != null) {
return answer;
}
}
}
}
}
return answer;
}
| public String resolveClassName(String type) {
String answer = null;
if (type != null) {
if (getName().equals(type) || getNameWithoutPackage().equals(type)) {
return getName();
}
answer = tryResolveClassFromCompileUnit(type);
if (answer == null) {
// lets try class in same package
String packageName = getPackageName();
if (packageName != null && packageName.length() > 0) {
answer = tryResolveClassFromCompileUnit(packageName + "." + type);
}
}
if (answer == null) {
// lets try use the packages imported in the module
if (module != null) {
//System.out.println("Looking up inside the imported packages: " + module.getImportPackages());
for (Iterator iter = module.getImportPackages().iterator(); iter.hasNext(); ) {
String packageName = (String) iter.next();
answer = tryResolveClassFromCompileUnit(packageName + type);
if (answer != null) {
return answer;
}
}
}
}
}
return answer;
}
|
diff --git a/tests/api/TestJavaApi.java b/tests/api/TestJavaApi.java
index d3a1a55e..fba7a06f 100644
--- a/tests/api/TestJavaApi.java
+++ b/tests/api/TestJavaApi.java
@@ -1,21 +1,21 @@
public class TestJavaApi {
static {
System.loadLibrary("Juneiform");
}
public static void main(String[] args) {
System.out.println("JAVA api test");
System.out.println("version: " + Juneiform.VERSION);
System.out.println("build: " + Juneiform.BUILD_NUMBER);
FormatOptions fopts = new FormatOptions();
fopts.setLanguage(Juneiform.LANGUAGE_RUSSIAN);
RecognitionOptions ropts = new RecognitionOptions();
ropts.setLanguage(Juneiform.LANGUAGE_RUSSIAN);
Page p = Juneiform.recognize("@CMAKE_SOURCE_DIR@/images/test.bmp", ropts, fopts);
- String text = p.toString(Juneiform.FORMAT_TEXT);
+ String text = p.str(Juneiform.FORMAT_TEXT);
System.out.println(text);
}
};
| true | true | public static void main(String[] args) {
System.out.println("JAVA api test");
System.out.println("version: " + Juneiform.VERSION);
System.out.println("build: " + Juneiform.BUILD_NUMBER);
FormatOptions fopts = new FormatOptions();
fopts.setLanguage(Juneiform.LANGUAGE_RUSSIAN);
RecognitionOptions ropts = new RecognitionOptions();
ropts.setLanguage(Juneiform.LANGUAGE_RUSSIAN);
Page p = Juneiform.recognize("@CMAKE_SOURCE_DIR@/images/test.bmp", ropts, fopts);
String text = p.toString(Juneiform.FORMAT_TEXT);
System.out.println(text);
}
| public static void main(String[] args) {
System.out.println("JAVA api test");
System.out.println("version: " + Juneiform.VERSION);
System.out.println("build: " + Juneiform.BUILD_NUMBER);
FormatOptions fopts = new FormatOptions();
fopts.setLanguage(Juneiform.LANGUAGE_RUSSIAN);
RecognitionOptions ropts = new RecognitionOptions();
ropts.setLanguage(Juneiform.LANGUAGE_RUSSIAN);
Page p = Juneiform.recognize("@CMAKE_SOURCE_DIR@/images/test.bmp", ropts, fopts);
String text = p.str(Juneiform.FORMAT_TEXT);
System.out.println(text);
}
|
diff --git a/cogroo-common/src/main/java/br/ccsl/cogroo/tools/checker/Merger.java b/cogroo-common/src/main/java/br/ccsl/cogroo/tools/checker/Merger.java
index cc527bc..13b13c7 100644
--- a/cogroo-common/src/main/java/br/ccsl/cogroo/tools/checker/Merger.java
+++ b/cogroo-common/src/main/java/br/ccsl/cogroo/tools/checker/Merger.java
@@ -1,134 +1,134 @@
/**
* Copyright (C) 2008 CoGrOO Team (cogroo AT gmail DOT com)
*
* CoGrOO Team (cogroo AT gmail DOT com)
* LTA, PCS (Computer and Digital Systems Engineering Department),
* Escola Politécnica da Universidade de São Paulo
* Av. Prof. Luciano Gualberto, trav. 3, n. 380
* CEP 05508-900 - São Paulo - SP - BRAZIL
*
* http://cogroo.sourceforge.net/
*
* This file is part of CoGrOO.
*
* CoGrOO is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CoGrOO is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with CoGrOO. If not, see <http://www.gnu.org/licenses/>.
*/
package br.ccsl.cogroo.tools.checker;
import br.ccsl.cogroo.entities.impl.MorphologicalTag;
import br.ccsl.cogroo.tools.checker.rules.model.TagMask;
import br.ccsl.cogroo.tools.checker.rules.model.TagMask.Class;
import br.ccsl.cogroo.tools.checker.rules.model.TagMask.Gender;
import br.ccsl.cogroo.tools.checker.rules.model.TagMask.Number;
public class Merger {
private static TagMask toTagMask(MorphologicalTag tag) {
TagMask mask = new TagMask();
if (tag.getClazzE() != null) {
mask.setClazz(tag.getClazzE());
}
if (tag.getGenderE() != null) {
mask.setGender(tag.getGenderE());
}
if (tag.getNumberE() != null) {
mask.setNumber(tag.getNumberE());
}
if (tag.getCase() != null) {
mask.setCase(tag.getCase());
}
if (tag.getPersonE() != null) {
mask.setPerson(tag.getPersonE());
}
if (tag.getTense() != null) {
mask.setTense(tag.getTense());
}
if (tag.getMood() != null) {
mask.setMood(tag.getMood());
}
if (tag.getPunctuation() != null) {
mask.setPunctuation(tag.getPunctuation());
}
return mask;
}
public static void generalizePOSTags(MorphologicalTag tag,
MorphologicalTag[] allTags) {
// this is generally true, we set gender neutral to avoid false positives.
if (tag.getClazzE().equals(Class.NUMERAL)) {
tag.setGender(Gender.NEUTRAL);
}
if (allTags == null || allTags.length == 0) {
// lets try to generalize gender and number....
if (tag.getGenderE() != null) {
tag.setGender(Gender.NEUTRAL);
}
if (tag.getNumberE() != null) {
tag.setNumber(Number.NEUTRAL);
}
} else
// now we try we check if the "tag" can be generalized in terms of gender
// and number
- if (allTags != null && allTags.length > 1
+ if (allTags != null && allTags.length >= 1
&& (tag.getGenderE() != null || tag.getNumberE() != null)) {
TagMask noGender = toTagMask(tag);
noGender.setGender(null);
TagMask noNumber = toTagMask(tag);
noGender.setGender(null);
boolean is2g = false;
boolean isSP = false;
for (MorphologicalTag test : allTags) {
if (test.match(noGender)) {
if (test.getGenderE() != null
&& !test.getGenderE().equals(tag.getGenderE())) {
is2g = true;
if (isSP) {
break;
}
}
}
if (test.getNumberE() != null && test.match(noNumber)) {
if (!test.getNumberE().equals(tag.getNumberE())) {
isSP = true;
if (is2g) {
break;
}
}
}
}
if (is2g) {
tag.setGender(Gender.NEUTRAL);
}
if (isSP) {
tag.setNumber(Number.NEUTRAL);
}
}
}
}
| true | true | public static void generalizePOSTags(MorphologicalTag tag,
MorphologicalTag[] allTags) {
// this is generally true, we set gender neutral to avoid false positives.
if (tag.getClazzE().equals(Class.NUMERAL)) {
tag.setGender(Gender.NEUTRAL);
}
if (allTags == null || allTags.length == 0) {
// lets try to generalize gender and number....
if (tag.getGenderE() != null) {
tag.setGender(Gender.NEUTRAL);
}
if (tag.getNumberE() != null) {
tag.setNumber(Number.NEUTRAL);
}
} else
// now we try we check if the "tag" can be generalized in terms of gender
// and number
if (allTags != null && allTags.length > 1
&& (tag.getGenderE() != null || tag.getNumberE() != null)) {
TagMask noGender = toTagMask(tag);
noGender.setGender(null);
TagMask noNumber = toTagMask(tag);
noGender.setGender(null);
boolean is2g = false;
boolean isSP = false;
for (MorphologicalTag test : allTags) {
if (test.match(noGender)) {
if (test.getGenderE() != null
&& !test.getGenderE().equals(tag.getGenderE())) {
is2g = true;
if (isSP) {
break;
}
}
}
if (test.getNumberE() != null && test.match(noNumber)) {
if (!test.getNumberE().equals(tag.getNumberE())) {
isSP = true;
if (is2g) {
break;
}
}
}
}
if (is2g) {
tag.setGender(Gender.NEUTRAL);
}
if (isSP) {
tag.setNumber(Number.NEUTRAL);
}
}
}
| public static void generalizePOSTags(MorphologicalTag tag,
MorphologicalTag[] allTags) {
// this is generally true, we set gender neutral to avoid false positives.
if (tag.getClazzE().equals(Class.NUMERAL)) {
tag.setGender(Gender.NEUTRAL);
}
if (allTags == null || allTags.length == 0) {
// lets try to generalize gender and number....
if (tag.getGenderE() != null) {
tag.setGender(Gender.NEUTRAL);
}
if (tag.getNumberE() != null) {
tag.setNumber(Number.NEUTRAL);
}
} else
// now we try we check if the "tag" can be generalized in terms of gender
// and number
if (allTags != null && allTags.length >= 1
&& (tag.getGenderE() != null || tag.getNumberE() != null)) {
TagMask noGender = toTagMask(tag);
noGender.setGender(null);
TagMask noNumber = toTagMask(tag);
noGender.setGender(null);
boolean is2g = false;
boolean isSP = false;
for (MorphologicalTag test : allTags) {
if (test.match(noGender)) {
if (test.getGenderE() != null
&& !test.getGenderE().equals(tag.getGenderE())) {
is2g = true;
if (isSP) {
break;
}
}
}
if (test.getNumberE() != null && test.match(noNumber)) {
if (!test.getNumberE().equals(tag.getNumberE())) {
isSP = true;
if (is2g) {
break;
}
}
}
}
if (is2g) {
tag.setGender(Gender.NEUTRAL);
}
if (isSP) {
tag.setNumber(Number.NEUTRAL);
}
}
}
|
diff --git a/sch-kp-ejb-impl/src/main/java/hu/sch/kp/ejb/EntitlementManagerBean.java b/sch-kp-ejb-impl/src/main/java/hu/sch/kp/ejb/EntitlementManagerBean.java
index 18f40ff1..c6f748f2 100644
--- a/sch-kp-ejb-impl/src/main/java/hu/sch/kp/ejb/EntitlementManagerBean.java
+++ b/sch-kp-ejb-impl/src/main/java/hu/sch/kp/ejb/EntitlementManagerBean.java
@@ -1,42 +1,42 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package hu.sch.kp.ejb;
import hu.sch.domain.Felhasznalo;
import hu.sch.kp.services.EntitlementManagerRemote;
import hu.sch.kp.services.UserManagerLocal;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* @author aldaris
*/
@Stateless
public class EntitlementManagerBean implements EntitlementManagerRemote {
@EJB(name = "UserManagerBean")
UserManagerLocal userManager;
@PersistenceContext
EntityManager em;
public Felhasznalo createUserEntry(Felhasznalo user) {
- if (!user.getNeptunkod().isEmpty()) {
+ if (user.getNeptunkod() != null) {
Query q = em.createNamedQuery("findUserByNeptunCode");
q.setParameter("neptun", user.getNeptunkod());
try {
Felhasznalo exists = (Felhasznalo) q.getSingleResult();
return exists;
} catch (Exception e) {
}
}
em.persist(user);
em.flush();
return user;
}
}
| true | true | public Felhasznalo createUserEntry(Felhasznalo user) {
if (!user.getNeptunkod().isEmpty()) {
Query q = em.createNamedQuery("findUserByNeptunCode");
q.setParameter("neptun", user.getNeptunkod());
try {
Felhasznalo exists = (Felhasznalo) q.getSingleResult();
return exists;
} catch (Exception e) {
}
}
em.persist(user);
em.flush();
return user;
}
| public Felhasznalo createUserEntry(Felhasznalo user) {
if (user.getNeptunkod() != null) {
Query q = em.createNamedQuery("findUserByNeptunCode");
q.setParameter("neptun", user.getNeptunkod());
try {
Felhasznalo exists = (Felhasznalo) q.getSingleResult();
return exists;
} catch (Exception e) {
}
}
em.persist(user);
em.flush();
return user;
}
|
diff --git a/src/org/meta_environment/rascal/interpreter/matching/ListPattern.java b/src/org/meta_environment/rascal/interpreter/matching/ListPattern.java
index 0609d9911a..23d7458dca 100644
--- a/src/org/meta_environment/rascal/interpreter/matching/ListPattern.java
+++ b/src/org/meta_environment/rascal/interpreter/matching/ListPattern.java
@@ -1,601 +1,603 @@
package org.meta_environment.rascal.interpreter.matching;
import java.util.HashSet;
import java.util.List;
import org.eclipse.imp.pdb.facts.IList;
import org.eclipse.imp.pdb.facts.IValue;
import org.eclipse.imp.pdb.facts.IValueFactory;
import org.eclipse.imp.pdb.facts.type.Type;
import org.meta_environment.rascal.interpreter.IEvaluatorContext;
import org.meta_environment.rascal.interpreter.asserts.ImplementationError;
import org.meta_environment.rascal.interpreter.env.Environment;
import org.meta_environment.rascal.interpreter.result.Result;
import org.meta_environment.rascal.interpreter.result.ResultFactory;
import org.meta_environment.rascal.interpreter.staticErrors.RedeclaredVariableError;
import org.meta_environment.rascal.interpreter.staticErrors.UnexpectedTypeError;
import org.meta_environment.rascal.interpreter.types.ConcreteSyntaxType;
import org.meta_environment.uptr.SymbolAdapter;
public class ListPattern extends AbstractMatchingResult {
private List<IMatchingResult> patternChildren; // The elements of this list pattern
private int patternSize; // The number of elements in this list pattern
private int delta = 1; // increment to next list elements:
// delta=1 abstract lists
// delta=2 skip layout between elements
// delta=4 skip layout, separator, layout between elements
private int reducedPatternSize; // (patternSize + delta - 1)/delta
private IList listSubject; // The subject as list
private Type listSubjectType; // The type of the subject
private Type listSubjectElementType; // The type of list elements
private int subjectSize; // Length of the subject
private int reducedSubjectSize; // (subjectSize + delta - 1) / delta
private boolean [] isListVar; // Determine which elements are list or variables
private boolean [] isBindingVar; // Determine which elements are binding occurrences of variables
private String [] varName; // Name of ith variable
private HashSet<String> allVars; // Names of list variables declared in this pattern
private int [] listVarStart; // Cursor start position list variable; indexed by pattern position
private int [] listVarLength; // Current length matched by list variable
private int [] listVarMinLength; // Minimal length to be matched by list variable
private int [] listVarMaxLength; // Maximal length that can be matched by list variable
private int [] listVarOccurrences; // Number of occurrences of list variable in the pattern
private int subjectCursor; // Cursor in the subject
private int patternCursor; // Cursor in the pattern
private boolean firstMatch; // First match after initialization?
private boolean forward; // Moving to the right?
private boolean debug = false;
public ListPattern(IValueFactory vf, IEvaluatorContext ctx, List<IMatchingResult> list){
this(vf,ctx, list, 1); // Default delta=1; Set to 2 to run DeltaListPatternTests
}
ListPattern(IValueFactory vf, IEvaluatorContext ctx, List<IMatchingResult> list, int delta){
super(vf, ctx);
if(delta < 1)
throw new ImplementationError("Wrong delta");
this.delta = delta;
this.patternChildren = list;
this.patternSize = list.size();
this.reducedPatternSize = (patternSize + delta - 1) / delta;
if (debug) {
System.err.println("patternSize=" + patternSize);
System.err.println("reducedPatternSize=" + reducedPatternSize);
}
}
@Override
public java.util.List<String> getVariables(){
java.util.LinkedList<String> res = new java.util.LinkedList<String> ();
for (int i = 0; i < patternChildren.size(); i += delta) {
res.addAll(patternChildren.get(i).getVariables());
}
return res;
}
@Override
public IValue toIValue(Environment env){
IValue[] vals = new IValue[patternChildren.size()];
for (int i = 0; i < patternChildren.size(); i += delta) {
vals[i] = patternChildren.get(i).toIValue(env);
}
return vf.list(vals);
}
public static boolean isAnyListType(Type type){
return type.isListType()|| isConcreteListType(type); //<------ disabled to let other tests work.
}
public static boolean isConcreteListType(Type type){ // <--- this code does not work because I donot understand the type structure of Tree
if (type instanceof ConcreteSyntaxType) {
SymbolAdapter sym = new SymbolAdapter(((ConcreteSyntaxType)type).getSymbol());
return sym.isAnyList();
}
return false;
}
@Override
public void initMatch(Result<IValue> subject){
super.initMatch(subject);
if(debug) {
System.err.println("List: initMatch: subject=" + subject);
}
if (!subject.getType().isListType()) {
hasNext = false;
return;
} else {
listSubject = (IList) subject.getValue();
listSubjectType = listSubject.getType();
listSubjectElementType = listSubject.getElementType();
}
subjectCursor = 0;
patternCursor = 0;
subjectSize = ((IList) subject.getValue()).length();
reducedSubjectSize = (subjectSize + delta - 1) / delta;
if (debug) {
System.err.println("reducedPatternSize=" + reducedPatternSize);
System.err.println("reducedSubjectSize=" + reducedSubjectSize);
}
isListVar = new boolean[patternSize];
isBindingVar = new boolean[patternSize];
varName = new String[patternSize];
allVars = new HashSet<String>();
listVarStart = new int[patternSize];
listVarLength = new int[patternSize];
listVarMinLength = new int[patternSize];
listVarMaxLength = new int[patternSize];
listVarOccurrences = new int[patternSize];
int nListVar = 0;
/*
* Pass #1: determine the list variables
*/
for(int i = 0; i < patternSize; i += delta){
IMatchingResult child = patternChildren.get(i);
isListVar[i] = false;
isBindingVar[i] = false;
Environment env = ctx.getCurrentEnvt();
if(child instanceof TypedVariablePattern && isAnyListType(child.getType(env))){ // <------
TypedVariablePattern patVar = (TypedVariablePattern) child;
Type childType = child.getType(env);
String name = patVar.getName();
varName[i] = name;
if(!patVar.isAnonymous() && allVars.contains(name)){
throw new RedeclaredVariableError(name, getAST());
}
// TODO JURGEN thinks this code is dead, it is handled by the AbstractPatternConcreteListVariable case
if (listSubject.getType().isListType() && childType instanceof ConcreteSyntaxType) {
throw new ImplementationError("We thought this code was dead");
// ConcreteSyntaxType cType = (ConcreteSyntaxType)childType;
// if (cType.isConcreteCFList()) {
// ConcreteSyntaxType eType = cType.getConcreteCFListElementType();
// if (listSubject.getType().getElementType().comparable(eType)) {
// // Copied from below
// if(!patVar.isAnonymous()) {
// allVars.add(name);
// }
// isListVar[i] = true;
// isBindingVar[i] = true;
// listVarOccurrences[i] = 1;
// nListVar++;
// }
// }
}
else if(childType.comparable(listSubject.getType())){ // <------- change to let this work for concrete lists as well
/*
* An explicitly declared list variable.
*/
if(!patVar.isAnonymous()) {
allVars.add(name);
}
isListVar[i] = isAnyListType(childType);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
} else {
throw new UnexpectedTypeError(childType, listSubject.getType(), getAST());
}
}
else if(child instanceof MultiVariablePattern){
MultiVariablePattern multiVar = (MultiVariablePattern) child;
String name = multiVar.getName();
if(!multiVar.isAnonymous() && allVars.contains(name)){
throw new RedeclaredVariableError(name, getAST());
}
varName[i] = name;
isListVar[i] = true;
if(!multiVar.isAnonymous())
allVars.add(name);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
}
else if (child instanceof ConcreteListVariablePattern) {
ConcreteListVariablePattern listVar = (ConcreteListVariablePattern) child;
String name = listVar.getName();
varName[i] = name;
isListVar[i] = true;
if(!listVar.isAnonymous())
allVars.add(name);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
}
else if(child instanceof QualifiedNamePattern){
QualifiedNamePattern qualName = (QualifiedNamePattern) child;
String name = qualName.getName();
varName[i] = name;
if(!qualName.isAnonymous() && allVars.contains(name)){
/*
* A variable that was declared earlier in the pattern
*/
isListVar[i] = true;
nListVar++;
listVarOccurrences[i]++;
} else if(qualName.isAnonymous()){
/*
* Nothing to do
*/
} else {
Result<IValue> varRes = env.getVariable(name);
if(varRes == null){
// A completely new variable, nothing to do
} else {
Type varType = varRes.getType();
if (isAnyListType(varType)){ // <-----
/*
* A variable declared in the current scope.
*/
if(varType.comparable(listSubjectType)){ // <-- let this also work for concrete lists
isListVar[i] = true;
isBindingVar[i] = varRes.getValue() == null;
nListVar++;
} else {
throw new UnexpectedTypeError(listSubjectType,varType, getAST());
}
} else {
if(!varType.comparable(listSubjectElementType)){
throw new UnexpectedTypeError(listSubjectType, varType, getAST());
}
}
}
}
} else {
if (debug) {
System.err.println("List: child " + child + " " + child);
System.err.println("List: child is a" + child.getClass());
}
Type childType = child.getType(env);
- if(!childType.comparable(listSubjectElementType)){
+ // TODO: pattern matching should be specialized such that matching appl(prod...)'s does not
+ // need to use list matching on the fixed arity children of the application of a production
+ if(!(childType instanceof ConcreteSyntaxType) && !childType.comparable(listSubjectElementType)){
throw new UnexpectedTypeError(listSubjectElementType,childType, getAST());
}
java.util.List<String> childVars = child.getVariables();
if(!childVars.isEmpty()){
allVars.addAll(childVars);
isListVar[nListVar] = false;
nListVar++;
}
}
}
/*
* Pass #2: assign minimum and maximum length to each list variable
*/
for(int i = 0; i < patternSize; i += delta){
if(isListVar[i]){
// TODO: reduce max length according to number of occurrences
listVarMaxLength[i] = delta * Math.max(reducedSubjectSize - (reducedPatternSize - nListVar), 0);
listVarLength[i] = 0;
listVarMinLength[i] = delta * ((nListVar == 1) ? Math.max(reducedSubjectSize - reducedPatternSize - 1, 0) : 0);
if (debug) {
System.err.println("listvar " + i + " min= " + listVarMinLength[i] + " max=" + listVarMaxLength[i]);
}
}
}
firstMatch = true;
hasNext = subject.getType().isListType() &&
reducedSubjectSize >= reducedPatternSize - nListVar;
if(debug) {
System.err.println("List: hasNext=" + hasNext);
}
}
@Override
public Type getType(Environment env) {
if(patternSize == 0){
return tf.listType(tf.voidType());
}
Type elemType = tf.voidType();
for(int i = 0; i < patternSize; i += delta){
Type childType = patternChildren.get(i).getType(env);
if(childType.isListType()){
elemType = elemType.lub(childType.getElementType());
} else {
elemType = elemType.lub(childType);
}
}
if(debug) {
System.err.println("ListPattern.getType: " + tf.listType(elemType));
}
return tf.listType(elemType);
}
@Override
public boolean hasNext(){
if(debug) {
System.err.println("List: hasNext=" + (initialized && hasNext));
}
return initialized && hasNext;
}
private void matchBoundListVar(IList previousBinding){
if(debug) {
System.err.println("matchBoundListVar: " + previousBinding);
}
assert isListVar[patternCursor];
int start = listVarStart[patternCursor];
int length = listVarLength[patternCursor];
for(int i = 0; i < previousBinding.length(); i += delta){
if(debug)System.err.println("comparing: " + previousBinding.get(i) + " and " + listSubject.get(subjectCursor + i));
if(!previousBinding.get(i).isEqual(listSubject.get(subjectCursor + i))){
forward = false;
listVarLength[patternCursor] = 0;
patternCursor -= delta;
if(debug)System.err.println("child fails");
return;
}
}
subjectCursor = start + length;
if(debug)System.err.println("child matches, subjectCursor=" + subjectCursor);
patternCursor += delta;
}
private IList makeSubList(int start, int length){
assert isListVar[patternCursor];
// TODO: wrap concrete lists in an appl(list( )) again.
if(start > subjectSize)
return listSubject.sublist(0,0);
else {
return listSubject.sublist(start, length);
}
}
/*
* We are positioned in the pattern at a list variable and match it with
* the current subject starting at the current position.
* On success, the cursors are advanced.
* On failure, switch to backtracking (forward = false) mode.
*/
private void matchBindingListVar(IMatchingResult child){
assert isListVar[patternCursor];
int start = listVarStart[patternCursor];
int length = listVarLength[patternCursor];
// int reducedLength = (length == 0) ? 0 : ((length < delta) ? 1 : Math.max(length - delta + 1, 0)); // round to nearest unskipped element
int reducedLength = (length <= 1) ? length : (length - (length-1)%delta);
if (debug) {
System.err.println("length=" + length);
System.err.println("reducedLength=" + reducedLength);
}
IList sublist = makeSubList(start, reducedLength);
if(debug)System.err.println("matchBindingListVar: init child #" + patternCursor + " (" + child + ") with " + sublist);
// TODO : check if we can use a static type here!?
child.initMatch(ResultFactory.makeResult(sublist.getType(), sublist, ctx));
if(child.next()){
subjectCursor = start + length;
if(debug)System.err.println("child matches, subjectCursor=" + subjectCursor);
patternCursor += delta;
} else {
forward = false;
listVarLength[patternCursor] = 0;
patternCursor -= delta;
if(debug)System.err.println("child fails, subjectCursor=" + subjectCursor);
}
}
/*
* Perform a list match. When forward=true we move to the right in the pattern
* and try to match the corresponding elements of the subject. When the end of the pattern
* and the subject are reaching, match returns true.
*
* When a non-matching element is encountered, we switch to moving to the left (forward==false)
* and try to find alternative options in list variables.
*
* When the left-hand side of the pattern is reached while moving to the left, match return false,
* and no more options are available: hasNext() will return false.
*
* @see org.meta_environment.rascal.interpreter.MatchPattern#match()
*/
@Override
public boolean next(){
if(debug)System.err.println("List.next: entering");
checkInitialized();
if(debug)System.err.println("AbstractPatternList.match: " + subject);
if(!hasNext)
return false;
forward = firstMatch;
firstMatch = false;
do {
/*
* Determine the various termination conditions.
*/
if(debug)System.err.println("List.do: patternCursor=" + patternCursor + ", subjectCursor=" + subjectCursor);
if(forward){
if(patternCursor >= patternSize){
if(subjectCursor >= subjectSize){
if(debug)System.err.println(">>> match returns true");
// hasNext = (subjectCursor > subjectSize) && (patternCursor > patternSize); // JURGEN GUESSES THIS COULD BE RIGHT
return true;
}
forward = false;
patternCursor -= delta;
}
} else {
if(patternCursor >= patternSize){
patternCursor -= delta;
subjectCursor -= delta; // Ok?
}
}
if(patternCursor < 0 || subjectCursor < 0){
hasNext = false;
if(debug)System.err.println(">>> match returns false: patternCursor=" + patternCursor + ", forward=" + forward + ", subjectCursor=" + subjectCursor);
return false;
}
/*
* Perform actions for the current pattern element
*/
IMatchingResult child = patternChildren.get(patternCursor);
if(debug){
System.err.println(this);
System.err.println("loop: patternCursor=" + patternCursor +
", forward=" + forward +
", subjectCursor= " + subjectCursor +
", child=" + child +
", isListVar=" + isListVar[patternCursor] +
", class=" + child.getClass());
}
/*
* A binding occurrence of a list variable
*/
if(isListVar[patternCursor] && isBindingVar[patternCursor]){
if(forward){
listVarStart[patternCursor] = subjectCursor;
if(patternCursor == patternSize - 1){
if (debug) {
System.err.println("subjectSize=" + subjectSize);
System.err.println("subjectCursor=" + subjectCursor);
}
listVarLength[patternCursor] = Math.max(subjectSize - subjectCursor, 0);
} else {
listVarLength[patternCursor] = listVarMinLength[patternCursor];
}
} else {
listVarLength[patternCursor] += delta;
forward = true;
}
if(debug)System.err.println("list var: start: " + listVarStart[patternCursor] +
", len=" + listVarLength[patternCursor] +
", minlen=" + listVarMinLength[patternCursor] +
", maxlen=" + listVarMaxLength[patternCursor]);
if(listVarLength[patternCursor] > listVarMaxLength[patternCursor] ||
listVarStart[patternCursor] + listVarLength[patternCursor] >= subjectSize + delta){
subjectCursor = listVarStart[patternCursor];
if(debug)System.err.println("Length failure, subjectCursor=" + subjectCursor);
forward = false;
listVarLength[patternCursor] = 0;
patternCursor -= delta;
} else {
matchBindingListVar(child);
}
/*
* Reference to a previously defined list variable
*/
}
else if(isListVar[patternCursor] &&
!isBindingVar[patternCursor] &&
ctx.getCurrentEnvt().getVariable(varName[patternCursor]).getType().isListType()){
if(forward){
listVarStart[patternCursor] = subjectCursor;
Result<IValue> varRes = ctx.getCurrentEnvt().getVariable(varName[patternCursor]);
IValue varVal = varRes.getValue();
if(varRes.getType().isListType()){
assert varVal != null && varVal.getType().isListType();
int varLength = ((IList)varVal).length();
listVarLength[patternCursor] = varLength;
if(subjectCursor + varLength > subjectSize){
forward = false;
patternCursor -= delta;
} else {
matchBoundListVar((IList) varVal);
}
}
} else {
subjectCursor = listVarStart[patternCursor];
patternCursor -= delta;
}
/*
* Any other element of the pattern
*/
} else {
if(forward && subjectCursor < subjectSize){
if(debug)System.err.println("AbstractPatternList.match: init child " + patternCursor + " with " + listSubject.get(subjectCursor));
IValue childValue = listSubject.get(subjectCursor);
// TODO: check if we can use a static type here?!
child.initMatch(ResultFactory.makeResult(childValue.getType(), childValue, ctx));
if(child.next()){
subjectCursor += delta;
patternCursor += delta;
if(debug)System.err.println("AbstractPatternList.match: child matches, subjectCursor=" + subjectCursor);
} else {
forward = false;
patternCursor -= delta;
}
} else {
if(subjectCursor < subjectSize && child.next()){
if(debug)System.err.println("child has next:" + child);
forward = true;
subjectCursor += delta;
patternCursor += delta;
} else {
forward = false;
subjectCursor -= delta;
patternCursor -= delta;
}
}
}
} while (true);
}
@Override
public String toString(){
StringBuffer s = new StringBuffer();
s.append("[");
if(initialized){
String sep = "";
for(int i = 0; i < Math.min(patternCursor,patternSize); i++){
s.append(sep).append(patternChildren.get(i).toString());
sep = ", ";
}
if(patternCursor < patternSize){
s.append("...");
}
s.append("]").append("==").append(subject.toString());
} else {
s.append("**uninitialized**]");
}
return s.toString();
}
}
| true | true | public void initMatch(Result<IValue> subject){
super.initMatch(subject);
if(debug) {
System.err.println("List: initMatch: subject=" + subject);
}
if (!subject.getType().isListType()) {
hasNext = false;
return;
} else {
listSubject = (IList) subject.getValue();
listSubjectType = listSubject.getType();
listSubjectElementType = listSubject.getElementType();
}
subjectCursor = 0;
patternCursor = 0;
subjectSize = ((IList) subject.getValue()).length();
reducedSubjectSize = (subjectSize + delta - 1) / delta;
if (debug) {
System.err.println("reducedPatternSize=" + reducedPatternSize);
System.err.println("reducedSubjectSize=" + reducedSubjectSize);
}
isListVar = new boolean[patternSize];
isBindingVar = new boolean[patternSize];
varName = new String[patternSize];
allVars = new HashSet<String>();
listVarStart = new int[patternSize];
listVarLength = new int[patternSize];
listVarMinLength = new int[patternSize];
listVarMaxLength = new int[patternSize];
listVarOccurrences = new int[patternSize];
int nListVar = 0;
/*
* Pass #1: determine the list variables
*/
for(int i = 0; i < patternSize; i += delta){
IMatchingResult child = patternChildren.get(i);
isListVar[i] = false;
isBindingVar[i] = false;
Environment env = ctx.getCurrentEnvt();
if(child instanceof TypedVariablePattern && isAnyListType(child.getType(env))){ // <------
TypedVariablePattern patVar = (TypedVariablePattern) child;
Type childType = child.getType(env);
String name = patVar.getName();
varName[i] = name;
if(!patVar.isAnonymous() && allVars.contains(name)){
throw new RedeclaredVariableError(name, getAST());
}
// TODO JURGEN thinks this code is dead, it is handled by the AbstractPatternConcreteListVariable case
if (listSubject.getType().isListType() && childType instanceof ConcreteSyntaxType) {
throw new ImplementationError("We thought this code was dead");
// ConcreteSyntaxType cType = (ConcreteSyntaxType)childType;
// if (cType.isConcreteCFList()) {
// ConcreteSyntaxType eType = cType.getConcreteCFListElementType();
// if (listSubject.getType().getElementType().comparable(eType)) {
// // Copied from below
// if(!patVar.isAnonymous()) {
// allVars.add(name);
// }
// isListVar[i] = true;
// isBindingVar[i] = true;
// listVarOccurrences[i] = 1;
// nListVar++;
// }
// }
}
else if(childType.comparable(listSubject.getType())){ // <------- change to let this work for concrete lists as well
/*
* An explicitly declared list variable.
*/
if(!patVar.isAnonymous()) {
allVars.add(name);
}
isListVar[i] = isAnyListType(childType);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
} else {
throw new UnexpectedTypeError(childType, listSubject.getType(), getAST());
}
}
else if(child instanceof MultiVariablePattern){
MultiVariablePattern multiVar = (MultiVariablePattern) child;
String name = multiVar.getName();
if(!multiVar.isAnonymous() && allVars.contains(name)){
throw new RedeclaredVariableError(name, getAST());
}
varName[i] = name;
isListVar[i] = true;
if(!multiVar.isAnonymous())
allVars.add(name);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
}
else if (child instanceof ConcreteListVariablePattern) {
ConcreteListVariablePattern listVar = (ConcreteListVariablePattern) child;
String name = listVar.getName();
varName[i] = name;
isListVar[i] = true;
if(!listVar.isAnonymous())
allVars.add(name);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
}
else if(child instanceof QualifiedNamePattern){
QualifiedNamePattern qualName = (QualifiedNamePattern) child;
String name = qualName.getName();
varName[i] = name;
if(!qualName.isAnonymous() && allVars.contains(name)){
/*
* A variable that was declared earlier in the pattern
*/
isListVar[i] = true;
nListVar++;
listVarOccurrences[i]++;
} else if(qualName.isAnonymous()){
/*
* Nothing to do
*/
} else {
Result<IValue> varRes = env.getVariable(name);
if(varRes == null){
// A completely new variable, nothing to do
} else {
Type varType = varRes.getType();
if (isAnyListType(varType)){ // <-----
/*
* A variable declared in the current scope.
*/
if(varType.comparable(listSubjectType)){ // <-- let this also work for concrete lists
isListVar[i] = true;
isBindingVar[i] = varRes.getValue() == null;
nListVar++;
} else {
throw new UnexpectedTypeError(listSubjectType,varType, getAST());
}
} else {
if(!varType.comparable(listSubjectElementType)){
throw new UnexpectedTypeError(listSubjectType, varType, getAST());
}
}
}
}
} else {
if (debug) {
System.err.println("List: child " + child + " " + child);
System.err.println("List: child is a" + child.getClass());
}
Type childType = child.getType(env);
if(!childType.comparable(listSubjectElementType)){
throw new UnexpectedTypeError(listSubjectElementType,childType, getAST());
}
java.util.List<String> childVars = child.getVariables();
if(!childVars.isEmpty()){
allVars.addAll(childVars);
isListVar[nListVar] = false;
nListVar++;
}
}
}
/*
* Pass #2: assign minimum and maximum length to each list variable
*/
for(int i = 0; i < patternSize; i += delta){
if(isListVar[i]){
// TODO: reduce max length according to number of occurrences
listVarMaxLength[i] = delta * Math.max(reducedSubjectSize - (reducedPatternSize - nListVar), 0);
listVarLength[i] = 0;
listVarMinLength[i] = delta * ((nListVar == 1) ? Math.max(reducedSubjectSize - reducedPatternSize - 1, 0) : 0);
if (debug) {
System.err.println("listvar " + i + " min= " + listVarMinLength[i] + " max=" + listVarMaxLength[i]);
}
}
}
firstMatch = true;
hasNext = subject.getType().isListType() &&
reducedSubjectSize >= reducedPatternSize - nListVar;
if(debug) {
System.err.println("List: hasNext=" + hasNext);
}
}
| public void initMatch(Result<IValue> subject){
super.initMatch(subject);
if(debug) {
System.err.println("List: initMatch: subject=" + subject);
}
if (!subject.getType().isListType()) {
hasNext = false;
return;
} else {
listSubject = (IList) subject.getValue();
listSubjectType = listSubject.getType();
listSubjectElementType = listSubject.getElementType();
}
subjectCursor = 0;
patternCursor = 0;
subjectSize = ((IList) subject.getValue()).length();
reducedSubjectSize = (subjectSize + delta - 1) / delta;
if (debug) {
System.err.println("reducedPatternSize=" + reducedPatternSize);
System.err.println("reducedSubjectSize=" + reducedSubjectSize);
}
isListVar = new boolean[patternSize];
isBindingVar = new boolean[patternSize];
varName = new String[patternSize];
allVars = new HashSet<String>();
listVarStart = new int[patternSize];
listVarLength = new int[patternSize];
listVarMinLength = new int[patternSize];
listVarMaxLength = new int[patternSize];
listVarOccurrences = new int[patternSize];
int nListVar = 0;
/*
* Pass #1: determine the list variables
*/
for(int i = 0; i < patternSize; i += delta){
IMatchingResult child = patternChildren.get(i);
isListVar[i] = false;
isBindingVar[i] = false;
Environment env = ctx.getCurrentEnvt();
if(child instanceof TypedVariablePattern && isAnyListType(child.getType(env))){ // <------
TypedVariablePattern patVar = (TypedVariablePattern) child;
Type childType = child.getType(env);
String name = patVar.getName();
varName[i] = name;
if(!patVar.isAnonymous() && allVars.contains(name)){
throw new RedeclaredVariableError(name, getAST());
}
// TODO JURGEN thinks this code is dead, it is handled by the AbstractPatternConcreteListVariable case
if (listSubject.getType().isListType() && childType instanceof ConcreteSyntaxType) {
throw new ImplementationError("We thought this code was dead");
// ConcreteSyntaxType cType = (ConcreteSyntaxType)childType;
// if (cType.isConcreteCFList()) {
// ConcreteSyntaxType eType = cType.getConcreteCFListElementType();
// if (listSubject.getType().getElementType().comparable(eType)) {
// // Copied from below
// if(!patVar.isAnonymous()) {
// allVars.add(name);
// }
// isListVar[i] = true;
// isBindingVar[i] = true;
// listVarOccurrences[i] = 1;
// nListVar++;
// }
// }
}
else if(childType.comparable(listSubject.getType())){ // <------- change to let this work for concrete lists as well
/*
* An explicitly declared list variable.
*/
if(!patVar.isAnonymous()) {
allVars.add(name);
}
isListVar[i] = isAnyListType(childType);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
} else {
throw new UnexpectedTypeError(childType, listSubject.getType(), getAST());
}
}
else if(child instanceof MultiVariablePattern){
MultiVariablePattern multiVar = (MultiVariablePattern) child;
String name = multiVar.getName();
if(!multiVar.isAnonymous() && allVars.contains(name)){
throw new RedeclaredVariableError(name, getAST());
}
varName[i] = name;
isListVar[i] = true;
if(!multiVar.isAnonymous())
allVars.add(name);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
}
else if (child instanceof ConcreteListVariablePattern) {
ConcreteListVariablePattern listVar = (ConcreteListVariablePattern) child;
String name = listVar.getName();
varName[i] = name;
isListVar[i] = true;
if(!listVar.isAnonymous())
allVars.add(name);
isBindingVar[i] = true;
listVarOccurrences[i] = 1;
nListVar++;
}
else if(child instanceof QualifiedNamePattern){
QualifiedNamePattern qualName = (QualifiedNamePattern) child;
String name = qualName.getName();
varName[i] = name;
if(!qualName.isAnonymous() && allVars.contains(name)){
/*
* A variable that was declared earlier in the pattern
*/
isListVar[i] = true;
nListVar++;
listVarOccurrences[i]++;
} else if(qualName.isAnonymous()){
/*
* Nothing to do
*/
} else {
Result<IValue> varRes = env.getVariable(name);
if(varRes == null){
// A completely new variable, nothing to do
} else {
Type varType = varRes.getType();
if (isAnyListType(varType)){ // <-----
/*
* A variable declared in the current scope.
*/
if(varType.comparable(listSubjectType)){ // <-- let this also work for concrete lists
isListVar[i] = true;
isBindingVar[i] = varRes.getValue() == null;
nListVar++;
} else {
throw new UnexpectedTypeError(listSubjectType,varType, getAST());
}
} else {
if(!varType.comparable(listSubjectElementType)){
throw new UnexpectedTypeError(listSubjectType, varType, getAST());
}
}
}
}
} else {
if (debug) {
System.err.println("List: child " + child + " " + child);
System.err.println("List: child is a" + child.getClass());
}
Type childType = child.getType(env);
// TODO: pattern matching should be specialized such that matching appl(prod...)'s does not
// need to use list matching on the fixed arity children of the application of a production
if(!(childType instanceof ConcreteSyntaxType) && !childType.comparable(listSubjectElementType)){
throw new UnexpectedTypeError(listSubjectElementType,childType, getAST());
}
java.util.List<String> childVars = child.getVariables();
if(!childVars.isEmpty()){
allVars.addAll(childVars);
isListVar[nListVar] = false;
nListVar++;
}
}
}
/*
* Pass #2: assign minimum and maximum length to each list variable
*/
for(int i = 0; i < patternSize; i += delta){
if(isListVar[i]){
// TODO: reduce max length according to number of occurrences
listVarMaxLength[i] = delta * Math.max(reducedSubjectSize - (reducedPatternSize - nListVar), 0);
listVarLength[i] = 0;
listVarMinLength[i] = delta * ((nListVar == 1) ? Math.max(reducedSubjectSize - reducedPatternSize - 1, 0) : 0);
if (debug) {
System.err.println("listvar " + i + " min= " + listVarMinLength[i] + " max=" + listVarMaxLength[i]);
}
}
}
firstMatch = true;
hasNext = subject.getType().isListType() &&
reducedSubjectSize >= reducedPatternSize - nListVar;
if(debug) {
System.err.println("List: hasNext=" + hasNext);
}
}
|
diff --git a/src/skittles/sim/BatchSkittles.java b/src/skittles/sim/BatchSkittles.java
index 22fdc4e..bc558fb 100644
--- a/src/skittles/sim/BatchSkittles.java
+++ b/src/skittles/sim/BatchSkittles.java
@@ -1,17 +1,17 @@
package skittles.sim;
import java.io.File;
/**
* Runs all the sims specific in the configs/ directory.
*/
public class BatchSkittles
{
public static void main( String[] args )
{
File dir = new File("configs/");
for (String s: dir.list()) {
- new Game(s).runGame();
+ new Game("configs/" + s).runGame();
}
}
}
| true | true | public static void main( String[] args )
{
File dir = new File("configs/");
for (String s: dir.list()) {
new Game(s).runGame();
}
}
| public static void main( String[] args )
{
File dir = new File("configs/");
for (String s: dir.list()) {
new Game("configs/" + s).runGame();
}
}
|
diff --git a/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java b/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java
index 8ecde780..1fe1044b 100644
--- a/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java
+++ b/52n-wps-server/src/main/java/org/n52/wps/server/request/InputHandler.java
@@ -1,1215 +1,1217 @@
/***************************************************************
This implementation provides a framework to publish processes to the
web through the OGC Web Processing Service interface. The framework
is extensible in terms of processes and data handlers. It is compliant
to the WPS version 0.4.0 (OGC 05-007r4).
Copyright (C) 2006 by con terra GmbH
Authors:
Theodor Foerster, ITC, Enschede, the Netherlands
Carsten Priess, Institute for geoinformatics, University of
Muenster, Germany
Timon Ter Braak, University of Twente, the Netherlands
Bastian Schaeffer, Institute for geoinformatics, University of Muenster, Germany
Matthias Mueller, TU Dresden
Contact: Albert Remke, con terra GmbH, Martin-Luther-King-Weg 24,
48155 Muenster, Germany, [email protected]
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program (see gnu-gpl v2.txt); if not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA or visit the web page of the Free
Software Foundation, http://www.fsf.org.
Created on: 13.06.2006
***************************************************************/
package org.n52.wps.server.request;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import net.opengis.ows.x11.DomainMetadataType;
import net.opengis.ows.x11.RangeType;
import net.opengis.ows.x11.ValueType;
import net.opengis.wps.x100.ComplexDataDescriptionType;
import net.opengis.wps.x100.ComplexDataType;
import net.opengis.wps.x100.InputDescriptionType;
import net.opengis.wps.x100.InputReferenceType;
import net.opengis.wps.x100.InputType;
import net.opengis.wps.x100.ProcessDescriptionType;
import org.apache.log4j.Logger;
import org.n52.wps.io.IOHandler;
import org.n52.wps.io.IParser;
import org.n52.wps.io.ParserFactory;
import org.n52.wps.io.data.IData;
import org.n52.wps.io.data.binding.bbox.GTReferenceEnvelope;
import org.n52.wps.io.data.binding.literal.LiteralByteBinding;
import org.n52.wps.io.data.binding.literal.LiteralDoubleBinding;
import org.n52.wps.io.data.binding.literal.LiteralFloatBinding;
import org.n52.wps.io.data.binding.literal.LiteralIntBinding;
import org.n52.wps.io.data.binding.literal.LiteralLongBinding;
import org.n52.wps.io.data.binding.literal.LiteralShortBinding;
import org.n52.wps.io.datahandler.parser.GML2BasicParser;
import org.n52.wps.io.datahandler.parser.GML3BasicParser;
import org.n52.wps.io.datahandler.parser.SimpleGMLParser;
import org.n52.wps.server.ExceptionReport;
import org.n52.wps.server.RepositoryManager;
import org.n52.wps.server.request.strategy.ReferenceStrategyRegister;
import org.n52.wps.util.BasicXMLTypeFactory;
import org.w3c.dom.Node;
/**
* Handles the input of the client and stores it into a Map.
*/
public class InputHandler {
private static Logger LOGGER = Logger.getLogger(InputHandler.class);
private Map<String, List<IData>> inputData = new HashMap<String, List<IData>>();
private ProcessDescriptionType processDesc;
private String algorithmIdentifier = null; // Needed to take care of handling a conflict between different parsers.
/**
* Initializes a parser that handles each (line of) input based on the type of input.
* @see #handleComplexData(IOValueType)
* @see #handleComplexValueReference(IOValueType)
* @see #handleLiteralData(IOValueType)
* @see #handleBBoxValue(IOValueType)
* @param inputs The client input
*/
public InputHandler(InputType[] inputs, String algorithmIdentifier) throws ExceptionReport{
this.algorithmIdentifier = algorithmIdentifier;
this.processDesc = RepositoryManager.getInstance().getProcessDescription(algorithmIdentifier);
if(processDesc==null){
throw new ExceptionReport("Error while accessing the process description for "+ algorithmIdentifier,
ExceptionReport.INVALID_PARAMETER_VALUE);
}
for(InputType input : inputs) {
String inputID = input.getIdentifier().getStringValue();
if(input.getData() != null) {
if(input.getData().getComplexData() != null) {
handleComplexData(input);
}
else if(input.getData().getLiteralData() != null) {
handleLiteralData(input);
}
else if(input.getData().getBoundingBoxData() != null) {
handleBBoxValue(input);
}
}
else if(input.getReference() != null) {
handleComplexValueReference(input);
}
else {
throw new ExceptionReport("Error while accessing the inputValue: " + inputID,
ExceptionReport.INVALID_PARAMETER_VALUE);
}
}
}
/**
* Handles the complexValue, which in this case should always include XML
* which can be parsed into a FeatureCollection.
* @param input The client input
* @throws ExceptionReport If error occured while parsing XML
*/
private void handleComplexData(InputType input) throws ExceptionReport{
String inputID = input.getIdentifier().getStringValue();
Node complexValueNode = input.getData().getComplexData().getDomNode();
String complexValue = "";
try {
complexValue = nodeToString(complexValueNode);
//remove complexvalue element. getFirstChild
complexValue = complexValue.substring(complexValue.indexOf(">")+1,complexValue.lastIndexOf("</"));
} catch (TransformerFactoryConfigurationError e1) {
throw new RuntimeException("Could not parse inline data. Reason " +e1);
} catch (TransformerException e1) {
throw new RuntimeException("Could not parse inline data. Reason " +e1);
}
InputDescriptionType inputReferenceDesc = null;
for(InputDescriptionType tempDesc : this.processDesc.getDataInputs().getInputArray()) {
if(inputID.equals(tempDesc.getIdentifier().getStringValue())) {
inputReferenceDesc = tempDesc;
break;
}
}
if(inputReferenceDesc == null) {
LOGGER.debug("input cannot be found in description for " + processDesc.getIdentifier().getStringValue() + "," + inputID);
}
//select parser
//1. mimeType set?
//yes--> set it
//1.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> schema or/and encoding are set?
//yes-->use it, look if only one mime type can be found
//not-->use default values
String schema = null;
String mimeType = null;
String encoding = null;
// overwrite with data format from request if appropriate
ComplexDataType data = input.getData().getComplexData();
if (data.isSetMimeType() && data.getMimeType() != null){
//mime type in request
mimeType = data.getMimeType();
ComplexDataDescriptionType format = null;
String defaultMimeType = inputReferenceDesc.getComplexData().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potentialFormat = inputReferenceDesc.getComplexData().getDefault().getFormat();
if(data.getSchema() != null && data.getEncoding() == null){
if(data.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
canUseDefault = true;
format = potentialFormat;
}
}
if(data.getSchema() == null && data.getEncoding() != null){
if(data.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(data.getSchema() != null && data.getEncoding() != null){
if(data.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && data.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(data.getSchema() == null && data.getEncoding() == null){
canUseDefault = true;
format = potentialFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats = inputReferenceDesc.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType potentialFormat : formats){
if(potentialFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(data.getSchema() != null && data.getEncoding() == null){
if(data.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
format = potentialFormat;
}
}
if(data.getSchema() == null && data.getEncoding() != null){
if(data.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(data.getSchema() != null && data.getEncoding() != null){
if(data.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && data.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(data.getSchema() == null && data.getEncoding() == null){
format = potentialFormat;
}
}
}
}
if(format == null){
throw new ExceptionReport("Could not determine intput format", ExceptionReport.INVALID_PARAMETER_VALUE);
}
mimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
encoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
schema = format.getSchema();
}
}else{
//mimeType not in request
if(mimeType==null && !data.isSetEncoding() && !data.isSetSchema()){
//nothing set, use default values
schema = inputReferenceDesc.getComplexData().getDefault().getFormat().getSchema();
mimeType = inputReferenceDesc.getComplexData().getDefault().getFormat().getMimeType();
encoding = inputReferenceDesc.getComplexData().getDefault().getFormat().getEncoding();
}else{
//do a smart search an look if a mimeType can be found for either schema and/or encoding
if(mimeType==null){
if(data.isSetEncoding() && !data.isSetSchema()){
//encoding set only
ComplexDataDescriptionType encodingFormat = null;
String defaultEncoding = inputReferenceDesc.getComplexData().getDefault().getFormat().getEncoding();
int found = 0;
String foundEncoding = null;
if(defaultEncoding.equalsIgnoreCase(data.getEncoding())){
foundEncoding = inputReferenceDesc.getComplexData().getDefault().getFormat().getEncoding();
encodingFormat = inputReferenceDesc.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputReferenceDesc.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(data.getEncoding())){
foundEncoding = tempFormat.getEncoding();
encodingFormat = tempFormat;
found = found +1;
}
}
}
if(found == 1){
encoding = foundEncoding;
mimeType = encodingFormat.getMimeType();
if(encodingFormat.isSetSchema()){
schema = encodingFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(data.isSetSchema() && !data.isSetEncoding()){
//schema set only
ComplexDataDescriptionType schemaFormat = null;
String defaultSchema = inputReferenceDesc.getComplexData().getDefault().getFormat().getSchema();
int found = 0;
String foundSchema = null;
//TODO: please review change
//Old version causes NullPointerException if default input is given by mimetype and not by schema:
/*
if(defaultSchema != null && defaultSchema.equalsIgnoreCase(data.getSchema())){
...
}
* */
if(defaultSchema != null && defaultSchema.equalsIgnoreCase(data.getSchema())){
foundSchema = inputReferenceDesc.getComplexData().getDefault().getFormat().getSchema();
schemaFormat = inputReferenceDesc.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputReferenceDesc.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
//TODO: please review change
//Old if-clause wouldn't be true ever and causes NullPointerException if one of the supported types is given by mimetype and not by schema:
/*
if(tempFormat.getEncoding().equalsIgnoreCase(data.getSchema())){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
*/
if(tempFormat.isSetSchema() && tempFormat.getSchema().equalsIgnoreCase(data.getSchema())){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
}
}
if(found == 1){
schema = foundSchema;
mimeType = schemaFormat.getMimeType();
if(schemaFormat.isSetEncoding()){
encoding = schemaFormat.getEncoding();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(data.isSetEncoding() && data.isSetSchema()){
//schema and encoding set
//encoding
String defaultEncoding = inputReferenceDesc.getComplexData().getDefault().getFormat().getEncoding();
List<ComplexDataDescriptionType> foundEncodingList = new ArrayList<ComplexDataDescriptionType>();
if(defaultEncoding.equalsIgnoreCase(data.getEncoding())){
foundEncodingList.add(inputReferenceDesc.getComplexData().getDefault().getFormat());
}else{
ComplexDataDescriptionType[] formats = inputReferenceDesc.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(data.getEncoding())){
foundEncodingList.add(tempFormat);
}
}
//schema
List<ComplexDataDescriptionType> foundSchemaList = new ArrayList<ComplexDataDescriptionType>();
String defaultSchema = inputReferenceDesc.getComplexData().getDefault().getFormat().getSchema();
//TODO: please review change
//Old version causes NullPointerException if default input is given by mimetype and not by schema:
//
//if(defaultSchema.equalsIgnoreCase(data.getSchema())){...
//
if(defaultSchema!= null && defaultSchema.equalsIgnoreCase(data.getSchema())){
foundSchemaList.add(inputReferenceDesc.getComplexData().getDefault().getFormat());
}else{
formats = inputReferenceDesc.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
/*
* TODO please review Change
* Old if-clause wouldn't be true ever and causes NullPointerException if one of the supported types is given by mimetype and not by schema:
*
* old code:
if(tempFormat.getEncoding().equalsIgnoreCase(data.getSchema())){
foundSchemaList.add(tempFormat);
}
*/
if(tempFormat.getSchema()!=null && tempFormat.getSchema().equalsIgnoreCase(data.getSchema())){
foundSchemaList.add(tempFormat);
}
}
}
//results
ComplexDataDescriptionType foundCommonFormat = null;
for(ComplexDataDescriptionType encodingFormat : foundEncodingList){
for(ComplexDataDescriptionType schemaFormat : foundSchemaList){
if(encodingFormat.equals(schemaFormat)){
foundCommonFormat = encodingFormat;
}
}
}
if(foundCommonFormat!=null){
mimeType = foundCommonFormat.getMimeType();
if(foundCommonFormat.isSetEncoding()){
encoding = foundCommonFormat.getEncoding();
}
if(foundCommonFormat.isSetSchema()){
schema = foundCommonFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
}
}
}
}
IParser parser = null;
try {
Class algorithmInput = RepositoryManager.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputID);
LOGGER.debug("Looking for matching Parser ..." +
" schema: " + schema +
" mimeType: " + mimeType +
" encoding: " + encoding);
parser = ParserFactory.getInstance().getParser(schema, mimeType, encoding, algorithmInput);
} catch (RuntimeException e) {
throw new ExceptionReport("Error obtaining input data", ExceptionReport.NO_APPLICABLE_CODE, e);
}
if(parser == null) {
throw new ExceptionReport("Error. No applicable parser found for " + schema + "," + mimeType + "," + encoding, ExceptionReport.NO_APPLICABLE_CODE);
}
IData collection = null;
// encoding is UTF-8 (or nothing and we default to UTF-8)
// everything that goes to this condition should be inline xml data
if (encoding == null || encoding.equals("") || encoding.equalsIgnoreCase(IOHandler.DEFAULT_ENCODING)){
try {
boolean xsiisIn = complexValue.contains("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
if(!xsiisIn){
complexValue = complexValue.replace("xsi:schemaLocation", "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation");
}
InputStream stream = new ByteArrayInputStream(complexValue.getBytes());
collection = parser.parse(stream, mimeType, schema);
}
catch(RuntimeException e) {
throw new ExceptionReport("Error occured, while XML parsing",
ExceptionReport.NO_APPLICABLE_CODE, e);
}
}
// in case encoding is base64
// everything that goes to this condition should be inline base64 data
else if (encoding.equalsIgnoreCase(IOHandler.ENCODING_BASE64)){
File f = null;
FileOutputStream fos = null;
try {
f = File.createTempFile("wps" + UUID.randomUUID(), "tmp");
fos = new FileOutputStream(f);
if(complexValue.startsWith("<xml-fragment")){
int startIndex = complexValue.indexOf(">");
complexValue = complexValue.substring(startIndex+1);
int endIndex = complexValue.indexOf("</xml-fragment");
complexValue = complexValue.substring(0,endIndex);
}
StringReader sr = new StringReader(complexValue);
int i = sr.read();
while(i != -1){
fos.write(i);
i = sr.read();
}
fos.close();
collection = parser.parseBase64(new FileInputStream(f), mimeType, schema);
System.gc();
f.delete();
} catch (IOException e) {
throw new ExceptionReport("Error occured, while Base64 extracting",
ExceptionReport.NO_APPLICABLE_CODE, e);
} finally {
try {
if (fos != null){
fos.close();
}
if (f != null){
f.delete();
}
} catch (Exception e) {
throw new ExceptionReport("Unable to generate tempfile", ExceptionReport.NO_APPLICABLE_CODE);
}
}
}
else {
throw new ExceptionReport("Unable to generate encoding " + encoding, ExceptionReport.NO_APPLICABLE_CODE);
}
//enable maxxoccurs of parameters with the same name.
if(inputData.containsKey(inputID)) {
List<IData> list = inputData.get(inputID);
list.add(collection);
}
else {
List<IData> list = new ArrayList<IData>();
list.add(collection);
inputData.put(inputID, list);
}
}
/**
* Handles the literalData
* @param input The client's input
* @throws ExceptionReport If the type of the parameter is invalid.
*/
private void handleLiteralData(InputType input) throws ExceptionReport {
String inputID = input.getIdentifier().getStringValue();
String parameter = input.getData().getLiteralData().getStringValue();
String xmlDataType = input.getData().getLiteralData().getDataType();
InputDescriptionType inputDesc = null;
for(InputDescriptionType tempDesc : this.processDesc.getDataInputs().getInputArray()) {
if(inputID.equals(tempDesc.getIdentifier().getStringValue())) {
inputDesc = tempDesc;
break;
}
}
if(xmlDataType == null) {
DomainMetadataType dataType = inputDesc.getLiteralData().getDataType();
xmlDataType = dataType != null ? dataType.getReference() : null;
}
//still null, assume string as default
if(xmlDataType == null) {
xmlDataType = BasicXMLTypeFactory.STRING_URI;
}
if(xmlDataType.contains("http://www.w3.org/TR/xmlschema-2#")){
xmlDataType = xmlDataType.replace("http://www.w3.org/TR/xmlschema-2#","xs:");
}
xmlDataType = xmlDataType.toLowerCase();
IData parameterObj = null;
try {
parameterObj = BasicXMLTypeFactory.getBasicJavaObject(xmlDataType, parameter);
}
catch(RuntimeException e) {
throw new ExceptionReport("The passed parameterValue: " + parameter + ", but should be of type: " + xmlDataType, ExceptionReport.INVALID_PARAMETER_VALUE);
}
//validate allowed values.
if(inputDesc.getLiteralData().isSetAllowedValues()){
if((!inputDesc.getLiteralData().isSetAnyValue())){
ValueType[] allowedValues = inputDesc.getLiteralData().getAllowedValues().getValueArray();
boolean foundAllowedValue = false;
for(ValueType allowedValue : allowedValues){
if(input.getData().getLiteralData().getStringValue().equals(allowedValue.getStringValue())){
foundAllowedValue = true;
}
}
RangeType[] allowedRanges = {};
if(parameterObj instanceof LiteralIntBinding || parameterObj instanceof LiteralDoubleBinding || parameterObj instanceof LiteralShortBinding || parameterObj instanceof LiteralFloatBinding || parameterObj instanceof LiteralLongBinding || parameterObj instanceof LiteralByteBinding){
allowedRanges = inputDesc.getLiteralData().getAllowedValues().getRangeArray();
for(RangeType allowedRange : allowedRanges){
foundAllowedValue = checkRange(parameterObj, allowedRange);
}
}
if(!foundAllowedValue && (allowedValues.length!=0 || allowedRanges.length!=0)){
throw new ExceptionReport("Input with ID " + inputID + " does not contain an allowed value. See ProcessDescription.", ExceptionReport.INVALID_PARAMETER_VALUE);
}
}
}
if(parameterObj == null) {
throw new ExceptionReport("XML datatype as LiteralParameter is not supported by the server: dataType " + xmlDataType,
ExceptionReport.INVALID_PARAMETER_VALUE);
}
//enable maxxoccurs of parameters with the same name.
if(inputData.containsKey(inputID)) {
List<IData> list = inputData.get(inputID);
list.add(parameterObj);
}
else {
List<IData> list = new ArrayList<IData>();
list.add(parameterObj);
inputData.put(inputID, list);
}
}
private boolean checkRange(IData parameterObj, RangeType allowedRange){
List<?> l = allowedRange.getRangeClosure();
/*
* no closure info or RangeClosure is "closed", so include boundaries
*/
if(l == null || l.isEmpty() || l.get(0).equals("closed")){
if((parameterObj instanceof LiteralIntBinding)){
int min = new Integer(allowedRange.getMinimumValue().getStringValue());
int max = new Integer(allowedRange.getMaximumValue().getStringValue());
if((Integer)(parameterObj.getPayload())>=min && (Integer)parameterObj.getPayload()<=max){
return true;
}
}
if((parameterObj instanceof LiteralDoubleBinding)){
Double min = new Double(allowedRange.getMinimumValue().getStringValue());
Double max = new Double(allowedRange.getMaximumValue().getStringValue());
if((Double)(parameterObj.getPayload())>=min && (Double)parameterObj.getPayload()<=max){
return true;
}
}
if((parameterObj instanceof LiteralShortBinding)){
Short min = new Short(allowedRange.getMinimumValue().getStringValue());
Short max = new Short(allowedRange.getMaximumValue().getStringValue());
if((Short)(parameterObj.getPayload())>=min && (Short)parameterObj.getPayload()<=max){
return true;
}
}
if((parameterObj instanceof LiteralFloatBinding)){
Float min = new Float(allowedRange.getMinimumValue().getStringValue());
Float max = new Float(allowedRange.getMaximumValue().getStringValue());
if((Float)(parameterObj.getPayload())>=min && (Float)parameterObj.getPayload()<=max){
return true;
}
}
if((parameterObj instanceof LiteralLongBinding)){
Long min = new Long(allowedRange.getMinimumValue().getStringValue());
Long max = new Long(allowedRange.getMaximumValue().getStringValue());
if((Long)(parameterObj.getPayload())>=min && (Long)parameterObj.getPayload()<=max){
return true;
}
}
if((parameterObj instanceof LiteralByteBinding)){
Byte min = new Byte(allowedRange.getMinimumValue().getStringValue());
Byte max = new Byte(allowedRange.getMaximumValue().getStringValue());
if((Byte)(parameterObj.getPayload())>=min && (Byte)parameterObj.getPayload()<=max){
return true;
}
}
return false;
}
/*
* TODO:implement other closure cases
*/
return false;
}
/**
* Handles the ComplexValueReference
* @param input The client input
* @throws ExceptionReport If the input (as url) is invalid, or there is an error while parsing the XML.
*/
private void handleComplexValueReference(InputType input) throws ExceptionReport{
String inputID = input.getIdentifier().getStringValue();
ReferenceStrategyRegister register = ReferenceStrategyRegister.getInstance();
InputStream stream = register.resolveReference(input);
String dataURLString = input.getReference().getHref();
//dataURLString = URLDecoder.decode(dataURLString);
//dataURLString = dataURLString.replace("&", "");
LOGGER.debug("Loading data from: " + dataURLString);
/**
* initialize data format with default values defaults and overwrite with defaults from request if applicable
*/
InputDescriptionType inputPD = null;
for(InputDescriptionType tempDesc : this.processDesc.getDataInputs().getInputArray()) {
if(inputID.equals(tempDesc.getIdentifier().getStringValue())) {
inputPD = tempDesc;
break;
}
}
if(inputPD == null) { // check if there is a corresponding input identifier in the process description
LOGGER.debug("Input cannot be found in description for " + this.processDesc.getIdentifier().getStringValue() + "," + inputID);
throw new RuntimeException("Input cannot be found in description for " + this.processDesc.getIdentifier().getStringValue() + "," + inputID);
}
//select parser
//1. mimeType set?
//yes--> set it
//1.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> look in http stream
//2. mimeType set in http stream
//yes -->set it
//2.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> schema or/and encoding are set?
//yes-->use it, look if only one mime type can be found
//not-->use default values
String schema = null;
String mimeType = null;
String encoding = null;
// overwrite with data format from request if appropriate
InputReferenceType referenceData = input.getReference();
if (referenceData.isSetMimeType() && referenceData.getMimeType() != null){
//mime type in request
mimeType = referenceData.getMimeType();
ComplexDataDescriptionType format = null;
String defaultMimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potentialFormat = inputPD.getComplexData().getDefault().getFormat();
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
canUseDefault = true;
format = potentialFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType potentialFormat : formats){
if(potentialFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
format = potentialFormat;
}
}
}
}
if(format == null){
throw new ExceptionReport("Possibly multiple or none matching generators found for the input data with id = \"" + inputPD.getIdentifier().getStringValue() + "\". Is the MimeType (\"" + referenceData.getMimeType() + "\") correctly set?", ExceptionReport.INVALID_PARAMETER_VALUE);
//throw new ExceptionReport("Could not determine format of the input data (id= \"" + inputPD.getIdentifier().getStringValue() + "\"), given the mimetype \"" + referenceData.getMimeType() + "\"", ExceptionReport.INVALID_PARAMETER_VALUE);
}
mimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
encoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
schema = format.getSchema();
}
}else{
//mimeType not in request
//try to fetch mimetype from http stream
URL url;
try {
url = new URL(dataURLString);
URLConnection urlConnection = url.openConnection();
mimeType = urlConnection.getContentType();
if(mimeType.contains("GML2")){
mimeType = "text/xml; subtype=gml/2.0.0";
}
if(mimeType.contains("GML3")){
mimeType = "text/xml; subtype=gml/3.0.0";
}
ComplexDataDescriptionType format = null;
if(mimeType!=null){
String defaultMimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potentialFormat = inputPD.getComplexData().getDefault().getFormat();
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
canUseDefault = true;
format = potentialFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType potentialFormat : formats){
if(potentialFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
format = potentialFormat;
}
}
}
}
if(format == null){
//throw new ExceptionReport("Could not determine intput format. Possibly multiple or none matching generators found. MimeType Set?", ExceptionReport.INVALID_PARAMETER_VALUE);
// TODO Review error message
throw new ExceptionReport("Could not determine output format because none of the supported formats match the given schema (\"" + referenceData.getSchema() + "\") and encoding (\"" + referenceData.getEncoding() + "\"). (A mimetype was not specified)", ExceptionReport.INVALID_PARAMETER_VALUE);
}
mimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
encoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
schema = format.getSchema();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
LOGGER.debug("Could not determine MimeType from Input URL: " + dataURLString);
} catch (IOException e) {
e.printStackTrace();
LOGGER.debug("Could not determine MimeType from Input URL: " + dataURLString);
}
if(mimeType==null && !referenceData.isSetEncoding() && !referenceData.isSetSchema()){
//nothing set, use default values
schema = inputPD.getComplexData().getDefault().getFormat().getSchema();
mimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
encoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
}else{
//do a smart search an look if a mimeType can be found for either schema and/or encoding
if(mimeType==null){
if(referenceData.isSetEncoding() && !referenceData.isSetSchema()){
//encoding set only
ComplexDataDescriptionType encodingFormat = null;
String defaultEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
int found = 0;
String foundEncoding = null;
if(defaultEncoding.equalsIgnoreCase(referenceData.getEncoding())){
foundEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
encodingFormat = inputPD.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getEncoding())){
foundEncoding = tempFormat.getEncoding();
encodingFormat = tempFormat;
found = found +1;
}
}
}
if(found == 1){
encoding = foundEncoding;
mimeType = encodingFormat.getMimeType();
if(encodingFormat.isSetSchema()){
schema = encodingFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(referenceData.isSetSchema() && !referenceData.isSetEncoding()){
//schema set only
ComplexDataDescriptionType schemaFormat = null;
String defaultSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
int found = 0;
String foundSchema = null;
if(defaultSchema.equalsIgnoreCase(referenceData.getSchema())){
foundSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
schemaFormat = inputPD.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getSchema())){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
}
}
if(found == 1){
schema = foundSchema;
mimeType = schemaFormat.getMimeType();
if(schemaFormat.isSetEncoding()){
encoding = schemaFormat.getEncoding();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(referenceData.isSetEncoding() && referenceData.isSetSchema()){
//schema and encoding set
//encoding
String defaultEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
List<ComplexDataDescriptionType> foundEncodingList = new ArrayList<ComplexDataDescriptionType>();
if(defaultEncoding.equalsIgnoreCase(referenceData.getEncoding())){
foundEncodingList.add(inputPD.getComplexData().getDefault().getFormat());
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getEncoding())){
foundEncodingList.add(tempFormat);
}
}
//schema
List<ComplexDataDescriptionType> foundSchemaList = new ArrayList<ComplexDataDescriptionType>();
String defaultSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
if(defaultSchema.equalsIgnoreCase(referenceData.getSchema())){
foundSchemaList.add(inputPD.getComplexData().getDefault().getFormat());
}else{
formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getSchema())){
foundSchemaList.add(tempFormat);
}
}
}
//results
ComplexDataDescriptionType foundCommonFormat = null;
for(ComplexDataDescriptionType encodingFormat : foundEncodingList){
for(ComplexDataDescriptionType schemaFormat : foundSchemaList){
if(encodingFormat.equals(schemaFormat)){
foundCommonFormat = encodingFormat;
}
}
}
if(foundCommonFormat!=null){
mimeType = foundCommonFormat.getMimeType();
if(foundCommonFormat.isSetEncoding()){
encoding = foundCommonFormat.getEncoding();
}
if(foundCommonFormat.isSetSchema()){
schema = foundCommonFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
}
}
}
}
- LOGGER.debug("Loading parser for: "+ schema + "," + mimeType + "," + encoding);
+ LOGGER.debug("Loading parser for: schema = \""+ schema
+ + "\" , mimetype = \"" + mimeType
+ + "\", encoding = \"" + encoding + "\"");
IParser parser = null;
try {
Class algorithmInputClass = RepositoryManager.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputID);
if(algorithmInputClass == null) {
throw new RuntimeException("Could not determine internal input class for input" + inputID);
}
LOGGER.info("Looking for matching Parser ..." +
" schema: \"" + schema +
"\", mimeType: \"" + mimeType +
"\", encoding: \"" + encoding + "\"");
parser = ParserFactory.getInstance().getParser(schema, mimeType, encoding, algorithmInputClass);
if(parser == null) {
//throw new ExceptionReport("Error. No applicable parser found for " + schema + "," + mimeType + "," + encoding, ExceptionReport.NO_APPLICABLE_CODE);
throw new ExceptionReport("Error. No applicable parser found for schema=\"" + schema + "\", mimeType=\"" + mimeType + "\", encoding=\"" + encoding + "\"", ExceptionReport.NO_APPLICABLE_CODE);
}
} catch (RuntimeException e) {
throw new ExceptionReport("Error obtaining input data", ExceptionReport.NO_APPLICABLE_CODE, e);
}
/****PROXY*****/
/*String decodedURL = URLDecoder.decode(dataURLString);
decodedURL = decodedURL.replace("&", "&");
if(decodedURL.indexOf("&BBOX")==-1){
decodedURL = decodedURL.replace("BBOX", "&BBOX");
decodedURL = decodedURL.replace("outputFormat", "&outputFormat");
decodedURL = decodedURL.replace("SRS", "&SRS");
decodedURL = decodedURL.replace("REQUEST", "&REQUEST");
decodedURL = decodedURL.replace("VERSION", "&VERSION");
decodedURL = decodedURL.replace("SERVICE", "&SERVICE");
decodedURL = decodedURL.replace("format", "&format");
}*/
//lookup WFS
if(dataURLString.toUpperCase().contains("REQUEST=GETFEATURE") &&
dataURLString.toUpperCase().contains("SERVICE=WFS")){
if(parser instanceof SimpleGMLParser){
parser = new GML2BasicParser();
}
if(parser instanceof GML2BasicParser && !dataURLString.toUpperCase().contains("OUTPUTFORMAT=GML2")){
//make sure we get GML2
dataURLString = dataURLString+"&outputFormat=GML2";
}
if(parser instanceof GML3BasicParser && !dataURLString.toUpperCase().contains("OUTPUTFORMAT=GML3")){
//make sure we get GML3
dataURLString = dataURLString+"&outputFormat=GML3";
}
}
IData parsedInputData = parser.parse(stream, mimeType, schema);
//enable maxxoccurs of parameters with the same name.
if(inputData.containsKey(inputID)) {
List<IData> list = inputData.get(inputID);
list.add(parsedInputData);
inputData.put(inputID, list);
}
else {
List<IData> list = new ArrayList<IData>();
list.add(parsedInputData);
inputData.put(inputID, list);
}
}
/**
* Handles BBoxValue
* @param input The client input
*/
private void handleBBoxValue(InputType input) throws ExceptionReport{
String crs = input.getData().getBoundingBoxData().getCrs();
List lowerCorner = input.getData().getBoundingBoxData().getLowerCorner();
List upperCorner = input.getData().getBoundingBoxData().getUpperCorner();
if(lowerCorner.size()!=2 || upperCorner.size()!=2){
throw new ExceptionReport("Error while parsing the BBOX data", ExceptionReport.INVALID_PARAMETER_VALUE);
}
IData envelope = new GTReferenceEnvelope(lowerCorner.get(0),lowerCorner.get(1),upperCorner.get(0), upperCorner.get(1), crs);
List<IData> resultList = new ArrayList<IData>();
resultList.add(envelope);
inputData.put(input.getIdentifier().getStringValue(), resultList);
}
/**
* Gets the resulting InputLayers from the parser
* @return A map with the parsed input
*/
public Map<String, List<IData>> getParsedInputData(){
return inputData;
}
// private InputStream retrievingZippedContent(URLConnection conn) throws IOException{
// String contentType = conn.getContentEncoding();
// if(contentType != null && contentType.equals("gzip")) {
// return new GZIPInputStream(conn.getInputStream());
// }
// else{
// return conn.getInputStream();
// }
// }
private String nodeToString(Node node) throws TransformerFactoryConfigurationError, TransformerException {
StringWriter stringWriter = new StringWriter();
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.transform(new DOMSource(node), new StreamResult(stringWriter));
return stringWriter.toString();
}
}
| true | true | private void handleComplexValueReference(InputType input) throws ExceptionReport{
String inputID = input.getIdentifier().getStringValue();
ReferenceStrategyRegister register = ReferenceStrategyRegister.getInstance();
InputStream stream = register.resolveReference(input);
String dataURLString = input.getReference().getHref();
//dataURLString = URLDecoder.decode(dataURLString);
//dataURLString = dataURLString.replace("&", "");
LOGGER.debug("Loading data from: " + dataURLString);
/**
* initialize data format with default values defaults and overwrite with defaults from request if applicable
*/
InputDescriptionType inputPD = null;
for(InputDescriptionType tempDesc : this.processDesc.getDataInputs().getInputArray()) {
if(inputID.equals(tempDesc.getIdentifier().getStringValue())) {
inputPD = tempDesc;
break;
}
}
if(inputPD == null) { // check if there is a corresponding input identifier in the process description
LOGGER.debug("Input cannot be found in description for " + this.processDesc.getIdentifier().getStringValue() + "," + inputID);
throw new RuntimeException("Input cannot be found in description for " + this.processDesc.getIdentifier().getStringValue() + "," + inputID);
}
//select parser
//1. mimeType set?
//yes--> set it
//1.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> look in http stream
//2. mimeType set in http stream
//yes -->set it
//2.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> schema or/and encoding are set?
//yes-->use it, look if only one mime type can be found
//not-->use default values
String schema = null;
String mimeType = null;
String encoding = null;
// overwrite with data format from request if appropriate
InputReferenceType referenceData = input.getReference();
if (referenceData.isSetMimeType() && referenceData.getMimeType() != null){
//mime type in request
mimeType = referenceData.getMimeType();
ComplexDataDescriptionType format = null;
String defaultMimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potentialFormat = inputPD.getComplexData().getDefault().getFormat();
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
canUseDefault = true;
format = potentialFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType potentialFormat : formats){
if(potentialFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
format = potentialFormat;
}
}
}
}
if(format == null){
throw new ExceptionReport("Possibly multiple or none matching generators found for the input data with id = \"" + inputPD.getIdentifier().getStringValue() + "\". Is the MimeType (\"" + referenceData.getMimeType() + "\") correctly set?", ExceptionReport.INVALID_PARAMETER_VALUE);
//throw new ExceptionReport("Could not determine format of the input data (id= \"" + inputPD.getIdentifier().getStringValue() + "\"), given the mimetype \"" + referenceData.getMimeType() + "\"", ExceptionReport.INVALID_PARAMETER_VALUE);
}
mimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
encoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
schema = format.getSchema();
}
}else{
//mimeType not in request
//try to fetch mimetype from http stream
URL url;
try {
url = new URL(dataURLString);
URLConnection urlConnection = url.openConnection();
mimeType = urlConnection.getContentType();
if(mimeType.contains("GML2")){
mimeType = "text/xml; subtype=gml/2.0.0";
}
if(mimeType.contains("GML3")){
mimeType = "text/xml; subtype=gml/3.0.0";
}
ComplexDataDescriptionType format = null;
if(mimeType!=null){
String defaultMimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potentialFormat = inputPD.getComplexData().getDefault().getFormat();
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
canUseDefault = true;
format = potentialFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType potentialFormat : formats){
if(potentialFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
format = potentialFormat;
}
}
}
}
if(format == null){
//throw new ExceptionReport("Could not determine intput format. Possibly multiple or none matching generators found. MimeType Set?", ExceptionReport.INVALID_PARAMETER_VALUE);
// TODO Review error message
throw new ExceptionReport("Could not determine output format because none of the supported formats match the given schema (\"" + referenceData.getSchema() + "\") and encoding (\"" + referenceData.getEncoding() + "\"). (A mimetype was not specified)", ExceptionReport.INVALID_PARAMETER_VALUE);
}
mimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
encoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
schema = format.getSchema();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
LOGGER.debug("Could not determine MimeType from Input URL: " + dataURLString);
} catch (IOException e) {
e.printStackTrace();
LOGGER.debug("Could not determine MimeType from Input URL: " + dataURLString);
}
if(mimeType==null && !referenceData.isSetEncoding() && !referenceData.isSetSchema()){
//nothing set, use default values
schema = inputPD.getComplexData().getDefault().getFormat().getSchema();
mimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
encoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
}else{
//do a smart search an look if a mimeType can be found for either schema and/or encoding
if(mimeType==null){
if(referenceData.isSetEncoding() && !referenceData.isSetSchema()){
//encoding set only
ComplexDataDescriptionType encodingFormat = null;
String defaultEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
int found = 0;
String foundEncoding = null;
if(defaultEncoding.equalsIgnoreCase(referenceData.getEncoding())){
foundEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
encodingFormat = inputPD.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getEncoding())){
foundEncoding = tempFormat.getEncoding();
encodingFormat = tempFormat;
found = found +1;
}
}
}
if(found == 1){
encoding = foundEncoding;
mimeType = encodingFormat.getMimeType();
if(encodingFormat.isSetSchema()){
schema = encodingFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(referenceData.isSetSchema() && !referenceData.isSetEncoding()){
//schema set only
ComplexDataDescriptionType schemaFormat = null;
String defaultSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
int found = 0;
String foundSchema = null;
if(defaultSchema.equalsIgnoreCase(referenceData.getSchema())){
foundSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
schemaFormat = inputPD.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getSchema())){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
}
}
if(found == 1){
schema = foundSchema;
mimeType = schemaFormat.getMimeType();
if(schemaFormat.isSetEncoding()){
encoding = schemaFormat.getEncoding();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(referenceData.isSetEncoding() && referenceData.isSetSchema()){
//schema and encoding set
//encoding
String defaultEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
List<ComplexDataDescriptionType> foundEncodingList = new ArrayList<ComplexDataDescriptionType>();
if(defaultEncoding.equalsIgnoreCase(referenceData.getEncoding())){
foundEncodingList.add(inputPD.getComplexData().getDefault().getFormat());
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getEncoding())){
foundEncodingList.add(tempFormat);
}
}
//schema
List<ComplexDataDescriptionType> foundSchemaList = new ArrayList<ComplexDataDescriptionType>();
String defaultSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
if(defaultSchema.equalsIgnoreCase(referenceData.getSchema())){
foundSchemaList.add(inputPD.getComplexData().getDefault().getFormat());
}else{
formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getSchema())){
foundSchemaList.add(tempFormat);
}
}
}
//results
ComplexDataDescriptionType foundCommonFormat = null;
for(ComplexDataDescriptionType encodingFormat : foundEncodingList){
for(ComplexDataDescriptionType schemaFormat : foundSchemaList){
if(encodingFormat.equals(schemaFormat)){
foundCommonFormat = encodingFormat;
}
}
}
if(foundCommonFormat!=null){
mimeType = foundCommonFormat.getMimeType();
if(foundCommonFormat.isSetEncoding()){
encoding = foundCommonFormat.getEncoding();
}
if(foundCommonFormat.isSetSchema()){
schema = foundCommonFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
}
}
}
}
LOGGER.debug("Loading parser for: "+ schema + "," + mimeType + "," + encoding);
IParser parser = null;
try {
Class algorithmInputClass = RepositoryManager.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputID);
if(algorithmInputClass == null) {
throw new RuntimeException("Could not determine internal input class for input" + inputID);
}
LOGGER.info("Looking for matching Parser ..." +
" schema: \"" + schema +
"\", mimeType: \"" + mimeType +
"\", encoding: \"" + encoding + "\"");
parser = ParserFactory.getInstance().getParser(schema, mimeType, encoding, algorithmInputClass);
if(parser == null) {
//throw new ExceptionReport("Error. No applicable parser found for " + schema + "," + mimeType + "," + encoding, ExceptionReport.NO_APPLICABLE_CODE);
throw new ExceptionReport("Error. No applicable parser found for schema=\"" + schema + "\", mimeType=\"" + mimeType + "\", encoding=\"" + encoding + "\"", ExceptionReport.NO_APPLICABLE_CODE);
}
} catch (RuntimeException e) {
throw new ExceptionReport("Error obtaining input data", ExceptionReport.NO_APPLICABLE_CODE, e);
}
/****PROXY*****/
/*String decodedURL = URLDecoder.decode(dataURLString);
decodedURL = decodedURL.replace("&", "&");
if(decodedURL.indexOf("&BBOX")==-1){
decodedURL = decodedURL.replace("BBOX", "&BBOX");
decodedURL = decodedURL.replace("outputFormat", "&outputFormat");
decodedURL = decodedURL.replace("SRS", "&SRS");
decodedURL = decodedURL.replace("REQUEST", "&REQUEST");
decodedURL = decodedURL.replace("VERSION", "&VERSION");
decodedURL = decodedURL.replace("SERVICE", "&SERVICE");
decodedURL = decodedURL.replace("format", "&format");
}*/
//lookup WFS
if(dataURLString.toUpperCase().contains("REQUEST=GETFEATURE") &&
dataURLString.toUpperCase().contains("SERVICE=WFS")){
if(parser instanceof SimpleGMLParser){
parser = new GML2BasicParser();
}
if(parser instanceof GML2BasicParser && !dataURLString.toUpperCase().contains("OUTPUTFORMAT=GML2")){
//make sure we get GML2
dataURLString = dataURLString+"&outputFormat=GML2";
}
if(parser instanceof GML3BasicParser && !dataURLString.toUpperCase().contains("OUTPUTFORMAT=GML3")){
//make sure we get GML3
dataURLString = dataURLString+"&outputFormat=GML3";
}
}
IData parsedInputData = parser.parse(stream, mimeType, schema);
//enable maxxoccurs of parameters with the same name.
if(inputData.containsKey(inputID)) {
List<IData> list = inputData.get(inputID);
list.add(parsedInputData);
inputData.put(inputID, list);
}
else {
List<IData> list = new ArrayList<IData>();
list.add(parsedInputData);
inputData.put(inputID, list);
}
}
| private void handleComplexValueReference(InputType input) throws ExceptionReport{
String inputID = input.getIdentifier().getStringValue();
ReferenceStrategyRegister register = ReferenceStrategyRegister.getInstance();
InputStream stream = register.resolveReference(input);
String dataURLString = input.getReference().getHref();
//dataURLString = URLDecoder.decode(dataURLString);
//dataURLString = dataURLString.replace("&", "");
LOGGER.debug("Loading data from: " + dataURLString);
/**
* initialize data format with default values defaults and overwrite with defaults from request if applicable
*/
InputDescriptionType inputPD = null;
for(InputDescriptionType tempDesc : this.processDesc.getDataInputs().getInputArray()) {
if(inputID.equals(tempDesc.getIdentifier().getStringValue())) {
inputPD = tempDesc;
break;
}
}
if(inputPD == null) { // check if there is a corresponding input identifier in the process description
LOGGER.debug("Input cannot be found in description for " + this.processDesc.getIdentifier().getStringValue() + "," + inputID);
throw new RuntimeException("Input cannot be found in description for " + this.processDesc.getIdentifier().getStringValue() + "," + inputID);
}
//select parser
//1. mimeType set?
//yes--> set it
//1.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> look in http stream
//2. mimeType set in http stream
//yes -->set it
//2.1 schema/encoding set?
//yes-->set it
//not-->set default values for parser with matching mime type
//no--> schema or/and encoding are set?
//yes-->use it, look if only one mime type can be found
//not-->use default values
String schema = null;
String mimeType = null;
String encoding = null;
// overwrite with data format from request if appropriate
InputReferenceType referenceData = input.getReference();
if (referenceData.isSetMimeType() && referenceData.getMimeType() != null){
//mime type in request
mimeType = referenceData.getMimeType();
ComplexDataDescriptionType format = null;
String defaultMimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potentialFormat = inputPD.getComplexData().getDefault().getFormat();
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
canUseDefault = true;
format = potentialFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType potentialFormat : formats){
if(potentialFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
format = potentialFormat;
}
}
}
}
if(format == null){
throw new ExceptionReport("Possibly multiple or none matching generators found for the input data with id = \"" + inputPD.getIdentifier().getStringValue() + "\". Is the MimeType (\"" + referenceData.getMimeType() + "\") correctly set?", ExceptionReport.INVALID_PARAMETER_VALUE);
//throw new ExceptionReport("Could not determine format of the input data (id= \"" + inputPD.getIdentifier().getStringValue() + "\"), given the mimetype \"" + referenceData.getMimeType() + "\"", ExceptionReport.INVALID_PARAMETER_VALUE);
}
mimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
encoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
schema = format.getSchema();
}
}else{
//mimeType not in request
//try to fetch mimetype from http stream
URL url;
try {
url = new URL(dataURLString);
URLConnection urlConnection = url.openConnection();
mimeType = urlConnection.getContentType();
if(mimeType.contains("GML2")){
mimeType = "text/xml; subtype=gml/2.0.0";
}
if(mimeType.contains("GML3")){
mimeType = "text/xml; subtype=gml/3.0.0";
}
ComplexDataDescriptionType format = null;
if(mimeType!=null){
String defaultMimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
boolean canUseDefault = false;
if(defaultMimeType.equalsIgnoreCase(mimeType)){
ComplexDataDescriptionType potentialFormat = inputPD.getComplexData().getDefault().getFormat();
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
canUseDefault = true;
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
canUseDefault = true;
format = potentialFormat;
}
}
if(!canUseDefault){
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType potentialFormat : formats){
if(potentialFormat.getMimeType().equalsIgnoreCase(mimeType)){
if(referenceData.getSchema() != null && referenceData.getEncoding() == null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() != null){
if(referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() != null && referenceData.getEncoding() != null){
if(referenceData.getSchema().equalsIgnoreCase(potentialFormat.getSchema()) && referenceData.getEncoding().equalsIgnoreCase(potentialFormat.getEncoding())){
format = potentialFormat;
}
}
if(referenceData.getSchema() == null && referenceData.getEncoding() == null){
format = potentialFormat;
}
}
}
}
if(format == null){
//throw new ExceptionReport("Could not determine intput format. Possibly multiple or none matching generators found. MimeType Set?", ExceptionReport.INVALID_PARAMETER_VALUE);
// TODO Review error message
throw new ExceptionReport("Could not determine output format because none of the supported formats match the given schema (\"" + referenceData.getSchema() + "\") and encoding (\"" + referenceData.getEncoding() + "\"). (A mimetype was not specified)", ExceptionReport.INVALID_PARAMETER_VALUE);
}
mimeType = format.getMimeType();
if(format.isSetEncoding()){
//no encoding provided--> select default one for mimeType
encoding = format.getEncoding();
}
if(format.isSetSchema()){
//no encoding provided--> select default one for mimeType
schema = format.getSchema();
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
LOGGER.debug("Could not determine MimeType from Input URL: " + dataURLString);
} catch (IOException e) {
e.printStackTrace();
LOGGER.debug("Could not determine MimeType from Input URL: " + dataURLString);
}
if(mimeType==null && !referenceData.isSetEncoding() && !referenceData.isSetSchema()){
//nothing set, use default values
schema = inputPD.getComplexData().getDefault().getFormat().getSchema();
mimeType = inputPD.getComplexData().getDefault().getFormat().getMimeType();
encoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
}else{
//do a smart search an look if a mimeType can be found for either schema and/or encoding
if(mimeType==null){
if(referenceData.isSetEncoding() && !referenceData.isSetSchema()){
//encoding set only
ComplexDataDescriptionType encodingFormat = null;
String defaultEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
int found = 0;
String foundEncoding = null;
if(defaultEncoding.equalsIgnoreCase(referenceData.getEncoding())){
foundEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
encodingFormat = inputPD.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getEncoding())){
foundEncoding = tempFormat.getEncoding();
encodingFormat = tempFormat;
found = found +1;
}
}
}
if(found == 1){
encoding = foundEncoding;
mimeType = encodingFormat.getMimeType();
if(encodingFormat.isSetSchema()){
schema = encodingFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(referenceData.isSetSchema() && !referenceData.isSetEncoding()){
//schema set only
ComplexDataDescriptionType schemaFormat = null;
String defaultSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
int found = 0;
String foundSchema = null;
if(defaultSchema.equalsIgnoreCase(referenceData.getSchema())){
foundSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
schemaFormat = inputPD.getComplexData().getDefault().getFormat();
found = found +1;
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getSchema())){
foundSchema = tempFormat.getSchema();
schemaFormat =tempFormat;
found = found +1;
}
}
}
if(found == 1){
schema = foundSchema;
mimeType = schemaFormat.getMimeType();
if(schemaFormat.isSetEncoding()){
encoding = schemaFormat.getEncoding();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given schema not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
if(referenceData.isSetEncoding() && referenceData.isSetSchema()){
//schema and encoding set
//encoding
String defaultEncoding = inputPD.getComplexData().getDefault().getFormat().getEncoding();
List<ComplexDataDescriptionType> foundEncodingList = new ArrayList<ComplexDataDescriptionType>();
if(defaultEncoding.equalsIgnoreCase(referenceData.getEncoding())){
foundEncodingList.add(inputPD.getComplexData().getDefault().getFormat());
}else{
ComplexDataDescriptionType[] formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getEncoding())){
foundEncodingList.add(tempFormat);
}
}
//schema
List<ComplexDataDescriptionType> foundSchemaList = new ArrayList<ComplexDataDescriptionType>();
String defaultSchema = inputPD.getComplexData().getDefault().getFormat().getSchema();
if(defaultSchema.equalsIgnoreCase(referenceData.getSchema())){
foundSchemaList.add(inputPD.getComplexData().getDefault().getFormat());
}else{
formats = inputPD.getComplexData().getSupported().getFormatArray();
for(ComplexDataDescriptionType tempFormat : formats){
if(tempFormat.getEncoding().equalsIgnoreCase(referenceData.getSchema())){
foundSchemaList.add(tempFormat);
}
}
}
//results
ComplexDataDescriptionType foundCommonFormat = null;
for(ComplexDataDescriptionType encodingFormat : foundEncodingList){
for(ComplexDataDescriptionType schemaFormat : foundSchemaList){
if(encodingFormat.equals(schemaFormat)){
foundCommonFormat = encodingFormat;
}
}
}
if(foundCommonFormat!=null){
mimeType = foundCommonFormat.getMimeType();
if(foundCommonFormat.isSetEncoding()){
encoding = foundCommonFormat.getEncoding();
}
if(foundCommonFormat.isSetSchema()){
schema = foundCommonFormat.getSchema();
}
}else{
throw new ExceptionReport("Request incomplete. Could not determine a suitable input format based on the given input [mime Type missing and given encoding and schema are not unique]", ExceptionReport.MISSING_PARAMETER_VALUE);
}
}
}
}
}
}
LOGGER.debug("Loading parser for: schema = \""+ schema
+ "\" , mimetype = \"" + mimeType
+ "\", encoding = \"" + encoding + "\"");
IParser parser = null;
try {
Class algorithmInputClass = RepositoryManager.getInstance().getInputDataTypeForAlgorithm(this.algorithmIdentifier, inputID);
if(algorithmInputClass == null) {
throw new RuntimeException("Could not determine internal input class for input" + inputID);
}
LOGGER.info("Looking for matching Parser ..." +
" schema: \"" + schema +
"\", mimeType: \"" + mimeType +
"\", encoding: \"" + encoding + "\"");
parser = ParserFactory.getInstance().getParser(schema, mimeType, encoding, algorithmInputClass);
if(parser == null) {
//throw new ExceptionReport("Error. No applicable parser found for " + schema + "," + mimeType + "," + encoding, ExceptionReport.NO_APPLICABLE_CODE);
throw new ExceptionReport("Error. No applicable parser found for schema=\"" + schema + "\", mimeType=\"" + mimeType + "\", encoding=\"" + encoding + "\"", ExceptionReport.NO_APPLICABLE_CODE);
}
} catch (RuntimeException e) {
throw new ExceptionReport("Error obtaining input data", ExceptionReport.NO_APPLICABLE_CODE, e);
}
/****PROXY*****/
/*String decodedURL = URLDecoder.decode(dataURLString);
decodedURL = decodedURL.replace("&", "&");
if(decodedURL.indexOf("&BBOX")==-1){
decodedURL = decodedURL.replace("BBOX", "&BBOX");
decodedURL = decodedURL.replace("outputFormat", "&outputFormat");
decodedURL = decodedURL.replace("SRS", "&SRS");
decodedURL = decodedURL.replace("REQUEST", "&REQUEST");
decodedURL = decodedURL.replace("VERSION", "&VERSION");
decodedURL = decodedURL.replace("SERVICE", "&SERVICE");
decodedURL = decodedURL.replace("format", "&format");
}*/
//lookup WFS
if(dataURLString.toUpperCase().contains("REQUEST=GETFEATURE") &&
dataURLString.toUpperCase().contains("SERVICE=WFS")){
if(parser instanceof SimpleGMLParser){
parser = new GML2BasicParser();
}
if(parser instanceof GML2BasicParser && !dataURLString.toUpperCase().contains("OUTPUTFORMAT=GML2")){
//make sure we get GML2
dataURLString = dataURLString+"&outputFormat=GML2";
}
if(parser instanceof GML3BasicParser && !dataURLString.toUpperCase().contains("OUTPUTFORMAT=GML3")){
//make sure we get GML3
dataURLString = dataURLString+"&outputFormat=GML3";
}
}
IData parsedInputData = parser.parse(stream, mimeType, schema);
//enable maxxoccurs of parameters with the same name.
if(inputData.containsKey(inputID)) {
List<IData> list = inputData.get(inputID);
list.add(parsedInputData);
inputData.put(inputID, list);
}
else {
List<IData> list = new ArrayList<IData>();
list.add(parsedInputData);
inputData.put(inputID, list);
}
}
|
diff --git a/src/xdsbridge/src/test/java/com/vangent/hieos/services/xds/bridge/mapper/CDAToXDSMapperTest.java b/src/xdsbridge/src/test/java/com/vangent/hieos/services/xds/bridge/mapper/CDAToXDSMapperTest.java
index 45c31a07..3cbf5db1 100755
--- a/src/xdsbridge/src/test/java/com/vangent/hieos/services/xds/bridge/mapper/CDAToXDSMapperTest.java
+++ b/src/xdsbridge/src/test/java/com/vangent/hieos/services/xds/bridge/mapper/CDAToXDSMapperTest.java
@@ -1,208 +1,208 @@
/*
* This code is subject to the HIEOS License, Version 1.0
*
* Copyright(c) 2011 Vangent, Inc. All rights reserved.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vangent.hieos.services.xds.bridge.mapper;
import com.vangent.hieos.hl7v3util.model.subject.CodedValue;
import com.vangent.hieos.hl7v3util.model.subject.SubjectIdentifier;
import com.vangent.hieos.services.xds.bridge.message.XDSPnRMessage;
import com.vangent.hieos.services.xds.bridge.model.Document;
import com.vangent.hieos.services.xds.bridge.utils.DebugUtils;
import com.vangent.hieos.services.xds.bridge.utils.JUnitHelper;
import com.vangent.hieos.services.xds.bridge.utils.SubjectIdentifierUtils;
import com.vangent.hieos.xutil.iosupport.Io;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.InputStream;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Class description
*
*
* @version v1.0, 2011-06-13
* @author Jim Horner
*/
public class CDAToXDSMapperTest {
/** Field description */
private static final Logger logger =
Logger.getLogger(CDAToXDSMapperTest.class);
/**
* This method will test the business logic w/in the mapper
*
*
* @throws Exception
*/
@Test
public void createReplaceVariablesTest() throws Exception {
ContentParserConfig cfg =
JUnitHelper.createCDAToXDSContentParserConfig();
ContentParser gen = new ContentParser();
CDAToXDSMapper mapper = new CDAToXDSMapper(gen, cfg);
ClassLoader cl = getClass().getClassLoader();
InputStream xmlis = cl.getResourceAsStream(JUnitHelper.SALLY_GRANT);
assertNotNull(xmlis);
byte[] xml = Io.getBytesFromInputStream(xmlis);
assertNotNull(xml);
assertTrue(xml.length > 0);
Document doc = new Document();
CodedValue type = new CodedValue();
type.setCode("51855-5");
type.setCodeSystem("2.16.840.1.113883.6.1");
type.setCodeSystemName("LOINC");
doc.setType(type);
CodedValue format = new CodedValue();
format.setCode("urn:ihe:pcc:xds-ms:2007");
format.setCodeSystem("1.3.6.1.4.1.19376.1.2.3");
format.setCodeSystemName("XDS");
doc.setFormat(format);
doc.setContent(xml);
Map<String, String> repl = mapper.createReplaceVariables(doc);
logger.debug(DebugUtils.toPrettyString(repl));
// 1.2.36.1.2001.1003.0.8003611234567890
assertEquals("",
repl.get(ContentVariableName.AuthorPersonRoot.toString()));
assertEquals(
"1.2.36.1.2001.1003.0.8003611234567890",
repl.get(ContentVariableName.AuthorPersonExtension.toString()));
// "1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"
assertEquals("1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478",
repl.get(ContentVariableName.PatientIdRoot.toString()));
assertEquals("", repl.get(ContentVariableName.PatientIdExtension.toString()));
assertEquals("6fa11e467880478^^^&1.3.6.1.4.1.21367.2005.3.7&ISO",
repl.get(ContentVariableName.PatientIdCX.toString()));
// "1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478"
assertEquals(
"1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478",
repl.get(ContentVariableName.SourcePatientIdRoot.toString()));
assertEquals("",
repl.get(ContentVariableName.SourcePatientIdExtension.toString()));
assertEquals("6fa11e467880478^^^&1.3.6.1.4.1.21367.2005.3.7&ISO",
repl.get(ContentVariableName.SourcePatientIdCX.toString()));
}
/**
* Method description
*
*
* @throws Exception
*/
@Test
public void mapTest() throws Exception {
ContentParserConfig cfg =
JUnitHelper.createCDAToXDSContentParserConfig();
ContentParser gen = new ContentParser();
CDAToXDSMapper mapper = new CDAToXDSMapper(gen, cfg);
ClassLoader cl = getClass().getClassLoader();
InputStream xmlis = cl.getResourceAsStream(JUnitHelper.SALLY_GRANT);
assertNotNull(xmlis);
String xml = Io.getStringFromInputStream(xmlis);
assertNotNull(xml);
assertTrue(StringUtils.isNotBlank(xml));
Document doc = new Document();
CodedValue type = new CodedValue();
type.setCode("51855-5");
type.setCodeSystem("2.16.840.1.113883.6.1");
type.setCodeSystemName("LOINC");
doc.setType(type);
CodedValue format = new CodedValue();
format.setCode("urn:ihe:pcc:xds-ms:2007");
format.setCodeSystem("1.3.6.1.4.1.19376.1.2.3");
format.setCodeSystemName("XDS");
doc.setFormat(format);
doc.setContent(xml.getBytes());
SubjectIdentifier patientId =
SubjectIdentifierUtils.createSubjectIdentifier(
"1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478", null);
XDSPnRMessage pnr = mapper.map(patientId, doc);
assertNotNull(pnr);
- String pnrstr = DebugUtils.toPrettyString(pnr.getMessageNode());
+ String pnrstr = DebugUtils.toPrettyString(pnr.getElement());
logger.debug(pnrstr);
Pattern pattern = Pattern.compile("\\{.*?\\}");
Matcher matcher = pattern.matcher(pnrstr);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
sb.append(matcher.group());
sb.append("\n");
}
// assertEquals("Found unset tokens: " + sb.toString(), 0, sb.length());
// JUnitHelper.createXConfigInstance();
//
// String schemaLocation =
// String.format(
// "%s/../../config/schema/v3/XDS.b_DocumentRepository.xsd",
// System.getProperty("user.dir"));
//
// assertTrue("File " + schemaLocation + " not exist.",
// new File(schemaLocation).exists());
//
// XMLSchemaValidator schemaValidator =
// new XMLSchemaValidator(schemaLocation);
//
// //schemaValidator.validate(pnrstr);
}
}
| true | true | public void mapTest() throws Exception {
ContentParserConfig cfg =
JUnitHelper.createCDAToXDSContentParserConfig();
ContentParser gen = new ContentParser();
CDAToXDSMapper mapper = new CDAToXDSMapper(gen, cfg);
ClassLoader cl = getClass().getClassLoader();
InputStream xmlis = cl.getResourceAsStream(JUnitHelper.SALLY_GRANT);
assertNotNull(xmlis);
String xml = Io.getStringFromInputStream(xmlis);
assertNotNull(xml);
assertTrue(StringUtils.isNotBlank(xml));
Document doc = new Document();
CodedValue type = new CodedValue();
type.setCode("51855-5");
type.setCodeSystem("2.16.840.1.113883.6.1");
type.setCodeSystemName("LOINC");
doc.setType(type);
CodedValue format = new CodedValue();
format.setCode("urn:ihe:pcc:xds-ms:2007");
format.setCodeSystem("1.3.6.1.4.1.19376.1.2.3");
format.setCodeSystemName("XDS");
doc.setFormat(format);
doc.setContent(xml.getBytes());
SubjectIdentifier patientId =
SubjectIdentifierUtils.createSubjectIdentifier(
"1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478", null);
XDSPnRMessage pnr = mapper.map(patientId, doc);
assertNotNull(pnr);
String pnrstr = DebugUtils.toPrettyString(pnr.getMessageNode());
logger.debug(pnrstr);
Pattern pattern = Pattern.compile("\\{.*?\\}");
Matcher matcher = pattern.matcher(pnrstr);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
sb.append(matcher.group());
sb.append("\n");
}
// assertEquals("Found unset tokens: " + sb.toString(), 0, sb.length());
// JUnitHelper.createXConfigInstance();
//
// String schemaLocation =
// String.format(
// "%s/../../config/schema/v3/XDS.b_DocumentRepository.xsd",
// System.getProperty("user.dir"));
//
// assertTrue("File " + schemaLocation + " not exist.",
// new File(schemaLocation).exists());
//
// XMLSchemaValidator schemaValidator =
// new XMLSchemaValidator(schemaLocation);
//
// //schemaValidator.validate(pnrstr);
}
| public void mapTest() throws Exception {
ContentParserConfig cfg =
JUnitHelper.createCDAToXDSContentParserConfig();
ContentParser gen = new ContentParser();
CDAToXDSMapper mapper = new CDAToXDSMapper(gen, cfg);
ClassLoader cl = getClass().getClassLoader();
InputStream xmlis = cl.getResourceAsStream(JUnitHelper.SALLY_GRANT);
assertNotNull(xmlis);
String xml = Io.getStringFromInputStream(xmlis);
assertNotNull(xml);
assertTrue(StringUtils.isNotBlank(xml));
Document doc = new Document();
CodedValue type = new CodedValue();
type.setCode("51855-5");
type.setCodeSystem("2.16.840.1.113883.6.1");
type.setCodeSystemName("LOINC");
doc.setType(type);
CodedValue format = new CodedValue();
format.setCode("urn:ihe:pcc:xds-ms:2007");
format.setCodeSystem("1.3.6.1.4.1.19376.1.2.3");
format.setCodeSystemName("XDS");
doc.setFormat(format);
doc.setContent(xml.getBytes());
SubjectIdentifier patientId =
SubjectIdentifierUtils.createSubjectIdentifier(
"1.3.6.1.4.1.21367.2005.3.7.6fa11e467880478", null);
XDSPnRMessage pnr = mapper.map(patientId, doc);
assertNotNull(pnr);
String pnrstr = DebugUtils.toPrettyString(pnr.getElement());
logger.debug(pnrstr);
Pattern pattern = Pattern.compile("\\{.*?\\}");
Matcher matcher = pattern.matcher(pnrstr);
StringBuilder sb = new StringBuilder();
while (matcher.find()) {
sb.append(matcher.group());
sb.append("\n");
}
// assertEquals("Found unset tokens: " + sb.toString(), 0, sb.length());
// JUnitHelper.createXConfigInstance();
//
// String schemaLocation =
// String.format(
// "%s/../../config/schema/v3/XDS.b_DocumentRepository.xsd",
// System.getProperty("user.dir"));
//
// assertTrue("File " + schemaLocation + " not exist.",
// new File(schemaLocation).exists());
//
// XMLSchemaValidator schemaValidator =
// new XMLSchemaValidator(schemaLocation);
//
// //schemaValidator.validate(pnrstr);
}
|
diff --git a/src/main/java/com/jcabi/maven/plugin/AjcMojo.java b/src/main/java/com/jcabi/maven/plugin/AjcMojo.java
index a49f7e3..51439a5 100644
--- a/src/main/java/com/jcabi/maven/plugin/AjcMojo.java
+++ b/src/main/java/com/jcabi/maven/plugin/AjcMojo.java
@@ -1,402 +1,403 @@
/**
* Copyright (c) 2012-2013, JCabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jcabi.maven.plugin;
import com.google.common.io.Files;
import com.jcabi.aether.Classpath;
import com.jcabi.aspects.Cacheable;
import com.jcabi.aspects.Loggable;
import com.jcabi.log.Logger;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.TrueFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;
import org.aspectj.bridge.IMessage;
import org.aspectj.bridge.IMessageHolder;
import org.aspectj.tools.ajc.Main;
import org.jfrog.maven.annomojo.annotations.MojoGoal;
import org.jfrog.maven.annomojo.annotations.MojoParameter;
import org.jfrog.maven.annomojo.annotations.MojoPhase;
import org.slf4j.impl.StaticLoggerBinder;
import org.sonatype.aether.RepositorySystemSession;
import org.sonatype.aether.util.artifact.JavaScopes;
/**
* AspectJ compile CLASS files.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @since 0.7.16
* @link <a href="http://www.eclipse.org/aspectj/doc/next/devguide/ajc-ref.html">AJC compiler manual</a>
*/
@MojoGoal("ajc")
@MojoPhase("process-classes")
@ToString
@EqualsAndHashCode(callSuper = false, of = { "project", "scopes" })
@Loggable(Loggable.DEBUG)
@SuppressWarnings({ "PMD.TooManyMethods", "PMD.ExcessiveImports" })
public final class AjcMojo extends AbstractMojo {
/**
* Classpath separator.
*/
private static final String SEP = System.getProperty("path.separator");
/**
* Maven project.
*/
@MojoParameter(
expression = "${project}",
required = true,
readonly = true
)
private transient MavenProject project;
/**
* Maven project.
*/
@MojoParameter(
expression = "${repositorySystemSession}",
required = true,
readonly = true
)
private transient RepositorySystemSession session;
/**
* Compiled directory.
*/
@MojoParameter(
required = false,
readonly = false,
description = "Directory with compiled .class files",
defaultValue = "${project.build.outputDirectory}"
)
private transient File classesDirectory;
/**
* Directories with aspects.
*/
@MojoParameter(
required = false,
readonly = false,
description = "Directories with aspects"
)
private transient File[] aspectDirectories;
/**
* Temporary directory.
*/
@MojoParameter(
defaultValue = "${project.build.directory}/jcabi-ajc",
required = false,
readonly = false,
description = "Temporary directory for compiled classes"
)
private transient File tempDirectory;
/**
* Scopes to take into account.
*/
@MojoParameter(
required = false,
readonly = false,
description = "Scopes with aspects and libraries"
)
private transient String[] scopes;
/**
* {@inheritDoc}
*/
@Override
@Loggable(value = Loggable.DEBUG, limit = 1, unit = TimeUnit.MINUTES)
public void execute() throws MojoFailureException {
StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
this.classesDirectory.mkdirs();
this.tempDirectory.mkdirs();
final Main main = new Main();
final IMessageHolder mholder = new AjcMojo.MsgHolder();
final String jdk = "1.6";
main.run(
new String[] {
+ "-Xset:avoidFinal=true",
"-inpath",
this.classesDirectory.getAbsolutePath(),
"-sourceroots",
this.sourceroots(),
"-d",
this.tempDirectory.getAbsolutePath(),
"-classpath",
StringUtils.join(this.classpath(), AjcMojo.SEP),
"-aspectpath",
this.aspectpath(),
"-source",
jdk,
"-target",
jdk,
"-g:none",
"-encoding",
"UTF-8",
"-time",
"-showWeaveInfo",
"-warn:constructorName",
"-warn:packageDefaultMethod",
"-warn:deprecation",
"-warn:maskedCatchBlocks",
"-warn:unusedLocals",
"-warn:unusedArguments",
"-warn:unusedImports",
"-warn:syntheticAccess",
"-warn:assertIdentifier",
},
mholder
);
try {
FileUtils.copyDirectory(this.tempDirectory, this.classesDirectory);
} catch (IOException ex) {
throw new MojoFailureException("failed to copy files back", ex);
}
Logger.info(
this,
// @checkstyle LineLength (1 line)
"ajc result: %d file(s) processed, %d pointcut(s) woven, %d error(s), %d warning(s)",
AjcMojo.files(this.tempDirectory).size(),
mholder.numMessages(IMessage.WEAVEINFO, false),
mholder.numMessages(IMessage.ERROR, true),
mholder.numMessages(IMessage.WARNING, false)
);
if (mholder.hasAnyMessage(IMessage.ERROR, true)) {
throw new MojoFailureException("AJC failed, see log above");
}
}
/**
* Get classpath for AJC.
* @return Classpath
*/
@Cacheable(forever = true)
@Loggable(
value = Loggable.DEBUG,
limit = 1, unit = TimeUnit.MINUTES,
trim = false
)
private Collection<File> classpath() {
Collection<String> scps;
if (this.scopes == null) {
scps = Arrays.asList(
JavaScopes.COMPILE,
JavaScopes.PROVIDED,
JavaScopes.RUNTIME,
JavaScopes.SYSTEM
);
} else {
scps = Arrays.asList(this.scopes);
}
return new Classpath(
this.project,
this.session.getLocalRepository().getBasedir(),
scps
);
}
/**
* Get locations of all aspect libraries for AJC.
* @return Classpath
*/
@Cacheable(forever = true)
private String aspectpath() {
return new StringBuilder()
.append(StringUtils.join(this.classpath(), AjcMojo.SEP))
.append(AjcMojo.SEP)
.append(System.getProperty("java.class.path"))
.toString();
}
/**
* Get locations of all source roots (with aspects in source form).
* @return Directories separated
*/
@Cacheable(forever = true)
private String sourceroots() {
String path;
if (this.aspectDirectories == null
|| this.aspectDirectories.length == 0) {
path = Files.createTempDir().getAbsolutePath();
} else {
for (File dir : this.aspectDirectories) {
if (!dir.exists()) {
throw new IllegalStateException(
String.format("source directory %s is absent", dir)
);
}
}
path = StringUtils.join(this.aspectDirectories, AjcMojo.SEP);
}
return path;
}
/**
* Find all files in the directory.
* @param dir The directory
* @return List of them
*/
private static Collection<File> files(final File dir) {
final Collection<File> files = new LinkedList<File>();
final Collection<File> all = FileUtils.listFiles(
dir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE
);
for (File file : all) {
if (file.isFile()) {
files.add(file);
}
}
return files;
}
/**
* Message holder.
*/
private static final class MsgHolder implements IMessageHolder {
/**
* All messages seen so far.
*/
private final transient Collection<IMessage> messages =
new CopyOnWriteArrayList<IMessage>();
/**
* {@inheritDoc}
*/
@Override
public boolean hasAnyMessage(final IMessage.Kind kind,
final boolean greater) {
boolean has = false;
for (IMessage msg : this.messages) {
has = msg.getKind().equals(kind) || greater
&& IMessage.Kind.COMPARATOR
.compare(msg.getKind(), kind) > 0;
if (has) {
break;
}
}
return has;
}
/**
* {@inheritDoc}
*/
@Override
public int numMessages(final IMessage.Kind kind,
final boolean greater) {
int num = 0;
for (IMessage msg : this.messages) {
final boolean has = msg.getKind().equals(kind) || greater
&& IMessage.Kind.COMPARATOR
.compare(msg.getKind(), kind) > 0;
if (has) {
++num;
}
}
return num;
}
/**
* {@inheritDoc}
*/
@Override
public IMessage[] getMessages(final IMessage.Kind kind,
final boolean greater) {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public List<IMessage> getUnmodifiableListView() {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public void clearMessages() {
throw new UnsupportedOperationException();
}
/**
* {@inheritDoc}
*/
@Override
public boolean handleMessage(final IMessage msg) {
if (msg.getKind().equals(IMessage.ERROR)
|| msg.getKind().equals(IMessage.FAIL)
|| msg.getKind().equals(IMessage.ABORT)) {
Logger.error(AjcMojo.class, msg.getMessage());
} else if (msg.getKind().equals(IMessage.WARNING)) {
Logger.warn(AjcMojo.class, msg.getMessage());
} else if (msg.getKind().equals(IMessage.WEAVEINFO)) {
Logger.debug(AjcMojo.class, msg.getMessage());
} else if (msg.getKind().equals(IMessage.INFO)) {
Logger.debug(AjcMojo.class, msg.getMessage());
} else {
Logger.debug(AjcMojo.class, msg.getMessage());
}
this.messages.add(msg);
return true;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isIgnoring(final IMessage.Kind kind) {
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void dontIgnore(final IMessage.Kind kind) {
assert kind != null;
}
/**
* {@inheritDoc}
*/
@Override
public void ignore(final IMessage.Kind kind) {
assert kind != null;
}
}
}
| true | true | public void execute() throws MojoFailureException {
StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
this.classesDirectory.mkdirs();
this.tempDirectory.mkdirs();
final Main main = new Main();
final IMessageHolder mholder = new AjcMojo.MsgHolder();
final String jdk = "1.6";
main.run(
new String[] {
"-inpath",
this.classesDirectory.getAbsolutePath(),
"-sourceroots",
this.sourceroots(),
"-d",
this.tempDirectory.getAbsolutePath(),
"-classpath",
StringUtils.join(this.classpath(), AjcMojo.SEP),
"-aspectpath",
this.aspectpath(),
"-source",
jdk,
"-target",
jdk,
"-g:none",
"-encoding",
"UTF-8",
"-time",
"-showWeaveInfo",
"-warn:constructorName",
"-warn:packageDefaultMethod",
"-warn:deprecation",
"-warn:maskedCatchBlocks",
"-warn:unusedLocals",
"-warn:unusedArguments",
"-warn:unusedImports",
"-warn:syntheticAccess",
"-warn:assertIdentifier",
},
mholder
);
try {
FileUtils.copyDirectory(this.tempDirectory, this.classesDirectory);
} catch (IOException ex) {
throw new MojoFailureException("failed to copy files back", ex);
}
Logger.info(
this,
// @checkstyle LineLength (1 line)
"ajc result: %d file(s) processed, %d pointcut(s) woven, %d error(s), %d warning(s)",
AjcMojo.files(this.tempDirectory).size(),
mholder.numMessages(IMessage.WEAVEINFO, false),
mholder.numMessages(IMessage.ERROR, true),
mholder.numMessages(IMessage.WARNING, false)
);
if (mholder.hasAnyMessage(IMessage.ERROR, true)) {
throw new MojoFailureException("AJC failed, see log above");
}
}
| public void execute() throws MojoFailureException {
StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
this.classesDirectory.mkdirs();
this.tempDirectory.mkdirs();
final Main main = new Main();
final IMessageHolder mholder = new AjcMojo.MsgHolder();
final String jdk = "1.6";
main.run(
new String[] {
"-Xset:avoidFinal=true",
"-inpath",
this.classesDirectory.getAbsolutePath(),
"-sourceroots",
this.sourceroots(),
"-d",
this.tempDirectory.getAbsolutePath(),
"-classpath",
StringUtils.join(this.classpath(), AjcMojo.SEP),
"-aspectpath",
this.aspectpath(),
"-source",
jdk,
"-target",
jdk,
"-g:none",
"-encoding",
"UTF-8",
"-time",
"-showWeaveInfo",
"-warn:constructorName",
"-warn:packageDefaultMethod",
"-warn:deprecation",
"-warn:maskedCatchBlocks",
"-warn:unusedLocals",
"-warn:unusedArguments",
"-warn:unusedImports",
"-warn:syntheticAccess",
"-warn:assertIdentifier",
},
mholder
);
try {
FileUtils.copyDirectory(this.tempDirectory, this.classesDirectory);
} catch (IOException ex) {
throw new MojoFailureException("failed to copy files back", ex);
}
Logger.info(
this,
// @checkstyle LineLength (1 line)
"ajc result: %d file(s) processed, %d pointcut(s) woven, %d error(s), %d warning(s)",
AjcMojo.files(this.tempDirectory).size(),
mholder.numMessages(IMessage.WEAVEINFO, false),
mholder.numMessages(IMessage.ERROR, true),
mholder.numMessages(IMessage.WARNING, false)
);
if (mholder.hasAnyMessage(IMessage.ERROR, true)) {
throw new MojoFailureException("AJC failed, see log above");
}
}
|
diff --git a/eclipse/portal/plugins/com.liferay.ide.eclipse.layouttpl.core/src/com/liferay/ide/eclipse/layouttpl/core/facet/LayoutTplPluginFacetInstall.java b/eclipse/portal/plugins/com.liferay.ide.eclipse.layouttpl.core/src/com/liferay/ide/eclipse/layouttpl/core/facet/LayoutTplPluginFacetInstall.java
index bd9700655..fee79dab6 100644
--- a/eclipse/portal/plugins/com.liferay.ide.eclipse.layouttpl.core/src/com/liferay/ide/eclipse/layouttpl/core/facet/LayoutTplPluginFacetInstall.java
+++ b/eclipse/portal/plugins/com.liferay.ide.eclipse.layouttpl.core/src/com/liferay/ide/eclipse/layouttpl/core/facet/LayoutTplPluginFacetInstall.java
@@ -1,133 +1,133 @@
/*******************************************************************************
* Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
*******************************************************************************/
package com.liferay.ide.eclipse.layouttpl.core.facet;
import com.liferay.ide.eclipse.core.util.CoreUtil;
import com.liferay.ide.eclipse.core.util.FileUtil;
import com.liferay.ide.eclipse.project.core.facet.IPluginFacetConstants;
import com.liferay.ide.eclipse.project.core.facet.PluginFacetInstall;
import com.liferay.ide.eclipse.sdk.ISDKConstants;
import com.liferay.ide.eclipse.sdk.SDK;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClasspathEntry;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.wst.common.componentcore.datamodel.FacetInstallDataModelProvider;
import org.eclipse.wst.common.frameworks.datamodel.IDataModel;
import org.eclipse.wst.common.project.facet.core.IFacetedProjectWorkingCopy;
import org.eclipse.wst.common.project.facet.core.IProjectFacetVersion;
/**
* @author Greg Amerson
*/
public class LayoutTplPluginFacetInstall extends PluginFacetInstall {
@Override
public void execute(IProject project, IProjectFacetVersion fv, Object config, IProgressMonitor monitor)
throws CoreException {
super.execute(project, fv, config, monitor);
IDataModel model = (IDataModel) config;
IDataModel masterModel = (IDataModel) model.getProperty(FacetInstallDataModelProvider.MASTER_PROJECT_DM);
if (masterModel != null && masterModel.getBooleanProperty(CREATE_PROJECT_OPERATION)) {
// get the template zip for layouttpl and extract into the project
SDK sdk = getSDK();
String layoutTplName = this.masterModel.getStringProperty(LAYOUTTPL_NAME);
String displayName = this.masterModel.getStringProperty(DISPLAY_NAME);
IPath newLayoutTplPath = sdk.createNewLayoutTplProject(layoutTplName, displayName, getLiferayRuntime());
processNewFiles(newLayoutTplPath.append(layoutTplName + ISDKConstants.LAYOUTTPL_PLUGIN_PROJECT_SUFFIX), false);
// cleanup files
FileUtil.deleteDir(newLayoutTplPath.toFile(), true);
}
else {
setupDefaultOutputLocation();
}
removeUnneededClasspathEntries();
IResource libRes = project.findMember("docroot/WEB-INF/lib");
- if (libRes.exists()) {
+ if (libRes != null && libRes.exists()) {
IFolder libFolder = (IFolder) libRes;
IResource[] libFiles = libFolder.members(true);
if (CoreUtil.isNullOrEmpty(libFiles)) {
libRes.delete(true, monitor);
}
}
this.project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
protected void removeUnneededClasspathEntries() {
IFacetedProjectWorkingCopy facetedProject = getFacetedProject();
IJavaProject javaProject = JavaCore.create(facetedProject.getProject());
try {
IClasspathEntry[] existingClasspath = javaProject.getRawClasspath();
List<IClasspathEntry> newClasspath = new ArrayList<IClasspathEntry>();
for (IClasspathEntry entry : existingClasspath) {
if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
continue;
}
else if (entry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
String path = entry.getPath().toPortableString();
if (path.contains("org.eclipse.jdt.launching.JRE_CONTAINER") ||
path.contains("org.eclipse.jst.j2ee.internal.web.container") ||
path.contains("org.eclipse.jst.j2ee.internal.module.container")) {
continue;
}
}
newClasspath.add(entry);
}
javaProject.setRawClasspath(newClasspath.toArray(new IClasspathEntry[0]), null);
IResource sourceFolder =
javaProject.getProject().findMember(IPluginFacetConstants.PORTLET_PLUGIN_SDK_SOURCE_FOLDER);
if (sourceFolder.exists()) {
sourceFolder.delete(true, null);
}
}
catch (Exception e) {
}
}
@Override
protected boolean shouldInstallPluginLibraryDelegate() {
return false;
}
}
| true | true | public void execute(IProject project, IProjectFacetVersion fv, Object config, IProgressMonitor monitor)
throws CoreException {
super.execute(project, fv, config, monitor);
IDataModel model = (IDataModel) config;
IDataModel masterModel = (IDataModel) model.getProperty(FacetInstallDataModelProvider.MASTER_PROJECT_DM);
if (masterModel != null && masterModel.getBooleanProperty(CREATE_PROJECT_OPERATION)) {
// get the template zip for layouttpl and extract into the project
SDK sdk = getSDK();
String layoutTplName = this.masterModel.getStringProperty(LAYOUTTPL_NAME);
String displayName = this.masterModel.getStringProperty(DISPLAY_NAME);
IPath newLayoutTplPath = sdk.createNewLayoutTplProject(layoutTplName, displayName, getLiferayRuntime());
processNewFiles(newLayoutTplPath.append(layoutTplName + ISDKConstants.LAYOUTTPL_PLUGIN_PROJECT_SUFFIX), false);
// cleanup files
FileUtil.deleteDir(newLayoutTplPath.toFile(), true);
}
else {
setupDefaultOutputLocation();
}
removeUnneededClasspathEntries();
IResource libRes = project.findMember("docroot/WEB-INF/lib");
if (libRes.exists()) {
IFolder libFolder = (IFolder) libRes;
IResource[] libFiles = libFolder.members(true);
if (CoreUtil.isNullOrEmpty(libFiles)) {
libRes.delete(true, monitor);
}
}
this.project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
| public void execute(IProject project, IProjectFacetVersion fv, Object config, IProgressMonitor monitor)
throws CoreException {
super.execute(project, fv, config, monitor);
IDataModel model = (IDataModel) config;
IDataModel masterModel = (IDataModel) model.getProperty(FacetInstallDataModelProvider.MASTER_PROJECT_DM);
if (masterModel != null && masterModel.getBooleanProperty(CREATE_PROJECT_OPERATION)) {
// get the template zip for layouttpl and extract into the project
SDK sdk = getSDK();
String layoutTplName = this.masterModel.getStringProperty(LAYOUTTPL_NAME);
String displayName = this.masterModel.getStringProperty(DISPLAY_NAME);
IPath newLayoutTplPath = sdk.createNewLayoutTplProject(layoutTplName, displayName, getLiferayRuntime());
processNewFiles(newLayoutTplPath.append(layoutTplName + ISDKConstants.LAYOUTTPL_PLUGIN_PROJECT_SUFFIX), false);
// cleanup files
FileUtil.deleteDir(newLayoutTplPath.toFile(), true);
}
else {
setupDefaultOutputLocation();
}
removeUnneededClasspathEntries();
IResource libRes = project.findMember("docroot/WEB-INF/lib");
if (libRes != null && libRes.exists()) {
IFolder libFolder = (IFolder) libRes;
IResource[] libFiles = libFolder.members(true);
if (CoreUtil.isNullOrEmpty(libFiles)) {
libRes.delete(true, monitor);
}
}
this.project.refreshLocal(IResource.DEPTH_INFINITE, monitor);
}
|
diff --git a/src/zz/utils/properties/ArrayListProperty.java b/src/zz/utils/properties/ArrayListProperty.java
index daa58e7..c0e9597 100644
--- a/src/zz/utils/properties/ArrayListProperty.java
+++ b/src/zz/utils/properties/ArrayListProperty.java
@@ -1,168 +1,168 @@
/*
* Created on Dec 14, 2004
*/
package zz.utils.properties;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import zz.utils.IPublicCloneable;
import zz.utils.ReverseIteratorWrapper;
/**
* @author gpothier
*/
public class ArrayListProperty<E> extends AbstractListProperty<E>
{
private List<E> itsList = new MyList ();
public ArrayListProperty(Object aOwner)
{
super(aOwner);
}
public ArrayListProperty(Object aOwner, PropertyId<List<E>> aPropertyId)
{
super(aOwner, aPropertyId);
}
public List<E> get()
{
return itsList;
}
/**
* Changes the list that backs the property.
* This should be used with care, as it will not send any notification.
*/
protected void set (List<E> aList)
{
// The below code is a workaround for a strange jdk compile error.
if (aList != null && MyList.class.isAssignableFrom(aList.getClass()))
// if (aList instanceof MyList) This is the original code
itsList = ((MyList) aList);
else itsList = aList != null ? new MyList (aList) : null;
}
/**
* Resets the list.
* This should be used with care, as it will not send any notification.
*/
protected void reset()
{
set(new MyList());
}
public void clear()
{
for (int i = size()-1;i>=0;i--)
remove(i);
}
public Iterator<E> reverseIterator()
{
return new ReverseIteratorWrapper (get());
}
public IListProperty<E> cloneForOwner(Object aOwner, boolean aCloneValue)
{
// Note: we don't tell super to clone value, we handle it ourselves.
ArrayListProperty<E> theClone =
(ArrayListProperty) super.cloneForOwner(aOwner, false);
if (aCloneValue)
{
theClone.itsList = new MyList();
for (E theElement : itsList)
{
IPublicCloneable theClonable = (IPublicCloneable) theElement;
E theClonedElement = (E) theClonable.clone();
theClone.itsList.add (theClonedElement);
}
}
else
{
- theClone.itsList = new MyList(itsList);
+ theClone.itsList = itsList != null ? new MyList(itsList) : null;
}
return theClone;
}
/**
* This is our implementation of List, which override some methods in
* order to send notifications.
* @author gpothier
*/
protected class MyList extends ArrayList<E>
{
public MyList()
{
}
public MyList(Collection<? extends E> aContent)
{
addAll(aContent);
}
public boolean remove(Object aO)
{
int theIndex = indexOf(aO);
if (theIndex >= 0)
{
remove(theIndex);
return true;
}
else return false;
}
public E remove(int aIndex)
{
E theElement = super.remove(aIndex);
fireElementRemoved(aIndex, theElement);
return theElement;
}
public boolean add(E aElement)
{
boolean theResult = super.add(aElement);
fireElementAdded(size()-1, aElement);
return theResult;
}
public void add(int aIndex, E aElement)
{
super.add(aIndex, aElement);
fireElementAdded(aIndex, aElement);
}
public boolean addAll(Collection<? extends E> aCollection)
{
return addAll(0, aCollection);
}
public boolean addAll(int aIndex, Collection<? extends E> aCollection)
{
int theIndex = aIndex;
for (E theElement : aCollection)
add (theIndex++, theElement);
return aCollection.size() > 0;
}
public E set(int aIndex, E aElement)
{
E theElement = super.set(aIndex, aElement);
fireElementRemoved(aIndex, theElement);
fireElementAdded(aIndex, aElement);
return theElement;
}
}
}
| true | true | public IListProperty<E> cloneForOwner(Object aOwner, boolean aCloneValue)
{
// Note: we don't tell super to clone value, we handle it ourselves.
ArrayListProperty<E> theClone =
(ArrayListProperty) super.cloneForOwner(aOwner, false);
if (aCloneValue)
{
theClone.itsList = new MyList();
for (E theElement : itsList)
{
IPublicCloneable theClonable = (IPublicCloneable) theElement;
E theClonedElement = (E) theClonable.clone();
theClone.itsList.add (theClonedElement);
}
}
else
{
theClone.itsList = new MyList(itsList);
}
return theClone;
}
| public IListProperty<E> cloneForOwner(Object aOwner, boolean aCloneValue)
{
// Note: we don't tell super to clone value, we handle it ourselves.
ArrayListProperty<E> theClone =
(ArrayListProperty) super.cloneForOwner(aOwner, false);
if (aCloneValue)
{
theClone.itsList = new MyList();
for (E theElement : itsList)
{
IPublicCloneable theClonable = (IPublicCloneable) theElement;
E theClonedElement = (E) theClonable.clone();
theClone.itsList.add (theClonedElement);
}
}
else
{
theClone.itsList = itsList != null ? new MyList(itsList) : null;
}
return theClone;
}
|
diff --git a/client/globe/Globe.java b/client/globe/Globe.java
index 97f16e0..8b31384 100644
--- a/client/globe/Globe.java
+++ b/client/globe/Globe.java
@@ -1,518 +1,531 @@
/*
Copyright 2006 Jerry Huxtable
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.*;
import java.awt.image.*;
import java.awt.print.*;
import javax.swing.*;
import javax.swing.Timer;
import com.jhlabs.map.*;
import com.jhlabs.map.proj.*;
import com.jhlabs.map.util.*;
import com.jhlabs.map.layer.*;
/**
* A component which displays a globe.
*/
public class Globe extends JComponent {
protected static int quality_paint_delay = 100;
private Timer quality_paint_timer ;
protected static int force_repaint_delay = 10*60*1000;
private Timer force_repaint_timer ;
private BufferedImage buffered_image;
private boolean quality_image_buffered = false;
private long last_time_update = 0;
private Color day_color = new Color(0, 0, 1f, 0.1f);
private double max_zoom_factor = 20;
private double min_zoom_factor = 0.6;
protected Graphics2D g2;
private float globeRadius = 275;
protected Projection projection;
private boolean showSea = true;
private boolean showWorld = true;
private boolean showGraticule = true;
private boolean showDay = false;
private boolean showTest = false;
private boolean showTissot = false;
private ProjectionMouseListener mouseListener;
private PanZoomMouseListener zoomListener;
protected AffineTransform transform = new AffineTransform();
private Layer map;
private Layer mapLayer;
private Layer worldLayer;
private Layer graticuleLayer;
private Layer seaLayer;
private TissotLayer tissotLayer;
private Layer linkLayer;
private Layer selectedLayer;
private Style style = new Style( Color.black, Color.green );
// private float hue = 0.3f;
// private Style[] styles = {
// new Style( Color.black, Color.getHSBColor( hue, 0.5f, 1.0f ) ),
// new Style( Color.black, Color.getHSBColor( hue+0.05f, 0.5f, 1.0f ) ),
// new Style( Color.black, Color.getHSBColor( hue+0.1f, 0.5f, 1.0f ) ),
// new Style( Color.black, Color.getHSBColor( hue+0.15f, 0.5f, 1.0f ) )
// };
// private Style[] styles = {
// new Style( null, Color.getHSBColor( hue, 0.5f, 1.0f ) ),
// new Style( null, Color.getHSBColor( hue+0.3f, 0.5f, 1.0f ) ),
// new Style( null, Color.getHSBColor( hue+0.6f, 0.5f, 1.0f ) ),
// new Style( null, Color.getHSBColor( hue+0.9f, 0.5f, 1.0f ) )
// };
private Style[] styles = {
new Style( Color.white, new Color( 105f/255f, 143f/255f, 183f/255f, 1.0f ) ),
new Style( Color.white,new Color( 161f/255f, 193f/255f, 226f/255f, 1.0f ) ),
new Style( Color.white,new Color( 27f/255f, 84f/255f, 143f/255f, 1.0f ) ),
new Style( Color.white,new Color( 36f/255f, 56f/255f, 91f/255f, 1.0f ) ),
};
/*
private Style[] styles = {
new Style( Color.white, new Color( 105f/1020f, 143f/1020f, 183f/1020f, 1f ) ),
new Style( Color.white,new Color( 161f/1020f, 193f/1020f, 226f/1020f, 1f ) ),
new Style( Color.white,new Color( 27f/1020f, 84f/1020f, 143f/1020f, 1f ) ),
new Style( Color.white,new Color( 36f/1020f, 56f/1020f, 91f/1020f, 1f ) ),
};
*/
private Projection last_projection;
private AffineTransform last_transform;
private double original_zoom = 1;
public Globe() {
// Create the map projection
projection = new OrthographicAzimuthalProjection();
// The easiest way to scale the projection is to change the Earth's radius. We could also use an AffineTransform.
projection.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
projection.initialize();
map = new Layer();
map.setProjection( projection );
map.setTransform( transform );
map.addLayer( new BackgroundLayer() );
map.addLayer( mapLayer = new Layer() );
mapLayer.addLayer( seaLayer = new SeaLayer() );
try {
// Layer shadowLayer = new ShadowLayer();
// Layer lightLayer = new EffectLayer( new com.jhlabs.image.LightFilter() );
// map.addLayer( shadowLayer );
// shadowLayer.addLayer( lightLayer );
// map.addLayer( worldLayer = new ShapefileLayer( getClass().getResource("world.shp"), style ) );
SeaLayer seaLayer2;
mapLayer.addLayer( seaLayer2 = new SeaLayer( null ) );
seaLayer2.addLayer( worldLayer = new ShapefileLayer( getClass().getResource("world.shp"), getClass().getResource("world.dbf"), style ) );
// mapLayer.addLayer( worldLayer = new ShapefileLayer( new File("out.shp").toURL(), new Style( Color.black, null ) ) );
}
catch ( IOException e ) {
e.printStackTrace();
}
mapLayer.addLayer( graticuleLayer = new GraticuleLayer() );
mapLayer.addLayer( tissotLayer = new TissotLayer() );
tissotLayer.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.5f) );
linkLayer = new LinkLayer( worldLayer );
// createInterruptedMap();
// map.addLayer( linkLayer );
AffineTransform t = new AffineTransform();
t.translate( 100, 100 );
linkLayer.setTransform( t );
linkLayer.setStyle( new Style( Color.black, Color.orange ) );
Projection lp = new OrthographicAzimuthalProjection();
linkLayer.setProjection( lp );
lp.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
lp.initialize();
int index = 0;
for ( Iterator it = worldLayer.getFeaturesIterator(); it.hasNext(); ) {
Feature feature = (Feature)it.next();
if ( !(feature instanceof PointFeature) )//FIXME
feature.setStyle( styles[index++ % styles.length] );
}
// Add the virtual trackball
addMouseListener( mouseListener = new ProjectionMouseListener( this, projection, transform ) );
addMouseListener( zoomListener = new PanZoomMouseListener( this, transform ) );
- //Add the mousewheel listener
- addMouseWheelListener(
- new MouseWheelListener() {
- public void mouseWheelMoved(MouseWheelEvent e) {
- int steps = e.getWheelRotation();
- mouseZoom(-steps);
- }
- }
- );
+ //Add the mousewheel listener.
+ //We don't use the mousewheel to zoom in/out the globe as the
+ //browser also catch it and we end up zooming and scrolling on
+ //Windows!
+ if (false){
+ addMouseWheelListener(
+ new MouseWheelListener() {
+ public void mouseWheelMoved(MouseWheelEvent e) {
+ int steps = e.getWheelRotation();
+ mouseZoom(-steps);
+ }
+ }
+ );
+ }else{
+ addMouseWheelListener(
+ new MouseWheelListener() {
+ public void mouseWheelMoved(MouseWheelEvent e) {
+ mouseZoom(0);// to force a repaint.
+ }
+ }
+ );
+ }
//Setting up the timer that forces a quality paint after a short idle time
//This one is used to transition from fast to quality draw
quality_paint_timer = new Timer(42,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Globe.this.repaint();
}
});
quality_paint_timer.setRepeats(false);
quality_paint_timer.setInitialDelay(quality_paint_delay);
//Setting up the other timer that forces a repaint after a long idle time
//This one is essentially used to refresh the night
force_repaint_timer = new Timer(42,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
quality_image_buffered = false;
Globe.this.repaint();
}
});
force_repaint_timer.setRepeats(false);
force_repaint_timer.setInitialDelay(force_repaint_delay);
}
public void mouseZoom(int steps) {
double zoom_factor = Math.pow(1.05, steps);
zoom_factor = Math.min(original_zoom * max_zoom_factor / transform.getScaleX(), zoom_factor);
zoom_factor = Math.max(original_zoom * min_zoom_factor/ transform.getScaleX(), zoom_factor);
transform.scale(zoom_factor,zoom_factor);
this.repaint();
}
public void createInterruptedMap() {
AffineTransform t;
LinkLayer l1 = new LinkLayer( mapLayer );
Point2D.Double in = new Point2D.Double();
Point2D.Double out = new Point2D.Double();
Point2D.Double out0 = new Point2D.Double();
Projection p = new SinusoidalProjection();
p.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
p.setMinLongitudeDegrees( -90 );
p.setMaxLongitudeDegrees( 75 );
p.setProjectionLongitudeDegrees( -90 );
in.x = -20;
in.y = 0;
p.transform(in, out);
p.setFalseEasting( out0.x-out.x );
l1.setProjection( p );
t = new AffineTransform();
t.translate( 0, -150 );
t.scale( 0.5, 0.5 );
l1.setTransform( t );
LinkLayer l2 = new LinkLayer( mapLayer );
p = new SinusoidalProjection();
p.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
p.setMinLongitudeDegrees( -85 );
p.setMaxLongitudeDegrees( 120 );
p.setProjectionLongitudeDegrees( 65 );
in.x = -20;
in.y = 0;
p.transform(in, out);
p.setFalseEasting( out0.x-out.x );
l2.setProjection( p );
l2.setTransform( t );
map.addLayer( l1 );
map.addLayer( l2 );
}
public Layer getMap() {
return map;
}
public void selectLayer( Layer layer ) {
selectedLayer = layer;
if ( layer.getProjection() != null )
mouseListener.setProjection( layer.getProjection() );
if ( layer.getTransform() != null )
zoomListener.setTransform( layer.getTransform() );
}
public void setShowWorld( boolean showWorld ) {
this.showWorld = showWorld;
}
public boolean getShowWorld() {
return showWorld;
}
public void setShowGraticule( boolean showGraticule ) {
this.showGraticule = showGraticule;
}
public boolean getShowGraticule() {
return showGraticule;
}
public void setShowDay( boolean showDay ) {
this.showDay = showDay;
}
public boolean getShowDay() {
return showDay;
}
public void setShowSea( boolean showSea ) {
this.showSea = showSea;
}
public boolean getShowSea() {
return showSea;
}
public void setShowTissot( boolean showTissot ) {
this.showTissot = showTissot;
}
public boolean getShowTissot() {
return showTissot;
}
public void setProjection( Projection projection ) {
this.projection = projection;
if ( projection != null ) {
projection.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
projection.initialize();
}
if ( selectedLayer != null )
selectedLayer.setProjection( projection );
else
map.setProjection( projection );
mouseListener.setProjection( projection );
}
public Projection getProjection() {
return projection;
}
public void print() {
try {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable( new Printable() {
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
g2d.translate(200, 300);
g2d.scale( 0.6f, 0.6f );
// Turn off double buffering
paint(g2d);
// Turn double buffering back on
return(PAGE_EXISTS);
}
}
});
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}
catch ( Exception e ) {
e.printStackTrace();
}
}
/**
* Resize the globe to fit in the given space
*/
public void resizeGlobe(double max_dimension) {
original_zoom = max_dimension/(3*globeRadius);
transform.scale(max_dimension/(3*globeRadius),max_dimension/(3*globeRadius));
}
/**
* Tell if the specified point (given by longitude, latitude coordinates) is
* visible or not.(Does not consider the scale factor that can make a visible
* point render out of the screen.
*
* @param longitude
* @param latitude
* @return if the point is visible
*/
public boolean isVisible(double longitude, double latitude) {
double mapRadiusR, distanceFromCentre;
mapRadiusR= MapMath.DTR * ((AzimuthalProjection)projection).getMapRadius();
distanceFromCentre = MapMath.greatCircleDistance(
MapMath.DTR *longitude, MapMath.DTR * latitude,
projection.getProjectionLongitude(), projection.getProjectionLatitude() );
boolean is_visible = distanceFromCentre <= mapRadiusR;
return is_visible;
}
public boolean compareProjection (Projection p1, Projection p2) {
return (p1.getPROJ4Description().equals(p2.getPROJ4Description()));
}
public void checkChanges () {
if (!transform.equals(last_transform) || !(compareProjection(projection,last_projection))) {
last_transform = (AffineTransform) transform.clone();
last_projection = (Projection) projection.clone();
last_time_update = System.currentTimeMillis();
buffered_image = null;
quality_image_buffered = false;
}
}
public boolean readyToQualityPaint() {
long time_passed = System.currentTimeMillis() - last_time_update;
return (time_passed > quality_paint_delay);
}
protected void createG2 (Graphics g) {
g2 = (Graphics2D)g;
// Put the origin at bottom left
g2.translate( 0, getHeight() );
g2.scale( 1, -1 );
// Put the globe in the middle
g2.translate( getWidth()/2, getHeight()/2 );
Point2D.Float p = new Point2D.Float( 1, 0 );
transform.deltaTransform( p, p );
float rscale = 1.0f/(float)Math.sqrt( p.x*p.x + p.y*p.y );
g2.setStroke( new BasicStroke( rscale*0.5f ) );
g2.transform( transform );
}
protected void setFastGraphics (Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED);
}
protected void setQualityGraphics (Graphics2D g) {
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );
g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
g.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
}
private void paintDay (int numPoints) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
int current_day = cal.get(Calendar.DAY_OF_YEAR);
double current_time = cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE)/60;
double fractional_year = 2 * Math.PI * (current_day + current_time/24) /365.25;
double sun_declination =
0.396372-22.91327*Math.cos(fractional_year)+ 4.02543*Math.sin(fractional_year)
-0.387205*Math.cos(2*fractional_year)+0.051967*Math.sin(2*fractional_year)
-0.154527*Math.cos(3*fractional_year) + 0.084798*Math.sin(3*fractional_year);
double sun_longitude = - (360/24)*(current_time -12);
GeneralPath gc = new GeneralPath();
ProjectionPainter.smallCircle((float) sun_longitude,(float) sun_declination, 87, numPoints, gc, true );
gc.closePath();
ProjectionPainter pp = ProjectionPainter.getProjectionPainter( projection );
pp.drawPath( g2, gc, null, day_color );
}
public void forceRefresh() {
quality_image_buffered = false;
buffered_image = null;
this.repaint();
}
private void paintFast( Graphics g ) {
createG2(g);
setFastGraphics(g2);
MapGraphics mg = MapGraphics.getGraphics( g2, new Rectangle( getSize() ) );
seaLayer.setVisible( showSea );
tissotLayer.setVisible( false );
worldLayer.setVisible( showWorld );
graticuleLayer.setVisible( false );
map.paint( mg );
if ( showDay ) paintDay(10);
}
private void paintQuality( Graphics g ) {
createG2(g);
setQualityGraphics(g2);
MapGraphics mg = MapGraphics.getGraphics( g2, new Rectangle( getSize() ) );
seaLayer.setVisible( showSea );
tissotLayer.setVisible( showTissot );
worldLayer.setVisible( showWorld );
graticuleLayer.setVisible( showGraticule );
map.paint( mg );
if ( showDay ) paintDay(100);
}
public void paint( Graphics g ) {
checkChanges();
if (!quality_image_buffered) {
if (buffered_image == null) {
//Initialize the bufferdImage
Dimension size = this.getSize();
buffered_image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
//Paint the map fast and store it
Graphics2D ng = buffered_image.createGraphics();
paintFast(ng);
ng.dispose();
quality_paint_timer.restart();
}
else if (readyToQualityPaint()) {
//Initialize the bufferdImage
Dimension size = this.getSize();
buffered_image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB);
//Paint the quality map and store it
Graphics2D ng = buffered_image.createGraphics();
paintQuality(ng);
ng.dispose();
quality_image_buffered = true;
force_repaint_timer.restart();
}
}
g.drawImage(buffered_image, 0, 0, this);
createG2(g);
}
public Dimension getPreferredSize() {
return new Dimension( 1000, 800 );
}
}
| true | true | public Globe() {
// Create the map projection
projection = new OrthographicAzimuthalProjection();
// The easiest way to scale the projection is to change the Earth's radius. We could also use an AffineTransform.
projection.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
projection.initialize();
map = new Layer();
map.setProjection( projection );
map.setTransform( transform );
map.addLayer( new BackgroundLayer() );
map.addLayer( mapLayer = new Layer() );
mapLayer.addLayer( seaLayer = new SeaLayer() );
try {
// Layer shadowLayer = new ShadowLayer();
// Layer lightLayer = new EffectLayer( new com.jhlabs.image.LightFilter() );
// map.addLayer( shadowLayer );
// shadowLayer.addLayer( lightLayer );
// map.addLayer( worldLayer = new ShapefileLayer( getClass().getResource("world.shp"), style ) );
SeaLayer seaLayer2;
mapLayer.addLayer( seaLayer2 = new SeaLayer( null ) );
seaLayer2.addLayer( worldLayer = new ShapefileLayer( getClass().getResource("world.shp"), getClass().getResource("world.dbf"), style ) );
// mapLayer.addLayer( worldLayer = new ShapefileLayer( new File("out.shp").toURL(), new Style( Color.black, null ) ) );
}
catch ( IOException e ) {
e.printStackTrace();
}
mapLayer.addLayer( graticuleLayer = new GraticuleLayer() );
mapLayer.addLayer( tissotLayer = new TissotLayer() );
tissotLayer.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.5f) );
linkLayer = new LinkLayer( worldLayer );
// createInterruptedMap();
// map.addLayer( linkLayer );
AffineTransform t = new AffineTransform();
t.translate( 100, 100 );
linkLayer.setTransform( t );
linkLayer.setStyle( new Style( Color.black, Color.orange ) );
Projection lp = new OrthographicAzimuthalProjection();
linkLayer.setProjection( lp );
lp.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
lp.initialize();
int index = 0;
for ( Iterator it = worldLayer.getFeaturesIterator(); it.hasNext(); ) {
Feature feature = (Feature)it.next();
if ( !(feature instanceof PointFeature) )//FIXME
feature.setStyle( styles[index++ % styles.length] );
}
// Add the virtual trackball
addMouseListener( mouseListener = new ProjectionMouseListener( this, projection, transform ) );
addMouseListener( zoomListener = new PanZoomMouseListener( this, transform ) );
//Add the mousewheel listener
addMouseWheelListener(
new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
int steps = e.getWheelRotation();
mouseZoom(-steps);
}
}
);
//Setting up the timer that forces a quality paint after a short idle time
//This one is used to transition from fast to quality draw
quality_paint_timer = new Timer(42,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Globe.this.repaint();
}
});
quality_paint_timer.setRepeats(false);
quality_paint_timer.setInitialDelay(quality_paint_delay);
//Setting up the other timer that forces a repaint after a long idle time
//This one is essentially used to refresh the night
force_repaint_timer = new Timer(42,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
quality_image_buffered = false;
Globe.this.repaint();
}
});
force_repaint_timer.setRepeats(false);
force_repaint_timer.setInitialDelay(force_repaint_delay);
}
| public Globe() {
// Create the map projection
projection = new OrthographicAzimuthalProjection();
// The easiest way to scale the projection is to change the Earth's radius. We could also use an AffineTransform.
projection.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
projection.initialize();
map = new Layer();
map.setProjection( projection );
map.setTransform( transform );
map.addLayer( new BackgroundLayer() );
map.addLayer( mapLayer = new Layer() );
mapLayer.addLayer( seaLayer = new SeaLayer() );
try {
// Layer shadowLayer = new ShadowLayer();
// Layer lightLayer = new EffectLayer( new com.jhlabs.image.LightFilter() );
// map.addLayer( shadowLayer );
// shadowLayer.addLayer( lightLayer );
// map.addLayer( worldLayer = new ShapefileLayer( getClass().getResource("world.shp"), style ) );
SeaLayer seaLayer2;
mapLayer.addLayer( seaLayer2 = new SeaLayer( null ) );
seaLayer2.addLayer( worldLayer = new ShapefileLayer( getClass().getResource("world.shp"), getClass().getResource("world.dbf"), style ) );
// mapLayer.addLayer( worldLayer = new ShapefileLayer( new File("out.shp").toURL(), new Style( Color.black, null ) ) );
}
catch ( IOException e ) {
e.printStackTrace();
}
mapLayer.addLayer( graticuleLayer = new GraticuleLayer() );
mapLayer.addLayer( tissotLayer = new TissotLayer() );
tissotLayer.setComposite( AlphaComposite.getInstance( AlphaComposite.SRC_OVER, 0.5f) );
linkLayer = new LinkLayer( worldLayer );
// createInterruptedMap();
// map.addLayer( linkLayer );
AffineTransform t = new AffineTransform();
t.translate( 100, 100 );
linkLayer.setTransform( t );
linkLayer.setStyle( new Style( Color.black, Color.orange ) );
Projection lp = new OrthographicAzimuthalProjection();
linkLayer.setProjection( lp );
lp.setEllipsoid( new Ellipsoid("", globeRadius, globeRadius, 0, "") );
lp.initialize();
int index = 0;
for ( Iterator it = worldLayer.getFeaturesIterator(); it.hasNext(); ) {
Feature feature = (Feature)it.next();
if ( !(feature instanceof PointFeature) )//FIXME
feature.setStyle( styles[index++ % styles.length] );
}
// Add the virtual trackball
addMouseListener( mouseListener = new ProjectionMouseListener( this, projection, transform ) );
addMouseListener( zoomListener = new PanZoomMouseListener( this, transform ) );
//Add the mousewheel listener.
//We don't use the mousewheel to zoom in/out the globe as the
//browser also catch it and we end up zooming and scrolling on
//Windows!
if (false){
addMouseWheelListener(
new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
int steps = e.getWheelRotation();
mouseZoom(-steps);
}
}
);
}else{
addMouseWheelListener(
new MouseWheelListener() {
public void mouseWheelMoved(MouseWheelEvent e) {
mouseZoom(0);// to force a repaint.
}
}
);
}
//Setting up the timer that forces a quality paint after a short idle time
//This one is used to transition from fast to quality draw
quality_paint_timer = new Timer(42,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Globe.this.repaint();
}
});
quality_paint_timer.setRepeats(false);
quality_paint_timer.setInitialDelay(quality_paint_delay);
//Setting up the other timer that forces a repaint after a long idle time
//This one is essentially used to refresh the night
force_repaint_timer = new Timer(42,new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
quality_image_buffered = false;
Globe.this.repaint();
}
});
force_repaint_timer.setRepeats(false);
force_repaint_timer.setInitialDelay(force_repaint_delay);
}
|
diff --git a/src/main/java/mx/edu/um/mateo/general/web/TipoClienteController.java b/src/main/java/mx/edu/um/mateo/general/web/TipoClienteController.java
index b2958994..ac8eae7b 100644
--- a/src/main/java/mx/edu/um/mateo/general/web/TipoClienteController.java
+++ b/src/main/java/mx/edu/um/mateo/general/web/TipoClienteController.java
@@ -1,304 +1,308 @@
/*
* The MIT License
*
* Copyright 2012 J. David Mendoza <[email protected]>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package mx.edu.um.mateo.general.web;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.mail.util.ByteArrayDataSource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import mx.edu.um.mateo.general.dao.TipoClienteDao;
import mx.edu.um.mateo.general.model.TipoCliente;
import mx.edu.um.mateo.general.model.Usuario;
import mx.edu.um.mateo.general.utils.Ambiente;
import mx.edu.um.mateo.general.utils.ReporteUtil;
import net.sf.jasperreports.engine.JRException;
import org.apache.commons.lang.StringUtils;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
/**
*
* @author J. David Mendoza <[email protected]>
*/
@Controller
@RequestMapping("/admin/tipoCliente")
public class TipoClienteController {
private static final Logger log = LoggerFactory.getLogger(TipoClienteController.class);
@Autowired
private TipoClienteDao tipoClienteDao;
@Autowired
private JavaMailSender mailSender;
@Autowired
private ResourceBundleMessageSource messageSource;
@Autowired
private Ambiente ambiente;
@Autowired
private ReporteUtil reporteUtil;
@RequestMapping
public String lista(HttpServletRequest request, HttpServletResponse response,
@RequestParam(required = false) String filtro,
@RequestParam(required = false) Long pagina,
@RequestParam(required = false) String tipo,
@RequestParam(required = false) String correo,
@RequestParam(required = false) String order,
@RequestParam(required = false) String sort,
+ Usuario usuario,
+ Errors errors,
Model modelo) {
log.debug("Mostrando lista de tipos de clientes");
Map<String, Object> params = new HashMap<>();
params.put("empresa", request.getSession().getAttribute("empresaId"));
if (StringUtils.isNotBlank(filtro)) {
params.put("filtro", filtro);
}
if (pagina != null) {
params.put("pagina", pagina);
modelo.addAttribute("pagina", pagina);
} else {
pagina = 1L;
modelo.addAttribute("pagina", pagina);
}
if (StringUtils.isNotBlank(order)) {
params.put("order", order);
params.put("sort", sort);
}
if (StringUtils.isNotBlank(tipo)) {
params.put("reporte", true);
params = tipoClienteDao.lista(params);
try {
generaReporte(tipo, (List<TipoCliente>) params.get("tiposDeCliente"), response);
return null;
} catch (JRException | IOException e) {
log.error("No se pudo generar el reporte", e);
+ params.remove("reporte");
+ errors.reject("error.generar.reporte");
}
}
if (StringUtils.isNotBlank(correo)) {
params.put("reporte", true);
params = tipoClienteDao.lista(params);
params.remove("reporte");
try {
enviaCorreo(correo, (List<TipoCliente>) params.get("tiposDeCliente"), request);
modelo.addAttribute("message", "lista.enviado.message");
modelo.addAttribute("messageAttrs", new String[]{messageSource.getMessage("tipoCliente.lista.label", null, request.getLocale()), ambiente.obtieneUsuario().getUsername()});
} catch (JRException | MessagingException e) {
log.error("No se pudo enviar el reporte por correo", e);
}
}
params = tipoClienteDao.lista(params);
modelo.addAttribute("tiposDeCliente", params.get("tiposDeCliente"));
// inicia paginado
Long cantidad = (Long) params.get("cantidad");
Integer max = (Integer) params.get("max");
Long cantidadDePaginas = cantidad / max;
List<Long> paginas = new ArrayList<>();
long i = 1;
do {
paginas.add(i);
} while (i++ < cantidadDePaginas);
List<TipoCliente> tiposDeCliente = (List<TipoCliente>) params.get("tiposDeCliente");
Long primero = ((pagina - 1) * max) + 1;
Long ultimo = primero + (tiposDeCliente.size() - 1);
String[] paginacion = new String[]{primero.toString(), ultimo.toString(), cantidad.toString()};
modelo.addAttribute("paginacion", paginacion);
modelo.addAttribute("paginas", paginas);
// termina paginado
return "admin/tipoCliente/lista";
}
@RequestMapping("/ver/{id}")
public String ver(@PathVariable Long id, Model modelo) {
log.debug("Mostrando tipoCliente {}", id);
TipoCliente tipoCliente = tipoClienteDao.obtiene(id);
modelo.addAttribute("tipoCliente", tipoCliente);
return "admin/tipoCliente/ver";
}
@RequestMapping("/nuevo")
public String nuevo(Model modelo) {
log.debug("Nuevo tipoCliente");
TipoCliente tipoCliente = new TipoCliente();
modelo.addAttribute("tipoCliente", tipoCliente);
return "admin/tipoCliente/nuevo";
}
@Transactional
@RequestMapping(value = "/crea", method = RequestMethod.POST)
public String crea(HttpServletRequest request, HttpServletResponse response, @Valid TipoCliente tipoCliente, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
for (String nombre : request.getParameterMap().keySet()) {
log.debug("Param: {} : {}", nombre, request.getParameterMap().get(nombre));
}
if (bindingResult.hasErrors()) {
log.debug("Hubo algun error en la forma, regresando");
return "admin/tipoCliente/nuevo";
}
try {
Usuario usuario = ambiente.obtieneUsuario();
tipoCliente = tipoClienteDao.crea(tipoCliente, usuario);
} catch (ConstraintViolationException e) {
log.error("No se pudo crear al tipoCliente", e);
errors.rejectValue("nombre", "campo.duplicado.message", new String[]{"nombre"}, null);
return "admin/tipoCliente/nuevo";
}
redirectAttributes.addFlashAttribute("message", "tipoCliente.creado.message");
redirectAttributes.addFlashAttribute("messageAttrs", new String[]{tipoCliente.getNombre()});
return "redirect:/admin/tipoCliente/ver/" + tipoCliente.getId();
}
@RequestMapping("/edita/{id}")
public String edita(@PathVariable Long id, Model modelo) {
log.debug("Edita tipoCliente {}", id);
TipoCliente tipoCliente = tipoClienteDao.obtiene(id);
modelo.addAttribute("tipoCliente", tipoCliente);
return "admin/tipoCliente/edita";
}
@Transactional
@RequestMapping(value = "/actualiza", method = RequestMethod.POST)
public String actualiza(HttpServletRequest request, @Valid TipoCliente tipoCliente, BindingResult bindingResult, Errors errors, Model modelo, RedirectAttributes redirectAttributes) {
if (bindingResult.hasErrors()) {
log.error("Hubo algun error en la forma, regresando");
return "admin/tipoCliente/edita";
}
try {
Usuario usuario = ambiente.obtieneUsuario();
tipoCliente = tipoClienteDao.actualiza(tipoCliente, usuario);
} catch (ConstraintViolationException e) {
log.error("No se pudo crear la tipoCliente", e);
errors.rejectValue("nombre", "campo.duplicado.message", new String[]{"nombre"}, null);
return "admin/tipoCliente/nuevo";
}
redirectAttributes.addFlashAttribute("message", "tipoCliente.actualizado.message");
redirectAttributes.addFlashAttribute("messageAttrs", new String[]{tipoCliente.getNombre()});
return "redirect:/admin/tipoCliente/ver/" + tipoCliente.getId();
}
@Transactional
@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo, @ModelAttribute TipoCliente tipoCliente, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
log.debug("Elimina tipoCliente");
try {
String nombre = tipoClienteDao.elimina(id);
redirectAttributes.addFlashAttribute("message", "tipoCliente.eliminado.message");
redirectAttributes.addFlashAttribute("messageAttrs", new String[]{nombre});
} catch (Exception e) {
log.error("No se pudo eliminar la tipoCliente " + id, e);
bindingResult.addError(new ObjectError("tipoCliente", new String[]{"tipoCliente.no.eliminado.message"}, null, null));
return "admin/tipoCliente/ver";
}
return "redirect:/admin/tipoCliente";
}
private void generaReporte(String tipo, List<TipoCliente> tiposDeCliente, HttpServletResponse response) throws JRException, IOException {
log.debug("Generando reporte {}", tipo);
byte[] archivo = null;
switch (tipo) {
case "PDF":
archivo = reporteUtil.generaPdf(tiposDeCliente, "/mx/edu/um/mateo/general/reportes/tiposDeCliente.jrxml");
response.setContentType("application/pdf");
response.addHeader("Content-Disposition", "attachment; filename=tiposDeCliente.pdf");
break;
case "CSV":
archivo = reporteUtil.generaCsv(tiposDeCliente, "/mx/edu/um/mateo/general/reportes/tiposDeCliente.jrxml");
response.setContentType("text/csv");
response.addHeader("Content-Disposition", "attachment; filename=tiposDeCliente.csv");
break;
case "XLS":
archivo = reporteUtil.generaXls(tiposDeCliente, "/mx/edu/um/mateo/general/reportes/tiposDeCliente.jrxml");
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=tiposDeCliente.xls");
}
if (archivo != null) {
response.setContentLength(archivo.length);
try (BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream())) {
bos.write(archivo);
bos.flush();
}
}
}
private void enviaCorreo(String tipo, List<TipoCliente> tiposDeCliente, HttpServletRequest request) throws JRException, MessagingException {
log.debug("Enviando correo {}", tipo);
byte[] archivo = null;
String tipoContenido = null;
switch (tipo) {
case "PDF":
archivo = reporteUtil.generaPdf(tiposDeCliente, "/mx/edu/um/mateo/general/reportes/tiposDeCliente.jrxml");
tipoContenido = "application/pdf";
break;
case "CSV":
archivo = reporteUtil.generaCsv(tiposDeCliente, "/mx/edu/um/mateo/general/reportes/tiposDeCliente.jrxml");
tipoContenido = "text/csv";
break;
case "XLS":
archivo = reporteUtil.generaXls(tiposDeCliente, "/mx/edu/um/mateo/general/reportes/tiposDeCliente.jrxml");
tipoContenido = "application/vnd.ms-excel";
}
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(ambiente.obtieneUsuario().getUsername());
String titulo = messageSource.getMessage("tipoCliente.lista.label", null, request.getLocale());
helper.setSubject(messageSource.getMessage("envia.correo.titulo.message", new String[]{titulo}, request.getLocale()));
helper.setText(messageSource.getMessage("envia.correo.contenido.message", new String[]{titulo}, request.getLocale()), true);
helper.addAttachment(titulo + "." + tipo, new ByteArrayDataSource(archivo, tipoContenido));
mailSender.send(message);
}
}
| false | true | public String lista(HttpServletRequest request, HttpServletResponse response,
@RequestParam(required = false) String filtro,
@RequestParam(required = false) Long pagina,
@RequestParam(required = false) String tipo,
@RequestParam(required = false) String correo,
@RequestParam(required = false) String order,
@RequestParam(required = false) String sort,
Model modelo) {
log.debug("Mostrando lista de tipos de clientes");
Map<String, Object> params = new HashMap<>();
params.put("empresa", request.getSession().getAttribute("empresaId"));
if (StringUtils.isNotBlank(filtro)) {
params.put("filtro", filtro);
}
if (pagina != null) {
params.put("pagina", pagina);
modelo.addAttribute("pagina", pagina);
} else {
pagina = 1L;
modelo.addAttribute("pagina", pagina);
}
if (StringUtils.isNotBlank(order)) {
params.put("order", order);
params.put("sort", sort);
}
if (StringUtils.isNotBlank(tipo)) {
params.put("reporte", true);
params = tipoClienteDao.lista(params);
try {
generaReporte(tipo, (List<TipoCliente>) params.get("tiposDeCliente"), response);
return null;
} catch (JRException | IOException e) {
log.error("No se pudo generar el reporte", e);
}
}
if (StringUtils.isNotBlank(correo)) {
params.put("reporte", true);
params = tipoClienteDao.lista(params);
params.remove("reporte");
try {
enviaCorreo(correo, (List<TipoCliente>) params.get("tiposDeCliente"), request);
modelo.addAttribute("message", "lista.enviado.message");
modelo.addAttribute("messageAttrs", new String[]{messageSource.getMessage("tipoCliente.lista.label", null, request.getLocale()), ambiente.obtieneUsuario().getUsername()});
} catch (JRException | MessagingException e) {
log.error("No se pudo enviar el reporte por correo", e);
}
}
| public String lista(HttpServletRequest request, HttpServletResponse response,
@RequestParam(required = false) String filtro,
@RequestParam(required = false) Long pagina,
@RequestParam(required = false) String tipo,
@RequestParam(required = false) String correo,
@RequestParam(required = false) String order,
@RequestParam(required = false) String sort,
Usuario usuario,
Errors errors,
Model modelo) {
log.debug("Mostrando lista de tipos de clientes");
Map<String, Object> params = new HashMap<>();
params.put("empresa", request.getSession().getAttribute("empresaId"));
if (StringUtils.isNotBlank(filtro)) {
params.put("filtro", filtro);
}
if (pagina != null) {
params.put("pagina", pagina);
modelo.addAttribute("pagina", pagina);
} else {
pagina = 1L;
modelo.addAttribute("pagina", pagina);
}
if (StringUtils.isNotBlank(order)) {
params.put("order", order);
params.put("sort", sort);
}
if (StringUtils.isNotBlank(tipo)) {
params.put("reporte", true);
params = tipoClienteDao.lista(params);
try {
generaReporte(tipo, (List<TipoCliente>) params.get("tiposDeCliente"), response);
return null;
} catch (JRException | IOException e) {
log.error("No se pudo generar el reporte", e);
params.remove("reporte");
errors.reject("error.generar.reporte");
}
}
if (StringUtils.isNotBlank(correo)) {
params.put("reporte", true);
params = tipoClienteDao.lista(params);
params.remove("reporte");
try {
enviaCorreo(correo, (List<TipoCliente>) params.get("tiposDeCliente"), request);
modelo.addAttribute("message", "lista.enviado.message");
modelo.addAttribute("messageAttrs", new String[]{messageSource.getMessage("tipoCliente.lista.label", null, request.getLocale()), ambiente.obtieneUsuario().getUsername()});
} catch (JRException | MessagingException e) {
log.error("No se pudo enviar el reporte por correo", e);
}
}
|
diff --git a/job/controller/src/main/java/org/talend/esb/job/controller/internal/RuntimeESBConsumer.java b/job/controller/src/main/java/org/talend/esb/job/controller/internal/RuntimeESBConsumer.java
index c4b5b35da..f79c725c9 100644
--- a/job/controller/src/main/java/org/talend/esb/job/controller/internal/RuntimeESBConsumer.java
+++ b/job/controller/src/main/java/org/talend/esb/job/controller/internal/RuntimeESBConsumer.java
@@ -1,379 +1,381 @@
/*
* #%L
* Talend :: ESB :: Job :: Controller
* %%
* Copyright (C) 2011 - 2012 Talend Inc.
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.talend.esb.job.controller.internal;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPFault;
import javax.xml.transform.Source;
import javax.xml.validation.Schema;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.soap.SOAPFaultException;
import org.apache.cxf.Bus;
import org.apache.cxf.BusException;
import org.apache.cxf.bus.spring.SpringBusFactory;
import org.apache.cxf.configuration.security.AuthorizationPolicy;
import org.apache.cxf.databinding.source.SourceDataBinding;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.endpoint.EndpointException;
import org.apache.cxf.feature.Feature;
import org.apache.cxf.frontend.ClientFactoryBean;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.jaxws.JaxWsClientFactoryBean;
import org.apache.cxf.message.Message;
import org.apache.cxf.service.Service;
import org.apache.cxf.service.model.InterfaceInfo;
import org.apache.cxf.service.model.ServiceInfo;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.ws.policy.WSPolicyFeature;
import org.apache.cxf.ws.security.SecurityConstants;
import org.apache.cxf.ws.security.trust.STSClient;
import org.apache.cxf.wsdl.EndpointReferenceUtils;
import org.talend.esb.job.controller.ESBEndpointConstants;
import org.talend.esb.job.controller.ESBEndpointConstants.EsbSecurity;
import org.talend.esb.job.controller.internal.util.DOM4JMarshaller;
import org.talend.esb.job.controller.internal.util.ServiceHelper;
import org.talend.esb.policy.correlation.feature.CorrelationIDFeature;
import org.talend.esb.sam.agent.feature.EventFeature;
import org.talend.esb.sam.common.handler.impl.CustomInfoHandler;
import org.talend.esb.servicelocator.cxf.LocatorFeature;
import routines.system.api.ESBConsumer;
//@javax.jws.WebService()
public class RuntimeESBConsumer implements ESBConsumer {
private static final Logger LOG = Logger.getLogger(RuntimeESBConsumer.class
.getName());
private static final String STS_WSDL_LOCATION = "sts.wsdl.location";
private static final String STS_X509_WSDL_LOCATION = "sts.x509.wsdl.location";
private static final String STS_NAMESPACE = "sts.namespace";
private static final String STS_SERVICE_NAME = "sts.service.name";
private static final String STS_ENDPOINT_NAME = "sts.endpoint.name";
private static final String STS_X509_ENDPOINT_NAME = "sts.x509.endpoint.name";
private static final String CONSUMER_SIGNATURE_PASSWORD =
"ws-security.signature.password";
private final String operationName;
private final boolean isRequestResponse;
private final EventFeature samFeature;
private final String soapAction;
private final List<Header> soapHeaders;
private AuthorizationPolicy authorizationPolicy;
private final ClientFactoryBean clientFactory;
private Client client;
private STSClient stsClient;
private boolean enhancedResponse;
RuntimeESBConsumer(final QName serviceName,
final QName portName,
String operationName,
String publishedEndpointUrl,
String wsdlURL,
boolean isRequestResponse,
final LocatorFeature slFeature,
final EventFeature samFeature,
boolean useServiceRegistry,
final SecurityArguments securityArguments,
Bus bus,
boolean logging,
String soapAction,
final List<Header> soapHeaders,
boolean enhancedResponse,
Object correlationIDCallbackHandler) {
this.operationName = operationName;
this.isRequestResponse = isRequestResponse;
this.samFeature = samFeature;
this.soapAction = soapAction;
this.soapHeaders = soapHeaders;
this.enhancedResponse = enhancedResponse;
clientFactory = new JaxWsClientFactoryBean() {
@Override
protected Endpoint createEndpoint() throws BusException,
EndpointException {
final Endpoint endpoint = super.createEndpoint();
// set portType = serviceName
InterfaceInfo ii = endpoint.getService().getServiceInfos()
.get(0).getInterface();
ii.setName(serviceName);
return endpoint;
}
};
clientFactory.setServiceName(serviceName);
clientFactory.setEndpointName(portName);
final String endpointUrl = (slFeature == null) ? publishedEndpointUrl
: "locator://" + serviceName.getLocalPart();
- clientFactory.setAddress(endpointUrl);
- if (null != wsdlURL) {
+ if (!useServiceRegistry) {
+ clientFactory.setAddress(endpointUrl);
+ }
+ if (!useServiceRegistry && null != wsdlURL) {
clientFactory.setWsdlURL(wsdlURL);
}
clientFactory.setServiceClass(this.getClass());
//for TESB-9006, create new bus when registry enabled but no wsdl-client/policy-client
//extension set on the old bus. (used to instead the action of refresh job controller bundle.
if (useServiceRegistry && !hasRegistryClientExtension(bus)) {
SpringBusFactory sbf = new SpringBusFactory();
bus = sbf.createBus();
}
clientFactory.setBus(bus);
final List<Feature> features = new ArrayList<Feature>();
if (slFeature != null) {
features.add(slFeature);
}
if (samFeature != null) {
features.add(samFeature);
}
if (correlationIDCallbackHandler != null && (!useServiceRegistry)) {
features.add(new CorrelationIDFeature());
}
if (null != securityArguments.getPolicy()) {
features.add(new WSPolicyFeature(securityArguments.getPolicy()));
}
if (logging) {
features.add(new org.apache.cxf.feature.LoggingFeature());
}
clientFactory.setFeatures(features);
Map<String, Object> clientProps = new HashMap<String, Object>();
if (EsbSecurity.BASIC == securityArguments.getEsbSecurity()) {
authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setUserName(securityArguments.getUsername());
authorizationPolicy.setPassword(securityArguments.getPassword());
authorizationPolicy.setAuthorizationType("Basic");
} else if (EsbSecurity.DIGEST == securityArguments.getEsbSecurity()) {
authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setUserName(securityArguments.getUsername());
authorizationPolicy.setPassword(securityArguments.getPassword());
authorizationPolicy.setAuthorizationType("Digest");
}
if (EsbSecurity.TOKEN == securityArguments.getEsbSecurity() || useServiceRegistry) {
clientProps.put(SecurityConstants.USERNAME, securityArguments.getUsername());
clientProps.put(SecurityConstants.PASSWORD, securityArguments.getPassword());
}
if (EsbSecurity.SAML == securityArguments.getEsbSecurity() || useServiceRegistry) {
final Map<String, String> stsPropsDef = securityArguments.getStsProperties();
stsClient = new STSClient(bus);
stsClient.setServiceQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_SERVICE_NAME)));
Map<String, Object> stsProps = new HashMap<String, Object>();
for (Map.Entry<String, String> entry : stsPropsDef.entrySet()) {
if (SecurityConstants.ALL_PROPERTIES.contains(entry.getKey())) {
stsProps.put(entry.getKey(), processFileURI(entry.getValue()));
}
}
if (null == securityArguments.getAlias()) {
stsClient.setWsdlLocation(stsPropsDef.get(STS_WSDL_LOCATION));
stsClient.setEndpointQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_ENDPOINT_NAME)));
stsProps.put(SecurityConstants.USERNAME, securityArguments.getUsername());
stsProps.put(SecurityConstants.PASSWORD, securityArguments.getPassword());
} else {
stsClient.setWsdlLocation(stsPropsDef.get(STS_X509_WSDL_LOCATION));
stsClient.setEndpointQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_X509_ENDPOINT_NAME)));
stsProps.put(SecurityConstants.STS_TOKEN_USERNAME, securityArguments.getAlias());
}
if (null != securityArguments.getRoleName() && securityArguments.getRoleName().length() != 0) {
ClaimValueCallbackHandler roleCallbackHandler = new ClaimValueCallbackHandler();
roleCallbackHandler.setClaimValue(securityArguments.getRoleName());
stsClient.setClaimsCallbackHandler(roleCallbackHandler);
}
if (null != securityArguments.getSecurityToken()) {
stsClient.setOnBehalfOf(securityArguments.getSecurityToken());
}
stsClient.setProperties(stsProps);
clientProps.put(SecurityConstants.STS_CLIENT, stsClient);
Map<String, String> clientPropsDef = securityArguments.getClientProperties();
for (Map.Entry<String, String> entry : clientPropsDef.entrySet()) {
if (SecurityConstants.ALL_PROPERTIES.contains(entry.getKey())) {
clientProps.put(entry.getKey(), processFileURI(entry.getValue()));
}
}
if (null == securityArguments.getAlias()) {
clientProps.put(SecurityConstants.CALLBACK_HANDLER,
new WSPasswordCallbackHandler(
clientPropsDef.get(SecurityConstants.SIGNATURE_USERNAME),
clientPropsDef.get(CONSUMER_SIGNATURE_PASSWORD)));
} else {
clientProps.put(SecurityConstants.SIGNATURE_USERNAME, securityArguments.getAlias());
clientProps.put(SecurityConstants.CALLBACK_HANDLER,
new WSPasswordCallbackHandler(
securityArguments.getAlias(),
securityArguments.getPassword()));
}
if (null != securityArguments.getCryptoProvider()) {
clientProps.put(SecurityConstants.ENCRYPT_CRYPTO, securityArguments.getCryptoProvider());
}
Object encryptUsername = clientProps.get(SecurityConstants.ENCRYPT_USERNAME);
if (encryptUsername == null || encryptUsername.toString().isEmpty()) {
clientProps.put(SecurityConstants.ENCRYPT_USERNAME, serviceName.toString());
}
}
clientProps.put("soap.no.validate.parts", Boolean.TRUE);
clientProps.put(ESBEndpointConstants.USE_SERVICE_REGISTRY_PROP,
Boolean.toString(useServiceRegistry));
if (correlationIDCallbackHandler != null) {
clientProps.put(
CorrelationIDFeature.CORRELATION_ID_CALLBACK_HANDLER, correlationIDCallbackHandler);
}
clientFactory.setProperties(clientProps);
}
@Override
@SuppressWarnings("unchecked")
public Object invoke(Object payload) throws Exception {
if (payload instanceof org.dom4j.Document) {
return sendDocument((org.dom4j.Document) payload);
} else if (payload instanceof java.util.Map) {
Map<?, ?> map = (Map<?, ?>) payload;
if (samFeature != null) {
Object samProps = map.get(ESBEndpointConstants.REQUEST_SAM_PROPS);
if (samProps != null) {
LOG.info("SAM custom properties received: " + samProps);
CustomInfoHandler ciHandler = new CustomInfoHandler();
ciHandler.setCustomInfo((Map<String, String>)samProps);
samFeature.setHandler(ciHandler);
}
}
return sendDocument((org.dom4j.Document) map
.get(ESBEndpointConstants.REQUEST_PAYLOAD));
} else {
throw new RuntimeException(
"Consumer try to send incompatible object: "
+ payload.getClass().getName());
}
}
private Object sendDocument(org.dom4j.Document doc) throws Exception {
Client client = getClient();
if (null != soapHeaders) {
client.getRequestContext().put(org.apache.cxf.headers.Header.HEADER_LIST, soapHeaders);
}
try {
//workaround for CXF-5169
Object svObj = client.getRequestContext().get(Message.SCHEMA_VALIDATION_ENABLED);
if (svObj instanceof String && ((String) svObj).equalsIgnoreCase("OUT")) {
//Service service = ServiceModelUtil.getService(message.getExchange());
Schema schema = EndpointReferenceUtils.getSchema(client.getEndpoint().getService().getServiceInfos().get(0),
client.getBus());
if (null != schema) {
schema.newValidator().validate(DOM4JMarshaller.documentToSource(doc));
}
}
Object[] result = client.invoke(operationName, DOM4JMarshaller.documentToSource(doc));
if (result != null) {
org.dom4j.Document response = DOM4JMarshaller.sourceToDocument((Source) result[0]);
if(enhancedResponse) {
Map<String, Object> enhancedBody = new HashMap<String, Object>();
enhancedBody.put("payload", response);
enhancedBody.put(CorrelationIDFeature.MESSAGE_CORRELATION_ID, client.getResponseContext().get(CorrelationIDFeature.MESSAGE_CORRELATION_ID));
return enhancedBody;
} else {
return response;
}
}
} catch (org.apache.cxf.binding.soap.SoapFault e) {
SOAPFault soapFault = ServiceHelper.createSoapFault(e);
if (soapFault == null) {
throw new WebServiceException(e);
}
SOAPFaultException exception = new SOAPFaultException(soapFault);
if (e instanceof Fault && e.getCause() != null) {
exception.initCause(e.getCause());
} else {
exception.initCause(e);
}
throw exception;
}
return null;
}
private Client getClient() throws BusException, EndpointException {
if (client == null) {
client = clientFactory.create();
//fix TESB-11750
Object isAuthzPolicyApplied = client.getRequestContext().get("isAuthzPolicyApplied");
if (null != stsClient && isAuthzPolicyApplied instanceof String &&
((String) isAuthzPolicyApplied).equals("false")) {
stsClient.setClaimsCallbackHandler(null);
}
if (null != authorizationPolicy) {
HTTPConduit conduit = (HTTPConduit) client.getConduit();
conduit.setAuthorization(authorizationPolicy);
}
final Service service = client.getEndpoint().getService();
service.setDataBinding(new SourceDataBinding());
final ServiceInfo si = service.getServiceInfos().get(0);
ServiceHelper.addOperation(si, operationName, isRequestResponse, soapAction);
}
return client;
}
private boolean hasRegistryClientExtension(Bus bus) {
return (bus.hasExtensionByName("org.talend.esb.registry.client.wsdl.RegistryFactoryBeanListener")
|| bus.hasExtensionByName("org.talend.esb.registry.client.policy.RegistryFactoryBeanListener"));
}
private static Object processFileURI(String fileURI) {
if (fileURI.startsWith("file:")) {
try {
return new URL(fileURI);
} catch (MalformedURLException e) {
}
}
return fileURI;
}
}
| true | true | RuntimeESBConsumer(final QName serviceName,
final QName portName,
String operationName,
String publishedEndpointUrl,
String wsdlURL,
boolean isRequestResponse,
final LocatorFeature slFeature,
final EventFeature samFeature,
boolean useServiceRegistry,
final SecurityArguments securityArguments,
Bus bus,
boolean logging,
String soapAction,
final List<Header> soapHeaders,
boolean enhancedResponse,
Object correlationIDCallbackHandler) {
this.operationName = operationName;
this.isRequestResponse = isRequestResponse;
this.samFeature = samFeature;
this.soapAction = soapAction;
this.soapHeaders = soapHeaders;
this.enhancedResponse = enhancedResponse;
clientFactory = new JaxWsClientFactoryBean() {
@Override
protected Endpoint createEndpoint() throws BusException,
EndpointException {
final Endpoint endpoint = super.createEndpoint();
// set portType = serviceName
InterfaceInfo ii = endpoint.getService().getServiceInfos()
.get(0).getInterface();
ii.setName(serviceName);
return endpoint;
}
};
clientFactory.setServiceName(serviceName);
clientFactory.setEndpointName(portName);
final String endpointUrl = (slFeature == null) ? publishedEndpointUrl
: "locator://" + serviceName.getLocalPart();
clientFactory.setAddress(endpointUrl);
if (null != wsdlURL) {
clientFactory.setWsdlURL(wsdlURL);
}
clientFactory.setServiceClass(this.getClass());
//for TESB-9006, create new bus when registry enabled but no wsdl-client/policy-client
//extension set on the old bus. (used to instead the action of refresh job controller bundle.
if (useServiceRegistry && !hasRegistryClientExtension(bus)) {
SpringBusFactory sbf = new SpringBusFactory();
bus = sbf.createBus();
}
clientFactory.setBus(bus);
final List<Feature> features = new ArrayList<Feature>();
if (slFeature != null) {
features.add(slFeature);
}
if (samFeature != null) {
features.add(samFeature);
}
if (correlationIDCallbackHandler != null && (!useServiceRegistry)) {
features.add(new CorrelationIDFeature());
}
if (null != securityArguments.getPolicy()) {
features.add(new WSPolicyFeature(securityArguments.getPolicy()));
}
if (logging) {
features.add(new org.apache.cxf.feature.LoggingFeature());
}
clientFactory.setFeatures(features);
Map<String, Object> clientProps = new HashMap<String, Object>();
if (EsbSecurity.BASIC == securityArguments.getEsbSecurity()) {
authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setUserName(securityArguments.getUsername());
authorizationPolicy.setPassword(securityArguments.getPassword());
authorizationPolicy.setAuthorizationType("Basic");
} else if (EsbSecurity.DIGEST == securityArguments.getEsbSecurity()) {
authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setUserName(securityArguments.getUsername());
authorizationPolicy.setPassword(securityArguments.getPassword());
authorizationPolicy.setAuthorizationType("Digest");
}
if (EsbSecurity.TOKEN == securityArguments.getEsbSecurity() || useServiceRegistry) {
clientProps.put(SecurityConstants.USERNAME, securityArguments.getUsername());
clientProps.put(SecurityConstants.PASSWORD, securityArguments.getPassword());
}
if (EsbSecurity.SAML == securityArguments.getEsbSecurity() || useServiceRegistry) {
final Map<String, String> stsPropsDef = securityArguments.getStsProperties();
stsClient = new STSClient(bus);
stsClient.setServiceQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_SERVICE_NAME)));
Map<String, Object> stsProps = new HashMap<String, Object>();
for (Map.Entry<String, String> entry : stsPropsDef.entrySet()) {
if (SecurityConstants.ALL_PROPERTIES.contains(entry.getKey())) {
stsProps.put(entry.getKey(), processFileURI(entry.getValue()));
}
}
if (null == securityArguments.getAlias()) {
stsClient.setWsdlLocation(stsPropsDef.get(STS_WSDL_LOCATION));
stsClient.setEndpointQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_ENDPOINT_NAME)));
stsProps.put(SecurityConstants.USERNAME, securityArguments.getUsername());
stsProps.put(SecurityConstants.PASSWORD, securityArguments.getPassword());
} else {
stsClient.setWsdlLocation(stsPropsDef.get(STS_X509_WSDL_LOCATION));
stsClient.setEndpointQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_X509_ENDPOINT_NAME)));
stsProps.put(SecurityConstants.STS_TOKEN_USERNAME, securityArguments.getAlias());
}
if (null != securityArguments.getRoleName() && securityArguments.getRoleName().length() != 0) {
ClaimValueCallbackHandler roleCallbackHandler = new ClaimValueCallbackHandler();
roleCallbackHandler.setClaimValue(securityArguments.getRoleName());
stsClient.setClaimsCallbackHandler(roleCallbackHandler);
}
if (null != securityArguments.getSecurityToken()) {
stsClient.setOnBehalfOf(securityArguments.getSecurityToken());
}
stsClient.setProperties(stsProps);
clientProps.put(SecurityConstants.STS_CLIENT, stsClient);
Map<String, String> clientPropsDef = securityArguments.getClientProperties();
for (Map.Entry<String, String> entry : clientPropsDef.entrySet()) {
if (SecurityConstants.ALL_PROPERTIES.contains(entry.getKey())) {
clientProps.put(entry.getKey(), processFileURI(entry.getValue()));
}
}
if (null == securityArguments.getAlias()) {
clientProps.put(SecurityConstants.CALLBACK_HANDLER,
new WSPasswordCallbackHandler(
clientPropsDef.get(SecurityConstants.SIGNATURE_USERNAME),
clientPropsDef.get(CONSUMER_SIGNATURE_PASSWORD)));
} else {
clientProps.put(SecurityConstants.SIGNATURE_USERNAME, securityArguments.getAlias());
clientProps.put(SecurityConstants.CALLBACK_HANDLER,
new WSPasswordCallbackHandler(
securityArguments.getAlias(),
securityArguments.getPassword()));
}
if (null != securityArguments.getCryptoProvider()) {
clientProps.put(SecurityConstants.ENCRYPT_CRYPTO, securityArguments.getCryptoProvider());
}
Object encryptUsername = clientProps.get(SecurityConstants.ENCRYPT_USERNAME);
if (encryptUsername == null || encryptUsername.toString().isEmpty()) {
clientProps.put(SecurityConstants.ENCRYPT_USERNAME, serviceName.toString());
}
}
clientProps.put("soap.no.validate.parts", Boolean.TRUE);
clientProps.put(ESBEndpointConstants.USE_SERVICE_REGISTRY_PROP,
Boolean.toString(useServiceRegistry));
if (correlationIDCallbackHandler != null) {
clientProps.put(
CorrelationIDFeature.CORRELATION_ID_CALLBACK_HANDLER, correlationIDCallbackHandler);
}
clientFactory.setProperties(clientProps);
}
| RuntimeESBConsumer(final QName serviceName,
final QName portName,
String operationName,
String publishedEndpointUrl,
String wsdlURL,
boolean isRequestResponse,
final LocatorFeature slFeature,
final EventFeature samFeature,
boolean useServiceRegistry,
final SecurityArguments securityArguments,
Bus bus,
boolean logging,
String soapAction,
final List<Header> soapHeaders,
boolean enhancedResponse,
Object correlationIDCallbackHandler) {
this.operationName = operationName;
this.isRequestResponse = isRequestResponse;
this.samFeature = samFeature;
this.soapAction = soapAction;
this.soapHeaders = soapHeaders;
this.enhancedResponse = enhancedResponse;
clientFactory = new JaxWsClientFactoryBean() {
@Override
protected Endpoint createEndpoint() throws BusException,
EndpointException {
final Endpoint endpoint = super.createEndpoint();
// set portType = serviceName
InterfaceInfo ii = endpoint.getService().getServiceInfos()
.get(0).getInterface();
ii.setName(serviceName);
return endpoint;
}
};
clientFactory.setServiceName(serviceName);
clientFactory.setEndpointName(portName);
final String endpointUrl = (slFeature == null) ? publishedEndpointUrl
: "locator://" + serviceName.getLocalPart();
if (!useServiceRegistry) {
clientFactory.setAddress(endpointUrl);
}
if (!useServiceRegistry && null != wsdlURL) {
clientFactory.setWsdlURL(wsdlURL);
}
clientFactory.setServiceClass(this.getClass());
//for TESB-9006, create new bus when registry enabled but no wsdl-client/policy-client
//extension set on the old bus. (used to instead the action of refresh job controller bundle.
if (useServiceRegistry && !hasRegistryClientExtension(bus)) {
SpringBusFactory sbf = new SpringBusFactory();
bus = sbf.createBus();
}
clientFactory.setBus(bus);
final List<Feature> features = new ArrayList<Feature>();
if (slFeature != null) {
features.add(slFeature);
}
if (samFeature != null) {
features.add(samFeature);
}
if (correlationIDCallbackHandler != null && (!useServiceRegistry)) {
features.add(new CorrelationIDFeature());
}
if (null != securityArguments.getPolicy()) {
features.add(new WSPolicyFeature(securityArguments.getPolicy()));
}
if (logging) {
features.add(new org.apache.cxf.feature.LoggingFeature());
}
clientFactory.setFeatures(features);
Map<String, Object> clientProps = new HashMap<String, Object>();
if (EsbSecurity.BASIC == securityArguments.getEsbSecurity()) {
authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setUserName(securityArguments.getUsername());
authorizationPolicy.setPassword(securityArguments.getPassword());
authorizationPolicy.setAuthorizationType("Basic");
} else if (EsbSecurity.DIGEST == securityArguments.getEsbSecurity()) {
authorizationPolicy = new AuthorizationPolicy();
authorizationPolicy.setUserName(securityArguments.getUsername());
authorizationPolicy.setPassword(securityArguments.getPassword());
authorizationPolicy.setAuthorizationType("Digest");
}
if (EsbSecurity.TOKEN == securityArguments.getEsbSecurity() || useServiceRegistry) {
clientProps.put(SecurityConstants.USERNAME, securityArguments.getUsername());
clientProps.put(SecurityConstants.PASSWORD, securityArguments.getPassword());
}
if (EsbSecurity.SAML == securityArguments.getEsbSecurity() || useServiceRegistry) {
final Map<String, String> stsPropsDef = securityArguments.getStsProperties();
stsClient = new STSClient(bus);
stsClient.setServiceQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_SERVICE_NAME)));
Map<String, Object> stsProps = new HashMap<String, Object>();
for (Map.Entry<String, String> entry : stsPropsDef.entrySet()) {
if (SecurityConstants.ALL_PROPERTIES.contains(entry.getKey())) {
stsProps.put(entry.getKey(), processFileURI(entry.getValue()));
}
}
if (null == securityArguments.getAlias()) {
stsClient.setWsdlLocation(stsPropsDef.get(STS_WSDL_LOCATION));
stsClient.setEndpointQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_ENDPOINT_NAME)));
stsProps.put(SecurityConstants.USERNAME, securityArguments.getUsername());
stsProps.put(SecurityConstants.PASSWORD, securityArguments.getPassword());
} else {
stsClient.setWsdlLocation(stsPropsDef.get(STS_X509_WSDL_LOCATION));
stsClient.setEndpointQName(
new QName(stsPropsDef.get(STS_NAMESPACE), stsPropsDef.get(STS_X509_ENDPOINT_NAME)));
stsProps.put(SecurityConstants.STS_TOKEN_USERNAME, securityArguments.getAlias());
}
if (null != securityArguments.getRoleName() && securityArguments.getRoleName().length() != 0) {
ClaimValueCallbackHandler roleCallbackHandler = new ClaimValueCallbackHandler();
roleCallbackHandler.setClaimValue(securityArguments.getRoleName());
stsClient.setClaimsCallbackHandler(roleCallbackHandler);
}
if (null != securityArguments.getSecurityToken()) {
stsClient.setOnBehalfOf(securityArguments.getSecurityToken());
}
stsClient.setProperties(stsProps);
clientProps.put(SecurityConstants.STS_CLIENT, stsClient);
Map<String, String> clientPropsDef = securityArguments.getClientProperties();
for (Map.Entry<String, String> entry : clientPropsDef.entrySet()) {
if (SecurityConstants.ALL_PROPERTIES.contains(entry.getKey())) {
clientProps.put(entry.getKey(), processFileURI(entry.getValue()));
}
}
if (null == securityArguments.getAlias()) {
clientProps.put(SecurityConstants.CALLBACK_HANDLER,
new WSPasswordCallbackHandler(
clientPropsDef.get(SecurityConstants.SIGNATURE_USERNAME),
clientPropsDef.get(CONSUMER_SIGNATURE_PASSWORD)));
} else {
clientProps.put(SecurityConstants.SIGNATURE_USERNAME, securityArguments.getAlias());
clientProps.put(SecurityConstants.CALLBACK_HANDLER,
new WSPasswordCallbackHandler(
securityArguments.getAlias(),
securityArguments.getPassword()));
}
if (null != securityArguments.getCryptoProvider()) {
clientProps.put(SecurityConstants.ENCRYPT_CRYPTO, securityArguments.getCryptoProvider());
}
Object encryptUsername = clientProps.get(SecurityConstants.ENCRYPT_USERNAME);
if (encryptUsername == null || encryptUsername.toString().isEmpty()) {
clientProps.put(SecurityConstants.ENCRYPT_USERNAME, serviceName.toString());
}
}
clientProps.put("soap.no.validate.parts", Boolean.TRUE);
clientProps.put(ESBEndpointConstants.USE_SERVICE_REGISTRY_PROP,
Boolean.toString(useServiceRegistry));
if (correlationIDCallbackHandler != null) {
clientProps.put(
CorrelationIDFeature.CORRELATION_ID_CALLBACK_HANDLER, correlationIDCallbackHandler);
}
clientFactory.setProperties(clientProps);
}
|
diff --git a/src/me/slaps/iCoLand/iCoLandCommandListener.java b/src/me/slaps/iCoLand/iCoLandCommandListener.java
index bf11ce6..19e2eb8 100644
--- a/src/me/slaps/iCoLand/iCoLandCommandListener.java
+++ b/src/me/slaps/iCoLand/iCoLandCommandListener.java
@@ -1,918 +1,925 @@
package me.slaps.iCoLand;
import java.io.File;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.nijiko.coelho.iConomy.iConomy;
import com.nijiko.coelho.iConomy.system.Account;
public class iCoLandCommandListener implements CommandExecutor {
Random rn = new Random();
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Messaging mess = new Messaging(sender);
if ( Config.debugMode1 ) {
String debug = "iCoLand.onCommand(): " + ((sender instanceof Player) ? "Player " + ((Player) sender).getName() : "Console") + " Command " + cmd.getName() + " args: ";
for (int i = 0; i < args.length; i++)
debug += args[i] + " ";
iCoLand.info(debug);
}
// is our command?
if ( Misc.isAny(cmd.getName(), "icl", "iCoLand", "iCoLand:icl", "iCoLand:iCoLand") ) {
if (Config.debugMode) iCoLand.info("Is an /icl or /iCoLand command");
// /icl
if ( args.length == 0 ) {
showHelp(sender, "");
return true;
// /icl help
} else if ( args[0].equalsIgnoreCase("help") ) {
if ( args.length == 1 ) {
showHelp(sender, "");
} else {
showHelp(sender, args[1] );
}
return true;
// /icl list
} else if (args[0].equalsIgnoreCase("list") ) {
if ( iCoLand.hasPermission(sender, "land.list") ) {
if ( args.length > 1 ) {
Integer page;
try {
page = Integer.parseInt(args[1]);
if ( page > 1 )
showList(sender, page-1);
else
mess.send("{ERR}Bad page #");
} catch(NumberFormatException ex) {
mess.send("{ERR}Error parsing page #!");
}
} else {
showList(sender, 0);
}
} else {
mess.send("{ERR}No access for list");
}
return true;
// /icl edit <LANDID> <name|perms> <tags>
} else if (args[0].equalsIgnoreCase("edit") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can not edit with this command");
} else if ( iCoLand.hasPermission(sender, "land.edit") ) {
Player player = (Player)sender;
if ( args.length > 3 ) {
Integer id;
try {
id = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error reading <LANDID>");
return true;
}
if ( iCoLand.landMgr.landIdExists(id) ) {
if ( iCoLand.landMgr.isOwner(player.getName(), id) ) {
if ( Misc.isAny(args[2], "name", "perms", "nospawn") ) {
String tags = "";
for(int i=3;i<args.length;i++) tags += args[i] + " ";
editLand(player, id, args[2], tags);
} else {
mess.send("{ERR}Not a valid category");
showHelp(sender,"edit");
}
} else {
mess.send("{ERR}Not owner of land ID# {PRM}"+id);
}
} else {
mess.send("{ERR}Land ID# {PRM}"+id+" {ERR}doesn't exist");
}
} else {
mess.send("{ERR}Too few arguments");
}
} else {
mess.send("{ERR}No access for edit");
}
return true;
// /icl modify <id> <perms|addons|name> <tags>
} else if (args[0].equalsIgnoreCase("modify") ) {
if ( iCoLand.hasPermission(sender, "admin.modify") ) {
if ( args.length < 4 ) {
mess.send("{ERR}Not enough arguments");
showHelp(sender, "modify");
} else {
Integer id;
try {
id = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
mess.send("{ERR}Error parsing <LANDID>");
return true;
}
if ( !iCoLand.landMgr.landIdExists(id) ) {
mess.send("{ERR}Land ID# {PRM}" + id + " {ERR}doesn't exist");
} else {
if ( Misc.isAny(args[2], "perms", "addons", "owner", "name") ) {
String tags = args[3];
for(int i=4;i<args.length;i++) tags += args[i];
adminEditLand(sender, id, args[2], tags);
} else {
mess.send("{ERR}Bad category");
}
}
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl select
} else if (args[0].equalsIgnoreCase("select") ) {
if ( iCoLand.hasPermission(sender, "basic.select") ) {
if ( !(sender instanceof Player) ) {
mess.send("Console can't select");
} else if ( args.length == 1 ) {
selectArea((Player)sender);
} else if ( args.length == 2 ) {
Player player = (Player)sender;
if ( args[1].equalsIgnoreCase("cancel") ) {
mess.send("{}Cancelling current selection.");
iCoLand.cmdMap.remove(player.getName());
iCoLand.tmpCuboidMap.remove(((Player)sender).getName());
} else if ( args[1].equalsIgnoreCase("fullheight") ) {
if ( iCoLand.tmpCuboidMap.containsKey(player.getName()) ) {
mess.send("{}Changing selection height to full height.");
iCoLand.tmpCuboidMap.get(player.getName()).setFullHeight();
+ int id = iCoLand.landMgr.intersectsExistingLand(iCoLand.tmpCuboidMap.get(player.getName()));
+ if ( id > 0 ) {
+ mess.send("{ERR}Intersects existing land!");
+ iCoLand.tmpCuboidMap.put(player.getName(), iCoLand.landMgr.getLandById(id).location);
+ } else {
+ mess.send("{}Selecting full height");
+ }
} else {
mess.send("{ERR}No currently selected land.");
}
} else {
int i = -1;
try {
i = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
}
if ( i > 0 ) {
if ( selectLand((Player)sender, i) ) {
mess.send("{}Selected land ID#{PRM}"+i);
} else {
mess.send("{ERR}No land ID#{PRM}"+i);
}
} else {
mess.send("Error parsing argument");
}
}
} else {
mess.send("{ERR}Too many arguments.");
showHelp(sender, "select");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl info [here|LANDID]
} else if (args[0].equalsIgnoreCase("info") ) {
if ( iCoLand.hasPermission(sender, "basic.info") ) {
if ( (args.length == 1) ) {
if ( sender instanceof Player )
showLandInfo(sender, "");
else
mess.send("{ERR}Console needs to supply arguments for this command");
} else if ( args.length == 2 ) {
showLandInfo(sender, args[1]);
} else {
mess.send("{ERR}Bad info command");
showHelp(sender, "info");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl buy land
// /icl buy addon <addon> <landID>
} else if (args[0].equalsIgnoreCase("buy") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can't buy");
} else if ( iCoLand.hasPermission(sender, "land.buy") ) {
if ( args.length == 1 ) {
mess.send("{ERR}Not enough arguments");
showHelp(sender,"buy");
} else {
if ( args.length == 2 && args[1].equalsIgnoreCase("land") ) {
buyLand(sender);
} else if ( args.length > 2 && args[1].equalsIgnoreCase("addon") ) {
if ( args.length == 4 ) {
if ( Config.isAddon(args[2]) ) {
try {
Integer id = Integer.parseInt(args[3]);
if ( iCoLand.landMgr.landIdExists(id) ) {
buyAddon((Player)sender, args[2], id);
} else {
mess.send("{ERR}Land ID# "+id+" does not exist!");
}
} catch (NumberFormatException ex) {
mess.send("{ERR}Error processing Land ID");
}
} else {
mess.send("{ERR}Not a valid addon");
}
} else {
mess.send("{ERR}Must specify which addon and land ID");
}
} else {
mess.send("{ERR}Bad buy command");
showHelp(sender, "buy");
}
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl sell land <ID>
// /icl sell addon <ADDON> <ID>
} else if (args[0].equalsIgnoreCase("sell") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can't sell land");
} else if ( iCoLand.hasPermission(sender, "land.sell") ){
if ( args.length == 3 && args[1].equalsIgnoreCase("land") ) {
Integer id = 0;
try {
id = Integer.parseInt(args[2]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error parsing ID#");
}
if ( iCoLand.landMgr.landIdExists(id) ) {
sellLand((Player)sender, id);
} else {
mess.send("{ERR}Land ID# "+id+" does not exist");
}
} else if ( args.length == 4 && args[1].equalsIgnoreCase("addon") ) {
Integer id = 0;
try {
id = Integer.parseInt(args[3]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error parsing ID#");
}
if ( iCoLand.landMgr.landIdExists(id) ) {
if ( Config.isAddon(args[2]) ) {
sellAddon((Player)sender, args[2], id);
} else {
mess.send("{ERR}Not valid addon: {PRM}"+args[2]);
}
} else {
mess.send("{ERR}Land ID# "+id+" does not exist");
}
} else {
mess.send("{ERR}Bad sell command");
showHelp(sender,"sell");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("importdb") ) {
if ( iCoLand.hasPermission(sender, "admin.importdb") ) {
iCoLand.landMgr.importDB(new File(iCoLand.pluginDirectory + File.separator + Config.importFile));
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("exportdb") ) {
if ( iCoLand.hasPermission(sender, "admin.exportdb") ) {
iCoLand.landMgr.exportDB(new File(iCoLand.pluginDirectory + File.separator + Config.exportFile));
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("fakedata") ) {
if ( iCoLand.hasPermission(sender, "admin.fakedata") ) {
if ( args.length > 1 ) {
Integer numLands = 0;
try {
numLands = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
long start = System.currentTimeMillis();
for(int i=0;i<numLands;i++) {
Location loc1 = new Location(iCoLand.server.getWorlds().get(0), rand(-4096,4096), rand(5,100), rand(-4096,4096));
Location loc2 = new Location(iCoLand.server.getWorlds().get(0), loc1.getBlockX()+rand(0,100), loc1.getBlockY()+rand(0,28), loc1.getBlockZ()+rand(0,100));
iCoLand.landMgr.addLand(new Cuboid(loc1,loc2), ((sender instanceof Player)?((Player)sender).getName():"kigam"), "", "");
}
if ( Config.debugMode ) iCoLand.info("Inserting "+numLands+" random lands took: "+(System.currentTimeMillis()-start)+" ms");
} else {
mess.send("{ERR}Not enough arguments");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("fixperms") ) {
if ( iCoLand.hasPermission(sender, "admin.fixperms") ) {
ArrayList<Land> lands = iCoLand.landMgr.getAllLands();
for(Land land: lands) {
iCoLand.landMgr.updatePerms(land.getID(), Land.writePermTags(land.canBuildDestroy));
}
mess.send("{}Done...");
} else {
mess.send("{ERR}No access for that...");
}
return true;
// unrecognized /icl command
} else {
mess.send("{}Unrecognized/invalid/malformed command!");
mess.send("{} Please use {CMD}/icl help {BKT}[{PRM}topic{BKT}] {}for help");
return true;
}
// command not recognized ( not /icl )
} else {
return false;
}
}
public int rand(int lo, int hi) {
int n = hi - lo + 1;
int i = rn.nextInt() % n;
if ( i < 0 )
i = -i;
return lo+i;
}
public boolean selectLand(Player player, int id) {
String playerName = player.getName();
Land land = iCoLand.landMgr.getLandById(id);
if ( land != null ) {
iCoLand.tmpCuboidMap.put(playerName, land.location);
return true;
} else {
return false;
}
}
public boolean selectArea(Player player) {
String playerName = player.getName();
Messaging mess = new Messaging((CommandSender)player);
if ( iCoLand.cmdMap.containsKey(playerName) && iCoLand.cmdMap.get(playerName).equals("select") ) {
mess.send("{ERR}Cancelling selection command.");
iCoLand.cmdMap.remove(playerName);
}
if ( iCoLand.tmpCuboidMap.containsKey(playerName) ) {
mess.send("{ERR}Unselecting current cuboid");
iCoLand.tmpCuboidMap.remove(playerName);
}
mess.send("{}Left Click 1st Corner");
iCoLand.cmdMap.put(playerName,"select");
return true;
}
public void editLand(Player player, Integer id, String category, String args) {
Messaging mess = new Messaging(player);
if ( category.equals("perms") ) {
if (iCoLand.landMgr.modifyPermTags(id, args))
mess.send("{}Permissions modified");
else
mess.send("{ERR}Problem modify permissions");
} else if ( category.equalsIgnoreCase("name") ) {
if ( iCoLand.landMgr.updateName(id, args.substring(0, (args.length()>35)?35:args.length())) )
mess.send("{}Location name changed");
else
mess.send("{ERR}Error changing location name");
} else if ( category.equalsIgnoreCase("nospawn") ) {
if ( iCoLand.landMgr.modifyNoSpawnTags(id, args) )
mess.send("{}NoSpawn list modified");
else
mess.send("{ERR}Problem modifying NoSpawn list");
}
}
public void adminEditLand(CommandSender sender, Integer id, String category, String tags) {
Messaging mess = new Messaging(sender);
if ( category.equals("perms") ) {
if (iCoLand.landMgr.modifyPermTags(id, tags))
mess.send("{}Permissions modified");
else
mess.send("{ERR}Problem modify permissions");
} else if ( category.equalsIgnoreCase("owner") ) {
if ( iCoLand.landMgr.updateOwner(id, tags) )
mess.send("{}Owner changed");
else
mess.send("{ERR}Problem modifying owner");
} else if ( category.equalsIgnoreCase("addons") ) {
if ( iCoLand.landMgr.toggleAddons(id, tags) )
mess.send("{}Addons modified");
else
mess.send("{ERR}Error modifying addons");
} else if ( category.equalsIgnoreCase("name") ) {
if ( iCoLand.landMgr.updateName(id, tags.substring(0, (tags.length()>35)?35:tags.length())) )
mess.send("{}Location name changed");
else
mess.send("{ERR}Error changing location name");
} else if ( category.equalsIgnoreCase("nospawn") ) {
if ( iCoLand.landMgr.modifyNoSpawnTags(id, tags) )
mess.send("{}NoSpawn list modified");
else
mess.send("{ERR}Problem modifying NoSpawn list");
} else {
mess.send("{ERR}Bad category");
}
}
public void showList(CommandSender sender, Integer page) {
Integer pageSize = 7;
ArrayList<Land> list;
int numLands = 0;
if( sender instanceof Player )
numLands = iCoLand.landMgr.countLandsOwnedBy(((Player)sender).getName());
else
numLands = iCoLand.landMgr.countLandsOwnedBy(null);
Messaging mess = new Messaging(sender);
if ( numLands == 0 ) {
mess.send("{ERR}You do not own any land");
} else {
if ( page*pageSize > numLands ) {
mess.send("{ERR}No lands on this page");
} else {
String playerName = (sender instanceof Player)?((Player)sender).getName():null;
list = iCoLand.landMgr.getLandsOwnedBy(playerName, pageSize, page*pageSize);
int pages = numLands / pageSize + (( numLands % pageSize > 0)?1:0);
mess.send("{}"+Misc.headerify("{CMD}Your Lands {BKT}({CMD}Page " + (page+1) + "{BKT}/{CMD}"+pages+"{BKT}){}"));
int i;
for(i=0;i<pageSize && i<list.size();i++) {
Land land = list.get(i);
mess.send("{PRM}ID#{}"+land.getID()+((land.active?"":"({ERR}I{})"))+
" "+
((land.locationName.isEmpty())?"":land.locationName+" ") +
"{PRM}V:{}"+land.location.volume()+" "+
"{PRM}[{}"+land.location.toDimString()+
"{PRM}] C{}"+land.location.toCenterCoords()
);
}
}
}
}
public void buyAddon(Player sender, String addon, Integer id) {
Messaging mess = new Messaging(sender);
Land land = iCoLand.landMgr.getLandById(id);
if ( land.owner.equalsIgnoreCase(sender.getName()) ) {
Account acc = iConomy.getBank().getAccount(sender.getName());
Account bank = iConomy.getBank().getAccount(Config.bankName);
double price = Double.valueOf(iCoLand.df.format(iCoLand.landMgr.getLandById(id).getAddonPrice(addon)));
if ( iCoLand.hasPermission(sender, "admin.nocost") ) {
if ( iCoLand.landMgr.addAddon(id, addon) )
mess.send("{}Bought addon {PRM}"+addon+"{} for {PRM}0 {BKT}({PRM}"+iCoLand.df.format(price)+"{BKT})");
else
mess.send("{ERR}Error buying addon");
} else if ( acc.getBalance() > price ) {
if ( iCoLand.landMgr.addAddon(id, addon) ) {
acc.subtract(price);
bank.add(price);
mess.send("{}Bought addon {PRM}"+addon+"{} for {PRM}"+iCoLand.df.format(price));
mess.send("{}Bank Balance: {PRM}"+iCoLand.df.format(acc.getBalance()));
} else {
mess.send("{ERR}Error buying addon");
}
} else {
mess.send("{ERR}Not enough in account. Bank: "+iCoLand.df.format(acc.getBalance())+
" Price: "+iCoLand.df.format(price));
}
} else {
mess.send("{ERR}Not owner of land ID# {PRM}"+id);
}
}
public void sellAddon(Player sender, String addon, Integer id) {
Messaging mess = new Messaging(sender);
Land land = iCoLand.landMgr.getLandById(id);
if ( land.owner.equalsIgnoreCase(sender.getName()) ) {
Account acc = iConomy.getBank().getAccount(sender.getName());
Account bank = iConomy.getBank().getAccount(Config.bankName);
double price = Double.valueOf(iCoLand.df.format(land.getAddonPrice(addon)));
double sellPrice = price*Config.sellTax;
if ( iCoLand.hasPermission(sender, "admin.nocost") ) {
if ( iCoLand.landMgr.removeAddon(id, addon) )
mess.send("{}Sold addon {PRM}"+addon+" on land ID# {PRM}"+id+"{} for {PRM}0 {BKT}({PRM}"+price+"{BKT})");
else
mess.send("{ERR}Error selling addon");
} else {
if ( iCoLand.landMgr.removeAddon(id, addon) ) {
acc.add(sellPrice);
bank.subtract(sellPrice);
mess.send("{}Sold addon {PRM}"+addon+" on land ID# {PRM}"+id+"{} for {PRM}"+price);
mess.send("{}Bank Balance: {PRM}"+acc.getBalance());
} else {
mess.send("{ERR}Error selling addon");
}
}
} else {
mess.send("{ERR}Not owner of land ID# {PRM}"+id);
}
}
public void purchaseLand(Player player, Cuboid newCuboid) {
Messaging mess = new Messaging(player);
String playerName = player.getName();
Account acc = iConomy.getBank().getAccount(playerName);
Account bank = iConomy.getBank().getAccount(Config.bankName);
double price = Double.valueOf(iCoLand.df.format(iCoLand.landMgr.getPrice(newCuboid)));
if ( (acc.getBalance() > price) || iCoLand.hasPermission(player, "admin.nocost") ) {
if ( iCoLand.landMgr.addLand(newCuboid, playerName, playerName+":t", "") ) {
if ( iCoLand.hasPermission(player, "admin.nocost") ) {
mess.send("{}Bought selected land for {PRM}0 {BKT}({PRM}"+iCoLand.df.format(price)+"{BKT})");
} else {
acc.subtract(price);
bank.add(price);
mess.send("{}Bought selected land for {PRM}"+iCoLand.df.format(price));
mess.send("{}Bank Balance: {PRM}"+iCoLand.df.format(acc.getBalance()));
}
iCoLand.cmdMap.remove(playerName);
} else {
mess.send("{ERR}Error buying land");
}
} else {
mess.send("{ERR}Not enough in account. Bank: "+iCoLand.df.format(acc.getBalance())+
" Price: "+iCoLand.df.format(price));
}
}
public void reactivateLand( Player player, int id ) {
Messaging mess = new Messaging(player);
String playerName = player.getName();
Account acc = iConomy.getBank().getAccount(playerName);
Account bank = iConomy.getBank().getAccount(Config.bankName);
Land land = iCoLand.landMgr.getLandById(id);
double tax = Double.valueOf(iCoLand.df.format(land.location.volume()*Config.pricePerBlock.get("raw")*Config.taxRate));
if ( iCoLand.hasPermission(player, "admin.nocost") || iCoLand.hasPermission(player, "admin.notax") ) {
iCoLand.landMgr.updateActive(id, true);
iCoLand.landMgr.updateTaxTime(id, new Timestamp(System.currentTimeMillis()));
mess.send("Land bought back for {PRM}0 {}("+iCoLand.df.format(tax)+")");
} else if ( acc.hasEnough(tax) ) {
acc.subtract(tax);
bank.add(tax);
iCoLand.landMgr.updateActive(id, true);
iCoLand.landMgr.updateTaxTime(id, new Timestamp(System.currentTimeMillis()));
mess.send("Land bought back for {PRM}"+iCoLand.df.format(tax));
} else {
mess.send("{ERR}Not enough money to pay past due taxes of {PRM}"+iCoLand.df.format(tax));
}
}
public void buyLand(CommandSender sender) {
Messaging mess = new Messaging(sender);
if ( sender instanceof Player ) {
String playerName = ((Player)sender).getName();
if ( iCoLand.tmpCuboidMap.containsKey(playerName) ) {
Cuboid newCuboid = iCoLand.tmpCuboidMap.get(playerName);
int id = iCoLand.landMgr.intersectsExistingLand(newCuboid);
Land land;
if ( id > 0 ) {
land = iCoLand.landMgr.getLandById(id);
if ( land.location.equals(newCuboid) ) {
if ( land.active ) {
mess.send("{ERR}Can't buy active land");
} else {
reactivateLand((Player)sender, id);
}
} else {
mess.send("{ERR}selection doesn't match zone");
}
} else if ( newCuboid.isValid() ) {
if ( iCoLand.hasPermission(sender, "admin.nolimits") ) {
purchaseLand((Player)sender, newCuboid);
} else {
if ( newCuboid.volume() <= Config.maxLandVolume ) {
if ( newCuboid.volume() >= Config.minLandVolume ) {
if ( iCoLand.landMgr.canClaimMoreVolume(playerName, newCuboid.volume() ) ) {
if ( iCoLand.landMgr.canClaimMoreLands(playerName) ) {
purchaseLand((Player)sender, newCuboid);
} else {
mess.send("{ERR}Can not claim over "+Config.maxLandsClaimable+" lands!");
}
} else {
mess.send("{ERR}Can not claim over "+Config.maxBlocksClaimable+" blocks!");
}
} else {
mess.send("{ERR}Volume must be at least "+Config.minLandVolume+" blocks!");
}
} else {
mess.send("{ERR}Too large, max volume is "+Config.maxLandVolume+" blocks!");
}
}
} else {
mess.send("{ERR}Invalid selection");
}
} else {
mess.send("{ERR}Nothing selected");
}
} else {
mess.send("Console can't buy land");
}
}
public void sellLand(Player sender, Integer id) {
Messaging mess = new Messaging(sender);
Land land = iCoLand.landMgr.getLandById(id);
if ( land.owner.equalsIgnoreCase(sender.getName()) ) {
if ( land.active ) {
Account acc = iConomy.getBank().getAccount(sender.getName());
Account bank = iConomy.getBank().getAccount(Config.bankName);
double price = Double.valueOf(iCoLand.df.format(land.getTotalPrice()));
double sellPrice = Double.valueOf(iCoLand.df.format(price*Config.sellTax));
if ( iCoLand.hasPermission(sender, "admin.nocost") ) {
iCoLand.landMgr.removeLandById(id);
mess.send("{}Sold land ID# {PRM}"+id+"{} for {PRM}0 {BKT}({PRM}"+sellPrice+"{BKT})");
} else {
acc.add(sellPrice);
bank.subtract(sellPrice);
iCoLand.landMgr.removeLandById(id);
mess.send("{}Sold land ID# {PRM}"+id+"{} for {PRM}"+sellPrice);
mess.send("{}Bank Balance: {PRM}"+acc.getBalance());
}
} else {
iCoLand.landMgr.removeLandById(id);
mess.send("{}Got rid of inactive land ID# {PRM}"+id);
}
} else {
mess.send("{ERR}Not owner of land ID# {PRM}"+id);
}
}
public void showHelp(CommandSender sender, String topic) {
Messaging mess = new Messaging(sender);
mess.send("{}"+Misc.headerify("{CMD}" + iCoLand.name + " {BKT}({CMD}" + iCoLand.codename + "{BKT}){}"));
if ( topic == null || topic.isEmpty() ) {
mess.send(" {CMD}/icl {}- main command");
mess.send(" {CMD}/icl {PRM}help {BKT}[{PRM}topic{BKT}] {}- help topics");
String topics = "";
if ( iCoLand.hasPermission(sender, "basic.select") ) topics += "select";
if ( iCoLand.hasPermission(sender, "basic.info") ) topics += " info";
if ( iCoLand.hasPermission(sender, "land.list") ) topics += " list";
if ( iCoLand.hasPermission(sender, "land.edit") ) topics += " edit";
if ( iCoLand.hasPermission(sender, "land.buy") ) topics += " buy";
if ( iCoLand.hasPermission(sender, "land.sell") ) topics += " sell";
if ( iCoLand.hasPermission(sender, "admin.modify") ) topics += " modify";
mess.send(" {} help topics: {CMD}" + topics);
} else if ( topic.equalsIgnoreCase("list") ) {
if ( iCoLand.hasPermission(sender, "land.list") ) {
mess.send(" {CMD}/icl {PRM}list {BKT}[{PRM}PAGE{BKT}] {}- lists owned land");
}
} else if ( topic.equalsIgnoreCase("select") ) {
if ( iCoLand.hasPermission(sender, "basic.select") ) {
mess.send(" {CMD}/icl {PRM}select {}- start cuboid selection process");
mess.send(" {}After typing this command, left click a block to set the first corner,");
mess.send(" {}then left click a 2nd block to set the second corner. This selects");
mess.send(" {}the {PRM}CUBE {} set by the 2 corner blocks.");
mess.send(" {CMD}/icl {PRM}select {BKT}[{PRM}cancel{BKT}|{PRM}fullheight{BKT}] {}");
mess.send(" {}pass an optional argument cancel to cancel the current selection");
mess.send(" {}or pass fullheight to modify your selection to be the full height.");
}
} else if ( topic.equalsIgnoreCase("info") ) {
if ( iCoLand.hasPermission(sender, "basic.info") ) {
mess.send(" {CMD}/icl {PRM}info {BKT}[{PRM}here{BKT}|{PRM}LANDID{BKT] {}- gets land info");
mess.send(" {}Optional arguments 'here' or <LANDID>");
mess.send(" {}Will give info on the selected land, or current location, or specific land ID#");
}
} else if ( topic.equalsIgnoreCase("buy") ) {
if ( iCoLand.hasPermission(sender, "land.buy") ) {
mess.send(" {CMD}/icl {PRM}buy {BKT}[{PRM}land{BKT}|{PRM}addon{BKT}] [{PRM}ADDON{BKT}] [{PRM}LANDID{BKT}] {}- purchase land or addons");
mess.send(" {}this command can be used to purchase land: {CMD}/icl buy land");
mess.send(" {}it can also be used to buy addons for a specific land ID# with:");
mess.send(" {}{CMD}/icl buy addon <ADDON> <LANDID>");
}
} else if ( topic.equalsIgnoreCase("sell") ) {
if ( iCoLand.hasPermission(sender, "land.sell") ) {
mess.send(" {CMD}/icl {PRM}sell {BKT}[{PRM}land{BKT}|{PRM}addon{BKT}] [{PRM}ADDON{BKT}] [{PRM}LANDID{BKT}] {}- purchase land or addons");
mess.send(" {}this command can be used to sell land: {CMD}/icl sell land");
mess.send(" {}it can also be used to sell addons for a specific land ID# with:");
mess.send(" {}{CMD}/icl sell addon <ADDON> <LANDID>");
}
} else if ( topic.equalsIgnoreCase("edit") ) {
if ( iCoLand.hasPermission(sender, "land.edit") ) {
mess.send(" {CMD}/icl {PRM}edit {BKT}<{PRM}LANDID{BKT}> <{PRM}perms{BKT}|{PRM}name{BKT}|{PRM}nospawn{BKT}> <{PRM}tags{BKT}>");
mess.send(" {}modifies config for land ( permissions, names )");
mess.send(" {}change location name example: {CMD}/icl edit 4 name This Land");
mess.send(" {}Tags for perms: {BKT}<{PRM}playerName{BKT}>{PRM}:{BKT}<{PRM}t{BKT}|{PRM}f{BKT}|{PRM}-{BKT}>");
mess.send(" {}{BKT}<{PRM}playerName{BKT}> {}- player to be affected ( or '{PRM}default{}' )");
mess.send(" {}{BKT}<{PRM}t{BKT}|{PRM}f{BKT}|{PRM}-{BKT}> {}- {PRM}t{}/{PRM}f{} for true/false (build/destroy)");
mess.send(" {}{PRM}- {}removes perm for playerName");
mess.send(" {}perm example: {CMD}/icl edit 4 perms default:f kigam:t jesus:t");
}
} else if ( topic.equalsIgnoreCase("modify") ) {
if ( iCoLand.hasPermission(sender, "admin.modify") ) {
mess.send(" {CMD}/icl {PRM}modify {BKT}<{PRM}LANDID{BKT}> <{PRM}perms{BKT}|{PRM}addons{BKT}|{PRM}owner{BKT}|{PRM}name{BKT}|{PRM}nospawn{BKT}> <{PRM}tags{BKT}> {}- modify land settings");
}
}
}
public void showSelectLandInfo(CommandSender sender, Cuboid select) {
Messaging mess = new Messaging(sender);
Integer id = iCoLand.landMgr.intersectsExistingLand(select);
if ( id > 0 && iCoLand.landMgr.getLandById(id).location.equals(select) ) {
showExistingLandInfo(sender, iCoLand.landMgr.getLandById(id));
} else if ( id > 0 ) {
mess.send("{ERR}Intersects existing land ID# "+id);
mess.send("{ERR}Selecting/showing land ID# "+id+" instead");
iCoLand.tmpCuboidMap.put(((Player)sender).getName(), iCoLand.landMgr.getLandById(id).location );
showExistingLandInfo(sender, iCoLand.landMgr.getLandById(id));
} else {
mess.send("{}"+Misc.headerify("{PRM}Unclaimed Land{}"));
mess.send("Dimensoins: " + select.toDimString() );
mess.send("Volume: " + select.volume() );
mess.send("Price: " + iCoLand.df.format(iCoLand.landMgr.getPrice(select)));
}
}
public void showSelectLandInfo(CommandSender sender, Integer id) {
showExistingLandInfo(sender, iCoLand.landMgr.getLandById(id));
}
public String formatTimeLeft(long due) {
String ret = "";
long now = System.currentTimeMillis();
DecimalFormat df = new DecimalFormat("#");
long secsleft = (long) (Math.abs(due-now)/1000.0);
long minsleft = (long) (Math.abs(due-now)/1000.0/60.0);
if ( due - now < 0 ) {
ret += "-";
}
if ( minsleft > 1440 ) {
long daysleft = Long.parseLong(df.format(secsleft/60.0/60.0/24.0));
long hoursleft = (minsleft/60)%daysleft;
ret += daysleft+" day"+((daysleft>1)?"s":"")+
((hoursleft>0)?
", "+hoursleft+" hour"+((hoursleft>1)?"s":"")
:"");
} else if ( minsleft > 60 ) {
long hoursleft = Long.parseLong(df.format(minsleft/60.0));
minsleft = minsleft - ( hoursleft*60 );
ret += hoursleft+" hour"+((hoursleft>1)?"s":"")+
((hoursleft == 1 )?", "+minsleft+" minute"+((minsleft > 1)?"s":""):"");
} else if ( minsleft > 0 ) {
secsleft = secsleft - ( minsleft*60 );
ret += minsleft+" minute"+((minsleft>1)?"s":"")+
((minsleft < 5)?", "+secsleft+" second"+((secsleft>1)?"s":""):"");
} else if ( secsleft >= 0 ) {
ret += secsleft+" second"+((secsleft>1)?"s":"");
}
return ret;
}
public void showExistingLandInfo(CommandSender sender, Land land) {
Messaging mess = new Messaging(sender);
mess.send("{}"+Misc.headerify("{} Land ID# {PRM}"+land.getID()+
((land.active)?"":" {ERR}INACTIVE")+
"{} --"+
(land.locationName.isEmpty()?"":" {PRM}"+land.locationName+" {}")
));
mess.send("{CMD}C: {}"+land.location.toCenterCoords()+" {CMD}V: {}"+land.location.volume()+" {CMD}D: {}"+land.location.toDimString());
mess.send("{CMD}Owner: {}"+land.owner);
if ( !(sender instanceof Player) || land.owner.equals(((Player)sender).getName()) || iCoLand.hasPermission(sender,"admin.bypass") ) {
if ( !land.locationName.isEmpty() )
mess.send("{CMD}Name: {}"+land.locationName);
mess.send("{CMD}Taxes Due: {PRM}"+
(iCoLand.hasPermission(land.location.LocMin.getWorld().getName(), land.owner, "admin.notax")?"0 {BKT}({PRM}"+(iCoLand.df.format(land.location.volume()*Config.pricePerBlock.get("raw")*Config.taxRate))+"{BKT})":
(iCoLand.df.format(land.location.volume()*Config.pricePerBlock.get("raw")*Config.taxRate)))+
" {BKT}({}"+
(land.active?
formatTimeLeft(land.dateTax.getTime()):
formatTimeLeft(land.dateTax.getTime()+Config.inactiveDeleteTime*60*1000))
+" left{BKT})"
);
mess.send("{CMD}Perms: {}"+Land.writePermTags(land.canBuildDestroy));
if ( land.hasAddon("nospawn") )
mess.send("{CMD}NoSpawn: {}"+land.noSpawn);
mess.send("{CMD}Addons: {}"+Land.writeAddonTags(land.addons));
mess.send("{CMD}Addon Prices: {}"+Land.writeAddonPrices(land));
}
}
public void showLandInfo(Player sender, String... args) {
Messaging mess = new Messaging(sender);
// use location search or selected search
String playerName = sender.getName();
if ( iCoLand.tmpCuboidMap.containsKey(playerName) ) {
Cuboid select = iCoLand.tmpCuboidMap.get(playerName);
if ( select.isValid() ) {
showSelectLandInfo((CommandSender)sender, select);
} else {
mess.send("{ERR}Current selection invalid! Use {CMD}/lwc select{} to cancel");
}
} else {
Location loc = sender.getLocation();
ArrayList<Integer> landids = iCoLand.landMgr.getLandIds(loc);
if ( landids.size() > 0 ) {
showSelectLandInfo((CommandSender)sender, landids.get(0));
} else {
mess.send("{ERR}No current selection, not on owned land");
}
}
}
public void showLandInfo(CommandSender sender, String... args) {
Messaging mess = new Messaging(sender);
if ( args.length == 0 ) {
showHelp(sender,"info");
} else {
if ( args[0].equalsIgnoreCase("here") ) {
if ( sender instanceof Player ) {
ArrayList<Integer> ids = iCoLand.landMgr.getLandIds(((Player)sender).getLocation());
if ( ids.size() > 0 ) {
showSelectLandInfo((CommandSender)sender, ids.get(0));
} else {
mess.send("{ERR}No land claimed where you are standing.");
}
} else {
mess.send("{ERR}Console can't use here");
}
} else {
Integer id = 0;
try {
id = Integer.parseInt(args[0]);
} catch (NumberFormatException e ) {
id = 0;
}
if ( id > 0 ) {
if ( iCoLand.landMgr.landIdExists(id)) {
showSelectLandInfo((CommandSender)sender, id);
} else {
mess.send("{ERR}Land ID# "+id+" does not exist");
}
} else {
if ( sender instanceof Player )
showLandInfo((Player)sender, args);
else
showHelp(sender,"info");
}
}
}
}
}
| true | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Messaging mess = new Messaging(sender);
if ( Config.debugMode1 ) {
String debug = "iCoLand.onCommand(): " + ((sender instanceof Player) ? "Player " + ((Player) sender).getName() : "Console") + " Command " + cmd.getName() + " args: ";
for (int i = 0; i < args.length; i++)
debug += args[i] + " ";
iCoLand.info(debug);
}
// is our command?
if ( Misc.isAny(cmd.getName(), "icl", "iCoLand", "iCoLand:icl", "iCoLand:iCoLand") ) {
if (Config.debugMode) iCoLand.info("Is an /icl or /iCoLand command");
// /icl
if ( args.length == 0 ) {
showHelp(sender, "");
return true;
// /icl help
} else if ( args[0].equalsIgnoreCase("help") ) {
if ( args.length == 1 ) {
showHelp(sender, "");
} else {
showHelp(sender, args[1] );
}
return true;
// /icl list
} else if (args[0].equalsIgnoreCase("list") ) {
if ( iCoLand.hasPermission(sender, "land.list") ) {
if ( args.length > 1 ) {
Integer page;
try {
page = Integer.parseInt(args[1]);
if ( page > 1 )
showList(sender, page-1);
else
mess.send("{ERR}Bad page #");
} catch(NumberFormatException ex) {
mess.send("{ERR}Error parsing page #!");
}
} else {
showList(sender, 0);
}
} else {
mess.send("{ERR}No access for list");
}
return true;
// /icl edit <LANDID> <name|perms> <tags>
} else if (args[0].equalsIgnoreCase("edit") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can not edit with this command");
} else if ( iCoLand.hasPermission(sender, "land.edit") ) {
Player player = (Player)sender;
if ( args.length > 3 ) {
Integer id;
try {
id = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error reading <LANDID>");
return true;
}
if ( iCoLand.landMgr.landIdExists(id) ) {
if ( iCoLand.landMgr.isOwner(player.getName(), id) ) {
if ( Misc.isAny(args[2], "name", "perms", "nospawn") ) {
String tags = "";
for(int i=3;i<args.length;i++) tags += args[i] + " ";
editLand(player, id, args[2], tags);
} else {
mess.send("{ERR}Not a valid category");
showHelp(sender,"edit");
}
} else {
mess.send("{ERR}Not owner of land ID# {PRM}"+id);
}
} else {
mess.send("{ERR}Land ID# {PRM}"+id+" {ERR}doesn't exist");
}
} else {
mess.send("{ERR}Too few arguments");
}
} else {
mess.send("{ERR}No access for edit");
}
return true;
// /icl modify <id> <perms|addons|name> <tags>
} else if (args[0].equalsIgnoreCase("modify") ) {
if ( iCoLand.hasPermission(sender, "admin.modify") ) {
if ( args.length < 4 ) {
mess.send("{ERR}Not enough arguments");
showHelp(sender, "modify");
} else {
Integer id;
try {
id = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
mess.send("{ERR}Error parsing <LANDID>");
return true;
}
if ( !iCoLand.landMgr.landIdExists(id) ) {
mess.send("{ERR}Land ID# {PRM}" + id + " {ERR}doesn't exist");
} else {
if ( Misc.isAny(args[2], "perms", "addons", "owner", "name") ) {
String tags = args[3];
for(int i=4;i<args.length;i++) tags += args[i];
adminEditLand(sender, id, args[2], tags);
} else {
mess.send("{ERR}Bad category");
}
}
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl select
} else if (args[0].equalsIgnoreCase("select") ) {
if ( iCoLand.hasPermission(sender, "basic.select") ) {
if ( !(sender instanceof Player) ) {
mess.send("Console can't select");
} else if ( args.length == 1 ) {
selectArea((Player)sender);
} else if ( args.length == 2 ) {
Player player = (Player)sender;
if ( args[1].equalsIgnoreCase("cancel") ) {
mess.send("{}Cancelling current selection.");
iCoLand.cmdMap.remove(player.getName());
iCoLand.tmpCuboidMap.remove(((Player)sender).getName());
} else if ( args[1].equalsIgnoreCase("fullheight") ) {
if ( iCoLand.tmpCuboidMap.containsKey(player.getName()) ) {
mess.send("{}Changing selection height to full height.");
iCoLand.tmpCuboidMap.get(player.getName()).setFullHeight();
} else {
mess.send("{ERR}No currently selected land.");
}
} else {
int i = -1;
try {
i = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
}
if ( i > 0 ) {
if ( selectLand((Player)sender, i) ) {
mess.send("{}Selected land ID#{PRM}"+i);
} else {
mess.send("{ERR}No land ID#{PRM}"+i);
}
} else {
mess.send("Error parsing argument");
}
}
} else {
mess.send("{ERR}Too many arguments.");
showHelp(sender, "select");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl info [here|LANDID]
} else if (args[0].equalsIgnoreCase("info") ) {
if ( iCoLand.hasPermission(sender, "basic.info") ) {
if ( (args.length == 1) ) {
if ( sender instanceof Player )
showLandInfo(sender, "");
else
mess.send("{ERR}Console needs to supply arguments for this command");
} else if ( args.length == 2 ) {
showLandInfo(sender, args[1]);
} else {
mess.send("{ERR}Bad info command");
showHelp(sender, "info");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl buy land
// /icl buy addon <addon> <landID>
} else if (args[0].equalsIgnoreCase("buy") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can't buy");
} else if ( iCoLand.hasPermission(sender, "land.buy") ) {
if ( args.length == 1 ) {
mess.send("{ERR}Not enough arguments");
showHelp(sender,"buy");
} else {
if ( args.length == 2 && args[1].equalsIgnoreCase("land") ) {
buyLand(sender);
} else if ( args.length > 2 && args[1].equalsIgnoreCase("addon") ) {
if ( args.length == 4 ) {
if ( Config.isAddon(args[2]) ) {
try {
Integer id = Integer.parseInt(args[3]);
if ( iCoLand.landMgr.landIdExists(id) ) {
buyAddon((Player)sender, args[2], id);
} else {
mess.send("{ERR}Land ID# "+id+" does not exist!");
}
} catch (NumberFormatException ex) {
mess.send("{ERR}Error processing Land ID");
}
} else {
mess.send("{ERR}Not a valid addon");
}
} else {
mess.send("{ERR}Must specify which addon and land ID");
}
} else {
mess.send("{ERR}Bad buy command");
showHelp(sender, "buy");
}
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl sell land <ID>
// /icl sell addon <ADDON> <ID>
} else if (args[0].equalsIgnoreCase("sell") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can't sell land");
} else if ( iCoLand.hasPermission(sender, "land.sell") ){
if ( args.length == 3 && args[1].equalsIgnoreCase("land") ) {
Integer id = 0;
try {
id = Integer.parseInt(args[2]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error parsing ID#");
}
if ( iCoLand.landMgr.landIdExists(id) ) {
sellLand((Player)sender, id);
} else {
mess.send("{ERR}Land ID# "+id+" does not exist");
}
} else if ( args.length == 4 && args[1].equalsIgnoreCase("addon") ) {
Integer id = 0;
try {
id = Integer.parseInt(args[3]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error parsing ID#");
}
if ( iCoLand.landMgr.landIdExists(id) ) {
if ( Config.isAddon(args[2]) ) {
sellAddon((Player)sender, args[2], id);
} else {
mess.send("{ERR}Not valid addon: {PRM}"+args[2]);
}
} else {
mess.send("{ERR}Land ID# "+id+" does not exist");
}
} else {
mess.send("{ERR}Bad sell command");
showHelp(sender,"sell");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("importdb") ) {
if ( iCoLand.hasPermission(sender, "admin.importdb") ) {
iCoLand.landMgr.importDB(new File(iCoLand.pluginDirectory + File.separator + Config.importFile));
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("exportdb") ) {
if ( iCoLand.hasPermission(sender, "admin.exportdb") ) {
iCoLand.landMgr.exportDB(new File(iCoLand.pluginDirectory + File.separator + Config.exportFile));
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("fakedata") ) {
if ( iCoLand.hasPermission(sender, "admin.fakedata") ) {
if ( args.length > 1 ) {
Integer numLands = 0;
try {
numLands = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
long start = System.currentTimeMillis();
for(int i=0;i<numLands;i++) {
Location loc1 = new Location(iCoLand.server.getWorlds().get(0), rand(-4096,4096), rand(5,100), rand(-4096,4096));
Location loc2 = new Location(iCoLand.server.getWorlds().get(0), loc1.getBlockX()+rand(0,100), loc1.getBlockY()+rand(0,28), loc1.getBlockZ()+rand(0,100));
iCoLand.landMgr.addLand(new Cuboid(loc1,loc2), ((sender instanceof Player)?((Player)sender).getName():"kigam"), "", "");
}
if ( Config.debugMode ) iCoLand.info("Inserting "+numLands+" random lands took: "+(System.currentTimeMillis()-start)+" ms");
} else {
mess.send("{ERR}Not enough arguments");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("fixperms") ) {
if ( iCoLand.hasPermission(sender, "admin.fixperms") ) {
ArrayList<Land> lands = iCoLand.landMgr.getAllLands();
for(Land land: lands) {
iCoLand.landMgr.updatePerms(land.getID(), Land.writePermTags(land.canBuildDestroy));
}
mess.send("{}Done...");
} else {
mess.send("{ERR}No access for that...");
}
return true;
// unrecognized /icl command
} else {
mess.send("{}Unrecognized/invalid/malformed command!");
mess.send("{} Please use {CMD}/icl help {BKT}[{PRM}topic{BKT}] {}for help");
return true;
}
// command not recognized ( not /icl )
} else {
return false;
}
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Messaging mess = new Messaging(sender);
if ( Config.debugMode1 ) {
String debug = "iCoLand.onCommand(): " + ((sender instanceof Player) ? "Player " + ((Player) sender).getName() : "Console") + " Command " + cmd.getName() + " args: ";
for (int i = 0; i < args.length; i++)
debug += args[i] + " ";
iCoLand.info(debug);
}
// is our command?
if ( Misc.isAny(cmd.getName(), "icl", "iCoLand", "iCoLand:icl", "iCoLand:iCoLand") ) {
if (Config.debugMode) iCoLand.info("Is an /icl or /iCoLand command");
// /icl
if ( args.length == 0 ) {
showHelp(sender, "");
return true;
// /icl help
} else if ( args[0].equalsIgnoreCase("help") ) {
if ( args.length == 1 ) {
showHelp(sender, "");
} else {
showHelp(sender, args[1] );
}
return true;
// /icl list
} else if (args[0].equalsIgnoreCase("list") ) {
if ( iCoLand.hasPermission(sender, "land.list") ) {
if ( args.length > 1 ) {
Integer page;
try {
page = Integer.parseInt(args[1]);
if ( page > 1 )
showList(sender, page-1);
else
mess.send("{ERR}Bad page #");
} catch(NumberFormatException ex) {
mess.send("{ERR}Error parsing page #!");
}
} else {
showList(sender, 0);
}
} else {
mess.send("{ERR}No access for list");
}
return true;
// /icl edit <LANDID> <name|perms> <tags>
} else if (args[0].equalsIgnoreCase("edit") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can not edit with this command");
} else if ( iCoLand.hasPermission(sender, "land.edit") ) {
Player player = (Player)sender;
if ( args.length > 3 ) {
Integer id;
try {
id = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error reading <LANDID>");
return true;
}
if ( iCoLand.landMgr.landIdExists(id) ) {
if ( iCoLand.landMgr.isOwner(player.getName(), id) ) {
if ( Misc.isAny(args[2], "name", "perms", "nospawn") ) {
String tags = "";
for(int i=3;i<args.length;i++) tags += args[i] + " ";
editLand(player, id, args[2], tags);
} else {
mess.send("{ERR}Not a valid category");
showHelp(sender,"edit");
}
} else {
mess.send("{ERR}Not owner of land ID# {PRM}"+id);
}
} else {
mess.send("{ERR}Land ID# {PRM}"+id+" {ERR}doesn't exist");
}
} else {
mess.send("{ERR}Too few arguments");
}
} else {
mess.send("{ERR}No access for edit");
}
return true;
// /icl modify <id> <perms|addons|name> <tags>
} else if (args[0].equalsIgnoreCase("modify") ) {
if ( iCoLand.hasPermission(sender, "admin.modify") ) {
if ( args.length < 4 ) {
mess.send("{ERR}Not enough arguments");
showHelp(sender, "modify");
} else {
Integer id;
try {
id = Integer.parseInt(args[1]);
} catch (NumberFormatException e) {
mess.send("{ERR}Error parsing <LANDID>");
return true;
}
if ( !iCoLand.landMgr.landIdExists(id) ) {
mess.send("{ERR}Land ID# {PRM}" + id + " {ERR}doesn't exist");
} else {
if ( Misc.isAny(args[2], "perms", "addons", "owner", "name") ) {
String tags = args[3];
for(int i=4;i<args.length;i++) tags += args[i];
adminEditLand(sender, id, args[2], tags);
} else {
mess.send("{ERR}Bad category");
}
}
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl select
} else if (args[0].equalsIgnoreCase("select") ) {
if ( iCoLand.hasPermission(sender, "basic.select") ) {
if ( !(sender instanceof Player) ) {
mess.send("Console can't select");
} else if ( args.length == 1 ) {
selectArea((Player)sender);
} else if ( args.length == 2 ) {
Player player = (Player)sender;
if ( args[1].equalsIgnoreCase("cancel") ) {
mess.send("{}Cancelling current selection.");
iCoLand.cmdMap.remove(player.getName());
iCoLand.tmpCuboidMap.remove(((Player)sender).getName());
} else if ( args[1].equalsIgnoreCase("fullheight") ) {
if ( iCoLand.tmpCuboidMap.containsKey(player.getName()) ) {
mess.send("{}Changing selection height to full height.");
iCoLand.tmpCuboidMap.get(player.getName()).setFullHeight();
int id = iCoLand.landMgr.intersectsExistingLand(iCoLand.tmpCuboidMap.get(player.getName()));
if ( id > 0 ) {
mess.send("{ERR}Intersects existing land!");
iCoLand.tmpCuboidMap.put(player.getName(), iCoLand.landMgr.getLandById(id).location);
} else {
mess.send("{}Selecting full height");
}
} else {
mess.send("{ERR}No currently selected land.");
}
} else {
int i = -1;
try {
i = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
}
if ( i > 0 ) {
if ( selectLand((Player)sender, i) ) {
mess.send("{}Selected land ID#{PRM}"+i);
} else {
mess.send("{ERR}No land ID#{PRM}"+i);
}
} else {
mess.send("Error parsing argument");
}
}
} else {
mess.send("{ERR}Too many arguments.");
showHelp(sender, "select");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl info [here|LANDID]
} else if (args[0].equalsIgnoreCase("info") ) {
if ( iCoLand.hasPermission(sender, "basic.info") ) {
if ( (args.length == 1) ) {
if ( sender instanceof Player )
showLandInfo(sender, "");
else
mess.send("{ERR}Console needs to supply arguments for this command");
} else if ( args.length == 2 ) {
showLandInfo(sender, args[1]);
} else {
mess.send("{ERR}Bad info command");
showHelp(sender, "info");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl buy land
// /icl buy addon <addon> <landID>
} else if (args[0].equalsIgnoreCase("buy") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can't buy");
} else if ( iCoLand.hasPermission(sender, "land.buy") ) {
if ( args.length == 1 ) {
mess.send("{ERR}Not enough arguments");
showHelp(sender,"buy");
} else {
if ( args.length == 2 && args[1].equalsIgnoreCase("land") ) {
buyLand(sender);
} else if ( args.length > 2 && args[1].equalsIgnoreCase("addon") ) {
if ( args.length == 4 ) {
if ( Config.isAddon(args[2]) ) {
try {
Integer id = Integer.parseInt(args[3]);
if ( iCoLand.landMgr.landIdExists(id) ) {
buyAddon((Player)sender, args[2], id);
} else {
mess.send("{ERR}Land ID# "+id+" does not exist!");
}
} catch (NumberFormatException ex) {
mess.send("{ERR}Error processing Land ID");
}
} else {
mess.send("{ERR}Not a valid addon");
}
} else {
mess.send("{ERR}Must specify which addon and land ID");
}
} else {
mess.send("{ERR}Bad buy command");
showHelp(sender, "buy");
}
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
// /icl sell land <ID>
// /icl sell addon <ADDON> <ID>
} else if (args[0].equalsIgnoreCase("sell") ) {
if ( !(sender instanceof Player) ) {
mess.send("{ERR}Console can't sell land");
} else if ( iCoLand.hasPermission(sender, "land.sell") ){
if ( args.length == 3 && args[1].equalsIgnoreCase("land") ) {
Integer id = 0;
try {
id = Integer.parseInt(args[2]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error parsing ID#");
}
if ( iCoLand.landMgr.landIdExists(id) ) {
sellLand((Player)sender, id);
} else {
mess.send("{ERR}Land ID# "+id+" does not exist");
}
} else if ( args.length == 4 && args[1].equalsIgnoreCase("addon") ) {
Integer id = 0;
try {
id = Integer.parseInt(args[3]);
} catch (NumberFormatException ex) {
mess.send("{ERR}Error parsing ID#");
}
if ( iCoLand.landMgr.landIdExists(id) ) {
if ( Config.isAddon(args[2]) ) {
sellAddon((Player)sender, args[2], id);
} else {
mess.send("{ERR}Not valid addon: {PRM}"+args[2]);
}
} else {
mess.send("{ERR}Land ID# "+id+" does not exist");
}
} else {
mess.send("{ERR}Bad sell command");
showHelp(sender,"sell");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("importdb") ) {
if ( iCoLand.hasPermission(sender, "admin.importdb") ) {
iCoLand.landMgr.importDB(new File(iCoLand.pluginDirectory + File.separator + Config.importFile));
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("exportdb") ) {
if ( iCoLand.hasPermission(sender, "admin.exportdb") ) {
iCoLand.landMgr.exportDB(new File(iCoLand.pluginDirectory + File.separator + Config.exportFile));
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("fakedata") ) {
if ( iCoLand.hasPermission(sender, "admin.fakedata") ) {
if ( args.length > 1 ) {
Integer numLands = 0;
try {
numLands = Integer.parseInt(args[1]);
} catch (NumberFormatException ex) {
ex.printStackTrace();
}
long start = System.currentTimeMillis();
for(int i=0;i<numLands;i++) {
Location loc1 = new Location(iCoLand.server.getWorlds().get(0), rand(-4096,4096), rand(5,100), rand(-4096,4096));
Location loc2 = new Location(iCoLand.server.getWorlds().get(0), loc1.getBlockX()+rand(0,100), loc1.getBlockY()+rand(0,28), loc1.getBlockZ()+rand(0,100));
iCoLand.landMgr.addLand(new Cuboid(loc1,loc2), ((sender instanceof Player)?((Player)sender).getName():"kigam"), "", "");
}
if ( Config.debugMode ) iCoLand.info("Inserting "+numLands+" random lands took: "+(System.currentTimeMillis()-start)+" ms");
} else {
mess.send("{ERR}Not enough arguments");
}
} else {
mess.send("{ERR}No access for that...");
}
return true;
} else if ( args[0].equalsIgnoreCase("fixperms") ) {
if ( iCoLand.hasPermission(sender, "admin.fixperms") ) {
ArrayList<Land> lands = iCoLand.landMgr.getAllLands();
for(Land land: lands) {
iCoLand.landMgr.updatePerms(land.getID(), Land.writePermTags(land.canBuildDestroy));
}
mess.send("{}Done...");
} else {
mess.send("{ERR}No access for that...");
}
return true;
// unrecognized /icl command
} else {
mess.send("{}Unrecognized/invalid/malformed command!");
mess.send("{} Please use {CMD}/icl help {BKT}[{PRM}topic{BKT}] {}for help");
return true;
}
// command not recognized ( not /icl )
} else {
return false;
}
}
|
diff --git a/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java b/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java
index 298192cc1..1a170c293 100644
--- a/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java
+++ b/dev/core/src/com/google/gwt/soyc/MakeTopLevelHtmlForPerm.java
@@ -1,916 +1,916 @@
/*
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.soyc;
import com.google.gwt.dev.util.Util;
import com.google.gwt.soyc.io.OutputDirectory;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A utility to make the top level HTTML file for one permutation.
*/
public class MakeTopLevelHtmlForPerm {
/**
* A dependency linker for the initial code download. It links to the
* dependencies for the initial download.
*/
public class DependencyLinkerForInitialCode implements DependencyLinker {
public String dependencyLinkForClass(String className) {
String packageName = globalInformation.getClassToPackage().get(className);
assert packageName != null;
return dependenciesFileName("initial", packageName) + "#" + className;
}
}
/**
* A dependency linker for the leftovers fragment. It links to leftovers
* status pages.
*/
public class DependencyLinkerForLeftoversFragment implements DependencyLinker {
public String dependencyLinkForClass(String className) {
return leftoversStatusFileName(className);
}
}
/**
* A dependency linker for the total program breakdown. It links to a split
* status page.
*
*/
public class DependencyLinkerForTotalBreakdown implements DependencyLinker {
public String dependencyLinkForClass(String className) {
return splitStatusFileName(className);
}
}
/**
* A dependency linker that never links to anything.
*/
public static class NullDependencyLinker implements DependencyLinker {
public String dependencyLinkForClass(String className) {
return null;
}
}
interface DependencyLinker {
String dependencyLinkForClass(String className);
}
/**
* By a convention shared with the compiler, the initial download is fragment
* number 0.
*/
private static final int FRAGMENT_NUMBER_INITIAL_DOWNLOAD = 0;
/**
* Just within this file, the convention is that the total program is fragment
* number -1.
*/
private static final int FRAGMENT_NUMBER_TOTAL_PROGRAM = -1;
/**
* A pattern describing the name of dependency graphs for code fragments
* corresponding to a specific split point. These can be either exclusive
* fragments or fragments of code for split points in the initial load
* sequence.
*/
private static final Pattern PATTERN_SP_INT = Pattern.compile("sp([0-9]+)");
private static String escapeXml(String unescaped) {
String escaped = unescaped.replaceAll("\\&", "&");
escaped = escaped.replaceAll("\\<", "<");
escaped = escaped.replaceAll("\\>", ">");
escaped = escaped.replaceAll("\\\"", """);
escaped = escaped.replaceAll("\\'", "'");
return escaped;
}
public static void makeTopLevelHtmlForAllPerms(
Map<String, String> allPermsInfo, OutputDirectory outDir)
throws IOException {
PrintWriter outFile = new PrintWriter(outDir.getOutputStream("index.html"));
addStandardHtmlProlog(outFile, "Compile report", "Compile report",
"Overview of permutations");
outFile.println("<ul>");
for (String permutationId : allPermsInfo.keySet()) {
String permutationInfo = allPermsInfo.get(permutationId);
outFile.print("<li><a href=\"SoycDashboard" + "-" + permutationId
+ "-index.html\">Permutation " + permutationId);
if (permutationInfo.length() > 0) {
outFile.println(" (" + permutationInfo + ")" + "</a></li>");
} else {
outFile.println("</a>");
}
}
outFile.println("</ul>");
addStandardHtmlEnding(outFile);
outFile.close();
}
private static void addSmallHtmlProlog(final PrintWriter outFile, String title) {
outFile.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"");
outFile.println("\"http://www.w3.org/TR/html4/strict.dtd\">");
outFile.println("<html>");
outFile.println("<head>");
outFile.println("<title>");
outFile.println(title);
outFile.println("</title>");
outFile.println("<style type=\"text/css\" media=\"screen\">");
outFile.println("@import url('goog.css');");
outFile.println("@import url('inlay.css');");
outFile.println("@import url('soyc.css');");
outFile.println("</style>");
outFile.println("</head>");
}
private static void addStandardHtmlEnding(final PrintWriter out) {
out.println("</div>");
out.println("</body>");
out.println("</html>");
}
private static void addStandardHtmlProlog(final PrintWriter outFile,
String title, String header1, String header2) {
outFile.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"");
outFile.println("\"http://www.w3.org/TR/html4/strict.dtd\">");
outFile.println("<html>");
outFile.println("<head>");
outFile.println("<title>");
outFile.println(title);
outFile.println("</title>");
outFile.println("<style type=\"text/css\" media=\"screen\">");
outFile.println("@import url('goog.css');");
outFile.println("@import url('inlay.css');");
outFile.println("@import url('soyc.css');");
outFile.println("</style>");
outFile.println("</head>");
outFile.println("<body>");
outFile.println("<div class=\"g-doc\">");
outFile.println("<div id=\"hd\" class=\"g-section g-tpl-50-50 g-split\">");
outFile.println("<div class=\"g-unit g-first\">");
outFile.println("<p>");
outFile.println("<a href=\"index.html\" id=\"gwt-logo\" class=\"soyc-ir\"><span>Google Web Toolkit</span></a>");
outFile.println("</p>");
outFile.println("</div>");
outFile.println("<div class=\"g-unit\">");
outFile.println("</div>");
outFile.println("</div>");
outFile.println("<div id=\"soyc-appbar-lrg\">");
outFile.println("<div class=\"g-section g-tpl-75-25 g-split\">");
outFile.println("<div class=\"g-unit g-first\">");
outFile.println("<h1>" + header1 + "</h1>");
outFile.println("</div>");
outFile.println("<div class=\"g-unit\"></div>");
outFile.println("</div>");
outFile.println("</div>");
outFile.println("<div id=\"bd\">");
outFile.println("<h2>" + header2 + "</h2>");
}
private static String classesInPackageFileName(SizeBreakdown breakdown,
String packageName, String permutationId) {
return breakdown.getId() + "_" + filename(packageName) + "-"
+ permutationId + "_Classes.html";
}
/**
* Convert a potentially long string into a short file name. The current
* implementation simply hashes the long name.
*/
private static String filename(String longFileName) {
try {
return Util.computeStrongName(longFileName.getBytes(Util.DEFAULT_ENCODING));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private static String headerLineForBreakdown(SizeBreakdown breakdown) {
return "(Analyzing code subset: " + breakdown.getDescription() + ")";
}
private static String shellFileName(SizeBreakdown breakdown,
String permutationId) {
return breakdown.getId() + "-" + permutationId + "-overallBreakdown.html";
}
/**
* Global information for this permutation.
*/
private final GlobalInformation globalInformation;
private final OutputDirectory outDir;
MakeTopLevelHtmlForPerm(GlobalInformation globalInformation,
OutputDirectory outDir) {
this.globalInformation = globalInformation;
this.outDir = outDir;
}
public void makeBreakdownShell(SizeBreakdown breakdown) throws IOException {
Map<String, CodeCollection> nameToCodeColl = breakdown.nameToCodeColl;
Map<String, LiteralsCollection> nameToLitColl = breakdown.nameToLitColl;
String packageBreakdownFileName = makePackageHtml(breakdown);
String codeTypeBreakdownFileName = makeCodeTypeHtml(breakdown,
nameToCodeColl, nameToLitColl);
PrintWriter outFile = new PrintWriter(getOutFile(shellFileName(breakdown,
getPermutationId())));
addStandardHtmlProlog(outFile, "Application breakdown analysis",
"Application breakdown analysis", "");
outFile.println("<div id=\"bd\"> ");
outFile.println("<h2>Package breakdown</h2>");
outFile.println("<iframe class='soyc-iframe-package' src=\""
+ packageBreakdownFileName + "\" scrolling=auto></iframe>");
outFile.println("<h2>Code type breakdown</h2>");
outFile.println("<iframe class='soyc-iframe-code' src=\""
+ codeTypeBreakdownFileName + "\" scrolling=auto></iframe>");
outFile.println("</div>");
addStandardHtmlEnding(outFile);
outFile.close();
}
public void makeCodeTypeClassesHtmls(SizeBreakdown breakdown)
throws IOException {
HashMap<String, CodeCollection> nameToCodeColl = breakdown.nameToCodeColl;
for (String codeType : nameToCodeColl.keySet()) {
// construct file name
String outFileName = breakdown.getId() + "_" + codeType + "-"
+ getPermutationId() + "Classes.html";
float sumSize = 0f;
TreeMap<Float, String> sortedClasses = new TreeMap<Float, String>(
Collections.reverseOrder());
for (String className : nameToCodeColl.get(codeType).classes) {
if (breakdown.classToSize.containsKey(className)) {
float curSize = 0f;
if (breakdown.classToSize.containsKey(className)) {
curSize = breakdown.classToSize.get(className);
}
if (curSize != 0f) {
sortedClasses.put(curSize, className);
sumSize += curSize;
}
}
}
final PrintWriter outFile = new PrintWriter(getOutFile(outFileName));
addStandardHtmlProlog(outFile, "Classes in package " + codeType,
"Classes in package " + codeType, headerLineForBreakdown(breakdown));
outFile.println("<table class=\"soyc-table\">");
outFile.println("<colgroup>");
outFile.println("<col id=\"soyc-splitpoint-type-col\">");
outFile.println("<col id=\"soyc-splitpoint-size-col\">");
outFile.println("</colgroup>");
outFile.println("<thead>");
outFile.println("<th>Code type</th>");
outFile.println("<th>Size <span class=\"soyc-th-units\">Bytes (% All Code)</span></th>");
outFile.println("</thead>");
for (Float size : sortedClasses.keySet()) {
String className = sortedClasses.get(size);
float perc = (size / sumSize) * 100;
outFile.println("<tr>");
outFile.println("<td>" + className + "</a></td>");
outFile.println("<td>");
outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">");
outFile.println("<div style=\"width:" + perc
+ "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>");
outFile.println("</div>");
outFile.println(size + " (" + formatNumber(perc) + "%)");
outFile.println("</td>");
outFile.println("</tr>");
}
addStandardHtmlEnding(outFile);
outFile.close();
}
}
public void makeDependenciesHtml() throws IOException {
for (String depGraphName : globalInformation.dependencies.keySet()) {
makeDependenciesHtml(depGraphName,
globalInformation.dependencies.get(depGraphName));
}
}
public void makeLeftoverStatusPages() throws IOException {
for (String className : globalInformation.getClassToPackage().keySet()) {
makeLeftoversStatusPage(className);
}
}
public void makeLiteralsClassesTableHtmls(SizeBreakdown breakdown)
throws IOException {
Map<String, LiteralsCollection> nameToLitColl = breakdown.nameToLitColl;
for (String literalType : nameToLitColl.keySet()) {
String outFileName = literalType + "-" + getPermutationId() + "Lits.html";
final PrintWriter outFile = new PrintWriter(getOutFile(breakdown.getId()
+ "_" + outFileName));
addStandardHtmlProlog(outFile, "Literals of type " + literalType,
"Literals of type " + literalType, headerLineForBreakdown(breakdown));
outFile.println("<table width=\"80%\" style=\"font-size: 11pt;\" bgcolor=\"white\">");
for (String literal : nameToLitColl.get(literalType).literals) {
if (literal.trim().length() == 0) {
literal = "[whitespace only string]";
}
String escliteral = escapeXml(literal);
outFile.println("<tr>");
outFile.println("<td>" + escliteral + "</td>");
outFile.println("</tr>");
}
outFile.println("</table>");
outFile.println("<center>");
addStandardHtmlEnding(outFile);
outFile.close();
}
}
/**
* Make size breakdowns for each package for one code collection.
*/
public void makePackageClassesHtmls(SizeBreakdown breakdown,
DependencyLinker depLinker) throws IOException {
for (String packageName : globalInformation.getPackageToClasses().keySet()) {
TreeMap<Float, String> sortedClasses = new TreeMap<Float, String>(
Collections.reverseOrder());
float sumSize = 0f;
for (String className : globalInformation.getPackageToClasses().get(
packageName)) {
float curSize = 0f;
if (!breakdown.classToSize.containsKey(className)) {
// This class not present in this code collection
} else {
curSize = breakdown.classToSize.get(className);
}
if (curSize != 0f) {
sumSize += curSize;
sortedClasses.put(curSize, className);
}
}
PrintWriter outFile = new PrintWriter(
getOutFile(classesInPackageFileName(breakdown, packageName,
getPermutationId())));
addStandardHtmlProlog(outFile, "Classes in package " + packageName,
"Classes in package " + packageName,
headerLineForBreakdown(breakdown));
outFile.println("<table class=\"soyc-table\">");
outFile.println("<colgroup>");
outFile.println("<col id=\"soyc-splitpoint-type-col\">");
outFile.println("<col id=\"soyc-splitpoint-size-col\">");
outFile.println("</colgroup>");
outFile.println("<thead>");
outFile.println("<th>Package</th>");
outFile.println("<th>Size <span class=\"soyc-th-units\">Bytes (% All Code)</span></th>");
outFile.println("</thead>");
for (Float size : sortedClasses.keySet()) {
String className = sortedClasses.get(size);
String drillDownFileName = depLinker.dependencyLinkForClass(className);
float perc = (size / sumSize) * 100;
outFile.println("<tr>");
if (drillDownFileName == null) {
outFile.println("<td>" + className + "</td>");
} else {
outFile.println("<td><a href=\"" + drillDownFileName
+ "\" target=\"_top\">" + className + "</a></td>");
}
outFile.println("<td>");
outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">");
outFile.println("<div style=\"width:" + perc
+ "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>");
outFile.println("</div>");
outFile.println(size + " (" + formatNumber(perc) + "%)");
outFile.println("</td>");
outFile.println("</tr>");
}
outFile.println("</table>");
addStandardHtmlEnding(outFile);
outFile.close();
}
}
public void makeSplitStatusPages() throws IOException {
for (String className : globalInformation.getClassToPackage().keySet()) {
makeSplitStatusPage(className);
}
}
public void makeTopLevelShell() throws IOException {
String permutationId = getPermutationId();
PrintWriter outFile = new PrintWriter(getOutFile("SoycDashboard" + "-"
+ getPermutationId() + "-index.html"));
addStandardHtmlProlog(outFile, "Compile report: Permutation "
+ permutationId, "Compile report: Permutation " + permutationId, "");
outFile.println("<div id=\"bd\">");
outFile.println("<div id=\"soyc-summary\" class=\"g-section\">");
outFile.println("<dl>");
outFile.println("<dt>Full code size</dt>");
outFile.println("<dd class=\"value\">"
- + globalInformation.getInitialCodeBreakdown().sizeAllCode
+ + globalInformation.getTotalCodeBreakdown().sizeAllCode
+ " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"total-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("<dl>");
outFile.println("<dt>Initial download size</dt>");
// TODO(kprobst) -- add percentage here: (48%)</dd>");
outFile.println("<dd class=\"value\">"
- + globalInformation.getTotalCodeBreakdown().sizeAllCode + " Bytes</dd>");
+ + globalInformation.getInitialCodeBreakdown().sizeAllCode + " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"initial-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("<dl>");
outFile.println("<dt>Left over code</dt>");
outFile.println("<dd class=\"value\">"
+ globalInformation.getLeftoversBreakdown().sizeAllCode + " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"leftovers-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("</div>");
outFile.println("<table id=\"soyc-table-splitpoints\" class=\"soyc-table\">");
outFile.println("<caption>");
outFile.println("<strong>Split Points</strong>");
outFile.println("</caption>");
outFile.println("<colgroup>");
outFile.println("<col id=\"soyc-splitpoint-number-col\">");
outFile.println("<col id=\"soyc-splitpoint-location-col\">");
outFile.println("<col id=\"soyc-splitpoint-size-col\">");
outFile.println("</colgroup>");
outFile.println("<thead>");
outFile.println("<th>#</th>");
outFile.println("<th>Location</th>");
outFile.println("<th>Size</th>");
outFile.println("</thead>");
outFile.println("<tbody>");
- if (globalInformation.getSplitPointToLocation().size() > 1) {
+ if (globalInformation.getSplitPointToLocation().size() >= 1) {
int numSplitPoints = globalInformation.getSplitPointToLocation().size();
float maxSize = globalInformation.getTotalCodeBreakdown().sizeAllCode;
for (int i = FRAGMENT_NUMBER_TOTAL_PROGRAM; i <= numSplitPoints + 1; i++) {
SizeBreakdown breakdown;
if (i == FRAGMENT_NUMBER_TOTAL_PROGRAM) {
continue;
} else if (i == numSplitPoints + 1) { // leftovers
continue;
} else if (i == FRAGMENT_NUMBER_INITIAL_DOWNLOAD) {
continue;
} else {
breakdown = globalInformation.splitPointCodeBreakdown(i);
}
String drillDownFileName = shellFileName(breakdown, getPermutationId());
String splitPointDescription = globalInformation.getSplitPointToLocation().get(
i);
float size = breakdown.sizeAllCode;
float ratio;
ratio = (size / maxSize) * 100;
outFile.println("<tr>");
outFile.println("<td>" + i + "</td>");
outFile.println("<td><a href=\"" + drillDownFileName + "\">"
+ splitPointDescription + "</a></td>");
outFile.println("<td>");
outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">");
outFile.println("<div style=\"width:" + ratio
+ "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>");
outFile.println("</div>");
outFile.println((int) size + " Bytes (" + formatNumber(ratio) + "%)");
outFile.println("</td>");
outFile.println("</tr>");
}
}
outFile.println("</tbody>");
outFile.println("</table>");
outFile.println("</div>");
addStandardHtmlEnding(outFile);
outFile.close();
}
private void addLefttoversStatus(String className, String packageName,
PrintWriter outFile) {
outFile.println("<ul class=\"soyc-exclusive\">");
if (globalInformation.dependencies != null) {
outFile.println("<li><a href=\""
+ dependenciesFileName("total", packageName) + "#" + className
+ "\">See why it's live</a></li>");
for (int sp = 1; sp <= globalInformation.getNumSplitPoints(); sp++) {
outFile.println("<li><a href=\""
+ dependenciesFileName("sp" + sp, packageName) + "#" + className
+ "\">See why it's not exclusive to s.p. #" + sp + " ("
+ globalInformation.getSplitPointToLocation().get(sp)
+ ")</a></li>");
}
}
outFile.println("</ul>");
}
/**
* Returns a file name for the dependencies list.
*/
private String dependenciesFileName(String depGraphName, String packageName) {
return "methodDependencies-" + depGraphName + "-" + filename(packageName)
+ "-" + getPermutationId() + ".html";
}
/**
* Format floating point number to two decimal points.
*
* @param number
* @return formatted number
*/
private String formatNumber(float number) {
DecimalFormat formatBy = new DecimalFormat("#.##");
return formatBy.format(number);
}
/**
* Return a {@link File} object for a file to be emitted into the output
* directory.
*/
private OutputStream getOutFile(String localFileName) throws IOException {
return outDir.getOutputStream(localFileName);
}
/**
* @return the ID for the current permutation
*/
private String getPermutationId() {
return globalInformation.getPermutationId();
}
/**
* Describe the code covered by the dependency graph with the supplied name.
*/
private String inferDepGraphDescription(String depGraphName) {
if (depGraphName.equals("initial")) {
return "Initially Live Code";
}
if (depGraphName.equals("total")) {
return "All Code";
}
Matcher matcher = PATTERN_SP_INT.matcher(depGraphName);
if (matcher.matches()) {
int splitPoint = Integer.valueOf(matcher.group(1));
if (isInitialSplitPoint(splitPoint)) {
return "Code Becoming Live at Split Point " + splitPoint;
} else {
return "Code not Exclusive to Split Point " + splitPoint;
}
}
throw new RuntimeException("Unexpected dependency graph name: "
+ depGraphName);
}
/**
* Returns whether a split point is initial or not.
*
* @param splitPoint
* @returns true of the split point is initial, false otherwise
*/
private boolean isInitialSplitPoint(int splitPoint) {
return globalInformation.getSplitPointInitialLoadSequence().contains(
splitPoint);
}
/**
* Makes a file name for a leftovers status file.
*
* @param className
* @return the file name of the leftovers status file
*/
private String leftoversStatusFileName(String className) {
return "leftoverStatus-" + filename(className) + "-" + getPermutationId()
+ ".html";
}
/**
* Produces an HTML file that breaks down by code type.
*
* @param breakdown
* @param nameToCodeColl
* @param nameToLitColl
* @return the name of the produced file
* @throws IOException
*/
private String makeCodeTypeHtml(SizeBreakdown breakdown,
Map<String, CodeCollection> nameToCodeColl,
Map<String, LiteralsCollection> nameToLitColl) throws IOException {
String outFileName = breakdown.getId() + "-" + getPermutationId()
+ "-codeTypeBreakdown.html";
float sumSize = 0f;
TreeMap<Float, String> sortedCodeTypes = new TreeMap<Float, String>(
Collections.reverseOrder());
for (String codeType : nameToCodeColl.keySet()) {
float curSize = nameToCodeColl.get(codeType).getCumPartialSize(breakdown);
sumSize += curSize;
if (curSize != 0f) {
sortedCodeTypes.put(curSize, codeType);
}
}
final PrintWriter outFile = new PrintWriter(getOutFile(outFileName));
addSmallHtmlProlog(outFile, "Code breakdown");
outFile.println("<body class=\"soyc-breakdown\">");
outFile.println("<div class=\"g-doc\">");
outFile.println("<table class=\"soyc-table\">");
outFile.println("<colgroup>");
outFile.println("<col id=\"soyc-splitpoint-type-col\">");
outFile.println("<col id=\"soyc-splitpoint-size-col\">");
outFile.println("</colgroup>");
outFile.println("<thead>");
outFile.println("<th>Type</th>");
outFile.println("<th>Size</th>");
outFile.println("</thead>");
for (Float size : sortedCodeTypes.keySet()) {
String codeType = sortedCodeTypes.get(size);
String drillDownFileName = breakdown.getId() + "_" + codeType + "-"
+ getPermutationId() + "Classes.html";
float perc = (size / sumSize) * 100;
outFile.println("<tr>");
outFile.println("<td><a href=\"" + drillDownFileName
+ "\" target=\"_top\">" + codeType + "</a></td>");
outFile.println("<td>");
outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">");
outFile.println("<div style=\"width:" + perc
+ "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>");
outFile.println("</div>");
outFile.println(size + " (" + formatNumber(perc) + "%)");
outFile.println("</td>");
outFile.println("</tr>");
}
outFile.println("</table>");
TreeMap<Float, String> sortedLitTypes = new TreeMap<Float, String>(
Collections.reverseOrder());
float curSize = nameToLitColl.get("string").size;
sumSize += curSize;
if (curSize != 0f) {
sortedLitTypes.put(curSize, "string");
}
for (Float size : sortedLitTypes.keySet()) {
String literal = sortedLitTypes.get(size);
String drillDownFileName = breakdown.getId() + "_" + literal + "-"
+ getPermutationId() + "Lits.html";
outFile.println("<p class=\"soyc-breakdown-strings\"><a href=\""
+ drillDownFileName + "\" target=\"_top\">Strings</a> occupy " + size
+ " bytes</p>");
}
addStandardHtmlEnding(outFile);
outFile.close();
return outFileName;
}
/**
* Produces an HTML file that displays dependencies.
*
* @param depGraphName name of dependency graph
* @param dependencies map of dependencies
* @throws IOException
*/
private void makeDependenciesHtml(String depGraphName,
Map<String, String> dependencies) throws IOException {
String depGraphDescription = inferDepGraphDescription(depGraphName);
PrintWriter outFile = null;
String curPackageName = "";
String curClassName = "";
for (String method : dependencies.keySet()) {
// this key set is already in alphabetical order
// get the package of this method, i.e., everything up to .[A-Z]
String packageName = method;
packageName = packageName.replaceAll("\\.\\p{Upper}.*", "");
String className = method;
className = className.replaceAll("::.*", "");
if ((curPackageName.compareTo("") == 0)
|| (curPackageName.compareTo(packageName) != 0)) {
curPackageName = packageName;
if (outFile != null) {
// finish up the current file
addStandardHtmlEnding(outFile);
outFile.close();
}
String outFileName = dependenciesFileName(depGraphName, curPackageName);
outFile = new PrintWriter(getOutFile(outFileName));
String packageDescription = packageName.length() == 0
? "the default package" : packageName;
addStandardHtmlProlog(outFile, "Method Dependencies for "
+ depGraphDescription, "Method Dependencies for "
+ depGraphDescription, "Showing Package: " + packageDescription);
}
String name = method;
if (curClassName.compareTo(className) != 0) {
name = className;
curClassName = className;
outFile.println("<a name=\"" + curClassName
+ "\"><h3 class=\"soyc-class-header\">Class: " + curClassName
+ "</a></h3>");
}
outFile.println("<div class='main'>");
outFile.println("<a class='toggle soyc-call-stack-link' onclick='toggle.call(this)'><span class='calledBy'> Call stack: </span>"
+ name + "</a>");
outFile.println("<ul class=\"soyc-call-stack-list\">");
String depMethod = dependencies.get(method);
while (depMethod != null) {
String nextDep = dependencies.get(depMethod);
if (nextDep != null) {
outFile.println("<li>" + depMethod + "</li>");
}
depMethod = nextDep;
}
outFile.println("</ul>");
outFile.println("</div>");
}
addStandardHtmlEnding(outFile);
outFile.close();
}
/**
* Produces an HTML file for leftovers status.
*
* @param className
* @throws IOException
*/
private void makeLeftoversStatusPage(String className) throws IOException {
String packageName = globalInformation.getClassToPackage().get(className);
PrintWriter outFile = new PrintWriter(
getOutFile(leftoversStatusFileName(className)));
addStandardHtmlProlog(outFile, "Leftovers page for " + className,
"Leftovers page for " + className, "");
outFile.println("<div id=\"bd\">");
outFile.println("<p>This class has some leftover code, neither initial nor exclusive to any split point:</p>");
addLefttoversStatus(className, packageName, outFile);
addStandardHtmlEnding(outFile);
outFile.close();
}
/**
* Produces an HTML file that shows information about a package.
*
* @param breakdown
* @return the name of the HTML file
* @throws IOException
*/
private String makePackageHtml(SizeBreakdown breakdown) throws IOException {
String outFileName = breakdown.getId() + "-" + getPermutationId() + "-"
+ "packageBreakdown.html";
Map<String, Integer> packageToPartialSize = breakdown.packageToSize;
TreeMap<Integer, String> sortedPackages = new TreeMap<Integer, String>(
Collections.reverseOrder());
float sumSize = 0f;
for (String packageName : packageToPartialSize.keySet()) {
sortedPackages.put(packageToPartialSize.get(packageName), packageName);
sumSize += packageToPartialSize.get(packageName);
}
final PrintWriter outFile = new PrintWriter(getOutFile(outFileName));
addSmallHtmlProlog(outFile, "Package breakdown");
outFile.println("<body class=\"soyc-breakdown\">");
outFile.println("<div class=\"g-doc\">");
outFile.println("<table class=\"soyc-table\">");
outFile.println("<colgroup>");
outFile.println("<col id=\"soyc-splitpoint-type-col\">");
outFile.println("<col id=\"soyc-splitpoint-size-col\">");
outFile.println("</colgroup>");
outFile.println("<thead>");
outFile.println("<th>Package</th>");
outFile.println("<th>Size <span class=\"soyc-th-units\">Bytes (% All Code)</span></th>");
outFile.println("</thead>");
for (int size : sortedPackages.keySet()) {
String packageName = sortedPackages.get(size);
String drillDownFileName = classesInPackageFileName(breakdown,
packageName, getPermutationId());
float perc = (size / sumSize) * 100;
outFile.println("<tr>");
outFile.println("<td><a href=\"" + drillDownFileName
+ "\" target=\"_top\">" + packageName + "</a></td>");
outFile.println("<td>");
outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">");
outFile.println("<div style=\"width:" + perc
+ "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>");
outFile.println("</div>");
outFile.println(size + " (" + formatNumber(perc) + "%)");
outFile.println("</td>");
outFile.println("</tr>");
}
outFile.println("</table>");
addStandardHtmlEnding(outFile);
outFile.close();
return outFileName;
}
private void makeSplitStatusPage(String className) throws IOException {
String packageName = globalInformation.getClassToPackage().get(className);
PrintWriter outFile = new PrintWriter(
getOutFile(splitStatusFileName(className)));
addStandardHtmlProlog(outFile, "Split point status for " + className,
"Split point status for " + className, "");
outFile.println("<div id=\"bd\">");
if (globalInformation.getInitialCodeBreakdown().classToSize.containsKey(className)) {
if (globalInformation.dependencies != null) {
outFile.println("<p>Some code is included in the initial fragment (<a href=\""
+ dependenciesFileName("initial", packageName)
+ "#"
+ className
+ "\">see why</a>)</p>");
} else {
outFile.println("<p>Some code is included in the initial fragment</p>");
}
}
for (int sp : splitPointsWithClass(className)) {
outFile.println("<p>Some code downloads with split point " + sp + ": "
+ globalInformation.getSplitPointToLocation().get(sp) + "</p>");
}
if (globalInformation.getLeftoversBreakdown().classToSize.containsKey(className)) {
outFile.println("<p>Some code is left over:</p>");
addLefttoversStatus(className, packageName, outFile);
}
addStandardHtmlEnding(outFile);
outFile.close();
}
/**
* Find which split points include code belonging to <code>className</code>.
*/
private Iterable<Integer> splitPointsWithClass(String className) {
List<Integer> sps = new ArrayList<Integer>();
for (int sp = 1; sp <= globalInformation.getNumSplitPoints(); sp++) {
Map<String, Integer> classToSize = globalInformation.splitPointCodeBreakdown(sp).classToSize;
if (classToSize.containsKey(className)) {
sps.add(sp);
}
}
return sps;
}
private String splitStatusFileName(String className) {
return "splitStatus-" + filename(className) + "-" + getPermutationId()
+ ".html";
}
}
| false | true | public void makeTopLevelShell() throws IOException {
String permutationId = getPermutationId();
PrintWriter outFile = new PrintWriter(getOutFile("SoycDashboard" + "-"
+ getPermutationId() + "-index.html"));
addStandardHtmlProlog(outFile, "Compile report: Permutation "
+ permutationId, "Compile report: Permutation " + permutationId, "");
outFile.println("<div id=\"bd\">");
outFile.println("<div id=\"soyc-summary\" class=\"g-section\">");
outFile.println("<dl>");
outFile.println("<dt>Full code size</dt>");
outFile.println("<dd class=\"value\">"
+ globalInformation.getInitialCodeBreakdown().sizeAllCode
+ " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"total-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("<dl>");
outFile.println("<dt>Initial download size</dt>");
// TODO(kprobst) -- add percentage here: (48%)</dd>");
outFile.println("<dd class=\"value\">"
+ globalInformation.getTotalCodeBreakdown().sizeAllCode + " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"initial-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("<dl>");
outFile.println("<dt>Left over code</dt>");
outFile.println("<dd class=\"value\">"
+ globalInformation.getLeftoversBreakdown().sizeAllCode + " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"leftovers-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("</div>");
outFile.println("<table id=\"soyc-table-splitpoints\" class=\"soyc-table\">");
outFile.println("<caption>");
outFile.println("<strong>Split Points</strong>");
outFile.println("</caption>");
outFile.println("<colgroup>");
outFile.println("<col id=\"soyc-splitpoint-number-col\">");
outFile.println("<col id=\"soyc-splitpoint-location-col\">");
outFile.println("<col id=\"soyc-splitpoint-size-col\">");
outFile.println("</colgroup>");
outFile.println("<thead>");
outFile.println("<th>#</th>");
outFile.println("<th>Location</th>");
outFile.println("<th>Size</th>");
outFile.println("</thead>");
outFile.println("<tbody>");
if (globalInformation.getSplitPointToLocation().size() > 1) {
int numSplitPoints = globalInformation.getSplitPointToLocation().size();
float maxSize = globalInformation.getTotalCodeBreakdown().sizeAllCode;
for (int i = FRAGMENT_NUMBER_TOTAL_PROGRAM; i <= numSplitPoints + 1; i++) {
SizeBreakdown breakdown;
if (i == FRAGMENT_NUMBER_TOTAL_PROGRAM) {
continue;
} else if (i == numSplitPoints + 1) { // leftovers
continue;
} else if (i == FRAGMENT_NUMBER_INITIAL_DOWNLOAD) {
continue;
} else {
breakdown = globalInformation.splitPointCodeBreakdown(i);
}
String drillDownFileName = shellFileName(breakdown, getPermutationId());
String splitPointDescription = globalInformation.getSplitPointToLocation().get(
i);
float size = breakdown.sizeAllCode;
float ratio;
ratio = (size / maxSize) * 100;
outFile.println("<tr>");
outFile.println("<td>" + i + "</td>");
outFile.println("<td><a href=\"" + drillDownFileName + "\">"
+ splitPointDescription + "</a></td>");
outFile.println("<td>");
outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">");
outFile.println("<div style=\"width:" + ratio
+ "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>");
outFile.println("</div>");
outFile.println((int) size + " Bytes (" + formatNumber(ratio) + "%)");
outFile.println("</td>");
outFile.println("</tr>");
}
}
outFile.println("</tbody>");
outFile.println("</table>");
outFile.println("</div>");
addStandardHtmlEnding(outFile);
outFile.close();
}
| public void makeTopLevelShell() throws IOException {
String permutationId = getPermutationId();
PrintWriter outFile = new PrintWriter(getOutFile("SoycDashboard" + "-"
+ getPermutationId() + "-index.html"));
addStandardHtmlProlog(outFile, "Compile report: Permutation "
+ permutationId, "Compile report: Permutation " + permutationId, "");
outFile.println("<div id=\"bd\">");
outFile.println("<div id=\"soyc-summary\" class=\"g-section\">");
outFile.println("<dl>");
outFile.println("<dt>Full code size</dt>");
outFile.println("<dd class=\"value\">"
+ globalInformation.getTotalCodeBreakdown().sizeAllCode
+ " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"total-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("<dl>");
outFile.println("<dt>Initial download size</dt>");
// TODO(kprobst) -- add percentage here: (48%)</dd>");
outFile.println("<dd class=\"value\">"
+ globalInformation.getInitialCodeBreakdown().sizeAllCode + " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"initial-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("<dl>");
outFile.println("<dt>Left over code</dt>");
outFile.println("<dd class=\"value\">"
+ globalInformation.getLeftoversBreakdown().sizeAllCode + " Bytes</dd>");
outFile.println("<dd class=\"report\"><a href=\"leftovers-" + permutationId
+ "-overallBreakdown.html\">Report</a></dd>");
outFile.println("</dl>");
outFile.println("</div>");
outFile.println("<table id=\"soyc-table-splitpoints\" class=\"soyc-table\">");
outFile.println("<caption>");
outFile.println("<strong>Split Points</strong>");
outFile.println("</caption>");
outFile.println("<colgroup>");
outFile.println("<col id=\"soyc-splitpoint-number-col\">");
outFile.println("<col id=\"soyc-splitpoint-location-col\">");
outFile.println("<col id=\"soyc-splitpoint-size-col\">");
outFile.println("</colgroup>");
outFile.println("<thead>");
outFile.println("<th>#</th>");
outFile.println("<th>Location</th>");
outFile.println("<th>Size</th>");
outFile.println("</thead>");
outFile.println("<tbody>");
if (globalInformation.getSplitPointToLocation().size() >= 1) {
int numSplitPoints = globalInformation.getSplitPointToLocation().size();
float maxSize = globalInformation.getTotalCodeBreakdown().sizeAllCode;
for (int i = FRAGMENT_NUMBER_TOTAL_PROGRAM; i <= numSplitPoints + 1; i++) {
SizeBreakdown breakdown;
if (i == FRAGMENT_NUMBER_TOTAL_PROGRAM) {
continue;
} else if (i == numSplitPoints + 1) { // leftovers
continue;
} else if (i == FRAGMENT_NUMBER_INITIAL_DOWNLOAD) {
continue;
} else {
breakdown = globalInformation.splitPointCodeBreakdown(i);
}
String drillDownFileName = shellFileName(breakdown, getPermutationId());
String splitPointDescription = globalInformation.getSplitPointToLocation().get(
i);
float size = breakdown.sizeAllCode;
float ratio;
ratio = (size / maxSize) * 100;
outFile.println("<tr>");
outFile.println("<td>" + i + "</td>");
outFile.println("<td><a href=\"" + drillDownFileName + "\">"
+ splitPointDescription + "</a></td>");
outFile.println("<td>");
outFile.println("<div class=\"soyc-bar-graph goog-inline-block\">");
outFile.println("<div style=\"width:" + ratio
+ "%;\" class=\"soyc-bar-graph-fill goog-inline-block\"></div>");
outFile.println("</div>");
outFile.println((int) size + " Bytes (" + formatNumber(ratio) + "%)");
outFile.println("</td>");
outFile.println("</tr>");
}
}
outFile.println("</tbody>");
outFile.println("</table>");
outFile.println("</div>");
addStandardHtmlEnding(outFile);
outFile.close();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.