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/Spike1/src/modelo/VentanaRegiones.java b/Spike1/src/modelo/VentanaRegiones.java
index 15277a3..b3dc9a5 100644
--- a/Spike1/src/modelo/VentanaRegiones.java
+++ b/Spike1/src/modelo/VentanaRegiones.java
@@ -1,171 +1,172 @@
package modelo;
import java.awt.Rectangle;
import java.util.Hashtable;
import java.util.List;
import java.util.Random;
import javax.swing.JProgressBar;
import utils.Graphic;
import ij.ImagePlus;
import ij.gui.Roi;
import ij.measure.ResultsTable;
import ij.plugin.filter.Analyzer;
import ij.process.ImageProcessor;
public class VentanaRegiones extends VentanaAbstracta {
private List<int[]> listaPixeles;
private Graphic imgPanel;
private Rectangle selection;
private Roi[] arrayRois;
private static int MIN = 8;
public VentanaRegiones(ImagePlus img, ImagePlus saliency,
ImagePlus convolucion, ImagePlus convolucionSaliency, int numHilo, Rectangle selection, Graphic imgPanel, JProgressBar progressBar, int[][] defectMatrix, List<int[]> pixeles) {
super(img, saliency, convolucion, convolucionSaliency, numHilo);
listaPixeles = pixeles;
this.imgPanel = imgPanel;
this.selection = selection;
this.progressBar = progressBar;
this.defectMatrix = defectMatrix;
}
@Override
public void run() {
ImageProcessor ip = getImage().getProcessor();
Hashtable <Integer, Integer> tablaPixelsPorRoi = new Hashtable<Integer, Integer>();
Hashtable <Integer, Integer> tablaPixelsConsideradosRoi = new Hashtable<Integer, Integer>();
Random rand = new Random();
for (int i = 0; i < arrayRois.length; i++ ){
ip.setRoi(arrayRois[i]);
Analyzer an = new Analyzer(getImage());
an.measure();
Analyzer.getResultsTable();
int numPixelPorRoi = (int) (ResultsTable.AREA * 0.1);
if (numPixelPorRoi < MIN){
numPixelPorRoi = MIN;
}
tablaPixelsPorRoi.put(i, numPixelPorRoi);
tablaPixelsConsideradosRoi.put(i, 0);
ip.resetRoi();
}
while(!listaPixeles.isEmpty()){
int randIndex = rand.nextInt(listaPixeles.size());
int[] coord = listaPixeles.get(randIndex);
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
if(index != -1){
if(tablaPixelsConsideradosRoi.get(index) < tablaPixelsPorRoi.get(index)){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
+ tablaPixelsConsideradosRoi.put(index, (tablaPixelsConsideradosRoi.get(index))+1);
}
}
}
listaPixeles.remove(randIndex);
setPorcentajeBarra();
}
/*
Iterator<int[]> it = listaPixeles.iterator();
while(it.hasNext()){
int[] coord = it.next();
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
// synchronized(this){
// for(int i=0; i<arrayRois.length; i++){
// imgPanel.addRectangle(arrayRois[i].getBounds().x + selection.x, arrayRois[i].getBounds().y + selection.y, arrayRois[i].getBounds().width, arrayRois[i].getBounds().height);
// imgPanel.repaint();
// }
// }
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
System.out.println("Coord0: " + coordX + " Coord1: " + coordY + " index: " + index);
if(index != -1){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
}
else{
System.out.println("No encontrado");
}
}
setPorcentajeBarra();
}
*/
}
private int getIndexRoi(int coordX, int coordY) {
Roi roi;
for(int i=0; i<arrayRois.length; i++){
roi = arrayRois[i];
if(roi.contains(coordX, coordY)){
return i;
}
}
return -1;
}
private synchronized void pintarVentana(int coordenadaX, int coordenadaY) {
int y = coordenadaY + selection.y;
// if(getNumHilo() == Runtime.getRuntime().availableProcessors() - 1){
// y -= getPropiedades().getTamVentana(); //para contrarrestar el solapamiento y que las ventanas no se salgan de la selecci�n
// }
imgPanel.drawWindow(coordenadaX + selection.x, y, getAnchuraVentana(), getAlturaVentana());
imgPanel.repaint();
}
private void imprimeRes(int coordX, int coordY, double prob) {
//para la coordenada Y, hay que determinar en qu� trozo de la imagen estamos analizando
int y = coordY + selection.y;
// if(getNumHilo() == Runtime.getRuntime().availableProcessors() - 1){
// y -= getPropiedades().getTamVentana(); //para contrarrestar el solapamiento y que las ventanas no se salgan de la selecci�n
// }
//CLASIFICACI�N CLASE NOMINAL
if(prob == 0){
imgPanel.addRectangle(coordX + selection.x, y, getAnchuraVentana(), getAlturaVentana());
imgPanel.repaint();
rellenarMatrizDefectos(coordX+ selection.x, y);
}
//REGRESI�N
// if(prob >= 0.5){
// imgPanel.addRectangle(coordX + selection.x, y, getAnchuraVentana(), getAlturaVentana());
// imgPanel.repaint();
// rellenarMatrizDefectos(coordX+ selection.x, y);
// }
}
public void setArrayRois(Roi[] array){
arrayRois = array;
}
public Roi[] getArrayRois(){
return arrayRois;
}
}
| true | true | public void run() {
ImageProcessor ip = getImage().getProcessor();
Hashtable <Integer, Integer> tablaPixelsPorRoi = new Hashtable<Integer, Integer>();
Hashtable <Integer, Integer> tablaPixelsConsideradosRoi = new Hashtable<Integer, Integer>();
Random rand = new Random();
for (int i = 0; i < arrayRois.length; i++ ){
ip.setRoi(arrayRois[i]);
Analyzer an = new Analyzer(getImage());
an.measure();
Analyzer.getResultsTable();
int numPixelPorRoi = (int) (ResultsTable.AREA * 0.1);
if (numPixelPorRoi < MIN){
numPixelPorRoi = MIN;
}
tablaPixelsPorRoi.put(i, numPixelPorRoi);
tablaPixelsConsideradosRoi.put(i, 0);
ip.resetRoi();
}
while(!listaPixeles.isEmpty()){
int randIndex = rand.nextInt(listaPixeles.size());
int[] coord = listaPixeles.get(randIndex);
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
if(index != -1){
if(tablaPixelsConsideradosRoi.get(index) < tablaPixelsPorRoi.get(index)){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
}
}
}
listaPixeles.remove(randIndex);
setPorcentajeBarra();
}
/*
Iterator<int[]> it = listaPixeles.iterator();
while(it.hasNext()){
int[] coord = it.next();
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
// synchronized(this){
// for(int i=0; i<arrayRois.length; i++){
// imgPanel.addRectangle(arrayRois[i].getBounds().x + selection.x, arrayRois[i].getBounds().y + selection.y, arrayRois[i].getBounds().width, arrayRois[i].getBounds().height);
// imgPanel.repaint();
// }
// }
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
System.out.println("Coord0: " + coordX + " Coord1: " + coordY + " index: " + index);
if(index != -1){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
}
else{
System.out.println("No encontrado");
}
}
setPorcentajeBarra();
}
*/
}
| public void run() {
ImageProcessor ip = getImage().getProcessor();
Hashtable <Integer, Integer> tablaPixelsPorRoi = new Hashtable<Integer, Integer>();
Hashtable <Integer, Integer> tablaPixelsConsideradosRoi = new Hashtable<Integer, Integer>();
Random rand = new Random();
for (int i = 0; i < arrayRois.length; i++ ){
ip.setRoi(arrayRois[i]);
Analyzer an = new Analyzer(getImage());
an.measure();
Analyzer.getResultsTable();
int numPixelPorRoi = (int) (ResultsTable.AREA * 0.1);
if (numPixelPorRoi < MIN){
numPixelPorRoi = MIN;
}
tablaPixelsPorRoi.put(i, numPixelPorRoi);
tablaPixelsConsideradosRoi.put(i, 0);
ip.resetRoi();
}
while(!listaPixeles.isEmpty()){
int randIndex = rand.nextInt(listaPixeles.size());
int[] coord = listaPixeles.get(randIndex);
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
if(index != -1){
if(tablaPixelsConsideradosRoi.get(index) < tablaPixelsPorRoi.get(index)){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
tablaPixelsConsideradosRoi.put(index, (tablaPixelsConsideradosRoi.get(index))+1);
}
}
}
listaPixeles.remove(randIndex);
setPorcentajeBarra();
}
/*
Iterator<int[]> it = listaPixeles.iterator();
while(it.hasNext()){
int[] coord = it.next();
int coordX = (coord[0] - selection.x) - getAnchuraVentana()/2;
int coordY = (coord[1] - selection.y) - getAlturaVentana()/2;
// synchronized(this){
// for(int i=0; i<arrayRois.length; i++){
// imgPanel.addRectangle(arrayRois[i].getBounds().x + selection.x, arrayRois[i].getBounds().y + selection.y, arrayRois[i].getBounds().width, arrayRois[i].getBounds().height);
// imgPanel.repaint();
// }
// }
if(coordX >= 0 && coordY >= 0 && coordX <= (getImage().getProcessor().getWidth() - getAnchuraVentana())
&& coordY <= (getImage().getProcessor().getHeight() - getAlturaVentana())){
//comprobar a qu� regi�n pertenece el p�xel
int index = getIndexRoi(coordX, coordY);
System.out.println("Coord0: " + coordX + " Coord1: " + coordY + " index: " + index);
if(index != -1){
pintarVentana(coordX, coordY);
ip.setRoi(coordX, coordY, getAnchuraVentana(), getAlturaVentana());
ejecutarCalculos(coordX, coordY, getImage());
double clase = clasificar();
imprimeRes(coordX, coordY, clase);
}
else{
System.out.println("No encontrado");
}
}
setPorcentajeBarra();
}
*/
}
|
diff --git a/src/com/cole2sworld/ColeBans/GlobalConf.java b/src/com/cole2sworld/ColeBans/GlobalConf.java
index 9dfbde8..037ec77 100644
--- a/src/com/cole2sworld/ColeBans/GlobalConf.java
+++ b/src/com/cole2sworld/ColeBans/GlobalConf.java
@@ -1,271 +1,272 @@
package com.cole2sworld.ColeBans;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
/**
* Configuration for ColeBans. Loaded from file on startup.
*
*/
//LOWPRI Check if there is a better way to do this
public final class GlobalConf {
/**
* Configuration we are using.
*/
public static FileConfiguration conf;
/**
* The main ConfigurationSection.
*/
public static ConfigurationSection settings;
/**
* Do we allow tempbans to be made?
*/
public static boolean allowTempBans = true;
/**
* Message when somebody tries to log in but is banned.
*/
public static String banMessage = "You are banned for %reason!";
/**
* Message when somebody tries to log in but is tempbanned.
*/
public static String tempBanMessage = "You are tempbanned! %time seconds remaining!";
/**
* Show fancy effects?
*/
public static boolean fancyEffects = true;
/**
* Color of the disconnect message when banned.
*/
public static String banColor = "DARK_RED";
/**
* Color of the disconnect message when kicked.
*/
public static String kickColor = "YELLOW";
/**
* Color of the disconnect message when tempbanned.
*/
public static String tempBanColor = "RED";
/**
* Announce when somebody is banned/kicked to the entire server?
*/
public static boolean announceBansAndKicks = true;
/**
* Prefix to use in the console.
*/
public static String logPrefix = "[ColeBans] ";
/**
* Which banhandler?
*/
public static String banHandlerConf = "MySQL";
/**
* Configuration section for SQL.
*
*/
public static class Sql {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* Username for the database.
*/
public static String user = "minecraft";
/**
* Password for the database.
*/
public static String pass = "password";
/**
* Host for the database.
*/
public static String host = "localhost";
/**
* Port for the database.
*/
public static String port = "3306";
/**
* Database name.
*/
public static String db = "minecraft";
/**
* Table prefix.
*/
public static String prefix = "cb_";
}
/**
* Configuration section for MCBans.
*
*/
public static class MCBans {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* The MCBans API key.
*/
public static String apiKey = "yourAPIKeyHere";
/**
* Whether or not to make full dumps of the banlist, including reasons.
*/
public static boolean fullBackups = false;
/**
* Lowest rep you can have and still be able to join.
*/
public static double minRep = 10;
}
/**
* Configuration section for YAML.
*
*/
public static class Yaml {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* The file to use.
*/
public static String file;
}
/**
* Configuration section for YAML.
*
*/
public static class Json {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* The file to use.
*/
public static String file;
}
/**
* Stuff the user shouldn't touch unless they know what they are doing.
* @author cole2
*
*/
public static class Advanced {
/**
* The raw section.
*/
public static ConfigurationSection section;
/**
* Which package do we get the banhandlers?
*/
public static String pkg;
/**
* What is the suffix on the banhandlers?
*/
public static String suffix;
}
/**
* Loads up the config from disk, or creates it if it does not exist.
*/
public static void loadConfig() throws RuntimeException {
File confFile = new File("./plugins/ColeBans/config.yml");
try {
if (confFile.exists()) {
conf.load(confFile);
try {
settings = conf.getConfigurationSection("settings");
allowTempBans = settings.getBoolean("allowTempBans");
banMessage = settings.getString("banMessage");
tempBanMessage = settings.getString("tempBanMessage");
fancyEffects = settings.getBoolean("fancyEffects");
banColor = settings.getString("banColor");
kickColor = settings.getString("kickColor");
tempBanColor = settings.getString("tempBanColor");
announceBansAndKicks = settings.getBoolean("announceBansAndKicks");
logPrefix = settings.getString("logPrefix")+" ";
+ banHandlerConf = settings.getString("banHandler");
Sql.section = settings.getConfigurationSection("mysql");
Sql.user = Sql.section.getString("user");
Sql.pass = Sql.section.getString("pass");
Sql.host = Sql.section.getString("host");
Sql.port = Sql.section.getString("port");
Sql.db = Sql.section.getString("db");
Sql.prefix = Sql.section.getString("prefix");
MCBans.section = settings.getConfigurationSection("mcbans");
MCBans.apiKey = MCBans.section.getString("apiKey");
MCBans.fullBackups = MCBans.section.getBoolean("fullBackups");
MCBans.minRep = MCBans.section.getDouble("minRep");
Advanced.section = settings.getConfigurationSection("advanced");
Advanced.pkg = Advanced.section.getString("package");
Advanced.suffix = Advanced.section.getString("suffix");
}
catch (NullPointerException e) {
Main.LOG.severe("[ColeBans] Your config file is outdated! Please delete it to regenerate it!");
Main.LOG.severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
else {
File dir = new File("./plugins/ColeBans");
dir.mkdir();
if (confFile.createNewFile()) {
if (confFile.canWrite()) {
System.out.println("[ColeBans] No config file exists, generating.");
FileOutputStream fos = new FileOutputStream(confFile);
String defaultConfig = ""+
"# For information on how to configure ColeBans, go to http://c2wr.com/cbconf\n"+
"settings:\n"+
" allowTempBans: true\n"+
" banMessage: You are banned for %reason!\n"+
" tempBanMessage: You are tempbanned! %time minute%plural remaining!\n"+
" fancyEffects: true\n"+
" banColor: DARK_RED\n"+
" kickColor: YELLOW\n"+
" tempBanColor: RED\n"+
" announceBansAndKicks: true\n"+
" logPrefix: [ColeBans]\n"+
" #banHandler can be MySQL, MCBans, YAML, or JSON.\n"+
" banHandler: YAML\n"+
" mysql:\n"+
" user: root\n"+
" pass: pass\n"+
" host: localhost\n"+
" port: 3306\n"+
" db: minecraft\n"+
" prefix: cb_\n"+
" mcbans:\n"+
" ###### THIS LINE IS VERY VERY IMPORTANT IF YOU CHOSE MCBANS FOR THE BAN HANDLER ######\n"+
" apiKey: yourAPIKeyHere\n"+
" # Set this to the BanHandler you want to use for the backups, or \"None\" to turn off backups.\n"+
" backup: None\n"+
" fullBackups: false\n"+
" #The minimum rep a player can have to join your server.\n"+
" minRep: 10\n"+
" yaml:\n"+
" fileName: banlist.yml\n"+
" json:\n"+
" fileName: banlist.json\n"+
" advanced:\n" +
" # The package is where to get the ban handlers. Only change this line if you know what you are doing.\n" +
" package: com.cole2sworld.ColeBans.handlers\n" +
" #The suffix is what is at the end of all the ban handlers. Only change this line if you know what you are doing.\n" +
" suffix: BanHandler";
fos.write(defaultConfig.getBytes("utf-8"));
loadConfig();
fos.close();
}
return;
}
else {
Main.LOG.severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
}
| true | true | public static void loadConfig() throws RuntimeException {
File confFile = new File("./plugins/ColeBans/config.yml");
try {
if (confFile.exists()) {
conf.load(confFile);
try {
settings = conf.getConfigurationSection("settings");
allowTempBans = settings.getBoolean("allowTempBans");
banMessage = settings.getString("banMessage");
tempBanMessage = settings.getString("tempBanMessage");
fancyEffects = settings.getBoolean("fancyEffects");
banColor = settings.getString("banColor");
kickColor = settings.getString("kickColor");
tempBanColor = settings.getString("tempBanColor");
announceBansAndKicks = settings.getBoolean("announceBansAndKicks");
logPrefix = settings.getString("logPrefix")+" ";
Sql.section = settings.getConfigurationSection("mysql");
Sql.user = Sql.section.getString("user");
Sql.pass = Sql.section.getString("pass");
Sql.host = Sql.section.getString("host");
Sql.port = Sql.section.getString("port");
Sql.db = Sql.section.getString("db");
Sql.prefix = Sql.section.getString("prefix");
MCBans.section = settings.getConfigurationSection("mcbans");
MCBans.apiKey = MCBans.section.getString("apiKey");
MCBans.fullBackups = MCBans.section.getBoolean("fullBackups");
MCBans.minRep = MCBans.section.getDouble("minRep");
Advanced.section = settings.getConfigurationSection("advanced");
Advanced.pkg = Advanced.section.getString("package");
Advanced.suffix = Advanced.section.getString("suffix");
}
catch (NullPointerException e) {
Main.LOG.severe("[ColeBans] Your config file is outdated! Please delete it to regenerate it!");
Main.LOG.severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
else {
File dir = new File("./plugins/ColeBans");
dir.mkdir();
if (confFile.createNewFile()) {
if (confFile.canWrite()) {
System.out.println("[ColeBans] No config file exists, generating.");
FileOutputStream fos = new FileOutputStream(confFile);
String defaultConfig = ""+
"# For information on how to configure ColeBans, go to http://c2wr.com/cbconf\n"+
"settings:\n"+
" allowTempBans: true\n"+
" banMessage: You are banned for %reason!\n"+
" tempBanMessage: You are tempbanned! %time minute%plural remaining!\n"+
" fancyEffects: true\n"+
" banColor: DARK_RED\n"+
" kickColor: YELLOW\n"+
" tempBanColor: RED\n"+
" announceBansAndKicks: true\n"+
" logPrefix: [ColeBans]\n"+
" #banHandler can be MySQL, MCBans, YAML, or JSON.\n"+
" banHandler: YAML\n"+
" mysql:\n"+
" user: root\n"+
" pass: pass\n"+
" host: localhost\n"+
" port: 3306\n"+
" db: minecraft\n"+
" prefix: cb_\n"+
" mcbans:\n"+
" ###### THIS LINE IS VERY VERY IMPORTANT IF YOU CHOSE MCBANS FOR THE BAN HANDLER ######\n"+
" apiKey: yourAPIKeyHere\n"+
" # Set this to the BanHandler you want to use for the backups, or \"None\" to turn off backups.\n"+
" backup: None\n"+
" fullBackups: false\n"+
" #The minimum rep a player can have to join your server.\n"+
" minRep: 10\n"+
" yaml:\n"+
" fileName: banlist.yml\n"+
" json:\n"+
" fileName: banlist.json\n"+
" advanced:\n" +
" # The package is where to get the ban handlers. Only change this line if you know what you are doing.\n" +
" package: com.cole2sworld.ColeBans.handlers\n" +
" #The suffix is what is at the end of all the ban handlers. Only change this line if you know what you are doing.\n" +
" suffix: BanHandler";
fos.write(defaultConfig.getBytes("utf-8"));
loadConfig();
fos.close();
}
return;
}
else {
Main.LOG.severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
| public static void loadConfig() throws RuntimeException {
File confFile = new File("./plugins/ColeBans/config.yml");
try {
if (confFile.exists()) {
conf.load(confFile);
try {
settings = conf.getConfigurationSection("settings");
allowTempBans = settings.getBoolean("allowTempBans");
banMessage = settings.getString("banMessage");
tempBanMessage = settings.getString("tempBanMessage");
fancyEffects = settings.getBoolean("fancyEffects");
banColor = settings.getString("banColor");
kickColor = settings.getString("kickColor");
tempBanColor = settings.getString("tempBanColor");
announceBansAndKicks = settings.getBoolean("announceBansAndKicks");
logPrefix = settings.getString("logPrefix")+" ";
banHandlerConf = settings.getString("banHandler");
Sql.section = settings.getConfigurationSection("mysql");
Sql.user = Sql.section.getString("user");
Sql.pass = Sql.section.getString("pass");
Sql.host = Sql.section.getString("host");
Sql.port = Sql.section.getString("port");
Sql.db = Sql.section.getString("db");
Sql.prefix = Sql.section.getString("prefix");
MCBans.section = settings.getConfigurationSection("mcbans");
MCBans.apiKey = MCBans.section.getString("apiKey");
MCBans.fullBackups = MCBans.section.getBoolean("fullBackups");
MCBans.minRep = MCBans.section.getDouble("minRep");
Advanced.section = settings.getConfigurationSection("advanced");
Advanced.pkg = Advanced.section.getString("package");
Advanced.suffix = Advanced.section.getString("suffix");
}
catch (NullPointerException e) {
Main.LOG.severe("[ColeBans] Your config file is outdated! Please delete it to regenerate it!");
Main.LOG.severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
else {
File dir = new File("./plugins/ColeBans");
dir.mkdir();
if (confFile.createNewFile()) {
if (confFile.canWrite()) {
System.out.println("[ColeBans] No config file exists, generating.");
FileOutputStream fos = new FileOutputStream(confFile);
String defaultConfig = ""+
"# For information on how to configure ColeBans, go to http://c2wr.com/cbconf\n"+
"settings:\n"+
" allowTempBans: true\n"+
" banMessage: You are banned for %reason!\n"+
" tempBanMessage: You are tempbanned! %time minute%plural remaining!\n"+
" fancyEffects: true\n"+
" banColor: DARK_RED\n"+
" kickColor: YELLOW\n"+
" tempBanColor: RED\n"+
" announceBansAndKicks: true\n"+
" logPrefix: [ColeBans]\n"+
" #banHandler can be MySQL, MCBans, YAML, or JSON.\n"+
" banHandler: YAML\n"+
" mysql:\n"+
" user: root\n"+
" pass: pass\n"+
" host: localhost\n"+
" port: 3306\n"+
" db: minecraft\n"+
" prefix: cb_\n"+
" mcbans:\n"+
" ###### THIS LINE IS VERY VERY IMPORTANT IF YOU CHOSE MCBANS FOR THE BAN HANDLER ######\n"+
" apiKey: yourAPIKeyHere\n"+
" # Set this to the BanHandler you want to use for the backups, or \"None\" to turn off backups.\n"+
" backup: None\n"+
" fullBackups: false\n"+
" #The minimum rep a player can have to join your server.\n"+
" minRep: 10\n"+
" yaml:\n"+
" fileName: banlist.yml\n"+
" json:\n"+
" fileName: banlist.json\n"+
" advanced:\n" +
" # The package is where to get the ban handlers. Only change this line if you know what you are doing.\n" +
" package: com.cole2sworld.ColeBans.handlers\n" +
" #The suffix is what is at the end of all the ban handlers. Only change this line if you know what you are doing.\n" +
" suffix: BanHandler";
fos.write(defaultConfig.getBytes("utf-8"));
loadConfig();
fos.close();
}
return;
}
else {
Main.LOG.severe("[ColeBans] COULD NOT LOAD WORKING CONFIG FILE. Aborting operation.");
Main.instance.onFatal();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvalidConfigurationException e) {
e.printStackTrace();
}
}
|
diff --git a/source/com/mucommander/ui/theme/ThemeWriter.java b/source/com/mucommander/ui/theme/ThemeWriter.java
index 283eec96..196b53b7 100644
--- a/source/com/mucommander/ui/theme/ThemeWriter.java
+++ b/source/com/mucommander/ui/theme/ThemeWriter.java
@@ -1,448 +1,448 @@
/*
* This file is part of muCommander, http://www.mucommander.com
* Copyright (C) 2002-2007 Maxence Bernard
*
* muCommander 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.
*
* muCommander 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.mucommander.ui.theme;
import com.mucommander.xml.XmlAttributes;
import com.mucommander.xml.XmlWriter;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
/**
* Class used to save themes in XML format.
* @author Nicolas Rinaudo
*/
class ThemeWriter implements ThemeXmlConstants {
// - Initialisation ------------------------------------------------------------------
// -----------------------------------------------------------------------------------
/**
* Prevents instanciation of the class.
*/
private ThemeWriter() {}
// - XML output ----------------------------------------------------------------------
// -----------------------------------------------------------------------------------
/**
* Saves the specified theme to the specified output stream.
* @param theme theme to save.
* @param stream where to write the theme to.
* @throws IOException thrown if any IO related error occurs.
*/
public static void write(ThemeData theme, OutputStream stream) throws IOException {
XmlWriter out;
out = new XmlWriter(stream);
out.startElement(ELEMENT_ROOT);
out.println();
// - File table description ------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_TABLE);
out.println();
// Global values.
if(theme.isColorSet(Theme.FILE_TABLE_BORDER_COLOR))
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(theme.getColor(Theme.FILE_TABLE_BORDER_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNMATCHED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNMATCHED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNMATCHED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNMATCHED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNMATCHED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNMATCHED_FOREGROUND_COLOR)));
if(theme.isFontSet(Theme.FILE_TABLE_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.FILE_TABLE_FONT)));
// Hidden files.
out.startElement(ELEMENT_HIDDEN);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.HIDDEN_FILE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_UNFOCUSED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_HIDDEN);
// Folders.
out.startElement(ELEMENT_FOLDER);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.FOLDER_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.FOLDER_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_FOLDER);
// Archives.
out.startElement(ELEMENT_ARCHIVE);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.ARCHIVE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
- if(theme.isColorSet(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR))
- out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR)));
+ if(theme.isColorSet(Theme.ARCHIVE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
+ out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_ARCHIVE);
// Symlink.
out.startElement(ELEMENT_SYMLINK);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SYMLINK_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SYMLINK_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
- if(theme.isColorSet(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR))
- out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR)));
+ if(theme.isColorSet(Theme.SYMLINK_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
+ out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SYMLINK);
// Marked files.
out.startElement(ELEMENT_MARKED);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.MARKED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.MARKED_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_MARKED);
// Plain files.
out.startElement(ELEMENT_FILE);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.FILE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.FILE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_FILE);
out.endElement(ELEMENT_TABLE);
// - Shell description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL);
out.println();
if(theme.isFontSet(Theme.SHELL_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.SHELL_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SHELL_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SHELL_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SHELL);
// - Shell history description ---------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL_HISTORY);
out.println();
if(theme.isFontSet(Theme.SHELL_HISTORY_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.SHELL_HISTORY_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SHELL_HISTORY_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_HISTORY_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SHELL_HISTORY_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_HISTORY_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SHELL_HISTORY);
// - Editor description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_EDITOR);
out.println();
if(theme.isFontSet(Theme.EDITOR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.EDITOR_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.EDITOR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.EDITOR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.EDITOR_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.EDITOR_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_EDITOR);
// - Location bar description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_LOCATION_BAR);
out.println();
if(theme.isFontSet(Theme.LOCATION_BAR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.LOCATION_BAR_FONT)));
if(theme.isColorSet(Theme.LOCATION_BAR_PROGRESS_COLOR))
out.writeStandAloneElement(ELEMENT_PROGRESS, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_PROGRESS_COLOR)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.LOCATION_BAR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.LOCATION_BAR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.LOCATION_BAR_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.LOCATION_BAR_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_LOCATION_BAR);
// - Volume label description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_STATUS_BAR);
out.println();
// Font.
if(theme.isFontSet(Theme.STATUS_BAR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.STATUS_BAR_FONT)));
// Colors.
if(theme.isColorSet(Theme.STATUS_BAR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.STATUS_BAR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.STATUS_BAR_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_BORDER_COLOR))
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(theme.getColor(Theme.STATUS_BAR_BORDER_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_OK_COLOR))
out.writeStandAloneElement(ELEMENT_OK, getColorAttributes(theme.getColor(Theme.STATUS_BAR_OK_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_WARNING_COLOR))
out.writeStandAloneElement(ELEMENT_WARNING, getColorAttributes(theme.getColor(Theme.STATUS_BAR_WARNING_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_CRITICAL_COLOR))
out.writeStandAloneElement(ELEMENT_CRITICAL, getColorAttributes(theme.getColor(Theme.STATUS_BAR_CRITICAL_COLOR)));
out.endElement(ELEMENT_STATUS_BAR);
out.endElement(ELEMENT_ROOT);
}
// - Helper methods ------------------------------------------------------------------
// -----------------------------------------------------------------------------------
/**
* Returns the XML attributes describing the specified font.
* @param font font to described as XML attributes.
* @return the XML attributes describing the specified font.
*/
private static XmlAttributes getFontAttributes(Font font) {
XmlAttributes attributes; // Stores the font's description.
attributes = new XmlAttributes();
// Font family and size.
attributes.add(ATTRIBUTE_FAMILY, font.getFamily());
attributes.add(ATTRIBUTE_SIZE, Integer.toString(font.getSize()));
// Font style.
if(font.isBold())
attributes.add(ATTRIBUTE_BOLD, VALUE_TRUE);
if(font.isItalic())
attributes.add(ATTRIBUTE_ITALIC, VALUE_TRUE);
return attributes;
}
/**
* Returns the XML attributes describing the specified color.
* @param color color to described as XML attributes.
* @return the XML attributes describing the specified color.
*/
private static XmlAttributes getColorAttributes(Color color) {
XmlAttributes attributes; // Stores the color's description.
StringBuffer buffer; // Used to build the color's string representation.
buffer = new StringBuffer();
// Red component.
if(color.getRed() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getRed(), 16));
// Green component.
if(color.getGreen() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getGreen(), 16));
// Blue component.
if(color.getBlue() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getBlue(), 16));
// Builds the XML attributes.
attributes = new XmlAttributes();
attributes.add(ATTRIBUTE_COLOR, buffer.toString());
if(color.getAlpha() != 255) {
buffer.setLength(0);
if(color.getAlpha() < 16)
buffer.append('0');
buffer.append(Integer.toString(color.getAlpha(), 16));
attributes.add(ATTRIBUTE_ALPHA, buffer.toString());
}
return attributes;
}
}
| false | true | public static void write(ThemeData theme, OutputStream stream) throws IOException {
XmlWriter out;
out = new XmlWriter(stream);
out.startElement(ELEMENT_ROOT);
out.println();
// - File table description ------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_TABLE);
out.println();
// Global values.
if(theme.isColorSet(Theme.FILE_TABLE_BORDER_COLOR))
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(theme.getColor(Theme.FILE_TABLE_BORDER_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNMATCHED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNMATCHED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNMATCHED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNMATCHED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNMATCHED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNMATCHED_FOREGROUND_COLOR)));
if(theme.isFontSet(Theme.FILE_TABLE_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.FILE_TABLE_FONT)));
// Hidden files.
out.startElement(ELEMENT_HIDDEN);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.HIDDEN_FILE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_UNFOCUSED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_HIDDEN);
// Folders.
out.startElement(ELEMENT_FOLDER);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.FOLDER_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.FOLDER_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_FOLDER);
// Archives.
out.startElement(ELEMENT_ARCHIVE);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.ARCHIVE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_ARCHIVE);
// Symlink.
out.startElement(ELEMENT_SYMLINK);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SYMLINK_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SYMLINK_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SYMLINK);
// Marked files.
out.startElement(ELEMENT_MARKED);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.MARKED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.MARKED_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_MARKED);
// Plain files.
out.startElement(ELEMENT_FILE);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.FILE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.FILE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_FILE);
out.endElement(ELEMENT_TABLE);
// - Shell description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL);
out.println();
if(theme.isFontSet(Theme.SHELL_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.SHELL_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SHELL_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SHELL_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SHELL);
// - Shell history description ---------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL_HISTORY);
out.println();
if(theme.isFontSet(Theme.SHELL_HISTORY_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.SHELL_HISTORY_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SHELL_HISTORY_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_HISTORY_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SHELL_HISTORY_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_HISTORY_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SHELL_HISTORY);
// - Editor description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_EDITOR);
out.println();
if(theme.isFontSet(Theme.EDITOR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.EDITOR_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.EDITOR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.EDITOR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.EDITOR_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.EDITOR_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_EDITOR);
// - Location bar description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_LOCATION_BAR);
out.println();
if(theme.isFontSet(Theme.LOCATION_BAR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.LOCATION_BAR_FONT)));
if(theme.isColorSet(Theme.LOCATION_BAR_PROGRESS_COLOR))
out.writeStandAloneElement(ELEMENT_PROGRESS, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_PROGRESS_COLOR)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.LOCATION_BAR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.LOCATION_BAR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.LOCATION_BAR_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.LOCATION_BAR_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_LOCATION_BAR);
// - Volume label description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_STATUS_BAR);
out.println();
// Font.
if(theme.isFontSet(Theme.STATUS_BAR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.STATUS_BAR_FONT)));
// Colors.
if(theme.isColorSet(Theme.STATUS_BAR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.STATUS_BAR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.STATUS_BAR_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_BORDER_COLOR))
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(theme.getColor(Theme.STATUS_BAR_BORDER_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_OK_COLOR))
out.writeStandAloneElement(ELEMENT_OK, getColorAttributes(theme.getColor(Theme.STATUS_BAR_OK_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_WARNING_COLOR))
out.writeStandAloneElement(ELEMENT_WARNING, getColorAttributes(theme.getColor(Theme.STATUS_BAR_WARNING_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_CRITICAL_COLOR))
out.writeStandAloneElement(ELEMENT_CRITICAL, getColorAttributes(theme.getColor(Theme.STATUS_BAR_CRITICAL_COLOR)));
out.endElement(ELEMENT_STATUS_BAR);
out.endElement(ELEMENT_ROOT);
}
| public static void write(ThemeData theme, OutputStream stream) throws IOException {
XmlWriter out;
out = new XmlWriter(stream);
out.startElement(ELEMENT_ROOT);
out.println();
// - File table description ------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_TABLE);
out.println();
// Global values.
if(theme.isColorSet(Theme.FILE_TABLE_BORDER_COLOR))
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(theme.getColor(Theme.FILE_TABLE_BORDER_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNMATCHED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNMATCHED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNMATCHED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_TABLE_UNMATCHED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNMATCHED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_TABLE_UNMATCHED_FOREGROUND_COLOR)));
if(theme.isFontSet(Theme.FILE_TABLE_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.FILE_TABLE_FONT)));
// Hidden files.
out.startElement(ELEMENT_HIDDEN);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.HIDDEN_FILE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_UNFOCUSED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.HIDDEN_FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_HIDDEN);
// Folders.
out.startElement(ELEMENT_FOLDER);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.FOLDER_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.FOLDER_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FOLDER_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FOLDER_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_FOLDER);
// Archives.
out.startElement(ELEMENT_ARCHIVE);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.ARCHIVE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.ARCHIVE_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_ARCHIVE);
// Symlink.
out.startElement(ELEMENT_SYMLINK);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SYMLINK_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SYMLINK_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SYMLINK_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SYMLINK);
// Marked files.
out.startElement(ELEMENT_MARKED);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.MARKED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.MARKED_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.MARKED_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.MARKED_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_MARKED);
// Plain files.
out.startElement(ELEMENT_FILE);
out.println();
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.FILE_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.FILE_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_BACKGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_UNFOCUSED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_UNFOCUSED_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_UNFOCUSED_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.FILE_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.FILE_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_FILE);
out.endElement(ELEMENT_TABLE);
// - Shell description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL);
out.println();
if(theme.isFontSet(Theme.SHELL_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.SHELL_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SHELL_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SHELL_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SHELL);
// - Shell history description ---------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_SHELL_HISTORY);
out.println();
if(theme.isFontSet(Theme.SHELL_HISTORY_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.SHELL_HISTORY_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.SHELL_HISTORY_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_HISTORY_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.SHELL_HISTORY_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.SHELL_HISTORY_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.SHELL_HISTORY_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_SHELL_HISTORY);
// - Editor description ----------------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_EDITOR);
out.println();
if(theme.isFontSet(Theme.EDITOR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.EDITOR_FONT)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.EDITOR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.EDITOR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.EDITOR_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.EDITOR_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.EDITOR_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_EDITOR);
// - Location bar description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_LOCATION_BAR);
out.println();
if(theme.isFontSet(Theme.LOCATION_BAR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.LOCATION_BAR_FONT)));
if(theme.isColorSet(Theme.LOCATION_BAR_PROGRESS_COLOR))
out.writeStandAloneElement(ELEMENT_PROGRESS, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_PROGRESS_COLOR)));
// Normal colors.
out.startElement(ELEMENT_NORMAL);
out.println();
if(theme.isColorSet(Theme.LOCATION_BAR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.LOCATION_BAR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_FOREGROUND_COLOR)));
out.endElement(ELEMENT_NORMAL);
// Selected colors.
out.startElement(ELEMENT_SELECTED);
out.println();
if(theme.isColorSet(Theme.LOCATION_BAR_SELECTED_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_SELECTED_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.LOCATION_BAR_SELECTED_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.LOCATION_BAR_SELECTED_FOREGROUND_COLOR)));
out.endElement(ELEMENT_SELECTED);
out.endElement(ELEMENT_LOCATION_BAR);
// - Volume label description ----------------------------------------------------
// -------------------------------------------------------------------------------
out.startElement(ELEMENT_STATUS_BAR);
out.println();
// Font.
if(theme.isFontSet(Theme.STATUS_BAR_FONT))
out.writeStandAloneElement(ELEMENT_FONT, getFontAttributes(theme.getFont(Theme.STATUS_BAR_FONT)));
// Colors.
if(theme.isColorSet(Theme.STATUS_BAR_BACKGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_BACKGROUND, getColorAttributes(theme.getColor(Theme.STATUS_BAR_BACKGROUND_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_FOREGROUND_COLOR))
out.writeStandAloneElement(ELEMENT_FOREGROUND, getColorAttributes(theme.getColor(Theme.STATUS_BAR_FOREGROUND_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_BORDER_COLOR))
out.writeStandAloneElement(ELEMENT_BORDER, getColorAttributes(theme.getColor(Theme.STATUS_BAR_BORDER_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_OK_COLOR))
out.writeStandAloneElement(ELEMENT_OK, getColorAttributes(theme.getColor(Theme.STATUS_BAR_OK_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_WARNING_COLOR))
out.writeStandAloneElement(ELEMENT_WARNING, getColorAttributes(theme.getColor(Theme.STATUS_BAR_WARNING_COLOR)));
if(theme.isColorSet(Theme.STATUS_BAR_CRITICAL_COLOR))
out.writeStandAloneElement(ELEMENT_CRITICAL, getColorAttributes(theme.getColor(Theme.STATUS_BAR_CRITICAL_COLOR)));
out.endElement(ELEMENT_STATUS_BAR);
out.endElement(ELEMENT_ROOT);
}
|
diff --git a/src/org/cyanogenmod/focal/picsphere/PicSphereManager.java b/src/org/cyanogenmod/focal/picsphere/PicSphereManager.java
index 0bf3517..ab1adae 100644
--- a/src/org/cyanogenmod/focal/picsphere/PicSphereManager.java
+++ b/src/org/cyanogenmod/focal/picsphere/PicSphereManager.java
@@ -1,279 +1,279 @@
/*
* Copyright (C) 2013 Guillaume Lesniak
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.cyanogenmod.focal.picsphere;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.AssetManager;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.TextureView;
import android.widget.FrameLayout;
import org.cyanogenmod.focal.CameraActivity;
import fr.xplod.focal.R;
import org.cyanogenmod.focal.SnapshotManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* This class manages the interaction and processing of Picture Spheres ("PicSphere"). PicSphere
* is basically an open-source clone of Google's PhotoSphere, using Hugin open-source panorama
* stitching libraries.
*
* Can you feel the awesomeness?
*/
public class PicSphereManager implements PicSphere.ProgressListener {
public final static String TAG = "PicSphereManager";
private List<PicSphere> mPicSpheres;
private CameraActivity mContext;
private SnapshotManager mSnapManager;
private Capture3DRenderer mCapture3DRenderer;
private PicSphereRenderingService mBoundService;
private FrameLayout mGLRootView;
private TextureView mGLSurfaceView;
private Handler mHandler;
private boolean mIsBound;
private ServiceConnection mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((PicSphereRenderingService.LocalBinder)service).getService();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
}
};
public PicSphereManager(CameraActivity context, SnapshotManager snapMan) {
mContext = context;
mSnapManager = snapMan;
mPicSpheres = new ArrayList<PicSphere>();
mHandler = new Handler();
mIsBound = false;
doBindService();
new Thread() {
public void run() { copyBinaries(); }
}.start();
}
/**
* Creates an empty PicSphere
* @return A PicSphere that is empty
*/
public PicSphere createPicSphere() {
PicSphere sphere = new PicSphere(mContext, mSnapManager);
mPicSpheres.add(sphere);
return sphere;
}
public void clearSpheres() {
mPicSpheres.clear();
}
/**
* Returns the 3D renderer context for PicSphere capture mode
*/
public Capture3DRenderer getRenderer() {
if (mCapture3DRenderer == null) {
// Initialize the 3D renderer
mCapture3DRenderer = new Capture3DRenderer(mContext, mContext.getCamManager());
// We route the camera preview to our texture
mGLRootView = (FrameLayout) mContext.findViewById(R.id.gl_renderer_container);
}
return mCapture3DRenderer;
}
/**
* Returns the progress of the currently rendering picsphere
* @return The percentage of progress, or -1 if no picsphere is rendering
*/
public int getRenderingProgress() {
if (mPicSpheres.size() > 0) {
return mPicSpheres.get(0).getRenderProgress();
}
return -1;
}
/**
* Starts rendering the provided PicSphere in a thread, and handles a service
* that will keep on processing even once Nemesis is closed
*
* @param sphere The PicSphere to render
*/
public void startRendering(final PicSphere sphere, final int orientation) {
// Notify toast
CameraActivity.notify(mContext.getString(R.string.picsphere_toast_background_render), 2500);
if (mIsBound && mBoundService != null) {
sphere.addProgressListener(this);
mBoundService.render(sphere, orientation);
} else {
doBindService();
mHandler.postDelayed(new Runnable() {
public void run() {
startRendering(sphere, orientation);
}
}, 500);
}
}
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
Log.v(TAG, "Binding PicSphere rendering service");
mContext.bindService(new Intent(mContext, PicSphereRenderingService.class),
mServiceConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
public void tearDown() {
if (mCapture3DRenderer != null) {
mCapture3DRenderer.onPause();
mCapture3DRenderer = null;
}
mPicSpheres.clear();
if (mIsBound) {
// Detach our existing connection.
mContext.unbindService(mServiceConnection);
mIsBound = false;
}
}
public void onPause() {
if (mCapture3DRenderer != null) {
mCapture3DRenderer.onPause();
}
mPicSpheres.clear();
}
public void onResume() {
if (mCapture3DRenderer != null) {
mCapture3DRenderer.onResume();
}
}
public int getSpheresCount() {
return mPicSpheres.size();
}
/**
* Copy the required binaries and libraries to the data folder
* @return
*/
private boolean copyBinaries() {
boolean result = true;
try {
String files[] = {
"autooptimiser", "pto_gen", "cpfind", "multiblend", "enfuse", "nona", "pano_modify",
"ptclean", "tiffinfo", "align_image_stack", "pto_var",
"libexiv2.so", "libglib-2.0.so", "libgmodule-2.0.so", "libgobject-2.0.so",
"libgthread-2.0.so", "libjpeg.so", "libpano13.so", "libtiff.so", "libtiffdecoder.so",
- "libvigraimpex.so", "libxmptoolkit.so"
+ "libvigraimpex.so"
};
final AssetManager am = mContext.getAssets();
for (String file : files) {
InputStream is = am.open("picsphere/" + file);
// Create the output file
File dir = mContext.getFilesDir();
File outFile = new File(dir, file);
if (outFile.exists())
outFile.delete();
OutputStream os = new FileOutputStream(outFile);
// Copy the file
byte[] buffer = new byte[1024];
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
if (!outFile.getName().endsWith(".so") && !outFile.setExecutable(true)) {
result = false;
}
os.flush();
os.close();
is.close();
}
} catch (Exception e) {
Log.e(TAG, "Error copying libraries and binaries", e);
result = false;
}
return result;
}
@Override
public void onRenderStart(PicSphere sphere) {
}
@Override
public void onStepChange(PicSphere sphere, int newStep) {
if (CameraActivity.getCameraMode() == CameraActivity.CAMERA_MODE_PICSPHERE) {
mContext.setHelperText(String.format(mContext.getString(
R.string.picsphere_rendering_progress), sphere.getRenderProgress()));
}
}
@Override
public void onRenderDone(PicSphere sphere) {
mPicSpheres.remove(sphere);
if (CameraActivity.getCameraMode() == CameraActivity.CAMERA_MODE_PICSPHERE) {
mContext.setHelperText(mContext.getString(R.string.picsphere_start_hint));
}
if (mCapture3DRenderer != null) {
mCapture3DRenderer.setCamPreviewVisible(true);
}
}
}
| true | true | private boolean copyBinaries() {
boolean result = true;
try {
String files[] = {
"autooptimiser", "pto_gen", "cpfind", "multiblend", "enfuse", "nona", "pano_modify",
"ptclean", "tiffinfo", "align_image_stack", "pto_var",
"libexiv2.so", "libglib-2.0.so", "libgmodule-2.0.so", "libgobject-2.0.so",
"libgthread-2.0.so", "libjpeg.so", "libpano13.so", "libtiff.so", "libtiffdecoder.so",
"libvigraimpex.so", "libxmptoolkit.so"
};
final AssetManager am = mContext.getAssets();
for (String file : files) {
InputStream is = am.open("picsphere/" + file);
// Create the output file
File dir = mContext.getFilesDir();
File outFile = new File(dir, file);
if (outFile.exists())
outFile.delete();
OutputStream os = new FileOutputStream(outFile);
// Copy the file
byte[] buffer = new byte[1024];
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
if (!outFile.getName().endsWith(".so") && !outFile.setExecutable(true)) {
result = false;
}
os.flush();
os.close();
is.close();
}
} catch (Exception e) {
Log.e(TAG, "Error copying libraries and binaries", e);
result = false;
}
return result;
}
| private boolean copyBinaries() {
boolean result = true;
try {
String files[] = {
"autooptimiser", "pto_gen", "cpfind", "multiblend", "enfuse", "nona", "pano_modify",
"ptclean", "tiffinfo", "align_image_stack", "pto_var",
"libexiv2.so", "libglib-2.0.so", "libgmodule-2.0.so", "libgobject-2.0.so",
"libgthread-2.0.so", "libjpeg.so", "libpano13.so", "libtiff.so", "libtiffdecoder.so",
"libvigraimpex.so"
};
final AssetManager am = mContext.getAssets();
for (String file : files) {
InputStream is = am.open("picsphere/" + file);
// Create the output file
File dir = mContext.getFilesDir();
File outFile = new File(dir, file);
if (outFile.exists())
outFile.delete();
OutputStream os = new FileOutputStream(outFile);
// Copy the file
byte[] buffer = new byte[1024];
int read;
while ((read = is.read(buffer)) != -1) {
os.write(buffer, 0, read);
}
if (!outFile.getName().endsWith(".so") && !outFile.setExecutable(true)) {
result = false;
}
os.flush();
os.close();
is.close();
}
} catch (Exception e) {
Log.e(TAG, "Error copying libraries and binaries", e);
result = false;
}
return result;
}
|
diff --git a/core/src/java/liquibase/commandline/CommandLineMigrator.java b/core/src/java/liquibase/commandline/CommandLineMigrator.java
index edf5a61b..d224a1da 100644
--- a/core/src/java/liquibase/commandline/CommandLineMigrator.java
+++ b/core/src/java/liquibase/commandline/CommandLineMigrator.java
@@ -1,787 +1,790 @@
package liquibase.commandline;
import liquibase.CompositeFileOpener;
import liquibase.FileSystemFileOpener;
import liquibase.database.DatabaseFactory;
import liquibase.diff.Diff;
import liquibase.diff.DiffResult;
import liquibase.diff.DiffStatusListener;
import liquibase.exception.CommandLineParsingException;
import liquibase.exception.JDBCException;
import liquibase.exception.ValidationFailedException;
import liquibase.migrator.Migrator;
import liquibase.util.StreamUtil;
import liquibase.util.StringUtils;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class for executing LiquiBase via the command line.
*/
public class CommandLineMigrator {
protected ClassLoader classLoader;
protected String driver;
protected String username;
protected String password;
protected String url;
protected String changeLogFile;
protected String classpath;
protected String contexts;
protected Boolean promptForNonLocalDatabase = null;
protected Boolean includeSystemClasspath;
protected String defaultsFile = "liquibase.properties";
protected String currentDateTimeFunction;
protected String command;
protected Set<String> commandParams = new HashSet<String>();
protected String logLevel;
public static void main(String args[]) throws CommandLineParsingException, IOException {
String shouldRunProperty = System.getProperty(Migrator.SHOULD_RUN_SYSTEM_PROPERTY);
if (shouldRunProperty != null && !Boolean.valueOf(shouldRunProperty)) {
System.out.println("Migrator did not run because '" + Migrator.SHOULD_RUN_SYSTEM_PROPERTY + "' system property was set to false");
return;
}
CommandLineMigrator commandLineMigrator = new CommandLineMigrator();
if (args.length == 1 && "--help".equals(args[0])) {
commandLineMigrator.printHelp(System.out);
return;
} else if (args.length == 1 && "--version".equals(args[0])) {
System.out.println("LiquiBase Version: " + new Migrator(null, null).getBuildVersion() + StreamUtil.getLineSeparator());
return;
}
commandLineMigrator.parseOptions(args);
File propertiesFile = new File(commandLineMigrator.defaultsFile);
if (propertiesFile.exists()) {
commandLineMigrator.parsePropertiesFile(new FileInputStream(propertiesFile));
}
List<String> setupMessages = commandLineMigrator.checkSetup();
if (setupMessages.size() > 0) {
commandLineMigrator.printHelp(setupMessages, System.out);
return;
}
try {
commandLineMigrator.applyDefaults();
commandLineMigrator.configureClassLoader();
commandLineMigrator.doMigration();
} catch (Throwable e) {
String message = e.getMessage();
if (e.getCause() != null) {
message = e.getCause().getMessage();
}
if (message == null) {
message = "Unknown Reason";
}
if (e.getCause() instanceof ValidationFailedException) {
((ValidationFailedException) e.getCause()).printDescriptiveError(System.out);
} else {
System.out.println("Migration Failed: " + message + generateLogLevelWarningMessage());
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).log(Level.SEVERE, message, e);
}
return;
}
if ("migrate".equals(commandLineMigrator.command)) {
System.out.println("Migration successful");
} else if (commandLineMigrator.command.startsWith("rollback") && !commandLineMigrator.command.endsWith("SQL")) {
System.out.println("Rollback successful");
}
}
private static String generateLogLevelWarningMessage() {
Logger logger = Logger.getLogger(Migrator.DEFAULT_LOG_NAME);
if (logger == null || logger.getLevel() == null || (logger.getLevel().equals(Level.OFF))) {
return "";
} else {
return ". For more information, use the --logLevel flag)";
}
}
/**
* On windows machines, it splits args on '=' signs. Put it back like it was.
*/
protected String[] fixupArgs(String[] args) {
List<String> fixedArgs = new ArrayList<String>();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--") && !arg.contains("=")) {
String nextArg = args[i + 1];
if (!nextArg.startsWith("--") && !isCommand(nextArg)) {
arg = arg + "=" + nextArg;
i++;
}
}
fixedArgs.add(arg);
}
return fixedArgs.toArray(new String[fixedArgs.size()]);
}
protected List<String> checkSetup() {
List<String> messages = new ArrayList<String>();
if (command == null) {
messages.add("Command not passed");
} else if (!isCommand(command)) {
messages.add("Unknown command: " + command);
} else {
if (username == null) {
messages.add("--username is required");
}
if (url == null) {
messages.add("--url is required");
}
if (isChangeLogRequired(command) && changeLogFile == null) {
messages.add("--changeLog is required");
}
}
return messages;
}
private boolean isChangeLogRequired(String command) {
return command.toLowerCase().startsWith("migrate")
|| command.toLowerCase().startsWith("rollback")
|| "validate".equals(command);
}
private boolean isCommand(String arg) {
return "migrate".equals(arg)
|| "migrateSQL".equalsIgnoreCase(arg)
|| "rollback".equalsIgnoreCase(arg)
|| "rollbackToDate".equalsIgnoreCase(arg)
|| "rollbackCount".equalsIgnoreCase(arg)
|| "rollbackSQL".equalsIgnoreCase(arg)
|| "rollbackToDateSQL".equalsIgnoreCase(arg)
|| "rollbackCountSQL".equalsIgnoreCase(arg)
|| "futureRollbackSQL".equalsIgnoreCase(arg)
|| "tag".equalsIgnoreCase(arg)
|| "listLocks".equalsIgnoreCase(arg)
|| "dropAll".equalsIgnoreCase(arg)
|| "releaseLocks".equalsIgnoreCase(arg)
|| "status".equalsIgnoreCase(arg)
|| "validate".equalsIgnoreCase(arg)
|| "help".equalsIgnoreCase(arg)
|| "diff".equalsIgnoreCase(arg)
|| "diffChangeLog".equalsIgnoreCase(arg)
|| "generateChangeLog".equalsIgnoreCase(arg)
|| "clearCheckSums".equalsIgnoreCase(arg)
|| "dbDoc".equalsIgnoreCase(arg)
|| "changelogSyncSQL".equalsIgnoreCase(arg);
}
protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException {
Properties props = new Properties();
props.load(propertiesInputStream);
for (Map.Entry entry : props.entrySet()) {
try {
Field field = getClass().getDeclaredField((String) entry.getKey());
Object currentValue = field.get(this);
if (currentValue == null) {
String value = entry.getValue().toString();
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value));
} else {
field.set(this, value);
}
}
} catch (Exception e) {
throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'");
}
}
}
protected void printHelp(List<String> errorMessages, PrintStream stream) {
stream.println("Errors:");
for (String message : errorMessages) {
stream.println(" " + message);
}
stream.println();
printHelp(stream);
}
protected void printHelp(PrintStream stream) {
stream.println("Usage: java -jar liquibase.jar [options] [command]");
stream.println("");
stream.println("Standard Commands:");
stream.println(" migrate Updates database to current version");
stream.println(" rollback <tag> Rolls back the database to the the state is was");
stream.println(" when the tag was applied");
stream.println(" rollbackToDate <date/time> Rolls back the database to the the state is was");
stream.println(" at the given date/time.");
stream.println(" Date Format: yyyy-MM-dd HH:mm:ss");
stream.println(" rollbackCount <value> Rolls back the last <value> change sets");
stream.println(" applied to the database");
stream.println(" migrateSQL Writes SQL to update database to current");
stream.println(" version to STDOUT");
stream.println(" rollbackSQL <tag> Writes SQL to roll back the database to that");
stream.println(" state it was in when the tag was applied");
stream.println(" to STDOUT");
stream.println(" rollbackToDateSQL <date/time> Writes SQL to roll back the database to that");
stream.println(" state it was in at the given date/time version");
stream.println(" to STDOUT");
stream.println(" rollbackCountSQL <value> Writes SQL to roll back the last");
stream.println(" <value> change sets to STDOUT");
stream.println(" applied to the database");
stream.println(" futureRollbackSQL Writes SQL to roll back the database to the ");
stream.println(" current state after the changes in the ");
stream.println(" changeslog have been applied");
stream.println(" generateChangeLog Writes Change Log XML to copy the current state");
stream.println(" of the database to standard out");
stream.println("");
stream.println("Diff Commands");
stream.println(" diff [diff parameters] Writes description of differences");
stream.println(" to standard out");
stream.println(" diffChangeLog [diff parameters] Writes Change Log XML to update");
stream.println(" the base database");
stream.println(" to the target database to standard out");
stream.println("");
stream.println("Documentation Commands");
stream.println(" dbDoc <outputDirectory> Generates Javadoc-like documentation");
stream.println(" based on current database and change log");
stream.println("");
stream.println("Maintenance Commands");
stream.println(" tag <tag string> 'Tags' the current database state for future rollback");
stream.println(" status [--verbose] Outputs count (list if --verbose) of unrun changesets");
stream.println(" validate Checks changelog for errors");
stream.println(" clearCheckSums Removes all saved checksums from database log.");
stream.println(" Useful for 'MD5Sum Check Failed' errors");
stream.println(" changelogSyncSQL Writes SQL to mark all changes as executed ");
stream.println(" in the database to STDOUT");
stream.println(" listLocks Lists who currently has locks on the");
stream.println(" database changelog");
stream.println(" releaseLocks Releases all locks on the database changelog");
stream.println(" dropAll Drop all database objects owned by user");
stream.println("");
stream.println("Required Parameters:");
stream.println(" --changeLogFile=<path and filename> Migration file");
stream.println(" --username=<value> Database username");
stream.println(" --password=<value> Database password");
stream.println(" --url=<value> Database URL");
stream.println("");
stream.println("Optional Parameters:");
stream.println(" --classpath=<value> Classpath containing");
stream.println(" migration files and JDBC Driver");
stream.println(" --driver=<jdbc.driver.ClassName> Database driver class name");
stream.println(" --contexts=<value> ChangeSet contexts to execute");
stream.println(" --defaultsFile=</path/to/file.properties> File with default option values");
stream.println(" (default: ./liquibase.properties)");
stream.println(" --includeSystemClasspath=<true|false> Include the system classpath");
stream.println(" in the LiquiBase classpath");
stream.println(" (default: true)");
stream.println(" --promptForNonLocalDatabase=<true|false> Prompt if non-localhost");
stream.println(" databases (default: false)");
stream.println(" --logLevel=<level> Execution log level");
stream.println(" (finest, finer, fine, info,");
stream.println(" warning, severe)");
stream.println(" --currentDateTimeFunction=<value> Overrides current date time function");
stream.println(" used in SQL.");
stream.println(" Useful for unsupported databases");
stream.println(" --help Prints this message");
stream.println(" --version Prints this version information");
stream.println("");
stream.println("Required Diff Parameters:");
stream.println(" --baseUsername=<value> Base Database username");
stream.println(" --basePassword=<value> Base Database password");
stream.println(" --baseUrl=<value> Base Database URL");
stream.println("");
stream.println("Optional Diff Parameters:");
stream.println(" --baseDriver=<jdbc.driver.ClassName> Base Database driver class name");
stream.println("");
stream.println("Default value for parameters can be stored in a file called");
stream.println("'liquibase.properties' that is read from the current working directory.");
stream.println("");
stream.println("Full documentation is available at");
stream.println("http://www.liquibase.org/manual/latest/command_line_migrator.html");
stream.println("");
}
public CommandLineMigrator() {
// options = createOptions();
}
protected void parseOptions(String[] args) throws CommandLineParsingException {
args = fixupArgs(args);
boolean seenCommand = false;
for (String arg : args) {
if (isCommand(arg)) {
this.command = arg;
seenCommand = true;
} else if (seenCommand) {
commandParams.add(arg);
} else if (arg.startsWith("--")) {
String[] splitArg = splitArg(arg);
String attributeName = splitArg[0];
String value = splitArg[1];
try {
Field field = getClass().getDeclaredField(attributeName);
if (field.getType().equals(Boolean.class)) {
field.set(this, Boolean.valueOf(value));
} else {
field.set(this, value);
}
} catch (Exception e) {
throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'");
}
} else {
throw new CommandLineParsingException("Parameters must start with a '--'");
}
}
}
private String[] splitArg(String arg) throws CommandLineParsingException {
String[] splitArg = arg.split("=");
if (splitArg.length < 2) {
throw new CommandLineParsingException("Could not parse '" + arg + "'");
} else if (splitArg.length > 2) {
StringBuffer secondHalf = new StringBuffer();
for (int j = 1; j < splitArg.length; j++) {
secondHalf.append(splitArg[j]).append("=");
}
splitArg = new String[]{
splitArg[0],
secondHalf.toString().replaceFirst("=$", "")
};
}
splitArg[0] = splitArg[0].replaceFirst("--", "");
return splitArg;
}
protected void applyDefaults() {
if (this.promptForNonLocalDatabase == null) {
this.promptForNonLocalDatabase = Boolean.FALSE;
}
if (this.logLevel == null) {
this.logLevel = "off";
}
if (this.includeSystemClasspath == null) {
this.includeSystemClasspath = Boolean.TRUE;
}
}
protected void configureClassLoader() throws CommandLineParsingException {
final List<URL> urls = new ArrayList<URL>();
if (this.classpath != null) {
String[] classpath;
if (isWindows()) {
classpath = this.classpath.split(";");
} else {
classpath = this.classpath.split(":");
}
for (String classpathEntry : classpath) {
File classPathFile = new File(classpathEntry);
if (!classPathFile.exists()) {
throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist");
}
try {
if (classpathEntry.endsWith(".war")) {
addWarFileClasspathEntries(classPathFile, urls);
} else if (classpathEntry.endsWith(".ear")) {
JarFile earZip = new JarFile(classPathFile);
Enumeration<? extends JarEntry> entries = earZip.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().toLowerCase().endsWith(".jar")) {
File jar = extract(earZip, entry);
urls.add(new URL("jar:" + jar.toURL() + "!/"));
jar.deleteOnExit();
} else if (entry.getName().toLowerCase().endsWith("war")) {
File warFile = extract(earZip, entry);
addWarFileClasspathEntries(warFile, urls);
}
}
} else {
urls.add(new File(classpathEntry).toURL());
}
} catch (Exception e) {
throw new CommandLineParsingException(e);
}
}
}
if (includeSystemClasspath) {
classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader());
}
});
} else {
classLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
public URLClassLoader run() {
return new URLClassLoader(urls.toArray(new URL[urls.size()]));
}
});
}
}
private void addWarFileClasspathEntries(File classPathFile, List<URL> urls) throws IOException {
URL url = new URL("jar:" + classPathFile.toURL() + "!/WEB-INF/classes/");
urls.add(url);
JarFile warZip = new JarFile(classPathFile);
Enumeration<? extends JarEntry> entries = warZip.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (entry.getName().startsWith("WEB-INF/lib")
&& entry.getName().toLowerCase().endsWith(".jar")) {
File jar = extract(warZip, entry);
urls.add(new URL("jar:" + jar.toURL() + "!/"));
jar.deleteOnExit();
}
}
}
private File extract(JarFile jar, JarEntry entry) throws IOException {
// expand to temp dir and add to list
File tempFile = File.createTempFile("migrator.tmp", null);
// read from jar and write to the tempJar file
BufferedInputStream inStream = null;
BufferedOutputStream outStream = null;
try {
inStream = new BufferedInputStream(jar.getInputStream(entry));
outStream = new BufferedOutputStream(
new FileOutputStream(tempFile));
int status;
while ((status = inStream.read()) != -1) {
outStream.write(status);
}
} finally {
if (outStream != null) {
try {
outStream.close();
} catch (IOException ioe) {
;
}
}
if (inStream != null) {
try {
inStream.close();
} catch (IOException ioe) {
;
}
}
}
return tempFile;
}
protected void doMigration() throws Exception {
if ("help".equalsIgnoreCase(command)) {
printHelp(System.out);
return;
}
if ("finest".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINEST);
} else if ("finer".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINER);
} else if ("fine".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINE);
} else if ("info".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.INFO);
} else if ("warning".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.WARNING);
} else if ("severe".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.SEVERE);
} else if ("off".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.OFF);
} else {
throw new CommandLineParsingException("Unknown log level: " + logLevel);
}
FileSystemFileOpener fsOpener = new FileSystemFileOpener();
CommandLineFileOpener clOpener = new CommandLineFileOpener(classLoader);
Migrator migrator = new Migrator(changeLogFile, new CompositeFileOpener(fsOpener, clOpener));
Driver driver;
try {
if (this.driver == null) {
this.driver = DatabaseFactory.getInstance().findDefaultDriver(url);
}
if (this.driver == null) {
throw new RuntimeException("Driver class was not specified and could not be determined from the url");
}
driver = (Driver) Class.forName(this.driver, true, classLoader).newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot get database driver: " + e.getMessage());
}
Properties info = new Properties();
info.put("user", username);
if (password != null) {
info.put("password", password);
}
Connection connection = driver.connect(url, info);
if (connection == null) {
throw new JDBCException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
}
if ("diff".equalsIgnoreCase(command)) {
doDiff(connection, createConnectionFromCommandParams(commandParams));
return;
} else if ("diffChangeLog".equalsIgnoreCase(command)) {
doDiffToChangeLog(connection, createConnectionFromCommandParams(commandParams));
return;
} else if ("generateChangeLog".equalsIgnoreCase(command)) {
doGenerateChangeLog(connection);
return;
}
try {
migrator.setContexts(contexts);
migrator.init(connection);
if ("listLocks".equalsIgnoreCase(command)) {
migrator.reportLocks(System.out);
return;
} else if ("releaseLocks".equalsIgnoreCase(command)) {
migrator.forceReleaseLock();
System.out.println("Successfully released all database change log locks for " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("tag".equalsIgnoreCase(command)) {
migrator.tag(commandParams.iterator().next());
System.out.println("Successfully tagged " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("dropAll".equals(command)) {
migrator.dropAll();
System.out.println("All objects dropped from " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("status".equalsIgnoreCase(command)) {
boolean runVerbose = false;
if (commandParams.contains("--verbose")) {
runVerbose = true;
}
migrator.reportStatus(runVerbose, System.out);
return;
} else if ("validate".equalsIgnoreCase(command)) {
try {
migrator.validate();
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
return;
}
System.out.println("No validation errors found");
return;
} else if ("clearCheckSums".equalsIgnoreCase(command)) {
migrator.clearCheckSums();
return;
} else if ("dbdoc".equalsIgnoreCase(command)) {
if (commandParams.size() == 0) {
throw new CommandLineParsingException("dbdoc requires an output directory");
}
+ if (changeLogFile == null) {
+ throw new CommandLineParsingException("dbdoc requires a changeLog parameter");
+ }
migrator.generateDocumentation(commandParams.iterator().next());
return;
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if ("migrate".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_MODE);
} else if ("changelogSyncSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_CHANGELOG_ONLY_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else if ("migrateSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else if ("rollback".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
if (commandParams == null) {
throw new CommandLineParsingException("rollback requires a rollback tag");
}
migrator.setRollbackToTag(commandParams.iterator().next());
} else if ("rollbackToDate".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
if (commandParams == null) {
throw new CommandLineParsingException("rollback requires a rollback date");
}
migrator.setRollbackToDate(dateFormat.parse(commandParams.iterator().next()));
} else if ("rollbackCount".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
migrator.setRollbackCount(Integer.parseInt(commandParams.iterator().next()));
} else if ("rollbackSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
if (commandParams == null) {
throw new CommandLineParsingException("rollbackSQL requires a rollback tag");
}
migrator.setRollbackToTag(commandParams.iterator().next());
} else if ("rollbackToDateSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
if (commandParams == null) {
throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date");
}
migrator.setRollbackToDate(dateFormat.parse(commandParams.iterator().next()));
} else if ("rollbackCountSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
migrator.setRollbackCount(Integer.valueOf(commandParams.iterator().next()));
} else if ("futureRollbackSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_FUTURE_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else {
throw new CommandLineParsingException("Unknown command: " + command);
}
} catch (ParseException e) {
throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd HH:mm:ss'");
}
// String promptForNonLocal = cmd.getOptionValue("promptForNonLocalDatabase");
// if (promptForNonLocal != null && Boolean.valueOf(promptForNonLocal)) {
// if (!migrator.isSaveToRunMigration()) {
//
// if (JOptionPane.showConfirmDialog(null, "You are running a database refactoring against a non-local database.\n" +
// "Database URL is: " + migrator.getDatabase().getConnectionURL() + "\n" +
// "Username is: " + migrator.getDatabase().getConnectionUsername() + "\n\n" +
// "Area you sure you want to do this?",
// "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) {
// System.out.println("Chose not to run against non-production database");
// System.exit(-1);
// }
// }
// }
migrator.migrate();
} finally {
connection.close();
}
}
private Connection createConnectionFromCommandParams(Set<String> commandParams) throws CommandLineParsingException, SQLException, JDBCException {
String driver = null;
String url = null;
String username = null;
String password = null;
for (String param : commandParams) {
String[] splitArg = splitArg(param);
String attributeName = splitArg[0];
String value = splitArg[1];
if ("baseDriver".equalsIgnoreCase(attributeName)) {
driver = value;
} else if ("baseUrl".equalsIgnoreCase(attributeName)) {
url = value;
} else if ("baseUsername".equals(attributeName)) {
username = value;
} else if ("basePassword".equals(attributeName)) {
password = value;
}
}
if (driver == null) {
driver = DatabaseFactory.getInstance().findDefaultDriver(url);
}
Driver driverObject;
try {
driverObject = (Driver) Class.forName(driver, true, classLoader).newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot get database driver: " + e.getMessage());
}
Properties info = new Properties();
info.put("user", username);
info.put("password", password);
Connection connection;
try {
connection = driverObject.connect(url, info);
} catch (SQLException e) {
throw new JDBCException("Connection could not be created to " + url + ": " + e.getMessage(), e);
}
if (connection == null) {
throw new JDBCException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
}
return connection;
}
private Writer getOutputWriter() {
return new OutputStreamWriter(System.out);
}
public boolean isWindows() {
return System.getProperty("os.name").startsWith("Windows ");
}
private void doDiff(Connection baseDatabase, Connection targetDatabase) throws JDBCException {
Diff diff = new Diff(baseDatabase, targetDatabase);
diff.addStatusListener(new OutDiffStatusListener());
DiffResult diffResult = diff.compare();
System.out.println("");
System.out.println("Diff Results:");
diffResult.printResult(System.out);
}
private void doDiffToChangeLog(Connection baseDatabase, Connection targetDatabase) throws JDBCException, IOException, ParserConfigurationException {
Diff diff = new Diff(baseDatabase, targetDatabase);
diff.addStatusListener(new OutDiffStatusListener());
DiffResult diffResult = diff.compare();
diffResult.printChangeLog(System.out, DatabaseFactory.getInstance().findCorrectDatabaseImplementation(targetDatabase));
}
private void doGenerateChangeLog(Connection originalDatabase) throws JDBCException, IOException, ParserConfigurationException {
Diff diff = new Diff(originalDatabase);
diff.addStatusListener(new OutDiffStatusListener());
DiffResult diffResult = diff.compare();
PrintStream outputStream = System.out;
if (StringUtils.trimToNull(changeLogFile) != null) {
File changeFile = new File(changeLogFile);
outputStream = new PrintStream(changeFile);
}
diffResult.printChangeLog(outputStream, DatabaseFactory.getInstance().findCorrectDatabaseImplementation(originalDatabase));
}
private static class OutDiffStatusListener implements DiffStatusListener {
public void statusUpdate(String message) {
System.err.println(message);
}
}
}
| true | true | protected void doMigration() throws Exception {
if ("help".equalsIgnoreCase(command)) {
printHelp(System.out);
return;
}
if ("finest".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINEST);
} else if ("finer".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINER);
} else if ("fine".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINE);
} else if ("info".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.INFO);
} else if ("warning".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.WARNING);
} else if ("severe".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.SEVERE);
} else if ("off".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.OFF);
} else {
throw new CommandLineParsingException("Unknown log level: " + logLevel);
}
FileSystemFileOpener fsOpener = new FileSystemFileOpener();
CommandLineFileOpener clOpener = new CommandLineFileOpener(classLoader);
Migrator migrator = new Migrator(changeLogFile, new CompositeFileOpener(fsOpener, clOpener));
Driver driver;
try {
if (this.driver == null) {
this.driver = DatabaseFactory.getInstance().findDefaultDriver(url);
}
if (this.driver == null) {
throw new RuntimeException("Driver class was not specified and could not be determined from the url");
}
driver = (Driver) Class.forName(this.driver, true, classLoader).newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot get database driver: " + e.getMessage());
}
Properties info = new Properties();
info.put("user", username);
if (password != null) {
info.put("password", password);
}
Connection connection = driver.connect(url, info);
if (connection == null) {
throw new JDBCException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
}
if ("diff".equalsIgnoreCase(command)) {
doDiff(connection, createConnectionFromCommandParams(commandParams));
return;
} else if ("diffChangeLog".equalsIgnoreCase(command)) {
doDiffToChangeLog(connection, createConnectionFromCommandParams(commandParams));
return;
} else if ("generateChangeLog".equalsIgnoreCase(command)) {
doGenerateChangeLog(connection);
return;
}
try {
migrator.setContexts(contexts);
migrator.init(connection);
if ("listLocks".equalsIgnoreCase(command)) {
migrator.reportLocks(System.out);
return;
} else if ("releaseLocks".equalsIgnoreCase(command)) {
migrator.forceReleaseLock();
System.out.println("Successfully released all database change log locks for " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("tag".equalsIgnoreCase(command)) {
migrator.tag(commandParams.iterator().next());
System.out.println("Successfully tagged " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("dropAll".equals(command)) {
migrator.dropAll();
System.out.println("All objects dropped from " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("status".equalsIgnoreCase(command)) {
boolean runVerbose = false;
if (commandParams.contains("--verbose")) {
runVerbose = true;
}
migrator.reportStatus(runVerbose, System.out);
return;
} else if ("validate".equalsIgnoreCase(command)) {
try {
migrator.validate();
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
return;
}
System.out.println("No validation errors found");
return;
} else if ("clearCheckSums".equalsIgnoreCase(command)) {
migrator.clearCheckSums();
return;
} else if ("dbdoc".equalsIgnoreCase(command)) {
if (commandParams.size() == 0) {
throw new CommandLineParsingException("dbdoc requires an output directory");
}
migrator.generateDocumentation(commandParams.iterator().next());
return;
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if ("migrate".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_MODE);
} else if ("changelogSyncSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_CHANGELOG_ONLY_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else if ("migrateSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else if ("rollback".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
if (commandParams == null) {
throw new CommandLineParsingException("rollback requires a rollback tag");
}
migrator.setRollbackToTag(commandParams.iterator().next());
} else if ("rollbackToDate".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
if (commandParams == null) {
throw new CommandLineParsingException("rollback requires a rollback date");
}
migrator.setRollbackToDate(dateFormat.parse(commandParams.iterator().next()));
} else if ("rollbackCount".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
migrator.setRollbackCount(Integer.parseInt(commandParams.iterator().next()));
} else if ("rollbackSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
if (commandParams == null) {
throw new CommandLineParsingException("rollbackSQL requires a rollback tag");
}
migrator.setRollbackToTag(commandParams.iterator().next());
} else if ("rollbackToDateSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
if (commandParams == null) {
throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date");
}
migrator.setRollbackToDate(dateFormat.parse(commandParams.iterator().next()));
} else if ("rollbackCountSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
migrator.setRollbackCount(Integer.valueOf(commandParams.iterator().next()));
} else if ("futureRollbackSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_FUTURE_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else {
throw new CommandLineParsingException("Unknown command: " + command);
}
} catch (ParseException e) {
throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd HH:mm:ss'");
}
// String promptForNonLocal = cmd.getOptionValue("promptForNonLocalDatabase");
// if (promptForNonLocal != null && Boolean.valueOf(promptForNonLocal)) {
// if (!migrator.isSaveToRunMigration()) {
//
// if (JOptionPane.showConfirmDialog(null, "You are running a database refactoring against a non-local database.\n" +
// "Database URL is: " + migrator.getDatabase().getConnectionURL() + "\n" +
// "Username is: " + migrator.getDatabase().getConnectionUsername() + "\n\n" +
// "Area you sure you want to do this?",
// "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) {
// System.out.println("Chose not to run against non-production database");
// System.exit(-1);
// }
// }
// }
migrator.migrate();
} finally {
connection.close();
}
}
| protected void doMigration() throws Exception {
if ("help".equalsIgnoreCase(command)) {
printHelp(System.out);
return;
}
if ("finest".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINEST);
} else if ("finer".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINER);
} else if ("fine".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.FINE);
} else if ("info".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.INFO);
} else if ("warning".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.WARNING);
} else if ("severe".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.SEVERE);
} else if ("off".equalsIgnoreCase(logLevel)) {
Logger.getLogger(Migrator.DEFAULT_LOG_NAME).setLevel(Level.OFF);
} else {
throw new CommandLineParsingException("Unknown log level: " + logLevel);
}
FileSystemFileOpener fsOpener = new FileSystemFileOpener();
CommandLineFileOpener clOpener = new CommandLineFileOpener(classLoader);
Migrator migrator = new Migrator(changeLogFile, new CompositeFileOpener(fsOpener, clOpener));
Driver driver;
try {
if (this.driver == null) {
this.driver = DatabaseFactory.getInstance().findDefaultDriver(url);
}
if (this.driver == null) {
throw new RuntimeException("Driver class was not specified and could not be determined from the url");
}
driver = (Driver) Class.forName(this.driver, true, classLoader).newInstance();
} catch (Exception e) {
throw new RuntimeException("Cannot get database driver: " + e.getMessage());
}
Properties info = new Properties();
info.put("user", username);
if (password != null) {
info.put("password", password);
}
Connection connection = driver.connect(url, info);
if (connection == null) {
throw new JDBCException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL");
}
if ("diff".equalsIgnoreCase(command)) {
doDiff(connection, createConnectionFromCommandParams(commandParams));
return;
} else if ("diffChangeLog".equalsIgnoreCase(command)) {
doDiffToChangeLog(connection, createConnectionFromCommandParams(commandParams));
return;
} else if ("generateChangeLog".equalsIgnoreCase(command)) {
doGenerateChangeLog(connection);
return;
}
try {
migrator.setContexts(contexts);
migrator.init(connection);
if ("listLocks".equalsIgnoreCase(command)) {
migrator.reportLocks(System.out);
return;
} else if ("releaseLocks".equalsIgnoreCase(command)) {
migrator.forceReleaseLock();
System.out.println("Successfully released all database change log locks for " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("tag".equalsIgnoreCase(command)) {
migrator.tag(commandParams.iterator().next());
System.out.println("Successfully tagged " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("dropAll".equals(command)) {
migrator.dropAll();
System.out.println("All objects dropped from " + migrator.getDatabase().getConnectionUsername() + "@" + migrator.getDatabase().getConnectionURL());
return;
} else if ("status".equalsIgnoreCase(command)) {
boolean runVerbose = false;
if (commandParams.contains("--verbose")) {
runVerbose = true;
}
migrator.reportStatus(runVerbose, System.out);
return;
} else if ("validate".equalsIgnoreCase(command)) {
try {
migrator.validate();
} catch (ValidationFailedException e) {
e.printDescriptiveError(System.out);
return;
}
System.out.println("No validation errors found");
return;
} else if ("clearCheckSums".equalsIgnoreCase(command)) {
migrator.clearCheckSums();
return;
} else if ("dbdoc".equalsIgnoreCase(command)) {
if (commandParams.size() == 0) {
throw new CommandLineParsingException("dbdoc requires an output directory");
}
if (changeLogFile == null) {
throw new CommandLineParsingException("dbdoc requires a changeLog parameter");
}
migrator.generateDocumentation(commandParams.iterator().next());
return;
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
if ("migrate".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_MODE);
} else if ("changelogSyncSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_CHANGELOG_ONLY_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else if ("migrateSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else if ("rollback".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
if (commandParams == null) {
throw new CommandLineParsingException("rollback requires a rollback tag");
}
migrator.setRollbackToTag(commandParams.iterator().next());
} else if ("rollbackToDate".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
if (commandParams == null) {
throw new CommandLineParsingException("rollback requires a rollback date");
}
migrator.setRollbackToDate(dateFormat.parse(commandParams.iterator().next()));
} else if ("rollbackCount".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.EXECUTE_ROLLBACK_MODE);
migrator.setRollbackCount(Integer.parseInt(commandParams.iterator().next()));
} else if ("rollbackSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
if (commandParams == null) {
throw new CommandLineParsingException("rollbackSQL requires a rollback tag");
}
migrator.setRollbackToTag(commandParams.iterator().next());
} else if ("rollbackToDateSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
if (commandParams == null) {
throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date");
}
migrator.setRollbackToDate(dateFormat.parse(commandParams.iterator().next()));
} else if ("rollbackCountSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
migrator.setRollbackCount(Integer.valueOf(commandParams.iterator().next()));
} else if ("futureRollbackSQL".equalsIgnoreCase(command)) {
migrator.setMode(Migrator.Mode.OUTPUT_FUTURE_ROLLBACK_SQL_MODE);
migrator.setOutputSQLWriter(getOutputWriter());
} else {
throw new CommandLineParsingException("Unknown command: " + command);
}
} catch (ParseException e) {
throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd HH:mm:ss'");
}
// String promptForNonLocal = cmd.getOptionValue("promptForNonLocalDatabase");
// if (promptForNonLocal != null && Boolean.valueOf(promptForNonLocal)) {
// if (!migrator.isSaveToRunMigration()) {
//
// if (JOptionPane.showConfirmDialog(null, "You are running a database refactoring against a non-local database.\n" +
// "Database URL is: " + migrator.getDatabase().getConnectionURL() + "\n" +
// "Username is: " + migrator.getDatabase().getConnectionUsername() + "\n\n" +
// "Area you sure you want to do this?",
// "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) == JOptionPane.NO_OPTION) {
// System.out.println("Chose not to run against non-production database");
// System.exit(-1);
// }
// }
// }
migrator.migrate();
} finally {
connection.close();
}
}
|
diff --git a/src/com/android/mms/data/RecipientsListLoader.java b/src/com/android/mms/data/RecipientsListLoader.java
index 5ea44b0e..e56ad8a2 100644
--- a/src/com/android/mms/data/RecipientsListLoader.java
+++ b/src/com/android/mms/data/RecipientsListLoader.java
@@ -1,159 +1,159 @@
/*
* Copyright (C) 2013 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.android.mms.data;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.android.mms.ui.SelectRecipientsList;
public class RecipientsListLoader extends AsyncTaskLoader<ArrayList<RecipientsListLoader.Result>> {
private ArrayList<Result> mResults;
public static class Result {
public PhoneNumber phoneNumber;
public Group group;
}
public RecipientsListLoader(Context context) {
super(context);
}
@Override
public ArrayList<Result> loadInBackground() {
final Context context = getContext();
ArrayList<PhoneNumber> phoneNumbers = PhoneNumber.getPhoneNumbers(context);
if (phoneNumbers == null) {
- return null;
+ return new ArrayList<Result>();
}
// Get things ready
ArrayList<Result> results = new ArrayList<Result>();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean showGroups = prefs.getBoolean(SelectRecipientsList.PREF_SHOW_GROUPS, true);
if (showGroups) {
ArrayList<Group> groups = Group.getGroups(context);
ArrayList<GroupMembership> groupMemberships = GroupMembership.getGroupMemberships(context);
Map<Long, ArrayList<Long>> groupIdWithContactsId = new HashMap<Long, ArrayList<Long>>();
// Store GID with all its CIDs
if (groups != null && groupMemberships != null) {
for (GroupMembership membership : groupMemberships) {
Long gid = membership.getGroupId();
Long uid = membership.getContactId();
if (!groupIdWithContactsId.containsKey(gid)) {
groupIdWithContactsId.put(gid, new ArrayList<Long>());
}
if (!groupIdWithContactsId.get(gid).contains(uid)) {
groupIdWithContactsId.get(gid).add(uid);
}
}
// For each PhoneNumber, find its GID, and add it to correct Group
for (PhoneNumber phoneNumber : phoneNumbers) {
long cid = phoneNumber.getContactId();
for (Map.Entry<Long, ArrayList<Long>> entry : groupIdWithContactsId.entrySet()) {
if (!entry.getValue().contains(cid)) {
continue;
}
for (Group group : groups) {
if (group.getId() == entry.getKey()) {
group.addPhoneNumber(phoneNumber);
phoneNumber.addGroup(group);
}
}
}
}
// Add the groups to the list first
for (Group group : groups) {
// Due to filtering there may be groups that have contacts, but no
// phone numbers. Filter those.
if (!group.getPhoneNumbers().isEmpty()) {
Result result = new Result();
result.group = group;
results.add(result);
}
}
}
}
// Add phone numbers to the list
for (PhoneNumber phoneNumber : phoneNumbers) {
Result result = new Result();
result.phoneNumber = phoneNumber;
results.add(result);
}
// We are done
return results;
}
// Called when there is new data to deliver to the client. The
// super class will take care of delivering it; the implementation
// here just adds a little more logic.
@Override
public void deliverResult(ArrayList<Result> results) {
mResults = results;
if (isStarted()) {
// If the Loader is started, immediately deliver its results.
super.deliverResult(results);
}
}
@Override
protected void onStartLoading() {
if (mResults != null) {
// If we currently have a result available, deliver it immediately.
deliverResult(mResults);
}
if (takeContentChanged() || mResults == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
@Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
@Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated if needed.
mResults = null;
}
}
| true | true | public ArrayList<Result> loadInBackground() {
final Context context = getContext();
ArrayList<PhoneNumber> phoneNumbers = PhoneNumber.getPhoneNumbers(context);
if (phoneNumbers == null) {
return null;
}
// Get things ready
ArrayList<Result> results = new ArrayList<Result>();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean showGroups = prefs.getBoolean(SelectRecipientsList.PREF_SHOW_GROUPS, true);
if (showGroups) {
ArrayList<Group> groups = Group.getGroups(context);
ArrayList<GroupMembership> groupMemberships = GroupMembership.getGroupMemberships(context);
Map<Long, ArrayList<Long>> groupIdWithContactsId = new HashMap<Long, ArrayList<Long>>();
// Store GID with all its CIDs
if (groups != null && groupMemberships != null) {
for (GroupMembership membership : groupMemberships) {
Long gid = membership.getGroupId();
Long uid = membership.getContactId();
if (!groupIdWithContactsId.containsKey(gid)) {
groupIdWithContactsId.put(gid, new ArrayList<Long>());
}
if (!groupIdWithContactsId.get(gid).contains(uid)) {
groupIdWithContactsId.get(gid).add(uid);
}
}
// For each PhoneNumber, find its GID, and add it to correct Group
for (PhoneNumber phoneNumber : phoneNumbers) {
long cid = phoneNumber.getContactId();
for (Map.Entry<Long, ArrayList<Long>> entry : groupIdWithContactsId.entrySet()) {
if (!entry.getValue().contains(cid)) {
continue;
}
for (Group group : groups) {
if (group.getId() == entry.getKey()) {
group.addPhoneNumber(phoneNumber);
phoneNumber.addGroup(group);
}
}
}
}
// Add the groups to the list first
for (Group group : groups) {
// Due to filtering there may be groups that have contacts, but no
// phone numbers. Filter those.
if (!group.getPhoneNumbers().isEmpty()) {
Result result = new Result();
result.group = group;
results.add(result);
}
}
}
}
// Add phone numbers to the list
for (PhoneNumber phoneNumber : phoneNumbers) {
Result result = new Result();
result.phoneNumber = phoneNumber;
results.add(result);
}
// We are done
return results;
}
| public ArrayList<Result> loadInBackground() {
final Context context = getContext();
ArrayList<PhoneNumber> phoneNumbers = PhoneNumber.getPhoneNumbers(context);
if (phoneNumbers == null) {
return new ArrayList<Result>();
}
// Get things ready
ArrayList<Result> results = new ArrayList<Result>();
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean showGroups = prefs.getBoolean(SelectRecipientsList.PREF_SHOW_GROUPS, true);
if (showGroups) {
ArrayList<Group> groups = Group.getGroups(context);
ArrayList<GroupMembership> groupMemberships = GroupMembership.getGroupMemberships(context);
Map<Long, ArrayList<Long>> groupIdWithContactsId = new HashMap<Long, ArrayList<Long>>();
// Store GID with all its CIDs
if (groups != null && groupMemberships != null) {
for (GroupMembership membership : groupMemberships) {
Long gid = membership.getGroupId();
Long uid = membership.getContactId();
if (!groupIdWithContactsId.containsKey(gid)) {
groupIdWithContactsId.put(gid, new ArrayList<Long>());
}
if (!groupIdWithContactsId.get(gid).contains(uid)) {
groupIdWithContactsId.get(gid).add(uid);
}
}
// For each PhoneNumber, find its GID, and add it to correct Group
for (PhoneNumber phoneNumber : phoneNumbers) {
long cid = phoneNumber.getContactId();
for (Map.Entry<Long, ArrayList<Long>> entry : groupIdWithContactsId.entrySet()) {
if (!entry.getValue().contains(cid)) {
continue;
}
for (Group group : groups) {
if (group.getId() == entry.getKey()) {
group.addPhoneNumber(phoneNumber);
phoneNumber.addGroup(group);
}
}
}
}
// Add the groups to the list first
for (Group group : groups) {
// Due to filtering there may be groups that have contacts, but no
// phone numbers. Filter those.
if (!group.getPhoneNumbers().isEmpty()) {
Result result = new Result();
result.group = group;
results.add(result);
}
}
}
}
// Add phone numbers to the list
for (PhoneNumber phoneNumber : phoneNumbers) {
Result result = new Result();
result.phoneNumber = phoneNumber;
results.add(result);
}
// We are done
return results;
}
|
diff --git a/src/com/android/phone/msim/MSimDialerActivity.java b/src/com/android/phone/msim/MSimDialerActivity.java
index 0e59f1f8..4871dbb6 100644
--- a/src/com/android/phone/msim/MSimDialerActivity.java
+++ b/src/com/android/phone/msim/MSimDialerActivity.java
@@ -1,269 +1,270 @@
/*
* Copyright (c) 2012-2013, The Linux Foundation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of The Linux Foundation, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.android.phone;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.DialogInterface;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.telephony.MSimTelephonyManager;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;
import android.view.KeyEvent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Button;
import com.android.internal.telephony.MSimConstants;
import com.android.internal.telephony.Phone;
import com.codeaurora.telephony.msim.MSimPhoneFactory;
import com.codeaurora.telephony.msim.SubscriptionManager;
import static com.android.internal.telephony.MSimConstants.SUBSCRIPTION_KEY;
/**
* While initiating MO call this class is used to provide
* a prompt option to user to choose the sub on which user
* want to make outgoing call.
*/
public class MSimDialerActivity extends Activity {
private static final String TAG = "MSimDialerActivity";
private static final boolean DBG = true;
private Context mContext;
private String mCallNumber;
private String mNumber;
private AlertDialog mAlertDialog = null;
private TextView mTextNumber;
private Intent mIntent;
private int mPhoneCount = 0;
public static final String PHONE_SUBSCRIPTION = "Subscription";
public static final int INVALID_SUB = 99;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
mContext = getApplicationContext();
mCallNumber = getResources().getString(R.string.call_number);
}
@Override
protected void onResume() {
super.onResume();
mPhoneCount = MSimTelephonyManager.getDefault().getPhoneCount();
mIntent = getIntent();
if (DBG) Log.v(TAG, "Intent = " + mIntent);
mNumber = PhoneNumberUtils.getNumberFromIntent(mIntent, this);
if (DBG) Log.v(TAG, "mNumber " + mNumber);
if (mNumber != null) {
mNumber = PhoneNumberUtils.convertKeypadLettersToDigits(mNumber);
mNumber = PhoneNumberUtils.stripSeparators(mNumber);
}
Phone phone = null;
boolean phoneInCall = false;
//checking if any of the phones are in use
for (int i = 0; i < mPhoneCount; i++) {
phone = MSimPhoneFactory.getPhone(i);
boolean inCall = isInCall(phone);
if ((phone != null) && (inCall)) {
phoneInCall = true;
break;
}
}
if (phoneInCall && !(MSimTelephonyManager.getDefault().getMultiSimConfiguration()
== MSimTelephonyManager.MultiSimVariants.DSDA)) {
if (DBG) Log.v(TAG, "subs [" + phone.getSubscription() + "] is in call");
// use the sub which is already in call
startOutgoingCall(phone.getSubscription());
} else {
if (DBG) Log.v(TAG, "launch dsdsdialer");
// if none in use, launch the MultiSimDialer
launchMSDialer();
}
Log.d(TAG, "end of onResume()");
}
protected void onPause() {
super.onPause();
if(DBG) Log.v(TAG, "onPause : " + mIntent);
if (mAlertDialog != null) {
mAlertDialog.dismiss();
mAlertDialog = null;
}
}
private int getSubscriptionForEmergencyCall(){
Log.d(TAG,"emergency call, getVoiceSubscriptionInService");
int sub = PhoneGlobals.getInstance().getVoiceSubscriptionInService();
return sub;
}
private void launchMSDialer() {
boolean isEmergency = PhoneNumberUtils.isEmergencyNumber(mNumber);
if (isEmergency) {
Log.d(TAG,"emergency call");
startOutgoingCall(getSubscriptionForEmergencyCall());
return;
}
LayoutInflater inflater = (LayoutInflater) mContext.
getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialer_ms,
(ViewGroup) findViewById(R.id.layout_root));
AlertDialog.Builder builder = new AlertDialog.Builder(MSimDialerActivity.this);
builder.setView(layout);
builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
Log.d(TAG, "key code is :" + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
mAlertDialog.dismiss();
startOutgoingCall(INVALID_SUB);
return true;
}
case KeyEvent.KEYCODE_CALL: {
Log.d(TAG, "event is" + event.getAction());
if (event.getAction() == KeyEvent.ACTION_UP) {
return true;
} else {
mAlertDialog.dismiss();
startOutgoingCall(MSimPhoneFactory.getVoiceSubscription());
return true;
}
}
case KeyEvent.KEYCODE_SEARCH:
return true;
default:
return false;
}
}
});
mAlertDialog = builder.create();
+ mAlertDialog.setCanceledOnTouchOutside(false);
mTextNumber = (TextView)layout.findViewById(R.id.CallNumber);
String vm = "";
if (mIntent.getData() != null)
vm = mIntent.getData().getScheme();
if ((vm != null) && (vm.equals("voicemail"))) {
mTextNumber.setText(mCallNumber + "VoiceMail" );
Log.d(TAG, "its voicemail!!!");
} else {
mTextNumber.setText(mCallNumber + mNumber);
}
Button callCancel = (Button)layout.findViewById(R.id.callcancel);
callCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAlertDialog.dismiss();
startOutgoingCall(INVALID_SUB);
}
});
Button[] callButton = new Button[mPhoneCount];
int[] callMark = {R.id.callmark1, R.id.callmark2, R.id.callmark3};
int[] subString = {R.string.sub_1, R.string.sub_2, R.string.sub_3};
int index = 0;
SubscriptionManager subManager = SubscriptionManager.getInstance();
for (index = 0; index < mPhoneCount; index++) {
if (subManager.isSubActive(index)) {
Button button = (Button) layout.findViewById(callMark[index]);
button.setVisibility(View.VISIBLE);
}
}
for (index = 0; index < mPhoneCount; index++) {
callButton[index] = (Button) layout.findViewById(callMark[index]);
callButton[index].setText(subString[index]);
callButton[index].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAlertDialog.dismiss();
switch (v.getId()) {
case R.id.callmark1:
startOutgoingCall(MSimConstants.SUB1);
break;
case R.id.callmark2:
startOutgoingCall(MSimConstants.SUB2);
break;
case R.id.callmark3:
startOutgoingCall(MSimConstants.SUB3);
break;
}
}
});
}
index = MSimPhoneFactory.getVoiceSubscription();
if (index < mPhoneCount) {
callButton[index].setBackgroundResource(R.drawable.highlight_btn_call);
}
mAlertDialog.show();
}
boolean isInCall(Phone phone) {
if (phone != null) {
if ((phone.getForegroundCall().getState().isAlive()) ||
(phone.getBackgroundCall().getState().isAlive()) ||
(phone.getRingingCall().getState().isAlive()))
return true;
}
return false;
}
private void startOutgoingCall(int subscription) {
mIntent.putExtra(SUBSCRIPTION_KEY, subscription);
mIntent.setClass(MSimDialerActivity.this, OutgoingCallBroadcaster.class);
if (DBG) Log.v(TAG, "startOutgoingCall for sub " +subscription
+ " from intent: "+ mIntent);
if (subscription < mPhoneCount) {
setResult(RESULT_OK, mIntent);
} else {
setResult(RESULT_CANCELED, mIntent);
Log.d(TAG, "call cancelled");
}
finish();
}
}
| true | true | private void launchMSDialer() {
boolean isEmergency = PhoneNumberUtils.isEmergencyNumber(mNumber);
if (isEmergency) {
Log.d(TAG,"emergency call");
startOutgoingCall(getSubscriptionForEmergencyCall());
return;
}
LayoutInflater inflater = (LayoutInflater) mContext.
getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialer_ms,
(ViewGroup) findViewById(R.id.layout_root));
AlertDialog.Builder builder = new AlertDialog.Builder(MSimDialerActivity.this);
builder.setView(layout);
builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
Log.d(TAG, "key code is :" + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
mAlertDialog.dismiss();
startOutgoingCall(INVALID_SUB);
return true;
}
case KeyEvent.KEYCODE_CALL: {
Log.d(TAG, "event is" + event.getAction());
if (event.getAction() == KeyEvent.ACTION_UP) {
return true;
} else {
mAlertDialog.dismiss();
startOutgoingCall(MSimPhoneFactory.getVoiceSubscription());
return true;
}
}
case KeyEvent.KEYCODE_SEARCH:
return true;
default:
return false;
}
}
});
mAlertDialog = builder.create();
mTextNumber = (TextView)layout.findViewById(R.id.CallNumber);
String vm = "";
if (mIntent.getData() != null)
vm = mIntent.getData().getScheme();
if ((vm != null) && (vm.equals("voicemail"))) {
mTextNumber.setText(mCallNumber + "VoiceMail" );
Log.d(TAG, "its voicemail!!!");
} else {
mTextNumber.setText(mCallNumber + mNumber);
}
Button callCancel = (Button)layout.findViewById(R.id.callcancel);
callCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAlertDialog.dismiss();
startOutgoingCall(INVALID_SUB);
}
});
Button[] callButton = new Button[mPhoneCount];
int[] callMark = {R.id.callmark1, R.id.callmark2, R.id.callmark3};
int[] subString = {R.string.sub_1, R.string.sub_2, R.string.sub_3};
int index = 0;
SubscriptionManager subManager = SubscriptionManager.getInstance();
for (index = 0; index < mPhoneCount; index++) {
if (subManager.isSubActive(index)) {
Button button = (Button) layout.findViewById(callMark[index]);
button.setVisibility(View.VISIBLE);
}
}
for (index = 0; index < mPhoneCount; index++) {
callButton[index] = (Button) layout.findViewById(callMark[index]);
callButton[index].setText(subString[index]);
callButton[index].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAlertDialog.dismiss();
switch (v.getId()) {
case R.id.callmark1:
startOutgoingCall(MSimConstants.SUB1);
break;
case R.id.callmark2:
startOutgoingCall(MSimConstants.SUB2);
break;
case R.id.callmark3:
startOutgoingCall(MSimConstants.SUB3);
break;
}
}
});
}
index = MSimPhoneFactory.getVoiceSubscription();
if (index < mPhoneCount) {
callButton[index].setBackgroundResource(R.drawable.highlight_btn_call);
}
mAlertDialog.show();
}
| private void launchMSDialer() {
boolean isEmergency = PhoneNumberUtils.isEmergencyNumber(mNumber);
if (isEmergency) {
Log.d(TAG,"emergency call");
startOutgoingCall(getSubscriptionForEmergencyCall());
return;
}
LayoutInflater inflater = (LayoutInflater) mContext.
getSystemService(LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.dialer_ms,
(ViewGroup) findViewById(R.id.layout_root));
AlertDialog.Builder builder = new AlertDialog.Builder(MSimDialerActivity.this);
builder.setView(layout);
builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
Log.d(TAG, "key code is :" + keyCode);
switch (keyCode) {
case KeyEvent.KEYCODE_BACK: {
mAlertDialog.dismiss();
startOutgoingCall(INVALID_SUB);
return true;
}
case KeyEvent.KEYCODE_CALL: {
Log.d(TAG, "event is" + event.getAction());
if (event.getAction() == KeyEvent.ACTION_UP) {
return true;
} else {
mAlertDialog.dismiss();
startOutgoingCall(MSimPhoneFactory.getVoiceSubscription());
return true;
}
}
case KeyEvent.KEYCODE_SEARCH:
return true;
default:
return false;
}
}
});
mAlertDialog = builder.create();
mAlertDialog.setCanceledOnTouchOutside(false);
mTextNumber = (TextView)layout.findViewById(R.id.CallNumber);
String vm = "";
if (mIntent.getData() != null)
vm = mIntent.getData().getScheme();
if ((vm != null) && (vm.equals("voicemail"))) {
mTextNumber.setText(mCallNumber + "VoiceMail" );
Log.d(TAG, "its voicemail!!!");
} else {
mTextNumber.setText(mCallNumber + mNumber);
}
Button callCancel = (Button)layout.findViewById(R.id.callcancel);
callCancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAlertDialog.dismiss();
startOutgoingCall(INVALID_SUB);
}
});
Button[] callButton = new Button[mPhoneCount];
int[] callMark = {R.id.callmark1, R.id.callmark2, R.id.callmark3};
int[] subString = {R.string.sub_1, R.string.sub_2, R.string.sub_3};
int index = 0;
SubscriptionManager subManager = SubscriptionManager.getInstance();
for (index = 0; index < mPhoneCount; index++) {
if (subManager.isSubActive(index)) {
Button button = (Button) layout.findViewById(callMark[index]);
button.setVisibility(View.VISIBLE);
}
}
for (index = 0; index < mPhoneCount; index++) {
callButton[index] = (Button) layout.findViewById(callMark[index]);
callButton[index].setText(subString[index]);
callButton[index].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mAlertDialog.dismiss();
switch (v.getId()) {
case R.id.callmark1:
startOutgoingCall(MSimConstants.SUB1);
break;
case R.id.callmark2:
startOutgoingCall(MSimConstants.SUB2);
break;
case R.id.callmark3:
startOutgoingCall(MSimConstants.SUB3);
break;
}
}
});
}
index = MSimPhoneFactory.getVoiceSubscription();
if (index < mPhoneCount) {
callButton[index].setBackgroundResource(R.drawable.highlight_btn_call);
}
mAlertDialog.show();
}
|
diff --git a/src/classes/com/sun/opengl/impl/GLDrawableHelper.java b/src/classes/com/sun/opengl/impl/GLDrawableHelper.java
index 014e35f7e..614b26096 100644
--- a/src/classes/com/sun/opengl/impl/GLDrawableHelper.java
+++ b/src/classes/com/sun/opengl/impl/GLDrawableHelper.java
@@ -1,150 +1,151 @@
/*
* Copyright (c) 2003 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* - Redistribution of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistribution in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
* INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
* PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN
* MICROSYSTEMS, INC. ("SUN") AND ITS LICENSORS SHALL NOT BE LIABLE FOR
* ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
* DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR
* ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR
* DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE
* DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY,
* ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF
* SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed or intended for use
* in the design, construction, operation or maintenance of any nuclear
* facility.
*
* Sun gratefully acknowledges that this software was originally authored
* and developed by Kenneth Bradley Russell and Christopher John Kline.
*/
package com.sun.opengl.impl;
import java.util.*;
import javax.media.opengl.*;
/** Encapsulates the implementation of most of the GLAutoDrawable's
methods to be able to share it between GLCanvas and GLJPanel. */
public class GLDrawableHelper {
private volatile List listeners = new ArrayList();
private static final boolean DEBUG = Debug.debug("GLDrawableHelper");
private static final boolean VERBOSE = Debug.verbose();
private boolean autoSwapBufferMode = true;
public GLDrawableHelper() {
}
public synchronized void addGLEventListener(GLEventListener listener) {
List newListeners = (List) ((ArrayList) listeners).clone();
newListeners.add(listener);
listeners = newListeners;
}
public synchronized void removeGLEventListener(GLEventListener listener) {
List newListeners = (List) ((ArrayList) listeners).clone();
newListeners.remove(listener);
listeners = newListeners;
}
public void init(GLAutoDrawable drawable) {
for (Iterator iter = listeners.iterator(); iter.hasNext(); ) {
((GLEventListener) iter.next()).init(drawable);
}
}
public void display(GLAutoDrawable drawable) {
for (Iterator iter = listeners.iterator(); iter.hasNext(); ) {
((GLEventListener) iter.next()).display(drawable);
}
}
public void reshape(GLAutoDrawable drawable,
int x, int y, int width, int height) {
for (Iterator iter = listeners.iterator(); iter.hasNext(); ) {
((GLEventListener) iter.next()).reshape(drawable, x, y, width, height);
}
}
public void setAutoSwapBufferMode(boolean onOrOff) {
autoSwapBufferMode = onOrOff;
}
public boolean getAutoSwapBufferMode() {
return autoSwapBufferMode;
}
private static final ThreadLocal perThreadInitAction = new ThreadLocal();
/** Principal helper method which runs a Runnable with the context
made current. This could have been made part of GLContext, but a
desired goal is to be able to implement the GLCanvas in terms of
the GLContext's public APIs, and putting it into a separate
class helps ensure that we don't inadvertently use private
methods of the GLContext or its implementing classes. */
public void invokeGL(GLDrawable drawable,
GLContext context,
Runnable runnable,
Runnable initAction) {
// Support for recursive makeCurrent() calls as well as calling
// other drawables' display() methods from within another one's
GLContext lastContext = GLContext.getCurrent();
Runnable lastInitAction = (Runnable) perThreadInitAction.get();
if (lastContext != null) {
lastContext.release();
}
int res = 0;
try {
res = context.makeCurrent();
if (res != GLContext.CONTEXT_NOT_CURRENT) {
+ perThreadInitAction.set(initAction);
if (res == GLContext.CONTEXT_CURRENT_NEW) {
if (DEBUG) {
System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction");
}
initAction.run();
}
if (DEBUG && VERBOSE) {
System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running runnable");
}
runnable.run();
if (autoSwapBufferMode) {
if (drawable != null) {
drawable.swapBuffers();
}
}
}
} finally {
try {
if (res != GLContext.CONTEXT_NOT_CURRENT) {
context.release();
}
} catch (Exception e) {
}
if (lastContext != null) {
int res2 = lastContext.makeCurrent();
if (res2 == GLContext.CONTEXT_CURRENT_NEW) {
lastInitAction.run();
}
}
}
}
}
| true | true | public void invokeGL(GLDrawable drawable,
GLContext context,
Runnable runnable,
Runnable initAction) {
// Support for recursive makeCurrent() calls as well as calling
// other drawables' display() methods from within another one's
GLContext lastContext = GLContext.getCurrent();
Runnable lastInitAction = (Runnable) perThreadInitAction.get();
if (lastContext != null) {
lastContext.release();
}
int res = 0;
try {
res = context.makeCurrent();
if (res != GLContext.CONTEXT_NOT_CURRENT) {
if (res == GLContext.CONTEXT_CURRENT_NEW) {
if (DEBUG) {
System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction");
}
initAction.run();
}
if (DEBUG && VERBOSE) {
System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running runnable");
}
runnable.run();
if (autoSwapBufferMode) {
if (drawable != null) {
drawable.swapBuffers();
}
}
}
} finally {
try {
if (res != GLContext.CONTEXT_NOT_CURRENT) {
context.release();
}
} catch (Exception e) {
}
if (lastContext != null) {
int res2 = lastContext.makeCurrent();
if (res2 == GLContext.CONTEXT_CURRENT_NEW) {
lastInitAction.run();
}
}
}
}
| public void invokeGL(GLDrawable drawable,
GLContext context,
Runnable runnable,
Runnable initAction) {
// Support for recursive makeCurrent() calls as well as calling
// other drawables' display() methods from within another one's
GLContext lastContext = GLContext.getCurrent();
Runnable lastInitAction = (Runnable) perThreadInitAction.get();
if (lastContext != null) {
lastContext.release();
}
int res = 0;
try {
res = context.makeCurrent();
if (res != GLContext.CONTEXT_NOT_CURRENT) {
perThreadInitAction.set(initAction);
if (res == GLContext.CONTEXT_CURRENT_NEW) {
if (DEBUG) {
System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running initAction");
}
initAction.run();
}
if (DEBUG && VERBOSE) {
System.err.println("GLDrawableHelper " + this + ".invokeGL(): Running runnable");
}
runnable.run();
if (autoSwapBufferMode) {
if (drawable != null) {
drawable.swapBuffers();
}
}
}
} finally {
try {
if (res != GLContext.CONTEXT_NOT_CURRENT) {
context.release();
}
} catch (Exception e) {
}
if (lastContext != null) {
int res2 = lastContext.makeCurrent();
if (res2 == GLContext.CONTEXT_CURRENT_NEW) {
lastInitAction.run();
}
}
}
}
|
diff --git a/bundles/binding/bluetooth/src/main/java/org/openhab/binding/bluetooth/internal/BluetoothBinding.java b/bundles/binding/bluetooth/src/main/java/org/openhab/binding/bluetooth/internal/BluetoothBinding.java
index ec0ed85b..ebfa04af 100644
--- a/bundles/binding/bluetooth/src/main/java/org/openhab/binding/bluetooth/internal/BluetoothBinding.java
+++ b/bundles/binding/bluetooth/src/main/java/org/openhab/binding/bluetooth/internal/BluetoothBinding.java
@@ -1,184 +1,185 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.binding.bluetooth.internal;
import java.util.HashMap;
import java.util.Map;
import org.openhab.binding.bluetooth.BluetoothEventHandler;
import org.openhab.core.events.EventPublisher;
import org.openhab.core.items.Item;
import org.openhab.core.library.items.NumberItem;
import org.openhab.core.library.items.StringItem;
import org.openhab.core.library.items.SwitchItem;
import org.openhab.core.library.types.DecimalType;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StringType;
import org.openhab.model.item.binding.BindingConfigParseException;
import org.openhab.model.item.binding.BindingConfigReader;
/**
* <p>This class is the default implementation to link the bluetooth discovery service
* to the openHAB event bus by parsing the binding configurations provided by the {@link GenericItemProvider}.</p>
*
* <p>The format of the binding configuration is simple and looks like this:
* <ul>
* <li>for switch items: bluetooth={<deviceAddress>} where <deviceAddress> is the technical address of the device, eg. EC935BD417C5</li>
* <li>for string items: bluetooth={*}</li>
* </p>
* <p>Switch items will receive an ON / OFF update on the bus, String items will be sent a comma separated list of all device names.
* If a friendly name cannot be resolved for a device, its address will be used instead as its name.</p>
*
* @author Kai Kreuzer
* @since 0.3.0
*
*/
public class BluetoothBinding implements BluetoothEventHandler, BindingConfigReader {
private static final String BLUETOOTH_BINDING_TYPE = "bluetooth";
/** stores information about switch items. The map has this content structure: context -> { deviceAddress, itemName } */
private Map<String, Map<String, String>> switchItems = new HashMap<String, Map<String, String>>();
/** stores information about string items. The map has this content structure: context -> itemName */
private Map<String, String> stringItems = new HashMap<String, String>();
/** stores information about measurement items. The map has this content structure: context -> itemName */
private Map<String, String> measurementItems = new HashMap<String, String>();
private EventPublisher eventPublisher;
public void setEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
public void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
@Override
public void handleDeviceInRange(BluetoothDevice device) {
if(eventPublisher!=null) {
// find the item associated to this address, if any
String itemName = null;
for(Map<String, String> map : switchItems.values()) {
itemName = map.get(device.getAddress());
if(itemName!=null) break;
}
if(itemName!=null) {
eventPublisher.postUpdate(itemName, OnOffType.ON);
}
}
}
@Override
public void handleDeviceOutOfRange(BluetoothDevice device) {
if(eventPublisher!=null) {
// find the item associated to this address, if any
String itemName = null;
for(Map<String, String> map : switchItems.values()) {
itemName = map.get(device.getAddress());
if(itemName!=null) break;
}
if(itemName!=null) {
eventPublisher.postUpdate(itemName, OnOffType.OFF);
}
}
}
@Override
public void handleAllDevicesInRange(Iterable<BluetoothDevice> devices) {
if(eventPublisher!=null) {
// build a comma separated list of all devices in range
StringBuilder sb = new StringBuilder();
int noOfDevices = 0;
for(BluetoothDevice device : devices) {
noOfDevices++;
+ handleDeviceInRange(device);
if(!device.getFriendlyName().trim().isEmpty()) {
sb.append(device.getFriendlyName());
} else {
sb.append(device.getAddress());
}
if(device.isPaired()) {
sb.append(" !");
}
sb.append(", ");
}
String deviceList = sb.length() > 0 ? sb.substring(0, sb.length()-2) : "-";
for(String itemName : stringItems.values()) {
eventPublisher.postUpdate(itemName, StringType.valueOf(deviceList));
}
for(String itemName : measurementItems.values()) {
eventPublisher.postUpdate(itemName, new DecimalType(noOfDevices));
}
}
}
@Override
public String getBindingType() {
return BLUETOOTH_BINDING_TYPE;
}
@Override
public void processBindingConfiguration(String context, Item item, String bindingConfig)
throws BindingConfigParseException {
if(item instanceof SwitchItem) {
Map<String, String> entry = switchItems.get(context);
if(entry==null) {
entry = new HashMap<String, String>();
}
entry.put(bindingConfig, item.getName());
switchItems.put(context, entry);
}
if(item instanceof StringItem && bindingConfig.equals("*")) {
stringItems.put(context, item.getName());
}
if(item instanceof NumberItem && bindingConfig.equals("*")) {
measurementItems.put(context, item.getName());
}
}
@Override
public boolean isActive() {
// only say that we are active if there are any items registered for that binding
return switchItems.size() > 0 || stringItems.size() > 0 || measurementItems.size() > 0;
}
@Override
public void removeConfigurations(String context) {
switchItems.remove(context);
stringItems.remove(context);
measurementItems.remove(context);
}
}
| true | true | public void handleAllDevicesInRange(Iterable<BluetoothDevice> devices) {
if(eventPublisher!=null) {
// build a comma separated list of all devices in range
StringBuilder sb = new StringBuilder();
int noOfDevices = 0;
for(BluetoothDevice device : devices) {
noOfDevices++;
if(!device.getFriendlyName().trim().isEmpty()) {
sb.append(device.getFriendlyName());
} else {
sb.append(device.getAddress());
}
if(device.isPaired()) {
sb.append(" !");
}
sb.append(", ");
}
String deviceList = sb.length() > 0 ? sb.substring(0, sb.length()-2) : "-";
for(String itemName : stringItems.values()) {
eventPublisher.postUpdate(itemName, StringType.valueOf(deviceList));
}
for(String itemName : measurementItems.values()) {
eventPublisher.postUpdate(itemName, new DecimalType(noOfDevices));
}
}
}
| public void handleAllDevicesInRange(Iterable<BluetoothDevice> devices) {
if(eventPublisher!=null) {
// build a comma separated list of all devices in range
StringBuilder sb = new StringBuilder();
int noOfDevices = 0;
for(BluetoothDevice device : devices) {
noOfDevices++;
handleDeviceInRange(device);
if(!device.getFriendlyName().trim().isEmpty()) {
sb.append(device.getFriendlyName());
} else {
sb.append(device.getAddress());
}
if(device.isPaired()) {
sb.append(" !");
}
sb.append(", ");
}
String deviceList = sb.length() > 0 ? sb.substring(0, sb.length()-2) : "-";
for(String itemName : stringItems.values()) {
eventPublisher.postUpdate(itemName, StringType.valueOf(deviceList));
}
for(String itemName : measurementItems.values()) {
eventPublisher.postUpdate(itemName, new DecimalType(noOfDevices));
}
}
}
|
diff --git a/src/com/github/dreamrec/Model.java b/src/com/github/dreamrec/Model.java
index 8387817..0bfcebe 100644
--- a/src/com/github/dreamrec/Model.java
+++ b/src/com/github/dreamrec/Model.java
@@ -1,136 +1,136 @@
package com.github.dreamrec;
/**
*
*/
public class Model {
private int xSize = 200; //data points per screen.
public static final int DIVIDER = 10; //frequency divider for slow graphics
private ListView<Integer> eyeDataList = new ListView<Integer>(); //list with raw incoming data of eye movements
private double frequency; //frequency Hz of the incoming data (for fast graphics)
private long startTime; //time when data recording was started
private int fastGraphIndex; //index for the first point on a screen for fast graphics
private int slowGraphIndex; //index for the first point on a screen for slow graphics
public ListView<Integer> getEyeDataList() {
return eyeDataList;
}
public void addEyeData(int data) {
eyeDataList.add(data);
}
public double getFrequency() {
return frequency;
}
public long getStartTime() {
return startTime;
}
public int getFastGraphIndex() {
return fastGraphIndex;
}
public int getSlowGraphIndex() {
return slowGraphIndex;
}
public void setFrequency(double frequency) {
this.frequency = frequency;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
public int getXSize() {
return xSize;
}
public void setXSize(int xSize) {
this.xSize = xSize;
}
public int getDataSize() {
return eyeDataList.size();
}
public void clear() {
eyeDataList.clear();
frequency = 0;
startTime = 0;
}
public int getCursorWidth() {
return xSize / DIVIDER;
}
public int getCursorPosition() {
return fastGraphIndex / DIVIDER - slowGraphIndex;
}
public void moveFastGraph(int newFastGraphIndex) {
newFastGraphIndex = checkGraphIndexBounds(newFastGraphIndex, getDataSize());
fastGraphIndex = newFastGraphIndex;
checkCursorScreenBounds();
}
public void moveSlowGraph(int newSlowGraphIndex) {
newSlowGraphIndex = checkGraphIndexBounds(newSlowGraphIndex, getDataSize() / DIVIDER);
slowGraphIndex = newSlowGraphIndex;
}
//correct graph index if it points to invalid data. Should be > 0 and < (getDataSize - xSize)
private int checkGraphIndexBounds(int newIndex, int dataSize) {
int maxValue = getIndexMax(dataSize);
newIndex = newIndex < 0 ? 0 : newIndex;
newIndex = newIndex > maxValue ? maxValue : newIndex;
return newIndex;
}
private int getIndexMax(int dataSize) {
int maxValue = dataSize - xSize - 1;
maxValue = maxValue < 0 ? 0 : maxValue;
return maxValue;
}
public boolean isFastGraphIndexMaximum() {
return fastGraphIndex == getIndexMax(getDataSize());
}
public void setFastGraphIndexMaximum() {
moveFastGraph(getIndexMax(getDataSize()));
}
public void moveCursor(int newCursorPosition) {
newCursorPosition = checkCursorIndexBounds(newCursorPosition, getDataSize() / DIVIDER);
// move cursor to new position, even if this new position is out of the screen
fastGraphIndex = (slowGraphIndex + newCursorPosition) * DIVIDER;
checkCursorScreenBounds();
}
private void checkCursorScreenBounds() {
//adjust slowGraphIndex to place cursor at the beginning of the screen
if (getCursorPosition() < 0) {
- slowGraphIndex -= getCursorPosition();
+ slowGraphIndex += getCursorPosition();
} else
//adjust slowGraphIndex to place cursor at the end of the screen
if (getCursorPosition() > xSize - getCursorWidth() - 1) {
slowGraphIndex += getCursorPosition() - xSize + getCursorWidth();
}
}
//correct cursor positions if it points to invalid data index: < 0 and > getDataSize
private int checkCursorIndexBounds(int newCursorPosition, int dataSize) {
int minValue = -slowGraphIndex;
int maxValue = dataSize - slowGraphIndex - getCursorWidth() - 1;
maxValue = maxValue < minValue ? minValue : maxValue;
newCursorPosition = newCursorPosition < minValue ? minValue : newCursorPosition;
newCursorPosition = newCursorPosition > maxValue ? maxValue : newCursorPosition;
return newCursorPosition;
}
}
| true | true | private void checkCursorScreenBounds() {
//adjust slowGraphIndex to place cursor at the beginning of the screen
if (getCursorPosition() < 0) {
slowGraphIndex -= getCursorPosition();
} else
//adjust slowGraphIndex to place cursor at the end of the screen
if (getCursorPosition() > xSize - getCursorWidth() - 1) {
slowGraphIndex += getCursorPosition() - xSize + getCursorWidth();
}
}
| private void checkCursorScreenBounds() {
//adjust slowGraphIndex to place cursor at the beginning of the screen
if (getCursorPosition() < 0) {
slowGraphIndex += getCursorPosition();
} else
//adjust slowGraphIndex to place cursor at the end of the screen
if (getCursorPosition() > xSize - getCursorWidth() - 1) {
slowGraphIndex += getCursorPosition() - xSize + getCursorWidth();
}
}
|
diff --git a/src/events/TransportUpdateEvent.java b/src/events/TransportUpdateEvent.java
index 4af24b1..4afbbf9 100644
--- a/src/events/TransportUpdateEvent.java
+++ b/src/events/TransportUpdateEvent.java
@@ -1,107 +1,107 @@
package events;
import java.util.Date;
import routes.DistributionCentre;
import routes.Vehicle;
import backend.Day;
public class TransportUpdateEvent extends Event {
private double costPerCC;
private double costPerG;
private int frequency;
private int durationInMinutes;
private Day day;
private DistributionCentre origin;
private DistributionCentre destination;
/**
* Creates a Transport Update Event, used to record a
* change in some Transport's variables
*
* @param costPerCC - Cost per cubic centimetre
* @param costPerG - Cost per gram
* @param frequency - how many times per day the transport runs
* @param durationInMinutes - duration of a transport event
* @param day - the day on which the transport departs
* @param origin - the DistributionCentre from which the transport departs
* @param destination - the DistributionCentre at which the transport arrives
*/
public TransportUpdateEvent(Vehicle vehicle, double costPerCC, double costPerG,
int frequency, int durationInMinutes, Date timestamp,
DistributionCentre origin, DistributionCentre destination) {
super(vehicle, timestamp);
this.costPerCC = costPerCC;
this.costPerG = costPerG;
this.frequency = frequency;
this.durationInMinutes = durationInMinutes;
this.origin = origin;
this.destination = destination;
}
public double getCostPerCC() {
return costPerCC;
}
public double getCostPerG() {
return costPerG;
}
public int getFrequency() {
return frequency;
}
public int getDurationInMinutes() {
return durationInMinutes;
}
public Day getDay() {
return day;
}
public void setDurationInMinutes(int durationInMinutes) {
this.durationInMinutes = durationInMinutes;
}
public void setDay(Day day) {
this.day = day;
}
public DistributionCentre getOrigin() {
return origin;
}
public DistributionCentre getDestination() {
return destination;
}
public Date getDate() {
// TODO Auto-generated method stub
return null;
}
public String displayString() {
- String str = "Discontinue Transport Event: \n" +
+ String str = "Update Transport Event: \n" +
"\tVehicle: "+super.getVehicle()+"\n"+
"\tCost per CC: "+costPerCC+"\n"+
"\tCost per g: "+costPerG+"\n"+
"\tFrequency: "+frequency+"\n"+
"\tDuration: "+durationInMinutes+"min \n"+
"\tOrigin: "+origin.displayString()+"\n"+
"\tDestination: "+destination.displayString()+"\n"
;
return str;
}
}
| true | true | public String displayString() {
String str = "Discontinue Transport Event: \n" +
"\tVehicle: "+super.getVehicle()+"\n"+
"\tCost per CC: "+costPerCC+"\n"+
"\tCost per g: "+costPerG+"\n"+
"\tFrequency: "+frequency+"\n"+
"\tDuration: "+durationInMinutes+"min \n"+
"\tOrigin: "+origin.displayString()+"\n"+
"\tDestination: "+destination.displayString()+"\n"
;
return str;
}
| public String displayString() {
String str = "Update Transport Event: \n" +
"\tVehicle: "+super.getVehicle()+"\n"+
"\tCost per CC: "+costPerCC+"\n"+
"\tCost per g: "+costPerG+"\n"+
"\tFrequency: "+frequency+"\n"+
"\tDuration: "+durationInMinutes+"min \n"+
"\tOrigin: "+origin.displayString()+"\n"+
"\tDestination: "+destination.displayString()+"\n"
;
return str;
}
|
diff --git a/core/src/main/java/brooklyn/location/basic/jclouds/JcloudsLocation.java b/core/src/main/java/brooklyn/location/basic/jclouds/JcloudsLocation.java
index c7b97fea2..42c0a4fb4 100644
--- a/core/src/main/java/brooklyn/location/basic/jclouds/JcloudsLocation.java
+++ b/core/src/main/java/brooklyn/location/basic/jclouds/JcloudsLocation.java
@@ -1,1384 +1,1384 @@
package brooklyn.location.basic.jclouds;
import static brooklyn.util.GroovyJavaMethods.elvis;
import static brooklyn.util.GroovyJavaMethods.truth;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.jclouds.compute.options.RunScriptOptions.Builder.overrideLoginCredentials;
import static org.jclouds.scriptbuilder.domain.Statements.exec;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.annotation.Nullable;
import org.jclouds.Constants;
import org.jclouds.compute.ComputeService;
import org.jclouds.compute.ComputeServiceContext;
import org.jclouds.compute.RunNodesException;
import org.jclouds.compute.callables.RunScriptOnNode;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.ExecResponse;
import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.NodeMetadataBuilder;
import org.jclouds.compute.domain.OperatingSystem;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.compute.domain.TemplateBuilder;
import org.jclouds.compute.domain.TemplateBuilderSpec;
import org.jclouds.compute.options.RunScriptOptions;
import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Credentials;
import org.jclouds.domain.LoginCredentials;
import org.jclouds.ec2.compute.options.EC2TemplateOptions;
import org.jclouds.openstack.nova.v2_0.compute.options.NovaTemplateOptions;
import org.jclouds.rest.AuthorizationException;
import org.jclouds.scriptbuilder.domain.InterpretableStatement;
import org.jclouds.scriptbuilder.domain.Statement;
import org.jclouds.scriptbuilder.domain.Statements;
import org.jclouds.scriptbuilder.statements.login.AdminAccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import brooklyn.entity.basic.Entities;
import brooklyn.location.MachineProvisioningLocation;
import brooklyn.location.NoMachinesAvailableException;
import brooklyn.location.OsDetails;
import brooklyn.location.basic.AbstractLocation;
import brooklyn.location.basic.BasicOsDetails;
import brooklyn.location.basic.SshMachineLocation;
import brooklyn.location.basic.jclouds.templates.PortableTemplateBuilder;
import brooklyn.util.KeyValueParser;
import brooklyn.util.MutableMap;
import brooklyn.util.Time;
import brooklyn.util.flags.SetFromFlag;
import brooklyn.util.flags.TypeCoercions;
import brooklyn.util.internal.Repeater;
import brooklyn.util.text.Identifiers;
import brooklyn.util.text.Strings;
import com.google.common.base.Charsets;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
import com.google.common.io.Files;
import com.google.common.util.concurrent.ListenableFuture;
/**
* For provisioning and managing VMs in a particular provider/region, using jclouds.
*
* Configuration flags include the following:
* - provider (e.g. "aws-ec2")
* - providerLocationId (e.g. "eu-west-1")
* - defaultImageId
*
* - user (defaults to "root" or other known superuser)
* - publicKeyFile
* - privateKeyFile
* - privateKeyPasspharse
*
* - loginUser (if should initially login as someone other that root / default VM superuser)
* - loginUser.privateKeyFile
* - loginUser.privateKeyPasspharse
*
* - customizer (implementation of {@link JcloudsLocationCustomizer})
* - customizers (collection of {@link JcloudsLocationCustomizer} instances)
*
* // deprecated
* - sshPublicKey
* - sshPrivateKey
* - rootSshPrivateKey (@Beta)
* - rootSshPublicKey (@Beta)
* - rootSshPublicKeyData (@Beta; calls templateOptions.authorizePublicKey())
* - dontCreateUser (otherwise if user != root, then creates this user)
*
* The flags can also includes values passed straight through to jclouds; to the TemplateBuilder:
* - minRam
* - hardwareId
* - imageSize
* - imageId
* - imageDescriptionRegex
* - imageNameRegex
* - imageDescriptionPattern (deprecated: use imageDescriptionRegex)
* - imageNamePattern (deprecated: use imageNameRegex)
*
* And flag values passed to TemplateOptions:
* - securityGroups (for ec2)
* - inboundPorts
* - userMetadata
* - runAsRoot
* - overrideLoginUser
*/
public class JcloudsLocation extends AbstractLocation implements MachineProvisioningLocation<SshMachineLocation> {
// TODO Needs a big overhaul of how config is being managed, and what the property names are (particularly for private-keys)
// TODO After converting from Groovy to Java, this is now very bad code! It relies entirely on putting
// things into and taking them out of maps; it's not type-safe, and it's thus very error-prone.
// In Groovy, that's considered ok but not in Java.
public static final Logger LOG = LoggerFactory.getLogger(JcloudsLocation.class);
public static final String ROOT_USERNAME = "root";
/** these userNames are known to be the preferred/required logins in some common/default images
* where root@ is not allowed to log in */
public static final List<String> ROOT_ALIASES = ImmutableList.of("ubuntu", "ec2-user");
public static final List<String> NON_ADDABLE_USERS = ImmutableList.<String>builder().add(ROOT_USERNAME).addAll(ROOT_ALIASES).build();
public static final int START_SSHABLE_TIMEOUT = 5*60*1000;
private final Map<String,Map<String, ? extends Object>> tagMapping = Maps.newLinkedHashMap();
private final Map<JcloudsSshMachineLocation,String> vmInstanceIds = Maps.newLinkedHashMap();
@SetFromFlag
private File localTempDir;
public JcloudsLocation(Map conf) {
super(conf);
}
public JcloudsLocation(String identity, String credential, String providerLocationId) {
this(MutableMap.of("identity", identity, "credential", credential, "providerLocationId", providerLocationId));
}
protected void configure(Map properties) {
super.configure(properties);
if (!truth(name)) {
name = (String) elvis(getConf().get("providerLocationId"),
truth(getConf().get(Constants.PROPERTY_ENDPOINT)) ?
getConf().get("provider")+":"+getConf().get(Constants.PROPERTY_ENDPOINT) :
elvis(getConf().get("provider"), "default"));
}
}
@Override
public String toString() {
Object identity = getConf().get("identity");
return getClass().getSimpleName()+"["+name+":"+(identity != null ? identity : null)+"]";
}
public String getProvider() {
return (String) getConf().get("provider");
}
public String getIdentity() {
return (String) getConf().get("identity");
}
public String getCredential() {
return (String) getConf().get("credential");
}
public String getEndpoint() {
return (String) getConf().get(Constants.PROPERTY_ENDPOINT);
}
public Map getConf() { return leftoverProperties; }
public void setTagMapping(Map<String,Map<String, ? extends Object>> val) {
tagMapping.clear();
tagMapping.putAll(val);
}
// TODO Delete this? In groovy it was wrong so presumably never called?!
public void setDefaultImageId(String val) {
getConf().put("defaultImageId", val);
}
// TODO Decide on semantics. If I give "TomcatServer" and "Ubuntu", then must I get back an image that matches both?
// Currently, just takes first match that it finds...
public Map<String,Object> getProvisioningFlags(Collection<String> tags) {
Map<String,Object> result = Maps.newLinkedHashMap();
Collection<String> unmatchedTags = Lists.newArrayList();
for (String it : tags) {
if (truth(tagMapping.get(it)) && !truth(result)) {
result.putAll(tagMapping.get(it));
} else {
unmatchedTags.add(it);
}
}
if (unmatchedTags.size() > 0) {
LOG.debug("Location {}, failed to match provisioning tags {}", this, unmatchedTags);
}
return result;
}
public static class BrooklynJcloudsSetupHolder {
// TODO this could use an external immutable pattern (unused kept internal, used for logging)
final JcloudsLocation instance;
public final Map allconf = Maps.newLinkedHashMap();
public final Map unusedConf = Maps.newLinkedHashMap();
Object _callerContext = null;
LoginCredentials customCredentials;
public BrooklynJcloudsSetupHolder(JcloudsLocation instance) {
this.instance = instance;
useConfig(instance.getConf());
}
@SuppressWarnings({ "unchecked", "rawtypes" })
BrooklynJcloudsSetupHolder useConfig(Map flags) {
allconf.putAll(flags);
unusedConf.putAll(flags);
return this;
}
private Object get(String key) {
unusedConf.remove(key);
return allconf.get(key);
}
private boolean use(String key) {
unusedConf.remove(key);
return truth(allconf.get(key));
}
@SuppressWarnings("unchecked")
private boolean setKeyFromKey(String targetKey, String key) {
if (!use(key)) return false;
Object value = get(key);
allconf.put(targetKey, value);
return true;
}
@SuppressWarnings("unchecked")
private <T> T setKeyToValue(String key, T value) {
allconf.put(key, value);
return value;
}
String provider;
String providerLocationId;
String user;
String privateKeyData, privateKeyPassphrase, publicKeyData, password;
/** @deprecated */
String sshPublicKeyData, sshPrivateKeyData;
List<JcloudsLocationCustomizer> customizers = new LinkedList<JcloudsLocationCustomizer>();
String loginUser;
String loginUser_privateKeyData, loginUser_privateKeyPassphrase, loginUser_password;
@SuppressWarnings("unchecked")
BrooklynJcloudsSetupHolder apply() {
try {
if (use("provider"))
provider = ""+get("provider");
if (use("providerLocationId"))
providerLocationId = ""+get("providerLocationId");
if (use("callerContext"))
_callerContext = get("callerContext");
// align user (brooklyn standard) and userName (jclouds standard) fields
// TODO don't default to root --> default later to what jclouds says
if (!use("user") && use("userName"))
setKeyFromKey("user", "userName");
if (use("user"))
user = (String) get("user");
// perhaps deprecate supply of data (and of different root key?) to keep it simpler?
if (truth(unusedConf.remove("publicKeyData")))
publicKeyData = sshPublicKeyData = ""+get("publicKeyData");
if (truth(unusedConf.remove("privateKeyData")))
privateKeyData = sshPrivateKeyData = ""+get("privateKeyData");
if (use("privateKeyFile")) {
if (truth(privateKeyData)) LOG.warn("privateKeyData and privateKeyFile both specified; preferring the former");
else
privateKeyData = sshPublicKeyData = setKeyToValue("sshPrivateKeyData", Files.toString(instance.getPrivateKeyFile(allconf), Charsets.UTF_8));
}
if (truth(unusedConf.remove("publicKeyFile"))) {
if (truth(publicKeyData)) LOG.warn("publicKeyData and publicKeyFile both specified; preferring the former");
else
publicKeyData = sshPublicKeyData = setKeyToValue("sshPublicKeyData", Files.toString(instance.getPublicKeyFile(allconf), Charsets.UTF_8));
} else if (!truth(publicKeyData) && truth(get("privateKeyFile"))) {
File f = new File(""+get("privateKeyFile")+".pub");
if (f.exists()) {
LOG.debug("Loading publicKeyData from privateKeyFile + .pub");
publicKeyData = sshPublicKeyData = setKeyToValue("sshPublicKeyData", Files.toString(f, Charsets.UTF_8));
}
}
// deprecated:
if (use("sshPublicKey"))
publicKeyData = sshPublicKeyData = setKeyToValue("sshPublicKeyData", Files.toString(asFile(allconf.get("sshPublicKey")), Charsets.UTF_8));
if (use("sshPrivateKey"))
privateKeyData = sshPrivateKeyData = setKeyToValue("sshPrivateKeyData", Files.toString(asFile(allconf.get("sshPrivateKey")), Charsets.UTF_8));
// are these two ever used:
if (use("rootSshPrivateKey")) {
LOG.warn("Using deprecated property rootSshPrivateKey; use loginUser{,.privateKeyFile,...} instead");
setKeyToValue("rootSshPrivateKeyData", Files.toString(asFile(allconf.get("rootSshPrivateKey")), Charsets.UTF_8));
}
if (use("rootSshPublicKey")) {
LOG.warn("Using deprecated property rootSshPublicKey; use loginUser{,.publicKeyFile} instead (though public key often not needed)");
setKeyToValue("rootSshPublicKeyData", Files.toString(asFile(allconf.get("rootSshPublicKey")), Charsets.UTF_8));
}
// above replaced with below
if (use("loginUser")) {
loginUser = ""+get("loginUser");
if (use("loginUser.privateKeyData")) {
loginUser_privateKeyData = ""+get("loginUser.privateKeyData");
}
if (use("loginUser.privateKeyFile")) {
if (loginUser_privateKeyData!=null)
LOG.warn("loginUser private key data and private key file specified; preferring from file");
loginUser_privateKeyData = setKeyToValue("loginUser.privateKeyData", Files.toString(asFile(allconf.get("loginUser.privateKeyFile")), Charsets.UTF_8));
}
if (use("loginUser.privateKeyPassphrase")) {
LOG.warn("loginUser.privateKeyPassphrase not supported by jclouds; use a key which does not have a passphrase for the loginUser");
loginUser_privateKeyPassphrase = ""+get("loginUser.privateKeyPassphrase");
}
if (use("loginUser.password")) {
loginUser_password = ""+get("loginUser.password");
}
// these we ignore
use("loginUser.publicKeyData");
use("loginUser.publicKeyFile");
if (loginUser.equals(user)) {
LOG.debug("Detected that jclouds loginUser is the same as regular user; we don't create this user");
}
}
if (use("dontCreateUser")) {
LOG.warn("Using deprecated property dontCreateUser; use login.user instead, set equal to the user to run as");
setKeyToValue("dontCreateUser", true);
}
// allows specifying a LoginCredentials object, for use by jclouds, if known for the VM (ie it is non-standard);
if (use("customCredentials"))
customCredentials = (LoginCredentials) get("customCredentials");
// following values are copies pass-through, no change
use("privateKeyPassphrase");
use("password");
use("noDefaultSshKeys");
if (use("customizer"))
customizers.add((JcloudsLocationCustomizer) get("customizer"));
if (use("customizers")) {
customizers.addAll((Collection<JcloudsLocationCustomizer>) get("customizers"));
}
return this;
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
String remove(String key) {
return (String) unusedConf.remove(key);
}
void warnIfUnused(String context) {
if (!unusedConf.isEmpty())
LOG.debug("NOTE: unused flags passed to "+context+" in "+
elvis(allconf.get("providerLocationId"), allconf.get("provider"))+": "+unusedConf);
}
public String getCallerContext() {
if (truth(_callerContext)) return _callerContext.toString();
return "thread "+Thread.currentThread().getId();
}
public String setUser(String u) {
String oldUser = user;
user = u;
allconf.put("user", u);
allconf.put("userName", u);
return oldUser;
}
public String setPassword(String password) {
String oldPassword = this.password;
this.password = password;
allconf.put("password", password);
return oldPassword;
}
public String setPrivateKeyData(String privateKeyData) {
String oldPrivateKeyData = this.privateKeyData;
this.privateKeyData = privateKeyData;
allconf.put("privateKeyData", privateKeyData);
allconf.put("sshPrivateKeyData", privateKeyData);
return oldPrivateKeyData;
}
public void set(String key, String value) {
allconf.put(key, value);
}
public boolean isDontCreateUser() {
if (!use("dontCreateUser")) return false;
Object v = get("dontCreateUser");
if (v==null) return false;
if (v instanceof Boolean) return ((Boolean)v).booleanValue();
if (v instanceof CharSequence) return Boolean.parseBoolean(((CharSequence)v).toString());
throw new IllegalArgumentException("dontCreateUser does not accept value '"+v+"' of type "+v.getClass());
}
public String getUser() {
return user;
}
}
public static final Set<String> getAllSupportedProperties() {
return ImmutableSet.<String>builder()
.addAll(SUPPORTED_BASIC_PROPERTIES)
.addAll(SUPPORTED_TEMPLATE_BUILDER_PROPERTIES.keySet())
.addAll(SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.keySet())
.build();
}
//FIXME use of this map and the unusedConf list, with the CredentialsFromEnv and JCloudsLocationFactory, seems overly complicated!
//also, we need a way to define imageId (and others?) with a specific location
public static final Collection<String> SUPPORTED_BASIC_PROPERTIES = ImmutableSet.of(
"provider", "identity", "credential", "groupId", "providerLocationId",
"userName", "user",
"publicKeyFile", "privateKeyFile", "publicKeyData", "privateKeyData", "privateKeyPassphrase",
"loginUser", "loginUser.password", "loginUser.publicKeyFile", "loginUser.privateKeyFile", "loginUser.publicKeyData", "loginUser.privateKeyData", "loginUser.privateKeyPassphrase",
// deprecated:
"sshPublicKey", "sshPrivateKey",
"rootSshPrivateKey", "rootSshPublicKey"
);
/** returns public key file, if one has been configured */
public File getPublicKeyFile() { return getPublicKeyFile(getConf()); }
public File getPublicKeyFile(Map allconf) { return elvis(asFile(allconf.get("publicKeyFile")), asFile(allconf.get("sshPublicKey"))); }
/** returns private key file, if one has been configured */
public File getPrivateKeyFile() { return getPrivateKeyFile(getConf()); }
public File getPrivateKeyFile(Map allconf) { return elvis(asFile(allconf.get("privateKeyFile")), asFile(allconf.get("sshPrivateKey"))); }
public ComputeService getComputeService() {
return getComputeService(MutableMap.of());
}
public ComputeService getComputeService(Map flags) {
BrooklynJcloudsSetupHolder setup = new BrooklynJcloudsSetupHolder(this).useConfig(flags).apply();
return JcloudsUtil.buildOrFindComputeService(setup.allconf, setup.unusedConf);
}
/** returns the location ID used by the provider, if set, e.g. us-west-1 */
public String getJcloudsProviderLocationId() {
return (String) getConf().get("providerLocationId");
}
public Set<? extends ComputeMetadata> listNodes() {
return listNodes(MutableMap.of());
}
public Set<? extends ComputeMetadata> listNodes(Map flags) {
return getComputeService(flags).listNodes();
}
public JcloudsSshMachineLocation obtain(TemplateBuilder tb) throws NoMachinesAvailableException {
return obtain(MutableMap.of(), tb);
}
public JcloudsSshMachineLocation obtain(Map flags, TemplateBuilder tb) throws NoMachinesAvailableException {
Map flags2 = MutableMap.builder().putAll(flags).put("templateBuilder", tb).build();
return obtain(flags2);
}
public JcloudsSshMachineLocation obtain() throws NoMachinesAvailableException {
return obtain(MutableMap.of());
}
public JcloudsSshMachineLocation obtain(Map flags) throws NoMachinesAvailableException {
BrooklynJcloudsSetupHolder setup = new BrooklynJcloudsSetupHolder(this).useConfig(flags).apply();
String groupId = elvis(setup.remove("groupId"), generateGroupId(setup.provider));
final ComputeService computeService = JcloudsUtil.buildOrFindComputeService(setup.allconf, setup.unusedConf);
NodeMetadata node = null;
try {
LOG.info("Creating VM in "+
elvis(setup.providerLocationId, setup.provider)+" for "+setup.getCallerContext());
Template template = buildTemplate(computeService, setup);
setup.warnIfUnused("JcloudsLocation.obtain");
Set<? extends NodeMetadata> nodes = computeService.createNodesInGroup(groupId, 1, template);
node = Iterables.getOnlyElement(nodes, null);
LOG.debug("jclouds created {} for {}", node, setup.getCallerContext());
if (node == null) {
throw new IllegalStateException("No nodes returned by jclouds create-nodes in "
+setup.provider+"/"+setup.providerLocationId+" for "+setup.getCallerContext());
}
LoginCredentials expectedCredentials = setup.customCredentials;
if (expectedCredentials!=null) {
//set userName and other data, from these credentials
Object oldUsername = setup.setUser(expectedCredentials.getUser());
LOG.debug("node {} username {} / {} (customCredentials)", new Object[] { node, expectedCredentials.getUser(), oldUsername });
if (truth(expectedCredentials.getPassword())) setup.setPassword(expectedCredentials.getPassword());
if (truth(expectedCredentials.getPrivateKey())) setup.setPrivateKeyData(expectedCredentials.getPrivateKey());
}
if (expectedCredentials==null) {
expectedCredentials = LoginCredentials.fromCredentials(node.getCredentials());
String user = setup.user;
LOG.debug("node {} username {} / {} (jclouds)", new Object[] { node, user, expectedCredentials.getUser() });
if (truth(expectedCredentials.getUser())) {
if (user==null) {
setup.setUser(user = expectedCredentials.getUser());
} else if ("root".equals(user) && ROOT_ALIASES.contains(expectedCredentials.getUser())) {
// deprecated, we used to default username to 'root'; now we leave null, then use autodetected credentials if no user specified
//
LOG.warn("overriding username 'root' in favour of '"+expectedCredentials.getUser()+"' at {}; this behaviour may be removed in future", node);
setup.setUser(user = expectedCredentials.getUser());
}
}
//override credentials
String pkd = elvis(setup.privateKeyData, expectedCredentials.getPrivateKey());
String pwd = elvis(setup.password, expectedCredentials.getPassword());
if (user==null || (pkd==null && pwd==null)) {
String missing = (user==null ? "user" : "credential");
LOG.warn("Not able to determine "+missing+" for "+this+" at "+node+"; will likely fail subsequently");
expectedCredentials = null;
} else {
LoginCredentials.Builder expectedCredentialsBuilder = LoginCredentials.builder().
user(user);
if (pkd!=null) expectedCredentialsBuilder.privateKey(pkd);
if (pwd!=null) expectedCredentialsBuilder.password(pwd);
expectedCredentials = expectedCredentialsBuilder.build();
}
}
if (expectedCredentials != null)
node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(expectedCredentials).build();
else
// only happens if something broke above...
expectedCredentials = LoginCredentials.fromCredentials(node.getCredentials());
// Wait for the VM to be reachable over SSH
if (setup.get("waitForSshable") != null ? truth(setup.get("waitForSshable")) : true) {
waitForReachable(computeService, node, expectedCredentials, setup);
}
JcloudsSshMachineLocation sshLocByHostname = createJcloudsSshMachineLocation(node, setup);
sshLocByHostname.setParentLocation(this);
vmInstanceIds.put(sshLocByHostname, node.getId());
// Apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, sshLocByHostname);
}
return sshLocByHostname;
} catch (RunNodesException e) {
if (e.getNodeErrors().size() > 0) {
node = Iterables.get(e.getNodeErrors().keySet(), 0);
}
LOG.error("Failed to start VM: {}", e.getMessage());
throw Throwables.propagate(e);
} catch (Exception e) {
LOG.error("Failed to start VM: {}", e.getMessage());
LOG.info(Throwables.getStackTraceAsString(e));
throw Throwables.propagate(e);
} finally {
//leave it open for reuse
// computeService.getContext().close();
}
}
protected void waitForReachable(final ComputeService computeService, NodeMetadata node, LoginCredentials expectedCredentials,
BrooklynJcloudsSetupHolder setup) {
String vmIp = JcloudsUtil.getFirstReachableAddress(this.getComputeService().getContext(), node);
final NodeMetadata nodeRef = node;
final LoginCredentials expectedCredentialsRef = expectedCredentials;
long delayMs = -1;
try {
delayMs = Time.parseTimeString(""+setup.get("waitForSshable"));
} catch (Exception e) {}
if (delayMs<=0) delayMs = START_SSHABLE_TIMEOUT;
LOG.info("Started VM in {} for {}; waiting for it to be sshable on {}@{}",
new Object[] {
elvis(setup.get("providerLocationId"), setup.get("provider")),
setup.getCallerContext(),
setup.user,
vmIp
});
boolean reachable = new Repeater()
.repeat()
.every(1,SECONDS)
.until(new Callable<Boolean>() {
public Boolean call() {
Statement statement = Statements.newStatementList(exec("hostname"));
// NB this assumes passwordless sudo !
ExecResponse response = computeService.runScriptOnNode(nodeRef.getId(), statement,
overrideLoginCredentials(expectedCredentialsRef));
return response.getExitStatus() == 0;
}})
.limitTimeTo(delayMs, MILLISECONDS)
.run();
if (!reachable) {
throw new IllegalStateException("SSH failed for "+
setup.user+"@"+vmIp+" (for "+setup.getCallerContext()+") after waiting "+
Time.makeTimeString(delayMs));
}
}
protected JcloudsSshMachineLocation createJcloudsSshMachineLocation(NodeMetadata node, BrooklynJcloudsSetupHolder setup) throws IOException {
String vmHostname = getPublicHostname(node, setup);
Map sshConfig = generateSshConfig(setup, node);
if (LOG.isDebugEnabled())
LOG.debug("creating JcloudsSshMachineLocation for {}@{} for {} with {}",
new Object[] {
setup.user,
vmHostname,
setup.getCallerContext(),
Entities.sanitize(sshConfig)
});
return new JcloudsSshMachineLocation(
MutableMap.builder()
.put("address", vmHostname)
.put("displayName", vmHostname)
.put("user", setup.user)
.put("config", sshConfig)
.put("localTempDir", localTempDir)
.build(),
this,
node);
}
public JcloudsSshMachineLocation rebindMachine(NodeMetadata metadata) throws NoMachinesAvailableException {
return rebindMachine(MutableMap.of(), metadata);
}
public JcloudsSshMachineLocation rebindMachine(Map flags, NodeMetadata metadata) throws NoMachinesAvailableException {
BrooklynJcloudsSetupHolder setup = new BrooklynJcloudsSetupHolder(this).useConfig(flags).apply();
if (!setup.use("id")) setup.set("id", metadata.getId());
setHostnameUpdatingCredentials(setup, metadata);
return rebindMachine(setup.allconf);
}
protected void setHostnameUpdatingCredentials(BrooklynJcloudsSetupHolder setup, NodeMetadata metadata) {
List<String> usersTried = new ArrayList<String>();
if (truth(setup.user)) {
if (setHostname(setup, metadata, false)) return;
usersTried.add(setup.user);
}
LoginCredentials credentials = metadata.getCredentials();
if (truth(credentials)) {
if (truth(credentials.getUser())) setup.setUser(credentials.getUser());
if (truth(credentials.getPrivateKey())) setup.setPrivateKeyData(credentials.getPrivateKey());
if (setHostname(setup, metadata, false)) return;
usersTried.add(setup.user);
}
for (String u: NON_ADDABLE_USERS) {
setup.setUser(u);
if (setHostname(setup, metadata, false)) {
LOG.warn("Auto-detected user at "+metadata+" as "+setup.user+" (other attempted users "+usersTried+" cannot access it)");
return;
}
usersTried.add(setup.user);
}
// just repeat, so we throw exception
LOG.warn("Failed to log in to "+metadata+", tried as users "+usersTried+" (throwing original exception)");
setHostname(setup, metadata, true);
}
protected boolean setHostname(BrooklynJcloudsSetupHolder setup, NodeMetadata metadata, boolean rethrow) {
try {
setup.set("hostname", getPublicHostname(metadata, setup));
return true;
} catch (Exception e) {
if (rethrow) {
LOG.warn("couldn't connect to "+metadata+" when trying to discover hostname (rethrowing): "+e);
throw Throwables.propagate(e);
}
return false;
}
}
/**
* Brings an existing machine with the given details under management.
* <p>
* Required fields are:
* <ul>
* <li>id: the jclouds VM id, e.g. "eu-west-1/i-5504f21d" (NB this is @see JcloudsSshMachineLocation#getJcloudsId() not #getId())
* <li>hostname: the public hostname or IP of the machine, e.g. "ec2-176-34-93-58.eu-west-1.compute.amazonaws.com"
* <li>userName: the username for ssh'ing into the machine
* <ul>
*/
public JcloudsSshMachineLocation rebindMachine(Map flags) throws NoMachinesAvailableException {
try {
BrooklynJcloudsSetupHolder setup = new BrooklynJcloudsSetupHolder(this).useConfig(flags).apply();
String id = (String) checkNotNull(setup.get("id"), "id");
String hostname = (String) checkNotNull(setup.get("hostname"), "hostname");
String user = (String) checkNotNull(setup.user, "user");
LOG.info("Rebinding to VM {} ({}@{}), in jclouds location for provider {}",
new Object[] {id, user, hostname, getProvider()});
ComputeService computeService = JcloudsUtil.buildComputeService(setup.allconf, setup.unusedConf);
NodeMetadata node = computeService.getNodeMetadata(id);
if (node == null) {
throw new IllegalArgumentException("Node not found with id "+id);
}
if (truth(setup.privateKeyData)) {
LoginCredentials expectedCredentials = LoginCredentials.fromCredentials(new Credentials(setup.user, setup.privateKeyData));
//override credentials
node = NodeMetadataBuilder.fromNodeMetadata(node).credentials(expectedCredentials).build();
}
// TODO confirm we can SSH ?
Map sshConfig = generateSshConfig(setup, node);
JcloudsSshMachineLocation sshLocByHostname = new JcloudsSshMachineLocation(
MutableMap.builder()
.put("address", hostname)
.put("displayName", hostname)
.put("user", user)
.put("config", sshConfig)
.build(),
this,
node);
sshLocByHostname.setParentLocation(this);
vmInstanceIds.put(sshLocByHostname, node.getId());
return sshLocByHostname;
} catch (IOException e) {
throw Throwables.propagate(e);
}
}
protected Map generateSshConfig(BrooklynJcloudsSetupHolder setup, NodeMetadata node) throws IOException {
Map sshConfig = Maps.newLinkedHashMap();
if (setup.password != null) {
sshConfig.put("password", setup.password);
} else if (node!=null && node.getCredentials().getPassword() != null) {
sshConfig.put("password", node.getCredentials().getPassword());
}
if (truth(setup.privateKeyData)) {
sshConfig.put("privateKeyData", setup.privateKeyData);
} else if (truth(setup.allconf.get("sshPrivateKeyData"))) {
LOG.warn("Using legacy sshPrivateKeyData but not privateKeyData");
Object d = setup.allconf.get("sshPrivateKeyData");
sshConfig.put("privateKeyData", d);
sshConfig.put("privateKey", d);
sshConfig.put("sshPrivateKeyData", d);
} else if (truth(getPrivateKeyFile())) {
LOG.warn("Using legacy keyFiles but not privateKeyData");
sshConfig.put("keyFiles", ImmutableList.of(getPrivateKeyFile().getCanonicalPath()));
}
if (truth(setup.allconf.get("privateKeyPassphrase"))) {
// NB: not supported in jclouds
sshConfig.put("privateKeyPassphrase", setup.privateKeyPassphrase);
}
return sshConfig;
}
public static String generateGroupId(String provider) {
// In jclouds 1.5, there are strict rules for group id: it must be DNS compliant, and no more than 15 characters
// TODO surely this can be overridden! it's so silly being so short in common places ... or at least set better metadata?
String user = System.getProperty("user.name");
String rand = Identifiers.makeRandomId(6);
String result = "brooklyn-" + user + "-" + rand;
if ("vcloud".equals(provider)) {
rand = Identifiers.makeRandomId(2);
result = "br-" + Strings.maxlen(user, 4) + "-" + rand;
}
return result.toLowerCase();
}
public static File asFile(Object o) {
if (o instanceof File) return (File)o;
if (o == null) return null;
return new File(o.toString());
}
public static String fileAsString(Object o) {
if (o instanceof String) return (String)o;
if (o instanceof File) return ((File)o).getAbsolutePath();
if (o==null) return null;
return o.toString();
}
public void release(SshMachineLocation machine) {
String instanceId = vmInstanceIds.remove(machine);
if (!truth(instanceId)) {
throw new IllegalArgumentException("Unknown machine "+machine);
}
LOG.info("Releasing machine {} in {}, instance id {}", new Object[] {machine, this, instanceId});
removeChildLocation(machine);
ComputeService computeService = null;
try {
computeService = JcloudsUtil.buildOrFindComputeService(getConf());
computeService.destroyNode(instanceId);
} catch (Exception e) {
LOG.error("Problem releasing machine "+machine+" in "+this+", instance id "+instanceId+
"; discarding instance and continuing...", e);
Throwables.propagate(e);
} finally {
/*
//don't close
if (computeService != null) {
try {
computeService.getContext().close();
} catch (Exception e) {
LOG.error "Problem closing compute-service's context; continuing...", e
}
}
*/
}
}
private static interface CustomizeTemplateBuilder {
void apply(TemplateBuilder tb, Map props, Object v);
}
private static interface CustomizeTemplateOptions {
void apply(TemplateOptions tb, Map props, Object v);
}
/** note, it is important these be written in correct camel case, so the routines
* which convert it to "min-ram" syntax and MIN_RAM syntax are correct */
public static final Map<String,CustomizeTemplateBuilder> SUPPORTED_TEMPLATE_BUILDER_PROPERTIES = ImmutableMap.<String,CustomizeTemplateBuilder>builder()
.put("minRam", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.minRam(TypeCoercions.coerce(v, Integer.class));
}})
.put("minCores", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.minCores(TypeCoercions.coerce(v, Double.class));
}})
.put("hardwareId", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.hardwareId(((CharSequence)v).toString());
}})
.put("imageId", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.imageId(((CharSequence)v).toString());
}})
.put("imageDescriptionRegex", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.imageDescriptionMatches(((CharSequence)v).toString());
}})
.put("imageNameRegex", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.imageNameMatches(((CharSequence)v).toString());
}})
.put("templateSpec", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.from(TemplateBuilderSpec.parse(((CharSequence)v).toString()));
}})
.put("defaultImageId", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
/* deferred */
}})
.put("templateBuilder", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
/* deferred */
}})
// following are deprecated in 0.4.0, kept for backwards compatibility:
.put("imageDescriptionPattern", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.imageDescriptionMatches(((CharSequence)v).toString());
}})
.put("imageNamePattern", new CustomizeTemplateBuilder() {
public void apply(TemplateBuilder tb, Map props, Object v) {
tb.imageNameMatches(((CharSequence)v).toString());
}})
.build();
public static final Map<String,CustomizeTemplateOptions> SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES = ImmutableMap.<String,CustomizeTemplateOptions>builder()
.put("securityGroups", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
if (t instanceof EC2TemplateOptions) {
String[] securityGroups = toStringArray(v);
((EC2TemplateOptions)t).securityGroups(securityGroups);
// jclouds 1.5, also support:
} else if (t instanceof NovaTemplateOptions) {
String[] securityGroups = toStringArray(v);
((NovaTemplateOptions)t).securityGroupNames(securityGroups);
} else {
LOG.info("ignoring securityGroups({}) in VM creation because not supported for cloud/type ({})", v, t);
}
}})
.put("userData", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
/* expects UUENCODED byte array or string */
if (t instanceof EC2TemplateOptions) {
byte[] bytes = toByteArray(v);
((EC2TemplateOptions)t).userData(bytes);
} else {
LOG.info("ignoring userData({}) in VM creation because not supported for cloud/type ({})", v, t);
}
}})
.put("inboundPorts", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
int[] inboundPorts = toIntArray(v);
if (LOG.isDebugEnabled()) LOG.debug("opening inbound ports {} for {}", Arrays.toString(inboundPorts), t);
t.inboundPorts(inboundPorts);
}})
.put("userMetadata", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
t.userMetadata(toMapStringString(v));
}})
.put("rootSshPublicKeyData", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
t.authorizePublicKey(((CharSequence)v).toString());
}})
.put("sshPublicKey", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
/* special; not included here */
}})
.put("userName", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
/* special; not included here */
}})
.put("runAsRoot", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
t.runAsRoot((Boolean)v);
}})
.put("loginUser", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
t.overrideLoginUser(((CharSequence)v).toString());
}})
.put("loginUser.password", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
t.overrideLoginPassword(((CharSequence)v).toString());
}})
.put("loginUser.privateKeyData", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
t.overrideLoginPrivateKey(((CharSequence)v).toString());
}})
.put("overrideLoginUser", new CustomizeTemplateOptions() {
public void apply(TemplateOptions t, Map props, Object v) {
LOG.warn("Using deprecated property overrideLoginUser; use loginUser instead");
t.overrideLoginUser(((CharSequence)v).toString());
}})
.build();
private static boolean listedAvailableTemplatesOnNoSuchTemplate = false;
private Template buildTemplate(ComputeService computeService, BrooklynJcloudsSetupHolder setup) {
TemplateBuilder templateBuilder = (TemplateBuilder) setup.get("templateBuilder");
if (templateBuilder==null)
templateBuilder = new PortableTemplateBuilder();
else
LOG.debug("jclouds using templateBuilder {} as base for provisioning in {} for {}", new Object[] {templateBuilder, this, setup.getCallerContext()});
if (setup.providerLocationId!=null) {
templateBuilder.locationId(setup.providerLocationId);
}
for (Map.Entry<String, CustomizeTemplateBuilder> entry : SUPPORTED_TEMPLATE_BUILDER_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateBuilder code = entry.getValue();
if (setup.use(name))
code.apply(templateBuilder, setup.allconf, setup.get(name));
}
if (templateBuilder instanceof PortableTemplateBuilder) {
((PortableTemplateBuilder)templateBuilder).attachComputeService(computeService);
// do the default last, and only if nothing else specified (guaranteed to be a PTB if nothing else specified)
if (setup.use("defaultImageId")) {
if (((PortableTemplateBuilder)templateBuilder).isBlank()) {
CharSequence defaultImageId = (CharSequence) setup.get("defaultImageId");
templateBuilder.imageId(defaultImageId.toString());
}
}
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, templateBuilder);
}
Template template;
try {
template = templateBuilder.build();
if (template==null) throw new NullPointerException("No template found (templateBuilder.build returned null)");
LOG.debug(""+this+" got template "+template+" (image "+template.getImage()+")");
if (template.getImage()==null) throw new NullPointerException("Template does not contain an image (templateBuilder.build returned invalid template)");
if (isBadTemplate(template.getImage())) {
// release candidates might break things :( TODO get the list and score them
if (templateBuilder instanceof PortableTemplateBuilder) {
if (((PortableTemplateBuilder)templateBuilder).getOsFamily()==null) {
templateBuilder.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04").os64Bit(true);
Template template2 = templateBuilder.build();
if (template2!=null) {
LOG.debug(""+this+" preferring template {} over {}", template2, template);
template = template2;
}
}
}
}
} catch (AuthorizationException e) {
LOG.warn("Error resolving template: not authorized (rethrowing: "+e+")");
throw new IllegalStateException("Not authorized to access cloud "+this+" to resolve "+templateBuilder, e);
} catch (Exception e) {
try {
synchronized (this) {
// delay subsequent log.warns (put in synch block) so the "Loading..." message is obvious
LOG.warn("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+" (rethrowing): "+e);
if (!listedAvailableTemplatesOnNoSuchTemplate) {
listedAvailableTemplatesOnNoSuchTemplate = true;
LOG.info("Loading available images at "+this+" for reference...");
Map m1 = new LinkedHashMap(setup.allconf);
if (m1.remove("imageId")!=null)
// don't apply default filters if user has tried to specify an image ID
m1.put("anyOwner", true);
ComputeService computeServiceLessRestrictive = JcloudsUtil.buildOrFindComputeService(m1, new MutableMap());
Set<? extends Image> imgs = computeServiceLessRestrictive.listImages();
LOG.info(""+imgs.size()+" available images at "+this);
for (Image img: imgs) {
LOG.info(" Image: "+img);
}
}
}
- throw new IllegalStateException("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+". See list of images in log.", e);
} catch (Exception e2) {
LOG.warn("Error loading available images to report (following original error matching template which will be rethrown): "+e2, e2);
throw new IllegalStateException("Unable to access cloud "+this+" to resolve "+templateBuilder, e);
}
+ throw new IllegalStateException("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+". See list of images in log.", e);
}
TemplateOptions options = template.getOptions();
for (Map.Entry<String, CustomizeTemplateOptions> entry : SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateOptions code = entry.getValue();
if (setup.use(name))
code.apply(options, setup.allconf, setup.get(name));
}
// Setup the user
//NB: we ignore private key here because, by default we probably should not be installing it remotely;
//also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
//but not elsewhere, e.g. on rackspace)
if (truth(setup.user) && !NON_ADDABLE_USERS.contains(setup.user) &&
!setup.user.equals(setup.loginUser) && !truth(setup.isDontCreateUser())) {
// create the user, if it's not the login user and not a known root-level user
// by default we now give these users sudo privileges.
// if you want something else, that can be specified manually,
// e.g. using jclouds UserAdd.Builder, with RunScriptOnNode, or template.options.runScript(xxx)
// (if that is a common use case, we could expose a property here)
// note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
AdminAccess.Builder adminBuilder = AdminAccess.builder().
adminUsername(setup.user).
grantSudoToAdminUser(true);
adminBuilder.adminPassword(setup.use("password") ? setup.password : Identifiers.makeRandomId(12));
if (setup.publicKeyData!=null)
adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(setup.publicKeyData);
else
adminBuilder.authorizeAdminPublicKey(false).adminPublicKey("ignored").lockSsh(true);
adminBuilder.installAdminPrivateKey(false).adminPrivateKey("ignored");
adminBuilder.resetLoginPassword(true).loginPassword(Identifiers.makeRandomId(12));
adminBuilder.lockSsh(true);
options.runScript(adminBuilder.build());
} else if (truth(setup.publicKeyData)) {
// don't create the user, but authorize the public key for the default user
options.authorizePublicKey(setup.publicKeyData);
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, options);
}
LOG.debug("jclouds using template {} / options {} to provision machine in {} for {}", new Object[] {template, options, this, setup.getCallerContext()});
return template;
}
// TODO we really need a better way to decide which images are preferred
// though to be fair this is similar to jclouds strategies
// we fall back to the "bad" images (^^^ above) if we can't find a good one above
// ---
// but in practice in AWS images name "rc-" and from "alphas" break things badly
// (apt repos don't work, etc)
private boolean isBadTemplate(Image image) {
String name = image.getName();
if (name != null && name.contains(".rc-")) return true;
OperatingSystem os = image.getOperatingSystem();
if (os!=null) {
String description = os.getDescription();
if (description != null && description.contains("-alpha"))
return true;
}
return false;
}
private String getPublicHostname(NodeMetadata node, BrooklynJcloudsSetupHolder setup) {
if ("aws-ec2".equals(setup != null ? setup.get("provider") : null)) {
String vmIp = null;
try {
vmIp = JcloudsUtil.getFirstReachableAddress(this.getComputeService().getContext(), node);
} catch (Exception e) {
LOG.warn("Error reaching aws-ec2 instance on port 22; falling back to jclouds metadata for address", e);
}
if (vmIp != null) {
try {
return getPublicHostnameAws(vmIp, setup);
} catch (Exception e) {
LOG.warn("Error querying aws-ec2 instance over ssh for its hostname; falling back to first reachable IP", e);
return vmIp;
}
}
}
return getPublicHostnameGeneric(node, setup);
}
private String getPublicHostnameGeneric(NodeMetadata node, @Nullable BrooklynJcloudsSetupHolder setup) {
//prefer the public address to the hostname because hostname is sometimes wrong/abbreviated
//(see that javadoc; also e.g. on rackspace, the hostname lacks the domain)
//TODO would it be better to prefer hostname, but first check that it is resolvable?
if (truth(node.getPublicAddresses())) {
return node.getPublicAddresses().iterator().next();
} else if (truth(node.getHostname())) {
return node.getHostname();
} else if (truth(node.getPrivateAddresses())) {
return node.getPrivateAddresses().iterator().next();
} else {
return null;
}
}
private String getPublicHostnameAws(String ip, BrooklynJcloudsSetupHolder setup) {
SshMachineLocation sshLocByIp = null;
try {
Map sshConfig = generateSshConfig(setup, null);
// TODO messy way to get an SSH session
sshLocByIp = new SshMachineLocation(MutableMap.of("address", ip, "user", setup.user, "config", sshConfig));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
int exitcode = sshLocByIp.run(
MutableMap.of("out", outStream, "err", errStream),
"echo `curl --silent --retry 20 http://169.254.169.254/latest/meta-data/public-hostname`; exit");
String outString = new String(outStream.toByteArray());
String[] outLines = outString.split("\n");
for (String line : outLines) {
if (line.startsWith("ec2-")) return line.trim();
}
throw new IllegalStateException("Could not obtain hostname for vm "+ip+"; exitcode="+exitcode+"; stdout="+outString+"; stderr="+new String(errStream.toByteArray()));
} catch (IOException e) {
throw Throwables.propagate(e);
} finally {
Closeables.closeQuietly(sshLocByIp);
}
}
public static class JcloudsSshMachineLocation extends SshMachineLocation {
final JcloudsLocation parent;
final NodeMetadata node;
private final RunScriptOnNode.Factory runScriptFactory;
public JcloudsSshMachineLocation(Map flags, JcloudsLocation parent, NodeMetadata node) {
super(flags);
this.parent = parent;
this.node = node;
ComputeServiceContext context = parent.getComputeService().getContext();
runScriptFactory = context.utils().injector().getInstance(RunScriptOnNode.Factory.class);
}
public NodeMetadata getNode() {
return node;
}
public JcloudsLocation getParent() {
return parent;
}
/** returns the hostname for use by peers in the same subnet,
* defaulting to public hostname if nothing special
* <p>
* for use e.g. in clouds like amazon where other machines
* in the same subnet need to use a different IP
*/
public String getSubnetHostname() {
if (truth(node.getPrivateAddresses()))
return node.getPrivateAddresses().iterator().next();
return parent.getPublicHostname(node, null);
}
public String getJcloudsId() {
return node.getId();
}
/** executes the given statements on the server using jclouds ScriptBuilder,
* wrapping in a script which is polled periodically.
* the output is returned once the script completes (disadvantage compared to other methods)
* but the process is nohupped and the SSH session is not kept,
* so very useful for long-running processes
*/
public ListenableFuture<ExecResponse> submitRunScript(String ...statements) {
return submitRunScript(new InterpretableStatement(statements));
}
public ListenableFuture<ExecResponse> submitRunScript(Statement script) {
return submitRunScript(script, new RunScriptOptions());
}
public ListenableFuture<ExecResponse> submitRunScript(Statement script, RunScriptOptions options) {
return runScriptFactory.submit(node, script, options);
}
/** uses submitRunScript to execute the commands, and throws error if it fails or returns non-zero */
public void execRemoteScript(String ...commands) {
try {
ExecResponse result = submitRunScript(commands).get();
if (result.getExitStatus()!=0)
throw new IllegalStateException("Error running remote commands (code "+result.getExitStatus()+"): "+commands);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw Throwables.propagate(e);
} catch (ExecutionException e) {
throw Throwables.propagate(e);
}
}
/**
* Retrieves the password for this VM, if one exists. The behaviour/implementation is different for different clouds.
* e.g. on Rackspace, the password for a windows VM is available immediately; on AWS-EC2, for a Windows VM you need
* to poll repeatedly until the password is available which can take up to 15 minutes.
*/
public String waitForPassword() {
// TODO Hacky; don't want aws specific stuff here but what to do?!
if (parent.getProvider().equals("aws-ec2")) {
try {
return JcloudsUtil.waitForPasswordOnAws(parent.getComputeService(), node, 15, TimeUnit.MINUTES);
} catch (TimeoutException e) {
throw Throwables.propagate(e);
}
} else {
LoginCredentials credentials = node.getCredentials();
return (credentials != null) ? credentials.getPassword() : null;
}
}
@Override
public OsDetails getOsDetails() {
if (node.getOperatingSystem() != null) {
return new BasicOsDetails(
node.getOperatingSystem().getName() != null
? node.getOperatingSystem().getName() : "linux",
node.getOperatingSystem().getArch() != null
? node.getOperatingSystem().getArch() : BasicOsDetails.OsArchs.I386,
node.getOperatingSystem().getVersion() != null
? node.getOperatingSystem().getVersion() : "unknown",
node.getOperatingSystem().is64Bit());
}
return super.getOsDetails();
}
}
private static double toDouble(Object v) {
if (v instanceof Number) {
return ((Number)v).doubleValue();
} else {
throw new IllegalArgumentException("Invalid type for double: "+v+" of type "+v.getClass());
}
}
private static int[] toIntArray(Object v) {
int[] result;
if (v instanceof Iterable) {
result = new int[Iterables.size((Iterable)v)];
int i = 0;
for (Object o : (Iterable)v) {
result[i++] = (Integer) o;
}
} else if (v instanceof int[]) {
result = (int[]) v;
} else if (v instanceof Object[]) {
result = new int[((Object[])v).length];
for (int i = 0; i < result.length; i++) {
result[i] = (Integer) ((Object[])v)[i];
}
} else if (v instanceof Integer) {
result = new int[] {(Integer)v};
} else {
throw new IllegalArgumentException("Invalid type for int[]: "+v+" of type "+v.getClass());
}
return result;
}
private static String[] toStringArray(Object v) {
Collection<String> result = Lists.newArrayList();
if (v instanceof Iterable) {
int i = 0;
for (Object o : (Iterable)v) {
result.add(o.toString());
}
} else if (v instanceof Object[]) {
for (int i = 0; i < ((Object[])v).length; i++) {
result.add(((Object[])v)[i].toString());
}
} else if (v instanceof String) {
result.add((String) v);
} else {
throw new IllegalArgumentException("Invalid type for String[]: "+v+" of type "+v.getClass());
}
return result.toArray(new String[0]);
}
private static byte[] toByteArray(Object v) {
if (v instanceof byte[]) {
return (byte[]) v;
} else if (v instanceof CharSequence) {
return v.toString().getBytes();
} else {
throw new IllegalArgumentException("Invalid type for byte[]: "+v+" of type "+v.getClass());
}
}
// Handles GString
private static Map<String,String> toMapStringString(Object v) {
if (v instanceof Map<?,?>) {
Map<String,String> result = Maps.newLinkedHashMap();
for (Map.Entry<?,?> entry : ((Map<?,?>)v).entrySet()) {
String key = ((CharSequence)entry.getKey()).toString();
String value = ((CharSequence)entry.getValue()).toString();
result.put(key, value);
}
return result;
} else if (v instanceof CharSequence) {
return KeyValueParser.parseMap(v.toString());
} else {
throw new IllegalArgumentException("Invalid type for Map<String,String>: "+v+" of type "+v.getClass());
}
}
}
| false | true | private Template buildTemplate(ComputeService computeService, BrooklynJcloudsSetupHolder setup) {
TemplateBuilder templateBuilder = (TemplateBuilder) setup.get("templateBuilder");
if (templateBuilder==null)
templateBuilder = new PortableTemplateBuilder();
else
LOG.debug("jclouds using templateBuilder {} as base for provisioning in {} for {}", new Object[] {templateBuilder, this, setup.getCallerContext()});
if (setup.providerLocationId!=null) {
templateBuilder.locationId(setup.providerLocationId);
}
for (Map.Entry<String, CustomizeTemplateBuilder> entry : SUPPORTED_TEMPLATE_BUILDER_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateBuilder code = entry.getValue();
if (setup.use(name))
code.apply(templateBuilder, setup.allconf, setup.get(name));
}
if (templateBuilder instanceof PortableTemplateBuilder) {
((PortableTemplateBuilder)templateBuilder).attachComputeService(computeService);
// do the default last, and only if nothing else specified (guaranteed to be a PTB if nothing else specified)
if (setup.use("defaultImageId")) {
if (((PortableTemplateBuilder)templateBuilder).isBlank()) {
CharSequence defaultImageId = (CharSequence) setup.get("defaultImageId");
templateBuilder.imageId(defaultImageId.toString());
}
}
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, templateBuilder);
}
Template template;
try {
template = templateBuilder.build();
if (template==null) throw new NullPointerException("No template found (templateBuilder.build returned null)");
LOG.debug(""+this+" got template "+template+" (image "+template.getImage()+")");
if (template.getImage()==null) throw new NullPointerException("Template does not contain an image (templateBuilder.build returned invalid template)");
if (isBadTemplate(template.getImage())) {
// release candidates might break things :( TODO get the list and score them
if (templateBuilder instanceof PortableTemplateBuilder) {
if (((PortableTemplateBuilder)templateBuilder).getOsFamily()==null) {
templateBuilder.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04").os64Bit(true);
Template template2 = templateBuilder.build();
if (template2!=null) {
LOG.debug(""+this+" preferring template {} over {}", template2, template);
template = template2;
}
}
}
}
} catch (AuthorizationException e) {
LOG.warn("Error resolving template: not authorized (rethrowing: "+e+")");
throw new IllegalStateException("Not authorized to access cloud "+this+" to resolve "+templateBuilder, e);
} catch (Exception e) {
try {
synchronized (this) {
// delay subsequent log.warns (put in synch block) so the "Loading..." message is obvious
LOG.warn("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+" (rethrowing): "+e);
if (!listedAvailableTemplatesOnNoSuchTemplate) {
listedAvailableTemplatesOnNoSuchTemplate = true;
LOG.info("Loading available images at "+this+" for reference...");
Map m1 = new LinkedHashMap(setup.allconf);
if (m1.remove("imageId")!=null)
// don't apply default filters if user has tried to specify an image ID
m1.put("anyOwner", true);
ComputeService computeServiceLessRestrictive = JcloudsUtil.buildOrFindComputeService(m1, new MutableMap());
Set<? extends Image> imgs = computeServiceLessRestrictive.listImages();
LOG.info(""+imgs.size()+" available images at "+this);
for (Image img: imgs) {
LOG.info(" Image: "+img);
}
}
}
throw new IllegalStateException("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+". See list of images in log.", e);
} catch (Exception e2) {
LOG.warn("Error loading available images to report (following original error matching template which will be rethrown): "+e2, e2);
throw new IllegalStateException("Unable to access cloud "+this+" to resolve "+templateBuilder, e);
}
}
TemplateOptions options = template.getOptions();
for (Map.Entry<String, CustomizeTemplateOptions> entry : SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateOptions code = entry.getValue();
if (setup.use(name))
code.apply(options, setup.allconf, setup.get(name));
}
// Setup the user
//NB: we ignore private key here because, by default we probably should not be installing it remotely;
//also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
//but not elsewhere, e.g. on rackspace)
if (truth(setup.user) && !NON_ADDABLE_USERS.contains(setup.user) &&
!setup.user.equals(setup.loginUser) && !truth(setup.isDontCreateUser())) {
// create the user, if it's not the login user and not a known root-level user
// by default we now give these users sudo privileges.
// if you want something else, that can be specified manually,
// e.g. using jclouds UserAdd.Builder, with RunScriptOnNode, or template.options.runScript(xxx)
// (if that is a common use case, we could expose a property here)
// note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
AdminAccess.Builder adminBuilder = AdminAccess.builder().
adminUsername(setup.user).
grantSudoToAdminUser(true);
adminBuilder.adminPassword(setup.use("password") ? setup.password : Identifiers.makeRandomId(12));
if (setup.publicKeyData!=null)
adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(setup.publicKeyData);
else
adminBuilder.authorizeAdminPublicKey(false).adminPublicKey("ignored").lockSsh(true);
adminBuilder.installAdminPrivateKey(false).adminPrivateKey("ignored");
adminBuilder.resetLoginPassword(true).loginPassword(Identifiers.makeRandomId(12));
adminBuilder.lockSsh(true);
options.runScript(adminBuilder.build());
} else if (truth(setup.publicKeyData)) {
// don't create the user, but authorize the public key for the default user
options.authorizePublicKey(setup.publicKeyData);
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, options);
}
LOG.debug("jclouds using template {} / options {} to provision machine in {} for {}", new Object[] {template, options, this, setup.getCallerContext()});
return template;
}
| private Template buildTemplate(ComputeService computeService, BrooklynJcloudsSetupHolder setup) {
TemplateBuilder templateBuilder = (TemplateBuilder) setup.get("templateBuilder");
if (templateBuilder==null)
templateBuilder = new PortableTemplateBuilder();
else
LOG.debug("jclouds using templateBuilder {} as base for provisioning in {} for {}", new Object[] {templateBuilder, this, setup.getCallerContext()});
if (setup.providerLocationId!=null) {
templateBuilder.locationId(setup.providerLocationId);
}
for (Map.Entry<String, CustomizeTemplateBuilder> entry : SUPPORTED_TEMPLATE_BUILDER_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateBuilder code = entry.getValue();
if (setup.use(name))
code.apply(templateBuilder, setup.allconf, setup.get(name));
}
if (templateBuilder instanceof PortableTemplateBuilder) {
((PortableTemplateBuilder)templateBuilder).attachComputeService(computeService);
// do the default last, and only if nothing else specified (guaranteed to be a PTB if nothing else specified)
if (setup.use("defaultImageId")) {
if (((PortableTemplateBuilder)templateBuilder).isBlank()) {
CharSequence defaultImageId = (CharSequence) setup.get("defaultImageId");
templateBuilder.imageId(defaultImageId.toString());
}
}
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, templateBuilder);
}
Template template;
try {
template = templateBuilder.build();
if (template==null) throw new NullPointerException("No template found (templateBuilder.build returned null)");
LOG.debug(""+this+" got template "+template+" (image "+template.getImage()+")");
if (template.getImage()==null) throw new NullPointerException("Template does not contain an image (templateBuilder.build returned invalid template)");
if (isBadTemplate(template.getImage())) {
// release candidates might break things :( TODO get the list and score them
if (templateBuilder instanceof PortableTemplateBuilder) {
if (((PortableTemplateBuilder)templateBuilder).getOsFamily()==null) {
templateBuilder.osFamily(OsFamily.UBUNTU).osVersionMatches("11.04").os64Bit(true);
Template template2 = templateBuilder.build();
if (template2!=null) {
LOG.debug(""+this+" preferring template {} over {}", template2, template);
template = template2;
}
}
}
}
} catch (AuthorizationException e) {
LOG.warn("Error resolving template: not authorized (rethrowing: "+e+")");
throw new IllegalStateException("Not authorized to access cloud "+this+" to resolve "+templateBuilder, e);
} catch (Exception e) {
try {
synchronized (this) {
// delay subsequent log.warns (put in synch block) so the "Loading..." message is obvious
LOG.warn("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+" (rethrowing): "+e);
if (!listedAvailableTemplatesOnNoSuchTemplate) {
listedAvailableTemplatesOnNoSuchTemplate = true;
LOG.info("Loading available images at "+this+" for reference...");
Map m1 = new LinkedHashMap(setup.allconf);
if (m1.remove("imageId")!=null)
// don't apply default filters if user has tried to specify an image ID
m1.put("anyOwner", true);
ComputeService computeServiceLessRestrictive = JcloudsUtil.buildOrFindComputeService(m1, new MutableMap());
Set<? extends Image> imgs = computeServiceLessRestrictive.listImages();
LOG.info(""+imgs.size()+" available images at "+this);
for (Image img: imgs) {
LOG.info(" Image: "+img);
}
}
}
} catch (Exception e2) {
LOG.warn("Error loading available images to report (following original error matching template which will be rethrown): "+e2, e2);
throw new IllegalStateException("Unable to access cloud "+this+" to resolve "+templateBuilder, e);
}
throw new IllegalStateException("Unable to match required VM template constraints "+templateBuilder+" when trying to provision VM in "+this+". See list of images in log.", e);
}
TemplateOptions options = template.getOptions();
for (Map.Entry<String, CustomizeTemplateOptions> entry : SUPPORTED_TEMPLATE_OPTIONS_PROPERTIES.entrySet()) {
String name = entry.getKey();
CustomizeTemplateOptions code = entry.getValue();
if (setup.use(name))
code.apply(options, setup.allconf, setup.get(name));
}
// Setup the user
//NB: we ignore private key here because, by default we probably should not be installing it remotely;
//also, it may not be valid for first login (it is created before login e.g. on amazon, so valid there;
//but not elsewhere, e.g. on rackspace)
if (truth(setup.user) && !NON_ADDABLE_USERS.contains(setup.user) &&
!setup.user.equals(setup.loginUser) && !truth(setup.isDontCreateUser())) {
// create the user, if it's not the login user and not a known root-level user
// by default we now give these users sudo privileges.
// if you want something else, that can be specified manually,
// e.g. using jclouds UserAdd.Builder, with RunScriptOnNode, or template.options.runScript(xxx)
// (if that is a common use case, we could expose a property here)
// note AdminAccess requires _all_ fields set, due to http://code.google.com/p/jclouds/issues/detail?id=1095
AdminAccess.Builder adminBuilder = AdminAccess.builder().
adminUsername(setup.user).
grantSudoToAdminUser(true);
adminBuilder.adminPassword(setup.use("password") ? setup.password : Identifiers.makeRandomId(12));
if (setup.publicKeyData!=null)
adminBuilder.authorizeAdminPublicKey(true).adminPublicKey(setup.publicKeyData);
else
adminBuilder.authorizeAdminPublicKey(false).adminPublicKey("ignored").lockSsh(true);
adminBuilder.installAdminPrivateKey(false).adminPrivateKey("ignored");
adminBuilder.resetLoginPassword(true).loginPassword(Identifiers.makeRandomId(12));
adminBuilder.lockSsh(true);
options.runScript(adminBuilder.build());
} else if (truth(setup.publicKeyData)) {
// don't create the user, but authorize the public key for the default user
options.authorizePublicKey(setup.publicKeyData);
}
// Finally, apply any optional app-specific customization.
for (JcloudsLocationCustomizer customizer : setup.customizers) {
customizer.customize(computeService, options);
}
LOG.debug("jclouds using template {} / options {} to provision machine in {} for {}", new Object[] {template, options, this, setup.getCallerContext()});
return template;
}
|
diff --git a/htroot/Settings_p.java b/htroot/Settings_p.java
index 6dc76bbfd..f25516118 100644
--- a/htroot/Settings_p.java
+++ b/htroot/Settings_p.java
@@ -1,243 +1,243 @@
// Settings.p.java
// -----------------------
// part of the AnomicHTTPD caching proxy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
// last change: 02.05.2004
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
// You must compile this file with
// javac -classpath .:../Classes Settings_p.java
// if the shell's current path is HTROOT
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.io.File;
import de.anomic.http.httpHeader;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.server.serverCore;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacySeedUploader;
public final class Settings_p {
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
serverObjects prop = new serverObjects();
//if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString());
prop.put("port", env.getConfig("port", "8080"));
prop.put("peerName", env.getConfig("peerName", "nameless"));
prop.put("staticIP", env.getConfig("staticIP", ""));
String peerLang = env.getConfig("htLocaleSelection", "default");
if (peerLang.equals("default")) peerLang = "en";
prop.put("peerLang", peerLang);
// http networking settings
prop.put("isTransparentProxy", env.getConfig("isTransparentProxy", "false").equals("true") ? 1 : 0);
prop.put("connectionKeepAliveSupport", env.getConfig("connectionKeepAliveSupport", "false").equals("true") ? 1 : 0);
// remote port forwarding settings
prop.put("portForwardingEnabled",env.getConfig("portForwardingEnabled","false").equals("true")? 1 : 0);
prop.put("portForwardingUseProxy",env.getConfig("portForwardingUseProxy", "false").equals("true")? 1 : 0);
prop.put("portForwardingPort",env.getConfig("portForwardingPort", ""));
prop.put("portForwardingHost",env.getConfig("portForwardingHost", ""));
prop.put("portForwardingHostPort",env.getConfig("portForwardingHostPort", ""));
prop.put("portForwardingHostUser",env.getConfig("portForwardingHostUser", ""));
prop.put("portForwardingHostPwd",env.getConfig("portForwardingHostPwd", ""));
// set values
String s;
int pos;
// admin password
if (env.getConfig("adminAccountBase64", "").length() == 0) {
// no password has been specified
prop.put("adminuser","admin");
} else {
s = env.getConfig("adminAccount", "admin:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("adminuser","admin");
} else {
prop.put("adminuser",s.substring(0, pos));
}
}
// remote proxy
prop.put("remoteProxyHost", env.getConfig("remoteProxyHost", ""));
prop.put("remoteProxyPort", env.getConfig("remoteProxyPort", ""));
prop.put("remoteProxyNoProxy", env.getConfig("remoteProxyNoProxy", ""));
prop.put("remoteProxyUseChecked", ((String) env.getConfig("remoteProxyUse", "false")).equals("true") ? 1 : 0);
// proxy access filter
prop.put("proxyfilter", env.getConfig("proxyClient", "*"));
// proxy password
if ( env.getConfig("use_proxyAccounts", "false").equals("false") ) {
// no password has been specified
prop.put("use_proxyAccounts", 0); //unchecked
} else {
prop.put("use_proxyAccounts", 1); //checked
/*s = env.getConfig("proxyAccount", "proxy:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("proxyuser","proxy");
} else {
prop.put("proxyuser",s.substring(0, pos));
}*/
}
// server access filter
prop.put("serverfilter", env.getConfig("serverClient", "*"));
// server password
if (env.getConfig("serverAccountBase64", "").length() == 0) {
// no password has been specified
prop.put("serveruser","server");
} else {
s = env.getConfig("serverAccount", "server:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("serveruser","server");
} else {
prop.put("serveruser",s.substring(0, pos));
}
}
// clientIP
prop.put("clientIP", (String) header.get("CLIENTIP", "<unknown>")); // read an artificial header addendum
/*
* seed upload settings
*/
// available methods
String enabledUploader = env.getConfig("seedUploadMethod", "none");
// for backward compatiblity ....
if ((enabledUploader.equalsIgnoreCase("Ftp")) ||
((enabledUploader.equals("")) &&
(env.getConfig("seedFTPPassword","").length() > 0) &&
(env.getConfig("seedFilePath", "").length() > 0))) {
enabledUploader = "Ftp";
env.setConfig("seedUploadMethod",enabledUploader);
}
HashMap uploaders = yacyCore.getSeedUploadMethods();
prop.put("seedUploadMethods", uploaders.size() + 1);
prop.put("seedUploadMethods_0_name", "none");
prop.put("seedUploadMethods_0_selected", enabledUploader.equals("none")?1:0);
prop.put("seedUploadMethods_0_file", "");
int count = 0;
Iterator uploaderKeys = uploaders.keySet().iterator();
while (uploaderKeys.hasNext()) {
count++;
String uploaderName = (String) uploaderKeys.next();
prop.put("seedUploadMethods_" +count+ "_name", uploaderName);
prop.put("seedUploadMethods_" +count+ "_selected", uploaderName.equals(enabledUploader)?1:0);
- prop.put("seedUploadMethods_" +count+ "_file", new File(env.getRootPath(), "htroot/yacy/seedUpload/yacySeedUpload" + uploaderName + ".html").toString());
+ prop.put("seedUploadMethods_" +count+ "_file", "yacy/seedUpload/yacySeedUpload" + uploaderName + ".html");
yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);
String[] configOptions = theUploader.getConfigurationOptions();
if (configOptions != null) {
for (int i=0; i<configOptions.length; i++) {
prop.put("seedUploadMethods_" +count+ "_" + configOptions[i], env.getConfig(configOptions[i], ""));
// prop.put("seedUpload" + uploaderName,1);
}
}
}
// general settings
prop.put("seedURL", env.getConfig("seedURL", ""));
/*
* Message forwarding configuration
*/
prop.put("msgForwardingEnabled",env.getConfig("msgForwardingEnabled","false").equals("true")? 1 : 0);
prop.put("msgForwardingCmd",env.getConfig("msgForwardingCmd", ""));
prop.put("msgForwardingTo",env.getConfig("msgForwardingTo", ""));
/*
* Parser Configuration
*/
plasmaSwitchboard sb = (plasmaSwitchboard)env;
Hashtable enabledParsers = sb.parser.getEnabledParserList();
Hashtable availableParsers = sb.parser.getAvailableParserList();
// fetching a list of all available mimetypes
List availableParserKeys = Arrays.asList(availableParsers.keySet().toArray(new String[availableParsers.size()]));
// sort it
Collections.sort(availableParserKeys);
// loop through the mimeTypes and add it to the properties
boolean allParsersEnabled = true;
int parserIdx = 0;
Iterator availableParserIter = availableParserKeys.iterator();
while (availableParserIter.hasNext()) {
String mimeType = (String) availableParserIter.next();
String parserName = (String) availableParsers.get(mimeType);
boolean parserIsEnabled = enabledParsers.containsKey(mimeType);
prop.put("parser_" + parserIdx + "_mime", mimeType);
prop.put("parser_" + parserIdx + "_name", parserName);
prop.put("parser_" + parserIdx + "_shortname", parserName.substring(parserName.lastIndexOf(".")+1));
prop.put("parser_" + parserIdx + "_status", parserIsEnabled ? 1:0);
allParsersEnabled &= parserIsEnabled;
parserIdx++;
}
prop.put("allParserEnabled",allParsersEnabled ? 1:0);
prop.put("parser", parserIdx);
// return rewrite properties
return prop;
}
}
| true | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
serverObjects prop = new serverObjects();
//if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString());
prop.put("port", env.getConfig("port", "8080"));
prop.put("peerName", env.getConfig("peerName", "nameless"));
prop.put("staticIP", env.getConfig("staticIP", ""));
String peerLang = env.getConfig("htLocaleSelection", "default");
if (peerLang.equals("default")) peerLang = "en";
prop.put("peerLang", peerLang);
// http networking settings
prop.put("isTransparentProxy", env.getConfig("isTransparentProxy", "false").equals("true") ? 1 : 0);
prop.put("connectionKeepAliveSupport", env.getConfig("connectionKeepAliveSupport", "false").equals("true") ? 1 : 0);
// remote port forwarding settings
prop.put("portForwardingEnabled",env.getConfig("portForwardingEnabled","false").equals("true")? 1 : 0);
prop.put("portForwardingUseProxy",env.getConfig("portForwardingUseProxy", "false").equals("true")? 1 : 0);
prop.put("portForwardingPort",env.getConfig("portForwardingPort", ""));
prop.put("portForwardingHost",env.getConfig("portForwardingHost", ""));
prop.put("portForwardingHostPort",env.getConfig("portForwardingHostPort", ""));
prop.put("portForwardingHostUser",env.getConfig("portForwardingHostUser", ""));
prop.put("portForwardingHostPwd",env.getConfig("portForwardingHostPwd", ""));
// set values
String s;
int pos;
// admin password
if (env.getConfig("adminAccountBase64", "").length() == 0) {
// no password has been specified
prop.put("adminuser","admin");
} else {
s = env.getConfig("adminAccount", "admin:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("adminuser","admin");
} else {
prop.put("adminuser",s.substring(0, pos));
}
}
// remote proxy
prop.put("remoteProxyHost", env.getConfig("remoteProxyHost", ""));
prop.put("remoteProxyPort", env.getConfig("remoteProxyPort", ""));
prop.put("remoteProxyNoProxy", env.getConfig("remoteProxyNoProxy", ""));
prop.put("remoteProxyUseChecked", ((String) env.getConfig("remoteProxyUse", "false")).equals("true") ? 1 : 0);
// proxy access filter
prop.put("proxyfilter", env.getConfig("proxyClient", "*"));
// proxy password
if ( env.getConfig("use_proxyAccounts", "false").equals("false") ) {
// no password has been specified
prop.put("use_proxyAccounts", 0); //unchecked
} else {
prop.put("use_proxyAccounts", 1); //checked
/*s = env.getConfig("proxyAccount", "proxy:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("proxyuser","proxy");
} else {
prop.put("proxyuser",s.substring(0, pos));
}*/
}
// server access filter
prop.put("serverfilter", env.getConfig("serverClient", "*"));
// server password
if (env.getConfig("serverAccountBase64", "").length() == 0) {
// no password has been specified
prop.put("serveruser","server");
} else {
s = env.getConfig("serverAccount", "server:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("serveruser","server");
} else {
prop.put("serveruser",s.substring(0, pos));
}
}
// clientIP
prop.put("clientIP", (String) header.get("CLIENTIP", "<unknown>")); // read an artificial header addendum
/*
* seed upload settings
*/
// available methods
String enabledUploader = env.getConfig("seedUploadMethod", "none");
// for backward compatiblity ....
if ((enabledUploader.equalsIgnoreCase("Ftp")) ||
((enabledUploader.equals("")) &&
(env.getConfig("seedFTPPassword","").length() > 0) &&
(env.getConfig("seedFilePath", "").length() > 0))) {
enabledUploader = "Ftp";
env.setConfig("seedUploadMethod",enabledUploader);
}
HashMap uploaders = yacyCore.getSeedUploadMethods();
prop.put("seedUploadMethods", uploaders.size() + 1);
prop.put("seedUploadMethods_0_name", "none");
prop.put("seedUploadMethods_0_selected", enabledUploader.equals("none")?1:0);
prop.put("seedUploadMethods_0_file", "");
int count = 0;
Iterator uploaderKeys = uploaders.keySet().iterator();
while (uploaderKeys.hasNext()) {
count++;
String uploaderName = (String) uploaderKeys.next();
prop.put("seedUploadMethods_" +count+ "_name", uploaderName);
prop.put("seedUploadMethods_" +count+ "_selected", uploaderName.equals(enabledUploader)?1:0);
prop.put("seedUploadMethods_" +count+ "_file", new File(env.getRootPath(), "htroot/yacy/seedUpload/yacySeedUpload" + uploaderName + ".html").toString());
yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);
String[] configOptions = theUploader.getConfigurationOptions();
if (configOptions != null) {
for (int i=0; i<configOptions.length; i++) {
prop.put("seedUploadMethods_" +count+ "_" + configOptions[i], env.getConfig(configOptions[i], ""));
// prop.put("seedUpload" + uploaderName,1);
}
}
}
// general settings
prop.put("seedURL", env.getConfig("seedURL", ""));
/*
* Message forwarding configuration
*/
prop.put("msgForwardingEnabled",env.getConfig("msgForwardingEnabled","false").equals("true")? 1 : 0);
prop.put("msgForwardingCmd",env.getConfig("msgForwardingCmd", ""));
prop.put("msgForwardingTo",env.getConfig("msgForwardingTo", ""));
/*
* Parser Configuration
*/
plasmaSwitchboard sb = (plasmaSwitchboard)env;
Hashtable enabledParsers = sb.parser.getEnabledParserList();
Hashtable availableParsers = sb.parser.getAvailableParserList();
// fetching a list of all available mimetypes
List availableParserKeys = Arrays.asList(availableParsers.keySet().toArray(new String[availableParsers.size()]));
// sort it
Collections.sort(availableParserKeys);
// loop through the mimeTypes and add it to the properties
boolean allParsersEnabled = true;
int parserIdx = 0;
Iterator availableParserIter = availableParserKeys.iterator();
while (availableParserIter.hasNext()) {
String mimeType = (String) availableParserIter.next();
String parserName = (String) availableParsers.get(mimeType);
boolean parserIsEnabled = enabledParsers.containsKey(mimeType);
prop.put("parser_" + parserIdx + "_mime", mimeType);
prop.put("parser_" + parserIdx + "_name", parserName);
prop.put("parser_" + parserIdx + "_shortname", parserName.substring(parserName.lastIndexOf(".")+1));
prop.put("parser_" + parserIdx + "_status", parserIsEnabled ? 1:0);
allParsersEnabled &= parserIsEnabled;
parserIdx++;
}
prop.put("allParserEnabled",allParsersEnabled ? 1:0);
prop.put("parser", parserIdx);
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
// return variable that accumulates replacements
serverObjects prop = new serverObjects();
//if (post == null) System.out.println("POST: NULL"); else System.out.println("POST: " + post.toString());
prop.put("port", env.getConfig("port", "8080"));
prop.put("peerName", env.getConfig("peerName", "nameless"));
prop.put("staticIP", env.getConfig("staticIP", ""));
String peerLang = env.getConfig("htLocaleSelection", "default");
if (peerLang.equals("default")) peerLang = "en";
prop.put("peerLang", peerLang);
// http networking settings
prop.put("isTransparentProxy", env.getConfig("isTransparentProxy", "false").equals("true") ? 1 : 0);
prop.put("connectionKeepAliveSupport", env.getConfig("connectionKeepAliveSupport", "false").equals("true") ? 1 : 0);
// remote port forwarding settings
prop.put("portForwardingEnabled",env.getConfig("portForwardingEnabled","false").equals("true")? 1 : 0);
prop.put("portForwardingUseProxy",env.getConfig("portForwardingUseProxy", "false").equals("true")? 1 : 0);
prop.put("portForwardingPort",env.getConfig("portForwardingPort", ""));
prop.put("portForwardingHost",env.getConfig("portForwardingHost", ""));
prop.put("portForwardingHostPort",env.getConfig("portForwardingHostPort", ""));
prop.put("portForwardingHostUser",env.getConfig("portForwardingHostUser", ""));
prop.put("portForwardingHostPwd",env.getConfig("portForwardingHostPwd", ""));
// set values
String s;
int pos;
// admin password
if (env.getConfig("adminAccountBase64", "").length() == 0) {
// no password has been specified
prop.put("adminuser","admin");
} else {
s = env.getConfig("adminAccount", "admin:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("adminuser","admin");
} else {
prop.put("adminuser",s.substring(0, pos));
}
}
// remote proxy
prop.put("remoteProxyHost", env.getConfig("remoteProxyHost", ""));
prop.put("remoteProxyPort", env.getConfig("remoteProxyPort", ""));
prop.put("remoteProxyNoProxy", env.getConfig("remoteProxyNoProxy", ""));
prop.put("remoteProxyUseChecked", ((String) env.getConfig("remoteProxyUse", "false")).equals("true") ? 1 : 0);
// proxy access filter
prop.put("proxyfilter", env.getConfig("proxyClient", "*"));
// proxy password
if ( env.getConfig("use_proxyAccounts", "false").equals("false") ) {
// no password has been specified
prop.put("use_proxyAccounts", 0); //unchecked
} else {
prop.put("use_proxyAccounts", 1); //checked
/*s = env.getConfig("proxyAccount", "proxy:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("proxyuser","proxy");
} else {
prop.put("proxyuser",s.substring(0, pos));
}*/
}
// server access filter
prop.put("serverfilter", env.getConfig("serverClient", "*"));
// server password
if (env.getConfig("serverAccountBase64", "").length() == 0) {
// no password has been specified
prop.put("serveruser","server");
} else {
s = env.getConfig("serverAccount", "server:void");
pos = s.indexOf(":");
if (pos < 0) {
prop.put("serveruser","server");
} else {
prop.put("serveruser",s.substring(0, pos));
}
}
// clientIP
prop.put("clientIP", (String) header.get("CLIENTIP", "<unknown>")); // read an artificial header addendum
/*
* seed upload settings
*/
// available methods
String enabledUploader = env.getConfig("seedUploadMethod", "none");
// for backward compatiblity ....
if ((enabledUploader.equalsIgnoreCase("Ftp")) ||
((enabledUploader.equals("")) &&
(env.getConfig("seedFTPPassword","").length() > 0) &&
(env.getConfig("seedFilePath", "").length() > 0))) {
enabledUploader = "Ftp";
env.setConfig("seedUploadMethod",enabledUploader);
}
HashMap uploaders = yacyCore.getSeedUploadMethods();
prop.put("seedUploadMethods", uploaders.size() + 1);
prop.put("seedUploadMethods_0_name", "none");
prop.put("seedUploadMethods_0_selected", enabledUploader.equals("none")?1:0);
prop.put("seedUploadMethods_0_file", "");
int count = 0;
Iterator uploaderKeys = uploaders.keySet().iterator();
while (uploaderKeys.hasNext()) {
count++;
String uploaderName = (String) uploaderKeys.next();
prop.put("seedUploadMethods_" +count+ "_name", uploaderName);
prop.put("seedUploadMethods_" +count+ "_selected", uploaderName.equals(enabledUploader)?1:0);
prop.put("seedUploadMethods_" +count+ "_file", "yacy/seedUpload/yacySeedUpload" + uploaderName + ".html");
yacySeedUploader theUploader = yacyCore.getSeedUploader(uploaderName);
String[] configOptions = theUploader.getConfigurationOptions();
if (configOptions != null) {
for (int i=0; i<configOptions.length; i++) {
prop.put("seedUploadMethods_" +count+ "_" + configOptions[i], env.getConfig(configOptions[i], ""));
// prop.put("seedUpload" + uploaderName,1);
}
}
}
// general settings
prop.put("seedURL", env.getConfig("seedURL", ""));
/*
* Message forwarding configuration
*/
prop.put("msgForwardingEnabled",env.getConfig("msgForwardingEnabled","false").equals("true")? 1 : 0);
prop.put("msgForwardingCmd",env.getConfig("msgForwardingCmd", ""));
prop.put("msgForwardingTo",env.getConfig("msgForwardingTo", ""));
/*
* Parser Configuration
*/
plasmaSwitchboard sb = (plasmaSwitchboard)env;
Hashtable enabledParsers = sb.parser.getEnabledParserList();
Hashtable availableParsers = sb.parser.getAvailableParserList();
// fetching a list of all available mimetypes
List availableParserKeys = Arrays.asList(availableParsers.keySet().toArray(new String[availableParsers.size()]));
// sort it
Collections.sort(availableParserKeys);
// loop through the mimeTypes and add it to the properties
boolean allParsersEnabled = true;
int parserIdx = 0;
Iterator availableParserIter = availableParserKeys.iterator();
while (availableParserIter.hasNext()) {
String mimeType = (String) availableParserIter.next();
String parserName = (String) availableParsers.get(mimeType);
boolean parserIsEnabled = enabledParsers.containsKey(mimeType);
prop.put("parser_" + parserIdx + "_mime", mimeType);
prop.put("parser_" + parserIdx + "_name", parserName);
prop.put("parser_" + parserIdx + "_shortname", parserName.substring(parserName.lastIndexOf(".")+1));
prop.put("parser_" + parserIdx + "_status", parserIsEnabled ? 1:0);
allParsersEnabled &= parserIsEnabled;
parserIdx++;
}
prop.put("allParserEnabled",allParsersEnabled ? 1:0);
prop.put("parser", parserIdx);
// return rewrite properties
return prop;
}
|
diff --git a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
index 8bdf2c4..9a33898 100644
--- a/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
+++ b/src/main/java/hudson/plugins/active_directory/ActiveDirectoryUnixAuthenticationProvider.java
@@ -1,124 +1,124 @@
package hudson.plugins.active_directory;
import com.sun.jndi.ldap.LdapCtxFactory;
import hudson.plugins.active_directory.ActiveDirectorySecurityRealm.DesciprotrImpl;
import org.acegisecurity.AuthenticationException;
import org.acegisecurity.BadCredentialsException;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.GrantedAuthorityImpl;
import org.acegisecurity.providers.AuthenticationProvider;
import org.acegisecurity.providers.UsernamePasswordAuthenticationToken;
import org.acegisecurity.providers.dao.AbstractUserDetailsAuthenticationProvider;
import org.acegisecurity.userdetails.UserDetails;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.UsernameNotFoundException;
import org.springframework.dao.DataAccessException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.SearchControls;
import static javax.naming.directory.SearchControls.SUBTREE_SCOPE;
import javax.naming.directory.SearchResult;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link AuthenticationProvider} with Active Directory, through LDAP.
*
* @author Kohsuke Kawaguchi
*/
public class ActiveDirectoryUnixAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider
implements UserDetailsService {
private final String domainName;
public ActiveDirectoryUnixAuthenticationProvider(String domainName) {
this.domainName = domainName;
}
/**
* We'd like to implement {@link UserDetailsService} ideally, but in short of keeping the manager user/password,
* we can't do so. In Active Directory authentication, we should support SPNEGO/Kerberos and
* that should eliminate the need for the "remember me" service.
*/
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
throw new UsernameNotFoundException("Active-directory plugin doesn't support user retrieval");
}
protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
// active directory authentication is not by comparing clear text password,
// so there's nothing to do here.
}
protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance(
"ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/',
props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
if(!renum.hasMore())
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
SearchResult result = renum.next();
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {// null if this user belongs to no group at all
for(int i=0; i<memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
Attribute att = atts.get("CN");
groups.add(new GrantedAuthorityImpl(att.get().toString()));
}
}
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
- LOGGER.log(Level.WARNING,"Failed to retrieve user information",e);
- throw new BadCredentialsException("Authentication was successful but more than one users in the directory matches the user name: "+username,e);
+ LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e);
+ throw new BadCredentialsException("Failed to retrieve user information for "+username,e);
}
}
private static String toDC(String domainName) {
StringBuilder buf = new StringBuilder();
for (String token : domainName.split("\\.")) {
if(token.length()==0) continue; // defensive check
if(buf.length()>0) buf.append(",");
buf.append("DC=").append(token);
}
return buf.toString();
}
private static final Logger LOGGER = Logger.getLogger(ActiveDirectoryUnixAuthenticationProvider.class.getName());
}
| true | true | protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance(
"ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/',
props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
if(!renum.hasMore())
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
SearchResult result = renum.next();
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {// null if this user belongs to no group at all
for(int i=0; i<memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
Attribute att = atts.get("CN");
groups.add(new GrantedAuthorityImpl(att.get().toString()));
}
}
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information",e);
throw new BadCredentialsException("Authentication was successful but more than one users in the directory matches the user name: "+username,e);
}
}
| protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
String password = null;
if(authentication!=null)
password = (String) authentication.getCredentials();
// bind by using the specified username/password
Hashtable props = new Hashtable();
String principalName = username + '@' + domainName;
props.put(Context.SECURITY_PRINCIPAL, principalName);
props.put(Context.SECURITY_CREDENTIALS,password);
DirContext context;
try {
context = LdapCtxFactory.getLdapCtxInstance(
"ldap://" + DesciprotrImpl.INSTANCE.obtainLDAPServer(domainName) + '/',
props);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to bind to LDAP",e);
throw new BadCredentialsException("Either no such user '"+principalName+"' or incorrect password",e);
}
try {
// locate this user's record
SearchControls controls = new SearchControls();
controls.setSearchScope(SUBTREE_SCOPE);
NamingEnumeration<SearchResult> renum = context.search(toDC(domainName),"(& (userPrincipalName="+principalName+")(objectClass=user))", controls);
if(!renum.hasMore())
throw new BadCredentialsException("Authentication was successful but cannot locate the user information for "+username);
SearchResult result = renum.next();
List<GrantedAuthority> groups = new ArrayList<GrantedAuthority>();
Attribute memberOf = result.getAttributes().get("memberOf");
if(memberOf!=null) {// null if this user belongs to no group at all
for(int i=0; i<memberOf.size(); i++) {
Attributes atts = context.getAttributes(memberOf.get(i).toString(), new String[]{"CN"});
Attribute att = atts.get("CN");
groups.add(new GrantedAuthorityImpl(att.get().toString()));
}
}
context.close();
return new ActiveDirectoryUserDetail(
username, password,
true, true, true, true,
groups.toArray(new GrantedAuthority[groups.size()])
);
} catch (NamingException e) {
LOGGER.log(Level.WARNING,"Failed to retrieve user information for "+username,e);
throw new BadCredentialsException("Failed to retrieve user information for "+username,e);
}
}
|
diff --git a/src/com/web/server/WebServer.java b/src/com/web/server/WebServer.java
index 9cdfd13..b17a2c4 100644
--- a/src/com/web/server/WebServer.java
+++ b/src/com/web/server/WebServer.java
@@ -1,600 +1,602 @@
package com.web.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.StringTokenizer;
import org.apache.commons.digester.Digester;
import org.apache.commons.digester.xmlrules.DigesterLoader;
import org.apache.log4j.Logger;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.web.services.ATAConfig;
import com.web.services.ATAServer;
import com.web.services.ATAConfigClient;
import com.web.services.ExecutorServiceThread;
public class WebServer extends Thread implements Runnable {
HashMap urlClassLoaderMap;
Logger logger=Logger.getLogger(WebServer.class);
Socket socket;
int requestPort;
String deployDirectory;
int shutdownPort;
Digester serverdigester;
public WebServer(){
this.socket=null;
this.requestPort=0;
this.deployDirectory=null;
this.shutdownPort=0;
serverdigester=null;
}
public WebServer(Socket sock,int requestPort,String deployDirectory,int shutdownPort,Digester serverdigester,HashMap urlClassLoaderMap){
this.socket=sock;
this.requestPort=requestPort;
this.deployDirectory=deployDirectory;
this.shutdownPort=shutdownPort;
this.serverdigester=serverdigester;
this.urlClassLoaderMap=urlClassLoaderMap;
}
public void run(){
byte[] response;
byte[] content;
byte[] uploadData = null;
HttpHeaderClient httpHeaderClient;
InputStream istream = null;
OutputStream ostream = null;
HttpHeaderServer serverParam=new HttpHeaderServer();
byte[] bt=new byte[9999999];
String value;
char c;
String endvalue="\r\n\r\n";
String urlFormEncoded;
int responseCode;
try{
istream=socket.getInputStream();
for(int i=0;i<bt.length;i++){
bt[i]=-1;
}
int availbleStream;
int totalBytRead=0;
while((availbleStream=istream.available())>0){
//System.out.println("availableStream="+availbleStream);
bt[totalBytRead]=(byte)istream.read();
totalBytRead++;
}
int ch;
if(totalBytRead==0)return;
//istream.read(bt,0,9999999);
int index=containbytes(bt,endvalue.getBytes());
if(index==-1)index=totalBytRead;
value=new String(ObtainBytes(bt,0,index));
- //System.out.println("sock="+socket);
+ logger.info("value="+value);
httpHeaderClient=parseHttpHeaders(value);
//if(httpHeaderClient.get)
//System.out.println(httpHeaderClient.getResourceToObtain());
if(httpHeaderClient.getContentType()!=null&&
httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)){
uploadData=ObtainBytes(bt,index+endvalue.length(),index+endvalue.length()+Integer.parseInt(httpHeaderClient.getContentLength()));
//System.out.println(new String(uploadData));
HashMap paramMap=new MultipartFormData().parseContent(uploadData,httpHeaderClient);
httpHeaderClient.setParameters(paramMap);
//logger.info(uploadData);
}
else if(httpHeaderClient.getContentType()!=null&&httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)){
urlFormEncoded=new String(ObtainBytes(bt,index+endvalue.length(), index+endvalue.length()+Integer.parseInt(httpHeaderClient.getContentLength())));
HashMap paramMap=parseUrlEncoded(urlFormEncoded);
httpHeaderClient.setParameters(paramMap);
}
//logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
ostream=socket.getOutputStream();
- logger.info(new String(bt));
+ //logger.info(new String(bt));
serverParam.setContentType("text/html");
URLDecoder decoder=new URLDecoder();
//System.out.println("content Length= "+socket);
responseCode=200;
content=ObtainContentExecutor(deployDirectory,httpHeaderClient.getResourceToObtain(),httpHeaderClient,serverdigester);
//System.out.println("content Length2= ");
if(content==null)content=obtainContent(deployDirectory+decoder.decode(httpHeaderClient.getResourceToObtain()));
if(content==null){
responseCode=404;
content=("<html><body><H1>The Request resource "+httpHeaderClient.resourceToObtain+" Not Found</H1><body></html>").getBytes();
}
//System.out.println("content Length3= ");
serverParam.setContentLength(""+content.length);
if(httpHeaderClient.getResourceToObtain().endsWith(".ico")){
serverParam.setContentType("image/png");
}
//System.out.println("content Length4= ");
response=formHttpResponseHeader(responseCode,serverParam,content);
- //System.out.println("Response="+new String(response));
+ //logger.info("Response="+new String(response));
//System.out.println("content Length= "+content.length);
ostream.write(response);
- ostream.flush();
+ //ostream.flush();
ostream.close();
+ socket.close();
}
catch (IOException e) {
Socket socket;
+ logger.error(e);
try {
socket = new Socket("localhost",shutdownPort);
OutputStream outputStream=socket.getOutputStream();
outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private byte[] ObtainBytes(byte[] content,int start,int end) throws Exception{
if(start>=end){
throw new Exception("Start byte should be lesser than end byte");
}
byte[] resultBt=new byte[end-start];
for(int count=start;count<end;count++){
resultBt[count-start]=content[count];
}
return resultBt;
}
private int containbytes(byte[] byt1,byte[] byt2){
int count=0;
boolean isEqual=true;
for(count=0;count<byt1.length;count++){
isEqual=true;
for(int secondbytcount=0;secondbytcount<byt2.length;secondbytcount++){
if(byt1[count+secondbytcount]!=byt2[secondbytcount]){
isEqual=false;
break;
}
}
if(isEqual){
return count;
}
}
return -1;
}
/**
* @param args
* @throws IOException
* @throws SAXException
*/
public static void main(String[] args) throws IOException, SAXException {
HashMap urlClassLoaderMap=new HashMap();
HashMap executorServicesMap=new HashMap();
HashMap ataMap=new HashMap<String,ATAConfig>();
Digester serverdigester = DigesterLoader.createDigester(new InputSource(new FileInputStream("./config/serverconfig-rules.xml")));
ServerConfig serverconfig=(ServerConfig)serverdigester.parse(new InputSource(new FileInputStream("./config/serverconfig.xml")));
//System.out.println(serverconfig.getPort());;
//System.out.println(serverconfig.getDeploydirectory());
WarDeployer warDeployer=new WarDeployer(serverconfig.getDeploydirectory(),urlClassLoaderMap,executorServicesMap);
warDeployer.start();
byte[] shutdownBt=new byte[50];
WebServerRequestProcessor webserverRequestProcessor=new WebServer().new WebServerRequestProcessor(urlClassLoaderMap,Integer.parseInt(serverconfig.getPort()),serverconfig.getDeploydirectory(),Integer.parseInt(serverconfig.getShutdownport()));
webserverRequestProcessor.start();
ExecutorServiceThread executorService=new ExecutorServiceThread(Integer.parseInt(serverconfig.getServicesport()),executorServicesMap,Integer.parseInt(serverconfig.getShutdownport()),ataMap);
executorService.start();
ATAServer ataServer=new ATAServer(serverconfig.getAtaaddress(),serverconfig.getAtaport(),ataMap);
ataServer.start();
ATAConfigClient ataClient=new ATAConfigClient(serverconfig.getAtaaddress(),serverconfig.getAtaport(),serverconfig.getServicesport(),executorServicesMap);
ataClient.start();
try {
ServerSocket serverSocket=new ServerSocket(Integer.parseInt(serverconfig.getShutdownport()));
while(true){
Socket sock=serverSocket.accept();
InputStream istream=sock.getInputStream();
istream.read(shutdownBt);
String shutdownStr=new String(shutdownBt);
String[] shutdownToken=shutdownStr.split("\r\n\r\n");
System.out.println(shutdownStr);
if(shutdownToken[0].startsWith("shutdown WebServer")){
break;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
webserverRequestProcessor.stop();
warDeployer.stop();
executorService.stop();
ataServer.stop();
ataClient.stop();
System.exit(0);
}
public HashMap parseUrlEncoded(String urlEncoded){
HashMap ParamValue=new HashMap();
URLDecoder urlDecoder=new URLDecoder();
StringTokenizer paramGroup = new StringTokenizer(urlDecoder.decode(urlEncoded), "&");
while(paramGroup.hasMoreTokens()){
StringTokenizer token= new StringTokenizer(paramGroup.nextToken(), "=");
String key="";
String value="";
if(token.hasMoreTokens())key=token.nextToken();
if(token.hasMoreTokens())value=token.nextToken();
ParamValue.put(key, value);
}
return ParamValue;
}
public byte[] ObtainContentExecutor(String deployDirectory,String resource,HttpHeaderClient httpHeaderClient,Digester serverdigester){
//System.out.println("In content Executor");
String[] resourcepath=resource.split("/");
//System.out.println("createDigester1");
Method method = null;
//System.out.println("createDigester2");
System.out.println();
Executors serverconfig;
if(resourcepath.length>1)
{
//System.out.println(resource);
try {
File file=new File(deployDirectory+"/"+resourcepath[1]+"/WEB-INF/executor-config.xml");
synchronized(serverdigester){
serverconfig=(Executors)serverdigester.parse(file);
}
HashMap urlMap=serverconfig.executorMap;
// System.out.println("ObtainUrlFromResource1");
String urlresource=ObtainUrlFromResource(resourcepath);
logger.info("urlresource"+urlresource);
Executor executor=(Executor) urlMap.get(urlresource);
WebClassLoader customClassLoader=null;
Class customClass=null;
System.out.println("ObtainUrlFromResource2"+executor);
synchronized(urlClassLoaderMap){
// System.out.println("custom class Loader1"+urlClassLoaderMap);
customClassLoader=(WebClassLoader) urlClassLoaderMap.get(deployDirectory+"/"+resourcepath[1]);
// System.out.println("custom class Loader2"+customClassLoader);
}
if(customClassLoader==null){
return null;
}
//System.out.println("CUSTOM CLASS lOADER path"+deployDirectory+"/"+resourcepath[1]);
//System.out.println("custom class loader" +customClassLoader);
if(executor==null){
//System.out.println("url resource"+urlresource);
String resourceClass=(String)customClassLoader.getClassMap().get(urlresource);
//System.out.println(resourceClass);
//System.out.println(customClassLoader.getClassMap());
if(resourceClass==null)return null;
customClass=customClassLoader.loadClass(resourceClass);
if(customClass==null)return null;
}
else customClass=customClassLoader.loadClass(executor.getExecutorclass());
logger.info(customClass.getClass());
/*if(httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("GET")||(executor==null&&customClass!=null)){
method= customClass.getDeclaredMethod("doGet", new Class[]{HttpHeaderClient.class});
}
else if(httpHeaderClient.getHttpMethod().trim().toUpperCase().equals("POST")){
method= customClass.getDeclaredMethod("doPost", new Class[]{HttpHeaderClient.class});
}*/
//method.setAccessible(false);
ExecutorInterface executorInstance=(ExecutorInterface)customClass.newInstance();
Object buffer =executorInstance.doGet(httpHeaderClient);
if(executor!=null&&executor.getResponseResource()!=null){
// System.out.println("executor resource"+executor.getResponseResource());
String resourceClass=(String)customClassLoader.getClassMap().get(executor.getResponseResource().trim());
customClass=customClassLoader.loadClass(resourceClass);
executorInstance=(ExecutorInterface)customClass.newInstance();
buffer =executorInstance.doGet(httpHeaderClient);
}
//System.out.println("executor resource 1");
//Object buffer = method.invoke(customClass.newInstance(), new Object[]{httpHeaderClient});
return buffer.toString().getBytes();
// logger.info(buffer.toString());
} catch (IOException | SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /*catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
private String ObtainUrlFromResource(String[] resource){
if(resource!=null&&resource.length>2){
StringBuffer resourcepath=new StringBuffer();
for(int resourcepathcount=2;resourcepathcount<resource.length;resourcepathcount++){
resourcepath.append("/");
resourcepath.append(resource[resourcepathcount]);
}
return resourcepath.toString();
}
return "";
}
public HttpHeaderClient parseHttpHeaders(String httpheader){
char c=(char)13;
String[] header=httpheader.split(""+c);
HttpHeaderClient httpClient=new HttpHeaderClient();
String httpHeader=header[0];
String[] httpHeaderArray=httpHeader.split(" ");
httpClient.setHttpMethod(httpHeaderArray[0]);
HashMap urlParams=new HashMap();
httpClient.setResourceToObtain(ObtainUrlAndParams(httpHeaderArray[1],urlParams));
httpClient.setParameters(urlParams);
httpClient.setHttpVersion(httpHeaderArray[2]);
String tmpHeader;
String[] headerParam;
String boundary;
String boundaryValue;
for(int i=1;i<header.length;i++){
tmpHeader=header[i];
logger.info(tmpHeader);
headerParam=splitHeaderParams(tmpHeader);
if(headerParam[0].equals(HttpHeaderParamNames.HOST)){
httpClient.setHost(headerParam[1]);
}
else if(headerParam[0].equals(HttpHeaderParamNames.ACCEPT)){
httpClient.setAcceptResource(headerParam[1]);
}
else if(headerParam[0].equals(HttpHeaderParamNames.ACCEPT_ENCODING)){
httpClient.setAcceptEncoding(headerParam[1]);
}
else if(headerParam[0].equals(HttpHeaderParamNames.ACCEPT_LANGUAGE)){
httpClient.setAcceptLanguage(headerParam[1]);
}
else if(headerParam[0].equals(HttpHeaderParamNames.CONNECTION)){
httpClient.setConnection(headerParam[1]);
}
else if(headerParam[0].equals(HttpHeaderParamNames.USERAGENT)){
httpClient.setUserAgent(headerParam[1]);
}
else if(headerParam[0].equals(HttpHeaderParamNames.CONTENTLENGTH)){
httpClient.setContentLength(headerParam[1]);
}
else if(headerParam[0].equals(HttpHeaderParamNames.CONTENTTYPE)){
String[] headerParamValue=headerParam[1].split(";");
httpClient.setContentType(headerParamValue[0].trim());
if(headerParamValue!=null&&headerParamValue.length>1){
if(httpClient.getContentType().equalsIgnoreCase(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)){
if(headerParamValue[1].contains(HttpHeaderParamNames.BOUNDARY)){
int equalToIndexInBoundary=headerParamValue[1].indexOf('=');
boundary=headerParamValue[1].substring(0,equalToIndexInBoundary).trim();
boundaryValue=headerParamValue[1].substring(equalToIndexInBoundary+1).trim();
httpClient.setBoundary(boundaryValue);
}
}
}
}
}
return httpClient;
}
public String ObtainUrlAndParams(String url,HashMap params){
URLDecoder decoder=new URLDecoder();
url=decoder.decode(url);
if (url.indexOf("?") > -1) {
String paramaters = url.substring(url.indexOf("?") + 1);
StringTokenizer paramGroup = new StringTokenizer(paramaters, "&");
while(paramGroup.hasMoreTokens()){
StringTokenizer value = new StringTokenizer(paramGroup.nextToken(), "=");
String param=null;
if(value.hasMoreTokens()){
param=value.nextToken();
}
String paramValue=null;
if(value.hasMoreTokens()){
paramValue=value.nextToken();
}
params.put(param,paramValue);
}
}
if(url.indexOf("?")!=-1){
return url.substring(0,url.indexOf("?"));
}
return url;
}
public String[] splitHeaderParams(String headerParams){
int indexToSplit=headerParams.indexOf(":");
String[] param=new String[2];
param[0]=headerParams.substring(0,indexToSplit).trim();
param[1]=headerParams.substring(indexToSplit+1).trim();
return param;
}
private byte[] formHttpResponseHeader(int responseCode,HttpHeaderServer httpHeader,byte[] content){
StringBuffer buffer=new StringBuffer();
String colon=": ";
String crlf="\r\n";
if(responseCode==200){
buffer.append("HTTP/1.1 200 OK");
buffer.append(crlf);
buffer.append(HttpHeaderServerParamNames.DATE);
buffer.append(colon);
buffer.append(httpHeader.getDate());
buffer.append(crlf);
buffer.append(HttpHeaderServerParamNames.SERVER);
buffer.append(colon);
buffer.append(httpHeader.getServer());
buffer.append(crlf);
buffer.append(HttpHeaderServerParamNames.CONTENT_TYPE);
buffer.append(colon);
buffer.append(httpHeader.getContentType());
buffer.append(crlf);
buffer.append(HttpHeaderServerParamNames.CONTENT_LENGTH);
buffer.append(colon);
buffer.append(httpHeader.getContentLength());
buffer.append(crlf);
buffer.append(HttpHeaderServerParamNames.LAST_MODIFIED);
buffer.append(colon);
buffer.append(httpHeader.getLastModified());
}
else if(responseCode==404){
buffer.append("HTTP/1.1 404 Not Found");
}
buffer.append(crlf);
buffer.append(crlf);
byte[] byt1=buffer.toString().getBytes();
byte[] byt2=new byte[byt1.length+content.length];
///System.out.println("Header="+new String(byt1));
for(int count=0;count<byt1.length;count++){
byt2[count]=byt1[count];
}
for(int count=0;count<content.length;count++){
byt2[count+byt1.length]=content[count];
}
//System.out.println("Header with content="+new String(byt2));
/*try {
buffer.append(new String(content, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
return byt2;
}
private byte[] obtainContent(String filepath){
byte[] filebt = null;
try {
File file=new File(filepath);
FileInputStream stream=new FileInputStream(filepath);
filebt=new byte[(int) file.length()];
stream.read(filebt,0,(int)file.length());
stream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
filebt=null;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
filebt=null;
e.printStackTrace();
}
catch(Exception ex){
filebt=null;
ex.printStackTrace();
}
return filebt;
}
public void addURL(URL url,WebClassLoader customClassLoader) throws IOException {
try {
customClassLoader.addURL(url);
} catch (Throwable t) {
t.printStackTrace();
}//end try catch
}//end method
class WebServerRequestProcessor extends Thread implements Runnable{
int requestPort;
String deployDirectory;
int shutdownPort;
HashMap urlClassLoaderMap;
public WebServerRequestProcessor(){
}
public WebServerRequestProcessor(HashMap urlClassLoaderMap,int requestPort,String deployDirectory,int shutdownPort){
this.requestPort=requestPort;
this.deployDirectory=deployDirectory;
this.shutdownPort=shutdownPort;
this.urlClassLoaderMap=urlClassLoaderMap;
}
public void run(){
ServerSocket serverSocket = null;
Socket sock=new Socket();
try {
serverSocket=new ServerSocket(this.requestPort);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Digester serverdigester = null;
try {
serverdigester = DigesterLoader.createDigester(new InputSource(new FileInputStream("./config/executorconfig-rules.xml")));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true){
try{
sock=serverSocket.accept();
//System.out.println("A new Socket="+sock);
WebServer webserver=new WebServer(sock,this.requestPort,this.deployDirectory,this.shutdownPort,serverdigester,urlClassLoaderMap);
webserver.start();
}
catch(Exception ex){
try {
socket = new Socket("localhost",shutdownPort);
OutputStream outputStream=socket.getOutputStream();
outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
}
| false | true | public void run(){
byte[] response;
byte[] content;
byte[] uploadData = null;
HttpHeaderClient httpHeaderClient;
InputStream istream = null;
OutputStream ostream = null;
HttpHeaderServer serverParam=new HttpHeaderServer();
byte[] bt=new byte[9999999];
String value;
char c;
String endvalue="\r\n\r\n";
String urlFormEncoded;
int responseCode;
try{
istream=socket.getInputStream();
for(int i=0;i<bt.length;i++){
bt[i]=-1;
}
int availbleStream;
int totalBytRead=0;
while((availbleStream=istream.available())>0){
//System.out.println("availableStream="+availbleStream);
bt[totalBytRead]=(byte)istream.read();
totalBytRead++;
}
int ch;
if(totalBytRead==0)return;
//istream.read(bt,0,9999999);
int index=containbytes(bt,endvalue.getBytes());
if(index==-1)index=totalBytRead;
value=new String(ObtainBytes(bt,0,index));
//System.out.println("sock="+socket);
httpHeaderClient=parseHttpHeaders(value);
//if(httpHeaderClient.get)
//System.out.println(httpHeaderClient.getResourceToObtain());
if(httpHeaderClient.getContentType()!=null&&
httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)){
uploadData=ObtainBytes(bt,index+endvalue.length(),index+endvalue.length()+Integer.parseInt(httpHeaderClient.getContentLength()));
//System.out.println(new String(uploadData));
HashMap paramMap=new MultipartFormData().parseContent(uploadData,httpHeaderClient);
httpHeaderClient.setParameters(paramMap);
//logger.info(uploadData);
}
else if(httpHeaderClient.getContentType()!=null&&httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)){
urlFormEncoded=new String(ObtainBytes(bt,index+endvalue.length(), index+endvalue.length()+Integer.parseInt(httpHeaderClient.getContentLength())));
HashMap paramMap=parseUrlEncoded(urlFormEncoded);
httpHeaderClient.setParameters(paramMap);
}
//logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
ostream=socket.getOutputStream();
logger.info(new String(bt));
serverParam.setContentType("text/html");
URLDecoder decoder=new URLDecoder();
//System.out.println("content Length= "+socket);
responseCode=200;
content=ObtainContentExecutor(deployDirectory,httpHeaderClient.getResourceToObtain(),httpHeaderClient,serverdigester);
//System.out.println("content Length2= ");
if(content==null)content=obtainContent(deployDirectory+decoder.decode(httpHeaderClient.getResourceToObtain()));
if(content==null){
responseCode=404;
content=("<html><body><H1>The Request resource "+httpHeaderClient.resourceToObtain+" Not Found</H1><body></html>").getBytes();
}
//System.out.println("content Length3= ");
serverParam.setContentLength(""+content.length);
if(httpHeaderClient.getResourceToObtain().endsWith(".ico")){
serverParam.setContentType("image/png");
}
//System.out.println("content Length4= ");
response=formHttpResponseHeader(responseCode,serverParam,content);
//System.out.println("Response="+new String(response));
//System.out.println("content Length= "+content.length);
ostream.write(response);
ostream.flush();
ostream.close();
}
catch (IOException e) {
Socket socket;
try {
socket = new Socket("localhost",shutdownPort);
OutputStream outputStream=socket.getOutputStream();
outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void run(){
byte[] response;
byte[] content;
byte[] uploadData = null;
HttpHeaderClient httpHeaderClient;
InputStream istream = null;
OutputStream ostream = null;
HttpHeaderServer serverParam=new HttpHeaderServer();
byte[] bt=new byte[9999999];
String value;
char c;
String endvalue="\r\n\r\n";
String urlFormEncoded;
int responseCode;
try{
istream=socket.getInputStream();
for(int i=0;i<bt.length;i++){
bt[i]=-1;
}
int availbleStream;
int totalBytRead=0;
while((availbleStream=istream.available())>0){
//System.out.println("availableStream="+availbleStream);
bt[totalBytRead]=(byte)istream.read();
totalBytRead++;
}
int ch;
if(totalBytRead==0)return;
//istream.read(bt,0,9999999);
int index=containbytes(bt,endvalue.getBytes());
if(index==-1)index=totalBytRead;
value=new String(ObtainBytes(bt,0,index));
logger.info("value="+value);
httpHeaderClient=parseHttpHeaders(value);
//if(httpHeaderClient.get)
//System.out.println(httpHeaderClient.getResourceToObtain());
if(httpHeaderClient.getContentType()!=null&&
httpHeaderClient.getContentType().equals(HttpHeaderParamNames.MULTIPARTFORMDATAVALUE)){
uploadData=ObtainBytes(bt,index+endvalue.length(),index+endvalue.length()+Integer.parseInt(httpHeaderClient.getContentLength()));
//System.out.println(new String(uploadData));
HashMap paramMap=new MultipartFormData().parseContent(uploadData,httpHeaderClient);
httpHeaderClient.setParameters(paramMap);
//logger.info(uploadData);
}
else if(httpHeaderClient.getContentType()!=null&&httpHeaderClient.getContentType().equals(HttpHeaderParamNames.URLENCODED)){
urlFormEncoded=new String(ObtainBytes(bt,index+endvalue.length(), index+endvalue.length()+Integer.parseInt(httpHeaderClient.getContentLength())));
HashMap paramMap=parseUrlEncoded(urlFormEncoded);
httpHeaderClient.setParameters(paramMap);
}
//logger.info(serverconfig.getDeploydirectory()+httpHeaderClient.getResourceToObtain());
ostream=socket.getOutputStream();
//logger.info(new String(bt));
serverParam.setContentType("text/html");
URLDecoder decoder=new URLDecoder();
//System.out.println("content Length= "+socket);
responseCode=200;
content=ObtainContentExecutor(deployDirectory,httpHeaderClient.getResourceToObtain(),httpHeaderClient,serverdigester);
//System.out.println("content Length2= ");
if(content==null)content=obtainContent(deployDirectory+decoder.decode(httpHeaderClient.getResourceToObtain()));
if(content==null){
responseCode=404;
content=("<html><body><H1>The Request resource "+httpHeaderClient.resourceToObtain+" Not Found</H1><body></html>").getBytes();
}
//System.out.println("content Length3= ");
serverParam.setContentLength(""+content.length);
if(httpHeaderClient.getResourceToObtain().endsWith(".ico")){
serverParam.setContentType("image/png");
}
//System.out.println("content Length4= ");
response=formHttpResponseHeader(responseCode,serverParam,content);
//logger.info("Response="+new String(response));
//System.out.println("content Length= "+content.length);
ostream.write(response);
//ostream.flush();
ostream.close();
socket.close();
}
catch (IOException e) {
Socket socket;
logger.error(e);
try {
socket = new Socket("localhost",shutdownPort);
OutputStream outputStream=socket.getOutputStream();
outputStream.write("shutdown WebServer\r\n\r\n".getBytes());
outputStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/main/java/cz/startnet/utils/pgdiff/parsers/CreateTriggerParser.java b/src/main/java/cz/startnet/utils/pgdiff/parsers/CreateTriggerParser.java
index 8759062..341628e 100644
--- a/src/main/java/cz/startnet/utils/pgdiff/parsers/CreateTriggerParser.java
+++ b/src/main/java/cz/startnet/utils/pgdiff/parsers/CreateTriggerParser.java
@@ -1,92 +1,93 @@
package cz.startnet.utils.pgdiff.parsers;
import cz.startnet.utils.pgdiff.schema.PgDatabase;
import cz.startnet.utils.pgdiff.schema.PgTrigger;
/**
* Parses CREATE TRIGGER commands.
*
* @author fordfrog
*/
public class CreateTriggerParser {
/**
* Creates a new CreateTableParser object.
*/
private CreateTriggerParser() {
}
/**
* Parses CREATE TRIGGER command.
*
* @param database database
* @param command CREATE TRIGGER command
*
* @throws ParserException Thrown if problem occured while parsing the
* command.
*/
public static void parse(final PgDatabase database, final String command) {
final Parser parser = new Parser(command);
parser.expect("CREATE", "TRIGGER");
final PgTrigger trigger = new PgTrigger();
trigger.setName(parser.parseIdentifier());
if (parser.expectOptional("BEFORE")) {
trigger.setBefore(true);
} else if (parser.expectOptional("AFTER")) {
trigger.setBefore(false);
}
boolean first = true;
while (true) {
if (!first && !parser.expectOptional("OR")) {
break;
}
if (parser.expectOptional("INSERT")) {
trigger.setOnInsert(true);
} else if (parser.expectOptional("UPDATE")) {
trigger.setOnUpdate(true);
} else if (parser.expectOptional("DELETE")) {
trigger.setOnDelete(true);
} else if (parser.expectOptional("TRUNCATE")) {
trigger.setOnTruncate(true);
} else if (first) {
break;
} else {
parser.throwUnsupportedCommand();
}
first = false;
}
parser.expect("ON");
- trigger.setTableName(parser.parseIdentifier());
+ trigger.setTableName(
+ ParserUtils.getObjectName(parser.parseIdentifier()));
if (parser.expectOptional("FOR")) {
parser.expectOptional("EACH");
if (parser.expectOptional("ROW")) {
trigger.setForEachRow(true);
} else if (parser.expectOptional("STATEMENT")) {
trigger.setForEachRow(false);
} else {
parser.throwUnsupportedCommand();
}
}
if (parser.expectOptional("WHEN")) {
parser.expect("(");
trigger.setWhen(parser.getExpression());
parser.expect(")");
}
parser.expect("EXECUTE", "PROCEDURE");
trigger.setFunction(parser.getRest());
database.getDefaultSchema().getTable(
trigger.getTableName()).addTrigger(trigger);
}
}
| true | true | public static void parse(final PgDatabase database, final String command) {
final Parser parser = new Parser(command);
parser.expect("CREATE", "TRIGGER");
final PgTrigger trigger = new PgTrigger();
trigger.setName(parser.parseIdentifier());
if (parser.expectOptional("BEFORE")) {
trigger.setBefore(true);
} else if (parser.expectOptional("AFTER")) {
trigger.setBefore(false);
}
boolean first = true;
while (true) {
if (!first && !parser.expectOptional("OR")) {
break;
}
if (parser.expectOptional("INSERT")) {
trigger.setOnInsert(true);
} else if (parser.expectOptional("UPDATE")) {
trigger.setOnUpdate(true);
} else if (parser.expectOptional("DELETE")) {
trigger.setOnDelete(true);
} else if (parser.expectOptional("TRUNCATE")) {
trigger.setOnTruncate(true);
} else if (first) {
break;
} else {
parser.throwUnsupportedCommand();
}
first = false;
}
parser.expect("ON");
trigger.setTableName(parser.parseIdentifier());
if (parser.expectOptional("FOR")) {
parser.expectOptional("EACH");
if (parser.expectOptional("ROW")) {
trigger.setForEachRow(true);
} else if (parser.expectOptional("STATEMENT")) {
trigger.setForEachRow(false);
} else {
parser.throwUnsupportedCommand();
}
}
if (parser.expectOptional("WHEN")) {
parser.expect("(");
trigger.setWhen(parser.getExpression());
parser.expect(")");
}
parser.expect("EXECUTE", "PROCEDURE");
trigger.setFunction(parser.getRest());
database.getDefaultSchema().getTable(
trigger.getTableName()).addTrigger(trigger);
}
| public static void parse(final PgDatabase database, final String command) {
final Parser parser = new Parser(command);
parser.expect("CREATE", "TRIGGER");
final PgTrigger trigger = new PgTrigger();
trigger.setName(parser.parseIdentifier());
if (parser.expectOptional("BEFORE")) {
trigger.setBefore(true);
} else if (parser.expectOptional("AFTER")) {
trigger.setBefore(false);
}
boolean first = true;
while (true) {
if (!first && !parser.expectOptional("OR")) {
break;
}
if (parser.expectOptional("INSERT")) {
trigger.setOnInsert(true);
} else if (parser.expectOptional("UPDATE")) {
trigger.setOnUpdate(true);
} else if (parser.expectOptional("DELETE")) {
trigger.setOnDelete(true);
} else if (parser.expectOptional("TRUNCATE")) {
trigger.setOnTruncate(true);
} else if (first) {
break;
} else {
parser.throwUnsupportedCommand();
}
first = false;
}
parser.expect("ON");
trigger.setTableName(
ParserUtils.getObjectName(parser.parseIdentifier()));
if (parser.expectOptional("FOR")) {
parser.expectOptional("EACH");
if (parser.expectOptional("ROW")) {
trigger.setForEachRow(true);
} else if (parser.expectOptional("STATEMENT")) {
trigger.setForEachRow(false);
} else {
parser.throwUnsupportedCommand();
}
}
if (parser.expectOptional("WHEN")) {
parser.expect("(");
trigger.setWhen(parser.getExpression());
parser.expect(")");
}
parser.expect("EXECUTE", "PROCEDURE");
trigger.setFunction(parser.getRest());
database.getDefaultSchema().getTable(
trigger.getTableName()).addTrigger(trigger);
}
|
diff --git a/bundles/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/diagram/palette/CustomMainPaletteViewer.java b/bundles/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/diagram/palette/CustomMainPaletteViewer.java
index 934b6a80a6..ed366d1ade 100644
--- a/bundles/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/diagram/palette/CustomMainPaletteViewer.java
+++ b/bundles/plugins/org.bonitasoft.studio.common.diagram/src/org/bonitasoft/studio/common/diagram/palette/CustomMainPaletteViewer.java
@@ -1,183 +1,183 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2.0 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.bonitasoft.studio.common.diagram.palette;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.LightweightSystem;
import org.eclipse.draw2d.StackLayout;
import org.eclipse.gef.editparts.SimpleRootEditPart;
import org.eclipse.gef.internal.ui.palette.editparts.ToolEntryEditPart;
import org.eclipse.gef.palette.PaletteDrawer;
import org.eclipse.gef.palette.PaletteEntry;
import org.eclipse.gef.palette.PaletteListener;
import org.eclipse.gef.palette.PaletteRoot;
import org.eclipse.gef.palette.ToolEntry;
import org.eclipse.gmf.runtime.gef.ui.palette.customize.PaletteViewerEx;
import org.eclipse.jface.action.MenuManager;
/**
* @author Romain Bioteau
*
*/
public class CustomMainPaletteViewer extends PaletteViewerEx {
private Set<String> filters = new HashSet<String>();
private String onlyDisplayedEntry;
protected ToolEntry activeEntry = null;
private List paletteListeners = new ArrayList();
private CustomToolPaletteViewer toolPalette;
public CustomMainPaletteViewer(){
setEditPartFactory(new CustomPaletteEditPartFactory());
}
protected void createDefaultRoot() {
setRootEditPart(new SimpleRootEditPart(){
@Override
protected IFigure createFigure() {
Figure figure = new Figure();
figure.setLayoutManager(new StackLayout());
return figure;
}
});
}
protected LightweightSystem createLightweightSystem() {
return new AsyncLightweightSystem();
}
public void hidePaletteEntry(String id){
filters.add(id);
}
@Override
public void addPaletteListener(PaletteListener paletteListener) {
if (paletteListeners != null)
paletteListeners.add(paletteListener);
}
public void removePaletteListener(PaletteListener paletteListener) {
paletteListeners.remove(paletteListener);
}
@Override
public void setPaletteRoot(PaletteRoot root) {
if (root == getPaletteRoot())
return;
super.setPaletteRoot(root);
if (getPaletteRoot() != null) {
final PaletteRoot filteredPalette = filterPaletteRoot(getPaletteRoot());
for(Object c : filteredPalette.getChildren()){
if(c instanceof PaletteDrawer){
((PaletteDrawer)c).setShowDefaultIcon(false);
((PaletteDrawer)c).setUserModificationPermission(PaletteDrawer.PERMISSION_NO_MODIFICATION);
}
}
getRootEditPart().setContents(getEditPartFactory().createEditPart(
getRootEditPart(),filteredPalette));
}
}
@Override
public void setContextMenu(MenuManager contextMenu) {
}
public void setActiveTool(ToolEntry newMode) {
if (newMode == null)
newMode = getPaletteRoot().getDefaultEntry();
if(newMode.equals(activeEntry) ){
fireModeChanged();
return;
}
if (activeEntry != null){
final ToolEntryEditPart toolEntryEditPart = getToolEntryEditPart(activeEntry);
if(toolEntryEditPart != null){
toolEntryEditPart.setToolSelected(false);
}
}
activeEntry = newMode;
if (activeEntry != null) {
ToolEntryEditPart editpart = getToolEntryEditPart(activeEntry);
if (editpart != null) {
editpart.setToolSelected(true);
}
}
fireModeChanged();
- if(toolPalette != null){
+ if(toolPalette != null && getControl() != null && !getControl().isDisposed()){
setEditDomain(toolPalette.getEditDomain());
toolPalette.setActiveTool(newMode);
}
}
/**
* @return the entry for the currently active tool
*/
public ToolEntry getActiveTool() {
return activeEntry;
}
protected void fireModeChanged() {
if (paletteListeners == null)
return;
for (int listener = 0; listener < paletteListeners.size(); listener++){
((PaletteListener) paletteListeners.get(listener)).activeToolChanged(this, activeEntry);
}
}
protected ToolEntryEditPart getToolEntryEditPart(ToolEntry entry) {
return (ToolEntryEditPart) getEditPartRegistry().get(entry);
}
private PaletteRoot filterPaletteRoot(PaletteRoot paletteRoot) {
PaletteRoot newRoot = new PaletteRoot();
for(Object child : paletteRoot.getChildren()){
if(child instanceof PaletteEntry){
final String id = ((PaletteEntry) child).getId();
if(onlyDisplayedEntry != null && onlyDisplayedEntry.equals(id)) {
newRoot.add((PaletteEntry) child);
break;
}else if(!filters.contains(id)){
newRoot.add((PaletteEntry) child);
}
}
}
return newRoot;
}
public void showOnlyPaletteEntry(String onlyDisplayedEntry) {
this.onlyDisplayedEntry = onlyDisplayedEntry;
}
public void setToolPaletteViewer(CustomToolPaletteViewer toolPalette) {
this.toolPalette = toolPalette;
}
}
| true | true | public void setActiveTool(ToolEntry newMode) {
if (newMode == null)
newMode = getPaletteRoot().getDefaultEntry();
if(newMode.equals(activeEntry) ){
fireModeChanged();
return;
}
if (activeEntry != null){
final ToolEntryEditPart toolEntryEditPart = getToolEntryEditPart(activeEntry);
if(toolEntryEditPart != null){
toolEntryEditPart.setToolSelected(false);
}
}
activeEntry = newMode;
if (activeEntry != null) {
ToolEntryEditPart editpart = getToolEntryEditPart(activeEntry);
if (editpart != null) {
editpart.setToolSelected(true);
}
}
fireModeChanged();
if(toolPalette != null){
setEditDomain(toolPalette.getEditDomain());
toolPalette.setActiveTool(newMode);
}
}
| public void setActiveTool(ToolEntry newMode) {
if (newMode == null)
newMode = getPaletteRoot().getDefaultEntry();
if(newMode.equals(activeEntry) ){
fireModeChanged();
return;
}
if (activeEntry != null){
final ToolEntryEditPart toolEntryEditPart = getToolEntryEditPart(activeEntry);
if(toolEntryEditPart != null){
toolEntryEditPart.setToolSelected(false);
}
}
activeEntry = newMode;
if (activeEntry != null) {
ToolEntryEditPart editpart = getToolEntryEditPart(activeEntry);
if (editpart != null) {
editpart.setToolSelected(true);
}
}
fireModeChanged();
if(toolPalette != null && getControl() != null && !getControl().isDisposed()){
setEditDomain(toolPalette.getEditDomain());
toolPalette.setActiveTool(newMode);
}
}
|
diff --git a/src/main/java/com/alecgorge/minecraft/jsonapi/packets/PacketRegistrar.java b/src/main/java/com/alecgorge/minecraft/jsonapi/packets/PacketRegistrar.java
index e3f00bb..194f5bf 100644
--- a/src/main/java/com/alecgorge/minecraft/jsonapi/packets/PacketRegistrar.java
+++ b/src/main/java/com/alecgorge/minecraft/jsonapi/packets/PacketRegistrar.java
@@ -1,52 +1,52 @@
package com.alecgorge.minecraft.jsonapi.packets;
import java.lang.reflect.Method;
import java.util.logging.Logger;
import net.minecraft.server.v1_4_R1.Packet;
public class PacketRegistrar {
static Method registrationMethod = null;
public static void register(int packetID, boolean isClientPacket, boolean isServerPacket, Class<? extends Packet> packetClass) {
if(registrationMethod == null) {
registrationMethod = findRegistrationMethod();
}
// is it still null?
if(registrationMethod == null) {
Logger.getLogger("Minecraft").warning("Couldn't find the packet registration method!");
}
else {
try {
if(Packet.l.get(packetID) != null) {
Packet.l.d(packetID); // remove the current packet registration if it exists
}
registrationMethod.invoke(null, new Object[] { packetID, isClientPacket, isServerPacket, packetClass });
} catch (Exception e) {
- e.printStackTrace();
+ // just smoosh the error, we are probably reloading
}
}
}
static Method findRegistrationMethod() {
try {
Class<Packet> p = Packet.class;
Method m = p.getDeclaredMethod("a", new Class<?>[] { Integer.TYPE, Boolean.TYPE, Boolean.TYPE, Class.class });
m.setAccessible(true);
return m;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void register(int packetID, Class<? extends Packet> packetClass) {
register(packetID, false, true, packetClass);
}
}
| true | true | public static void register(int packetID, boolean isClientPacket, boolean isServerPacket, Class<? extends Packet> packetClass) {
if(registrationMethod == null) {
registrationMethod = findRegistrationMethod();
}
// is it still null?
if(registrationMethod == null) {
Logger.getLogger("Minecraft").warning("Couldn't find the packet registration method!");
}
else {
try {
if(Packet.l.get(packetID) != null) {
Packet.l.d(packetID); // remove the current packet registration if it exists
}
registrationMethod.invoke(null, new Object[] { packetID, isClientPacket, isServerPacket, packetClass });
} catch (Exception e) {
e.printStackTrace();
}
}
}
| public static void register(int packetID, boolean isClientPacket, boolean isServerPacket, Class<? extends Packet> packetClass) {
if(registrationMethod == null) {
registrationMethod = findRegistrationMethod();
}
// is it still null?
if(registrationMethod == null) {
Logger.getLogger("Minecraft").warning("Couldn't find the packet registration method!");
}
else {
try {
if(Packet.l.get(packetID) != null) {
Packet.l.d(packetID); // remove the current packet registration if it exists
}
registrationMethod.invoke(null, new Object[] { packetID, isClientPacket, isServerPacket, packetClass });
} catch (Exception e) {
// just smoosh the error, we are probably reloading
}
}
}
|
diff --git a/uk.ac.diamond.scisoft.analysis.plotserver/src/uk/ac/diamond/scisoft/analysis/plotserver/AbstractPlotServer.java b/uk.ac.diamond.scisoft.analysis.plotserver/src/uk/ac/diamond/scisoft/analysis/plotserver/AbstractPlotServer.java
index a9c38464e..f6231450b 100644
--- a/uk.ac.diamond.scisoft.analysis.plotserver/src/uk/ac/diamond/scisoft/analysis/plotserver/AbstractPlotServer.java
+++ b/uk.ac.diamond.scisoft.analysis.plotserver/src/uk/ac/diamond/scisoft/analysis/plotserver/AbstractPlotServer.java
@@ -1,98 +1,98 @@
/*
* Copyright 2011 Diamond Light Source Ltd.
*
* 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 uk.ac.diamond.scisoft.analysis.plotserver;
import java.io.Serializable;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import uk.ac.diamond.scisoft.analysis.PlotServer;
abstract public class AbstractPlotServer implements PlotServer {
private Map<String, GuiBean> guiStore;
private Map<String, DataBean> dataStore;
private final boolean removeOnGet;
public AbstractPlotServer() {
this(false);
}
public AbstractPlotServer(boolean removeOnGet) {
super();
guiStore = new HashMap<String, GuiBean>();
dataStore = new HashMap<String, DataBean>();
this.removeOnGet = removeOnGet;
}
@Override
public DataBean getData(String guiName) throws Exception {
return removeOnGet ? dataStore.remove(guiName): dataStore.get(guiName);
}
@Override
public void setData(String guiName, DataBean data) throws Exception {
Serializable value = null;
if (data.getGuiParameters() != null) value = data.getGuiParameters().get(GuiParameters.PLOTOPERATION);
//if its a duplicate key and an PLOTOP_ADD we need to add the datasets to the old bean
if (value != null && value == GuiParameters.PLOTOP_ADD && dataStore.containsKey(guiName)) {
- for (DataSetWithAxisInformation set : data.data) dataStore.get(guiName).data.add(set);
+ for (DataSetWithAxisInformation set : data.getData()) dataStore.get(guiName).getData().add(set);
} else {
dataStore.put(guiName, data);
}
}
@Override
public GuiBean getGuiState(String guiName) throws Exception {
return removeOnGet ? guiStore.remove(guiName): guiStore.get(guiName);
}
@Override
public void updateGui(String guiName, GuiBean guiData) throws Exception {
guiStore.put(guiName, guiData);
}
@Override
public String[] getGuiNames() throws Exception {
Set<String> names = new HashSet<String>();
names.addAll(guiStore.keySet());
names.addAll(dataStore.keySet());
return names.toArray(new String[names.size()]);
}
/**
* Retrieve the Gui Store. Use with caution and understanding.
* @return guiStore
*/
protected Map<String, GuiBean> getGuiStore() {
return guiStore;
}
/**
* Retrieve the Data Store. Use with caution and understanding.
* @return dataStore
*/
protected Map<String, DataBean> getDataStore() {
return dataStore;
}
}
| true | true | public void setData(String guiName, DataBean data) throws Exception {
Serializable value = null;
if (data.getGuiParameters() != null) value = data.getGuiParameters().get(GuiParameters.PLOTOPERATION);
//if its a duplicate key and an PLOTOP_ADD we need to add the datasets to the old bean
if (value != null && value == GuiParameters.PLOTOP_ADD && dataStore.containsKey(guiName)) {
for (DataSetWithAxisInformation set : data.data) dataStore.get(guiName).data.add(set);
} else {
dataStore.put(guiName, data);
}
}
| public void setData(String guiName, DataBean data) throws Exception {
Serializable value = null;
if (data.getGuiParameters() != null) value = data.getGuiParameters().get(GuiParameters.PLOTOPERATION);
//if its a duplicate key and an PLOTOP_ADD we need to add the datasets to the old bean
if (value != null && value == GuiParameters.PLOTOP_ADD && dataStore.containsKey(guiName)) {
for (DataSetWithAxisInformation set : data.getData()) dataStore.get(guiName).getData().add(set);
} else {
dataStore.put(guiName, data);
}
}
|
diff --git a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java
index 1702374..bc61934 100644
--- a/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java
+++ b/src/main/java/org/mgenterprises/java/bukkit/gmcfps/Core/BasicCommands/GameManagementCommands.java
@@ -1,169 +1,169 @@
/*
* The MIT License
*
* Copyright 2013 Manuel Gauto.
*
* 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 org.mgenterprises.java.bukkit.gmcfps.Core.BasicCommands;
import java.util.HashMap;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.mgenterprises.java.bukkit.gmcfps.Core.GameManagement.Game;
import org.mgenterprises.java.bukkit.gmcfps.Core.GameManagement.GameManager;
import org.mgenterprises.java.bukkit.gmcfps.Core.Teams.Team;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicRocketLauncher;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicSMG;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicShotgun;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.BasicSniper;
import org.mgenterprises.java.bukkit.gmcfps.Core.Weapons.Implementations.Twa16GodWeapon;
/**
*
* @author Manuel Gauto
*/
public class GameManagementCommands implements CommandExecutor {
private GameManager gameManager;
private HashMap<String, Game> editing = new HashMap<String, Game>();
private HashMap<String, String> editingTeam = new HashMap<String, String>();
public GameManagementCommands(GameManager gameManager) {
this.gameManager = gameManager;
}
@Override
public boolean onCommand(CommandSender cs, Command cmnd, String string, String[] args) {
if (string.equalsIgnoreCase(Commands.JOIN.toString())) {
return processJoinCommand(cs, args);
} else if (string.equalsIgnoreCase(Commands.LEAVE.toString())) {
return processLeaveCommand(cs, args);
} else if (string.equalsIgnoreCase(Commands.GAME.toString())) {
return processWizard(cs, args);
}
return false;
}
private boolean processJoinCommand(CommandSender cs, String[] args) {
if (cs instanceof Player) {
if (((Player) cs).hasPermission("gfps.join") || ((Player) cs).isOp()) {
if (args.length >= 1) {
Player p = (Player) cs;
Game g = gameManager.getGameByName(args[0]);
if (g == null) {
p.sendRawMessage(ChatColor.BLUE + "Please enter a valid game name!");
} else {
if (g.registerPlayer(p)) {
p.sendRawMessage(ChatColor.BLUE + "You have joined: " + g.getName());
} else {
p.sendRawMessage(ChatColor.BLUE + g.getName() + " is full!");
}
return true;
}
}
return false;
} else {
cs.sendMessage(ChatColor.RED + "You do not have permission to do that!");
return true;
}
} else {
cs.sendMessage(ChatColor.BLUE + "Command must be executed by a player");
return true;
}
}
private boolean processLeaveCommand(CommandSender cs, String[] args) {
if (cs instanceof Player) {
if (((Player) cs).hasPermission("gfps.leave") || ((Player) cs).isOp()) {
Player p = (Player) cs;
Game g = gameManager.getGameByName(args[0]);
if (g == null) {
p.sendRawMessage(ChatColor.BLUE + "Please enter a valid game name!");
} else {
g.unregisterPlayer(p);
p.sendRawMessage(ChatColor.BLUE + "You have left your game!");
}
}
}
return true;
}
private boolean processWizard(CommandSender cs, String[] args) {
Player p = (Player) cs;
if (!p.hasPermission("gfps.create") && !p.isOp()) {
p.sendRawMessage(ChatColor.RED+"You do not have permission");
return true;
}
- if (args.length > 2 && args[0].equals("create")) {
+ if (args.length >= 2 && args[0].equals("create")) {
Game newGame = new Game(gameManager.getPluginReference(), args[1]);
this.editing.put(p.getName(), newGame);
p.sendRawMessage(ChatColor.AQUA + "Game " + newGame.getName() + " was Created!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + " Set the lobby as the location you are at with " + ChatColor.GREEN + "/game setlobby");
}
if (args[0].equals("setlobby")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getSpawnManager().setLobby(p.getLocation());
p.sendRawMessage(ChatColor.AQUA + "Game lobby set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Decide if the game will be free for all using " + ChatColor.GREEN + "/game setffa [true/false]");
}
if (args.length > 2 && args[0].equals("setffa")) {
Game newGame = this.editing.get(p.getName());
if (args[1].contains("t")) {
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.BLUE + "TRUE");
newGame.getFPSCore().getTeamManager().setFreeForAll(true);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
return true;
}
newGame.getFPSCore().getTeamManager().setFreeForAll(false);
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.RED + "FALSE");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
}
if (args.length > 2 && args[0].equals("addteam")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getTeamManager().registerTeam(new Team(args[1]));
p.sendRawMessage(ChatColor.AQUA + "Team " + args[1] + " was Added!");
this.editingTeam.put(p.getName(), args[1]);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Set the team spawn with " + ChatColor.GREEN + "/game setspawn");
}
if (args[0].equals("setspawn")) {
Game newGame = this.editing.get(p.getName());
Team edit = newGame.getFPSCore().getTeamManager().getTeam(this.editingTeam.get(p.getName()));
edit.setSpawn(p.getLocation());
this.editingTeam.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + "Team spawn set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add more teams or finish the game with " + ChatColor.GREEN + "/game done");
}
if (args[0].equals("done")) {
Game g = this.editing.get(p.getName());
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSMG(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSniper(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicRocketLauncher(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicShotgun(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new Twa16GodWeapon(g.getFPSCore().getWeaponManager()));
this.editing.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + g.getName()+" completed!");
}
return true;
}
}
| true | true | private boolean processWizard(CommandSender cs, String[] args) {
Player p = (Player) cs;
if (!p.hasPermission("gfps.create") && !p.isOp()) {
p.sendRawMessage(ChatColor.RED+"You do not have permission");
return true;
}
if (args.length > 2 && args[0].equals("create")) {
Game newGame = new Game(gameManager.getPluginReference(), args[1]);
this.editing.put(p.getName(), newGame);
p.sendRawMessage(ChatColor.AQUA + "Game " + newGame.getName() + " was Created!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + " Set the lobby as the location you are at with " + ChatColor.GREEN + "/game setlobby");
}
if (args[0].equals("setlobby")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getSpawnManager().setLobby(p.getLocation());
p.sendRawMessage(ChatColor.AQUA + "Game lobby set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Decide if the game will be free for all using " + ChatColor.GREEN + "/game setffa [true/false]");
}
if (args.length > 2 && args[0].equals("setffa")) {
Game newGame = this.editing.get(p.getName());
if (args[1].contains("t")) {
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.BLUE + "TRUE");
newGame.getFPSCore().getTeamManager().setFreeForAll(true);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
return true;
}
newGame.getFPSCore().getTeamManager().setFreeForAll(false);
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.RED + "FALSE");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
}
if (args.length > 2 && args[0].equals("addteam")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getTeamManager().registerTeam(new Team(args[1]));
p.sendRawMessage(ChatColor.AQUA + "Team " + args[1] + " was Added!");
this.editingTeam.put(p.getName(), args[1]);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Set the team spawn with " + ChatColor.GREEN + "/game setspawn");
}
if (args[0].equals("setspawn")) {
Game newGame = this.editing.get(p.getName());
Team edit = newGame.getFPSCore().getTeamManager().getTeam(this.editingTeam.get(p.getName()));
edit.setSpawn(p.getLocation());
this.editingTeam.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + "Team spawn set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add more teams or finish the game with " + ChatColor.GREEN + "/game done");
}
if (args[0].equals("done")) {
Game g = this.editing.get(p.getName());
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSMG(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSniper(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicRocketLauncher(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicShotgun(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new Twa16GodWeapon(g.getFPSCore().getWeaponManager()));
this.editing.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + g.getName()+" completed!");
}
return true;
}
| private boolean processWizard(CommandSender cs, String[] args) {
Player p = (Player) cs;
if (!p.hasPermission("gfps.create") && !p.isOp()) {
p.sendRawMessage(ChatColor.RED+"You do not have permission");
return true;
}
if (args.length >= 2 && args[0].equals("create")) {
Game newGame = new Game(gameManager.getPluginReference(), args[1]);
this.editing.put(p.getName(), newGame);
p.sendRawMessage(ChatColor.AQUA + "Game " + newGame.getName() + " was Created!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + " Set the lobby as the location you are at with " + ChatColor.GREEN + "/game setlobby");
}
if (args[0].equals("setlobby")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getSpawnManager().setLobby(p.getLocation());
p.sendRawMessage(ChatColor.AQUA + "Game lobby set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Decide if the game will be free for all using " + ChatColor.GREEN + "/game setffa [true/false]");
}
if (args.length > 2 && args[0].equals("setffa")) {
Game newGame = this.editing.get(p.getName());
if (args[1].contains("t")) {
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.BLUE + "TRUE");
newGame.getFPSCore().getTeamManager().setFreeForAll(true);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
return true;
}
newGame.getFPSCore().getTeamManager().setFreeForAll(false);
p.sendRawMessage(ChatColor.AQUA + "Free for all was set to " + ChatColor.RED + "FALSE");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add teams using " + ChatColor.GREEN + "/game addteam [name]");
}
if (args.length > 2 && args[0].equals("addteam")) {
Game newGame = this.editing.get(p.getName());
newGame.getFPSCore().getTeamManager().registerTeam(new Team(args[1]));
p.sendRawMessage(ChatColor.AQUA + "Team " + args[1] + " was Added!");
this.editingTeam.put(p.getName(), args[1]);
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Set the team spawn with " + ChatColor.GREEN + "/game setspawn");
}
if (args[0].equals("setspawn")) {
Game newGame = this.editing.get(p.getName());
Team edit = newGame.getFPSCore().getTeamManager().getTeam(this.editingTeam.get(p.getName()));
edit.setSpawn(p.getLocation());
this.editingTeam.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + "Team spawn set at your current location!");
p.sendRawMessage(ChatColor.AQUA + "Next Step: " + "Add more teams or finish the game with " + ChatColor.GREEN + "/game done");
}
if (args[0].equals("done")) {
Game g = this.editing.get(p.getName());
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSMG(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicSniper(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicRocketLauncher(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new BasicShotgun(g.getFPSCore().getWeaponManager()));
g.getFPSCore().getWeaponManager().registerWeapon(new Twa16GodWeapon(g.getFPSCore().getWeaponManager()));
this.editing.remove(p.getName());
p.sendRawMessage(ChatColor.AQUA + g.getName()+" completed!");
}
return true;
}
|
diff --git a/server/src/de/hpi/epc/validation/EPCSyntaxChecker.java b/server/src/de/hpi/epc/validation/EPCSyntaxChecker.java
index e6182db8..85bfe845 100644
--- a/server/src/de/hpi/epc/validation/EPCSyntaxChecker.java
+++ b/server/src/de/hpi/epc/validation/EPCSyntaxChecker.java
@@ -1,161 +1,161 @@
package de.hpi.epc.validation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.hpi.diagram.Diagram;
import de.hpi.diagram.DiagramEdge;
import de.hpi.diagram.DiagramNode;
import de.hpi.diagram.DiagramObject;
import de.hpi.petrinet.SyntaxChecker;
public class EPCSyntaxChecker implements SyntaxChecker {
private static final String NO_SOURCE = "Each edge must have a source";
private static final String NO_TARGET = "Each edge must have a target";
private static final String NOT_CONNECTED = "Node must be connected with edges";
private static final String NOT_CONNECTED_2 = "Node must be connected with more edges";
private static final String TOO_MANY_EDGES = "Node has too many connected edges";
private static final String NO_CORRECT_CONNECTOR = "Node is no correct conector";
private static final String MANY_STARTS = "There must be only one start event";
private static final String MANY_ENDS = "There must be only one end event";
private static final String FUNCTION_AFTER_OR = "There must be no functions after a splitting OR/XOR";
private static final String FUNCTION_AFTER_FUNCTION = "There must be no function after a function";
private static final String EVENT_AFTER_EVENT = "There must be no event after an event";
protected Diagram diagram;
protected Map<String,String> errors;
public EPCSyntaxChecker(Diagram diagram) {
this.diagram = diagram;
this.errors = new HashMap<String,String>();
}
public boolean checkSyntax() {
errors.clear();
if (diagram == null)
return false;
checkEdges();
checkNodes();
return errors.size() == 0;
}
public Map<String, String> getErrors() {
return errors;
}
protected void checkEdges() {
for (DiagramEdge edge: diagram.getEdges()) {
if (edge.getSource() == null)
addError(edge, NO_SOURCE);
if (edge.getTarget() == null)
addError(edge, NO_TARGET);
}
}
protected void checkNodes() {
List<DiagramNode> startEvents = new ArrayList<DiagramNode>();
List<DiagramNode> endEvents = new ArrayList<DiagramNode>();
for (DiagramNode node: diagram.getNodes()) {
int in = node.getIncomingEdges().size();
int out = node.getOutgoingEdges().size();
if (in == 0 && out == 0){
addError(node, NOT_CONNECTED);
}
else if ("Event".equals(node.getType())){
if (in == 1 && out == 0) endEvents.add(node);
else if (in == 0 && out == 1) startEvents.add(node);
else if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Event".equals(next.getType())) addError(next, EVENT_AFTER_EVENT);
}
}
else if (in == 0 || out == 0){
addError(node, NOT_CONNECTED_2);
}
else if ("Function".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())) addError(next, FUNCTION_AFTER_FUNCTION);
}
}
else if ("ProcessInterface".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
}
else if ("XorConnector".equals(node.getType()) || "OrConnector".equals(node.getType())){
if (in == 1 && out == 2){
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())){
addError(node, FUNCTION_AFTER_OR);
break;
}
}
- } else if (in == 1 && out ==2){
+ } else if (in == 2 && out == 1){
// nothing todo
} else {
addError(node, NO_CORRECT_CONNECTOR);
}
}
else if ("AndConnector".equals(node.getType())){
- if ( ! (in == 2 && out == 1) || (in == 1 && out ==2) ){
+ if ( ! ( (in == 2 && out == 1) || (in == 1 && out == 2) ) ){
addError(node, NO_CORRECT_CONNECTOR);
}
}
}
if (startEvents.size() > 1){
for (DiagramNode n : startEvents){
addError(n, MANY_STARTS);
}
}
if (endEvents.size() > 1){
for (DiagramNode n : endEvents){
addError(n, MANY_ENDS);
}
}
}
protected void addError(DiagramObject obj, String errorCode) {
String key = obj.getResourceId();
String oldErrorCode = errors.get(key);
if (oldErrorCode != null && oldErrorCode.startsWith("Multiple Errors: ")){
errors.put(obj.getResourceId(), oldErrorCode+", "+errorCode);
} else if (oldErrorCode != null){
errors.put(obj.getResourceId(), "Multiple Errors: "+oldErrorCode+", "+errorCode);
} else {
errors.put(obj.getResourceId(), errorCode);
}
}
private List<DiagramNode>getNextEventsOrFunctions(List<DiagramEdge> edges){
List<DiagramEdge> newEdges = new ArrayList<DiagramEdge>();
List<DiagramNode> result = new ArrayList<DiagramNode>();
for (DiagramEdge edge : edges){
newEdges.add(edge);
}
return getNextEventsOrFunctions(newEdges, result);
}
private List<DiagramNode>getNextEventsOrFunctions(List<DiagramEdge> edges, List<DiagramNode> result){
List<DiagramEdge> newEdges = new ArrayList<DiagramEdge>();
for (DiagramEdge edge : edges){
if ("ControlFlow".equals(edge.getType())){
DiagramNode target = edge.getTarget();
if ("Function".equals(target.getType()) || "Event".equals(target.getType())){
result.add(target);
} else {
newEdges.addAll(target.getOutgoingEdges());
}
}
}
if (newEdges.size() > 0){
return getNextEventsOrFunctions(newEdges, result);
}
return result;
}
}
| false | true | protected void checkNodes() {
List<DiagramNode> startEvents = new ArrayList<DiagramNode>();
List<DiagramNode> endEvents = new ArrayList<DiagramNode>();
for (DiagramNode node: diagram.getNodes()) {
int in = node.getIncomingEdges().size();
int out = node.getOutgoingEdges().size();
if (in == 0 && out == 0){
addError(node, NOT_CONNECTED);
}
else if ("Event".equals(node.getType())){
if (in == 1 && out == 0) endEvents.add(node);
else if (in == 0 && out == 1) startEvents.add(node);
else if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Event".equals(next.getType())) addError(next, EVENT_AFTER_EVENT);
}
}
else if (in == 0 || out == 0){
addError(node, NOT_CONNECTED_2);
}
else if ("Function".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())) addError(next, FUNCTION_AFTER_FUNCTION);
}
}
else if ("ProcessInterface".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
}
else if ("XorConnector".equals(node.getType()) || "OrConnector".equals(node.getType())){
if (in == 1 && out == 2){
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())){
addError(node, FUNCTION_AFTER_OR);
break;
}
}
} else if (in == 1 && out ==2){
// nothing todo
} else {
addError(node, NO_CORRECT_CONNECTOR);
}
}
else if ("AndConnector".equals(node.getType())){
if ( ! (in == 2 && out == 1) || (in == 1 && out ==2) ){
addError(node, NO_CORRECT_CONNECTOR);
}
}
}
if (startEvents.size() > 1){
for (DiagramNode n : startEvents){
addError(n, MANY_STARTS);
}
}
if (endEvents.size() > 1){
for (DiagramNode n : endEvents){
addError(n, MANY_ENDS);
}
}
}
| protected void checkNodes() {
List<DiagramNode> startEvents = new ArrayList<DiagramNode>();
List<DiagramNode> endEvents = new ArrayList<DiagramNode>();
for (DiagramNode node: diagram.getNodes()) {
int in = node.getIncomingEdges().size();
int out = node.getOutgoingEdges().size();
if (in == 0 && out == 0){
addError(node, NOT_CONNECTED);
}
else if ("Event".equals(node.getType())){
if (in == 1 && out == 0) endEvents.add(node);
else if (in == 0 && out == 1) startEvents.add(node);
else if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Event".equals(next.getType())) addError(next, EVENT_AFTER_EVENT);
}
}
else if (in == 0 || out == 0){
addError(node, NOT_CONNECTED_2);
}
else if ("Function".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())) addError(next, FUNCTION_AFTER_FUNCTION);
}
}
else if ("ProcessInterface".equals(node.getType())){
if (in > 1 || out > 1) addError(node, TOO_MANY_EDGES);
}
else if ("XorConnector".equals(node.getType()) || "OrConnector".equals(node.getType())){
if (in == 1 && out == 2){
for (DiagramNode next : getNextEventsOrFunctions(node.getOutgoingEdges())){
if ("Function".equals(next.getType())){
addError(node, FUNCTION_AFTER_OR);
break;
}
}
} else if (in == 2 && out == 1){
// nothing todo
} else {
addError(node, NO_CORRECT_CONNECTOR);
}
}
else if ("AndConnector".equals(node.getType())){
if ( ! ( (in == 2 && out == 1) || (in == 1 && out == 2) ) ){
addError(node, NO_CORRECT_CONNECTOR);
}
}
}
if (startEvents.size() > 1){
for (DiagramNode n : startEvents){
addError(n, MANY_STARTS);
}
}
if (endEvents.size() > 1){
for (DiagramNode n : endEvents){
addError(n, MANY_ENDS);
}
}
}
|
diff --git a/src/org/jacorb/orb/giop/MessageReceptorPool.java b/src/org/jacorb/orb/giop/MessageReceptorPool.java
index 5585f55f1..ee8640d17 100644
--- a/src/org/jacorb/orb/giop/MessageReceptorPool.java
+++ b/src/org/jacorb/orb/giop/MessageReceptorPool.java
@@ -1,87 +1,87 @@
/*
* JacORB - a free Java ORB
*
* Copyright (C) 1997-2004 Gerald Brose.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package org.jacorb.orb.giop;
import org.apache.avalon.framework.logger.Logger;
import org.apache.avalon.framework.configuration.Configuration;
import org.jacorb.util.threadpool.*;
/**
* MessageReceptorPool.java
*
* @author Nicolas Noffke
* @version $Id$
*/
public class MessageReceptorPool
{
private static final int MAX_DEFAULT = 1000;
private static final int MAX_IDLE_DEFAULT = 5;
private final ThreadPool pool;
/**
* @param config must be client or server to specify which configurationsubset should be used
* @param threadNamePrefix prefix that's used to name all threads that are created by this pool
* @param myConfiguration current configuration
* TODO configuration of this class should be enhanced. config param does not feel nice.
*/
public MessageReceptorPool(String config, String threadNamePrefix, Configuration myConfiguration)
{
- if (!config.equals("server") || !config.equals("client"))
+ if (!config.equals("server") && !config.equals("client"))
{
throw new IllegalArgumentException("must be client or server");
}
org.jacorb.config.Configuration configuration =
(org.jacorb.config.Configuration) myConfiguration;
final int maxConnectionThreads =
configuration.getAttributeAsInteger("jacorb.connection." + config + ".max_threads", MAX_DEFAULT);
final int maxIdleThreads = configuration.getAttributeAsInteger("jacorb.connection." + config + ".max_idle_receptor_threads", MAX_IDLE_DEFAULT);
Logger logger = configuration.getNamedLogger("jacorb.orb.giop");
if (logger.isDebugEnabled())
{
logger.debug("Maximum connection threads: " + maxConnectionThreads);
logger.debug("Maximum idle threads: " + maxIdleThreads);
}
pool =
new ThreadPool( threadNamePrefix,
new ConsumerFactory(){
public Consumer create()
{
return new MessageReceptor();
}
},
maxConnectionThreads,
maxIdleThreads ); //max idle threads
}
public void connectionCreated( GIOPConnection conn )
{
pool.putJob( conn );
}
}// MessageReceptorPool
| true | true | public MessageReceptorPool(String config, String threadNamePrefix, Configuration myConfiguration)
{
if (!config.equals("server") || !config.equals("client"))
{
throw new IllegalArgumentException("must be client or server");
}
org.jacorb.config.Configuration configuration =
(org.jacorb.config.Configuration) myConfiguration;
final int maxConnectionThreads =
configuration.getAttributeAsInteger("jacorb.connection." + config + ".max_threads", MAX_DEFAULT);
final int maxIdleThreads = configuration.getAttributeAsInteger("jacorb.connection." + config + ".max_idle_receptor_threads", MAX_IDLE_DEFAULT);
Logger logger = configuration.getNamedLogger("jacorb.orb.giop");
if (logger.isDebugEnabled())
{
logger.debug("Maximum connection threads: " + maxConnectionThreads);
logger.debug("Maximum idle threads: " + maxIdleThreads);
}
pool =
new ThreadPool( threadNamePrefix,
new ConsumerFactory(){
public Consumer create()
{
return new MessageReceptor();
}
},
maxConnectionThreads,
maxIdleThreads ); //max idle threads
}
| public MessageReceptorPool(String config, String threadNamePrefix, Configuration myConfiguration)
{
if (!config.equals("server") && !config.equals("client"))
{
throw new IllegalArgumentException("must be client or server");
}
org.jacorb.config.Configuration configuration =
(org.jacorb.config.Configuration) myConfiguration;
final int maxConnectionThreads =
configuration.getAttributeAsInteger("jacorb.connection." + config + ".max_threads", MAX_DEFAULT);
final int maxIdleThreads = configuration.getAttributeAsInteger("jacorb.connection." + config + ".max_idle_receptor_threads", MAX_IDLE_DEFAULT);
Logger logger = configuration.getNamedLogger("jacorb.orb.giop");
if (logger.isDebugEnabled())
{
logger.debug("Maximum connection threads: " + maxConnectionThreads);
logger.debug("Maximum idle threads: " + maxIdleThreads);
}
pool =
new ThreadPool( threadNamePrefix,
new ConsumerFactory(){
public Consumer create()
{
return new MessageReceptor();
}
},
maxConnectionThreads,
maxIdleThreads ); //max idle threads
}
|
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java b/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java
index 60d618205..97ca98d0c 100644
--- a/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java
+++ b/grails/src/web/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java
@@ -1,455 +1,456 @@
/*
* 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.servlet.mvc;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MissingPropertyException;
import groovy.lang.ProxyMetaClass;
import groovy.util.Proxy;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.collections.map.CompositeMap;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.commons.GrailsClassUtils;
import org.codehaus.groovy.grails.commons.metaclass.GenericDynamicProperty;
import org.codehaus.groovy.grails.scaffolding.GrailsScaffolder;
import org.codehaus.groovy.grails.web.metaclass.ChainDynamicMethod;
import org.codehaus.groovy.grails.web.metaclass.ControllerDynamicMethods;
import org.codehaus.groovy.grails.web.metaclass.GetParamsDynamicProperty;
import org.codehaus.groovy.grails.web.servlet.*;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.ControllerExecutionException;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoClosurePropertyForURIException;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.NoViewNameDefinedException;
import org.codehaus.groovy.grails.web.servlet.mvc.exceptions.UnknownControllerException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A helper class for handling controller requests
*
* @author Graeme Rocher
* @since 0.1
*
* Created: 12-Jan-2006
*/
public class SimpleGrailsControllerHelper implements GrailsControllerHelper {
private static final String SCAFFOLDER = "Scaffolder";
private GrailsApplication application;
private ApplicationContext applicationContext;
private Map chainModel = Collections.EMPTY_MAP;
private GrailsScaffolder scaffolder;
private ServletContext servletContext;
private GrailsApplicationAttributes grailsAttributes;
private Pattern uriPattern = Pattern.compile("/(\\w+)/?(\\w*)/?(\\w*)/?(.*)");
private GrailsWebRequest webRequest;
private static final Log LOG = LogFactory.getLog(SimpleGrailsControllerHelper.class);
private static final String DISPATCH_ACTION_PARAMETER = "_action";
private static final String ID_PARAMETER = "id";
private String id;
private String controllerName;
private String actionName;
private Map extraParams;
public SimpleGrailsControllerHelper(GrailsApplication application, ApplicationContext context, ServletContext servletContext) {
super();
this.application = application;
this.applicationContext = context;
this.servletContext = servletContext;
this.grailsAttributes = new DefaultGrailsApplicationAttributes(this.servletContext);
}
public ServletContext getServletContext() {
return this.servletContext;
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerClassByName(java.lang.String)
*/
public GrailsControllerClass getControllerClassByName(String name) {
return this.application.getController(name);
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerClassByURI(java.lang.String)
*/
public GrailsControllerClass getControllerClassByURI(String uri) {
return this.application.getControllerByURI(uri);
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#getControllerInstance(org.codehaus.groovy.grails.commons.GrailsControllerClass)
*/
public GroovyObject getControllerInstance(GrailsControllerClass controllerClass) {
return (GroovyObject)this.applicationContext.getBean(controllerClass.getFullName());
}
/**
* If in Proxy's are used in the Groovy context, unproxy (is that a word?) them by setting
* the adaptee as the value in the map so that they can be used in non-groovy view technologies
*
* @param model The model as a map
*/
private void removeProxiesFromModelObjects(Map model) {
for (Iterator keyIter = model.keySet().iterator(); keyIter.hasNext();) {
Object current = keyIter.next();
Object modelObject = model.get(current);
if(modelObject instanceof Proxy) {
model.put( current, ((Proxy)modelObject).getAdaptee() );
}
}
}
public ModelAndView handleURI(String uri, GrailsWebRequest webRequest) {
return handleURI(uri, webRequest, Collections.EMPTY_MAP);
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#handleURI(java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.util.Map)
*/
public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) {
if(uri == null)
throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!");
this.webRequest = webRequest;
uri = configureStateForUri(uri);
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
// if the action name is blank check its included as dispatch parameter
if(StringUtils.isBlank(actionName) && request.getParameter(DISPATCH_ACTION_PARAMETER) != null) {
actionName = GrailsClassUtils.getPropertyNameRepresentation(request.getParameter(DISPATCH_ACTION_PARAMETER));
uri = '/' + controllerName + '/' + actionName;
}
if(uri.endsWith("/"))
uri = uri.substring(0,uri.length() - 1);
// if the id is blank check if its a request parameter
if(StringUtils.isBlank(id) && request.getParameter(ID_PARAMETER) != null) {
id = request.getParameter(ID_PARAMETER);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]");
}
if(LOG.isTraceEnabled()) {
LOG.trace("Extra params from uri ["+extraParams+"] ");
}
// Step 2: lookup the controller in the application.
GrailsControllerClass controllerClass = getControllerClassByURI(uri);
if (controllerClass == null) {
throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
}
// parse the uri in its individual tokens
controllerName = WordUtils.uncapitalize(controllerClass.getName());
// Step 3: load controller from application context.
GroovyObject controller = getControllerInstance(controllerClass);
if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 403 error",e);
}
}
request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller );
// Step 3: if scaffolding retrieve scaffolder
if(controllerClass.isScaffolding()) {
this.scaffolder = (GrailsScaffolder)applicationContext.getBean( controllerClass.getFullName() + SCAFFOLDER );
if(this.scaffolder == null)
throw new IllegalStateException("Scaffolding set to true for controller ["+controllerClass.getFullName()+"] but no scaffolder available!");
}
// Step 4: get closure property name for URI.
if(StringUtils.isBlank(actionName))
actionName = controllerClass.getClosurePropertyName(uri);
if (StringUtils.isBlank(actionName)) {
// Step 4a: Check if scaffolding
if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName))
throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!");
}
// Step 4a: Set the action and controller name of the web request
webRequest.setActionName(actionName);
webRequest.setControllerName(controllerName);
// populate additional params from url
Map controllerParams = (Map)controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME);
request.setControllerParams(controllerParams);
if(!StringUtils.isBlank(id)) {
controllerParams.put(GrailsApplicationAttributes.ID_PARAM, id);
}
if(!extraParams.isEmpty()) {
for (Iterator i = extraParams.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
controllerParams.put(name,extraParams.get(name));
}
}
// set the flash scope instance to its next state and set on controller
FlashScope fs = this.grailsAttributes.getFlashScope(request);
fs.next();
// Step 4b: Set grails attributes in request scope
request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes);
// Step 5: get the view name for this URI.
String viewName = controllerClass.getViewByURI(uri);
// Step 5a: Check if there is a before interceptor if there is execute it
boolean executeAction = true;
if(controllerClass.isInterceptedBefore(controller,actionName)) {
Closure beforeInterceptor = controllerClass.getBeforeInterceptor(controller);
if(beforeInterceptor!= null) {
Object interceptorResult = beforeInterceptor.call();
if(interceptorResult instanceof Boolean) {
executeAction = ((Boolean)interceptorResult).booleanValue();
}
}
}
// if the interceptor returned false don't execute the action
if(!executeAction)
return null;
// Step 6: get closure from closure property
Closure action;
try {
action = (Closure)controller.getProperty(actionName);
// Step 7: process the action
Object returnValue = handleAction( controller,action,request,response,params );
// Step 8: determine return value type and handle accordingly
initChainModel(controller);
if(response.isRedirected()) {
return null;
}
ModelAndView mv = handleActionResponse(controller,returnValue,actionName,viewName);
// Step 9: Check if there is after interceptor
if(controllerClass.isInterceptedAfter(controller,actionName)) {
Closure afterInterceptor = controllerClass.getAfterInterceptor(controller);
- afterInterceptor.call(new Object[]{ mv.getModel() });
+ Map model = mv.getModel() != null ? mv.getModel() : Collections.EMPTY_MAP;
+ afterInterceptor.call(new Object[]{ model });
}
return mv;
}
catch(MissingPropertyException mpe) {
if(controllerClass.isScaffolding())
throw new IllegalStateException("Scaffolder supports action ["+actionName +"] for controller ["+controllerClass.getFullName()+"] but getAction returned null!");
else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 404 error",e);
}
}
}
}
private String configureStateForUri(String uri) {
// step 1: process the uri
if (uri.indexOf("?") > -1) {
uri = uri.substring(0, uri.indexOf("?"));
}
if(uri.indexOf('\\') > -1) {
uri = uri.replaceAll("\\\\", "/");
}
if(!uri.startsWith("/"))
uri = '/' + uri;
if(uri.endsWith("/"))
uri = uri.substring(0,uri.length() - 1);
id = null;
controllerName = null;
actionName = null;
extraParams = Collections.EMPTY_MAP;
Matcher m = uriPattern.matcher(uri);
if(m.find()) {
controllerName = m.group(1);
actionName = m.group(2);
uri = '/' + controllerName + '/' + actionName;
id = m.group(3);
String extraParamsString = m.group(4);
if(extraParamsString != null && extraParamsString.indexOf('/') > - 1) {
String[] tokens = extraParamsString.split("/");
extraParams = new HashMap();
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if(i == 0 || ((i % 2) == 0)) {
if((i + 1) < tokens.length) {
extraParams.put(token, tokens[i + 1]);
}
}
}
}
}
return uri;
}
public GrailsApplicationAttributes getGrailsAttributes() {
return this.grailsAttributes;
}
public Object handleAction(GroovyObject controller,Closure action, HttpServletRequest request, HttpServletResponse response) {
return handleAction(controller,action,request,response,Collections.EMPTY_MAP);
}
public Object handleAction(GroovyObject controller,Closure action, HttpServletRequest request, HttpServletResponse response, Map params) {
// if there are additional params add them to the params dynamic property
if(params != null && !params.isEmpty()) {
GrailsParameterMap paramsMap = (GrailsParameterMap)controller.getProperty("params");
paramsMap.putAll( params );
}
// Step 7: determine argument count and execute.
Object returnValue = action.call();
// Step 8: add any errors to the request
request.setAttribute( GrailsApplicationAttributes.ERRORS, controller.getProperty(ControllerDynamicMethods.ERRORS_PROPERTY) );
return returnValue;
}
/* (non-Javadoc)
* @see org.codehaus.groovy.grails.web.servlet.mvc.GrailsControllerHelper#handleActionResponse(org.codehaus.groovy.grails.commons.GrailsControllerClass, java.lang.Object, java.lang.String, java.lang.String)
*/
public ModelAndView handleActionResponse( GroovyObject controller,Object returnValue,String closurePropertyName, String viewName) {
boolean viewNameBlank = (viewName == null || viewName.length() == 0);
// reset the metaclass
ModelAndView explicityModelAndView = (ModelAndView)controller.getProperty(ControllerDynamicMethods.MODEL_AND_VIEW_PROPERTY);
if(!webRequest.isRenderView()) {
return null;
}
else if(explicityModelAndView != null) {
return explicityModelAndView;
}
else if (returnValue == null) {
if (viewNameBlank) {
return null;
} else {
Map model;
if(!this.chainModel.isEmpty()) {
model = new CompositeMap(this.chainModel, new BeanMap(controller));
}
else {
model = new BeanMap(controller);
}
return new ModelAndView(viewName, model);
}
} else if (returnValue instanceof Map) {
// remove any Proxy wrappers and set the adaptee as the value
Map returnModel = (Map)returnValue;
removeProxiesFromModelObjects(returnModel);
if(!this.chainModel.isEmpty()) {
returnModel.putAll(this.chainModel);
}
return new ModelAndView(viewName, returnModel);
} else if (returnValue instanceof ModelAndView) {
ModelAndView modelAndView = (ModelAndView)returnValue;
// remove any Proxy wrappers and set the adaptee as the value
Map modelMap = modelAndView.getModel();
removeProxiesFromModelObjects(modelMap);
if(!this.chainModel.isEmpty()) {
modelAndView.addAllObjects(this.chainModel);
}
if (modelAndView.getView() == null && modelAndView.getViewName() == null) {
if (viewNameBlank) {
throw new NoViewNameDefinedException("ModelAndView instance returned by and no view name defined by nor for closure on property [" + closurePropertyName + "] in controller [" + controller.getClass() + "]!");
} else {
modelAndView.setViewName(viewName);
}
}
return modelAndView;
}
else {
Map model;
if(!this.chainModel.isEmpty()) {
model = new CompositeMap(this.chainModel, new BeanMap(controller));
}
else {
model = new BeanMap(controller);
}
return new ModelAndView(viewName, model);
}
}
private void initChainModel(GroovyObject controller) {
FlashScope fs = this.grailsAttributes.getFlashScope((HttpServletRequest)controller.getProperty(ControllerDynamicMethods.REQUEST_PROPERTY));
if(fs.containsKey(ChainDynamicMethod.PROPERTY_CHAIN_MODEL)) {
this.chainModel = (Map)fs.get(ChainDynamicMethod.PROPERTY_CHAIN_MODEL);
if(this.chainModel == null)
this.chainModel = Collections.EMPTY_MAP;
}
}
}
| true | true | public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) {
if(uri == null)
throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!");
this.webRequest = webRequest;
uri = configureStateForUri(uri);
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
// if the action name is blank check its included as dispatch parameter
if(StringUtils.isBlank(actionName) && request.getParameter(DISPATCH_ACTION_PARAMETER) != null) {
actionName = GrailsClassUtils.getPropertyNameRepresentation(request.getParameter(DISPATCH_ACTION_PARAMETER));
uri = '/' + controllerName + '/' + actionName;
}
if(uri.endsWith("/"))
uri = uri.substring(0,uri.length() - 1);
// if the id is blank check if its a request parameter
if(StringUtils.isBlank(id) && request.getParameter(ID_PARAMETER) != null) {
id = request.getParameter(ID_PARAMETER);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]");
}
if(LOG.isTraceEnabled()) {
LOG.trace("Extra params from uri ["+extraParams+"] ");
}
// Step 2: lookup the controller in the application.
GrailsControllerClass controllerClass = getControllerClassByURI(uri);
if (controllerClass == null) {
throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
}
// parse the uri in its individual tokens
controllerName = WordUtils.uncapitalize(controllerClass.getName());
// Step 3: load controller from application context.
GroovyObject controller = getControllerInstance(controllerClass);
if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 403 error",e);
}
}
request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller );
// Step 3: if scaffolding retrieve scaffolder
if(controllerClass.isScaffolding()) {
this.scaffolder = (GrailsScaffolder)applicationContext.getBean( controllerClass.getFullName() + SCAFFOLDER );
if(this.scaffolder == null)
throw new IllegalStateException("Scaffolding set to true for controller ["+controllerClass.getFullName()+"] but no scaffolder available!");
}
// Step 4: get closure property name for URI.
if(StringUtils.isBlank(actionName))
actionName = controllerClass.getClosurePropertyName(uri);
if (StringUtils.isBlank(actionName)) {
// Step 4a: Check if scaffolding
if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName))
throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!");
}
// Step 4a: Set the action and controller name of the web request
webRequest.setActionName(actionName);
webRequest.setControllerName(controllerName);
// populate additional params from url
Map controllerParams = (Map)controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME);
request.setControllerParams(controllerParams);
if(!StringUtils.isBlank(id)) {
controllerParams.put(GrailsApplicationAttributes.ID_PARAM, id);
}
if(!extraParams.isEmpty()) {
for (Iterator i = extraParams.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
controllerParams.put(name,extraParams.get(name));
}
}
// set the flash scope instance to its next state and set on controller
FlashScope fs = this.grailsAttributes.getFlashScope(request);
fs.next();
// Step 4b: Set grails attributes in request scope
request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes);
// Step 5: get the view name for this URI.
String viewName = controllerClass.getViewByURI(uri);
// Step 5a: Check if there is a before interceptor if there is execute it
boolean executeAction = true;
if(controllerClass.isInterceptedBefore(controller,actionName)) {
Closure beforeInterceptor = controllerClass.getBeforeInterceptor(controller);
if(beforeInterceptor!= null) {
Object interceptorResult = beforeInterceptor.call();
if(interceptorResult instanceof Boolean) {
executeAction = ((Boolean)interceptorResult).booleanValue();
}
}
}
// if the interceptor returned false don't execute the action
if(!executeAction)
return null;
// Step 6: get closure from closure property
Closure action;
try {
action = (Closure)controller.getProperty(actionName);
// Step 7: process the action
Object returnValue = handleAction( controller,action,request,response,params );
// Step 8: determine return value type and handle accordingly
initChainModel(controller);
if(response.isRedirected()) {
return null;
}
ModelAndView mv = handleActionResponse(controller,returnValue,actionName,viewName);
// Step 9: Check if there is after interceptor
if(controllerClass.isInterceptedAfter(controller,actionName)) {
Closure afterInterceptor = controllerClass.getAfterInterceptor(controller);
afterInterceptor.call(new Object[]{ mv.getModel() });
}
return mv;
}
catch(MissingPropertyException mpe) {
if(controllerClass.isScaffolding())
throw new IllegalStateException("Scaffolder supports action ["+actionName +"] for controller ["+controllerClass.getFullName()+"] but getAction returned null!");
else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 404 error",e);
}
}
}
}
| public ModelAndView handleURI(String uri, GrailsWebRequest webRequest, Map params) {
if(uri == null)
throw new IllegalArgumentException("Controller URI [" + uri + "] cannot be null!");
this.webRequest = webRequest;
uri = configureStateForUri(uri);
GrailsHttpServletRequest request = webRequest.getCurrentRequest();
GrailsHttpServletResponse response = webRequest.getCurrentResponse();
// if the action name is blank check its included as dispatch parameter
if(StringUtils.isBlank(actionName) && request.getParameter(DISPATCH_ACTION_PARAMETER) != null) {
actionName = GrailsClassUtils.getPropertyNameRepresentation(request.getParameter(DISPATCH_ACTION_PARAMETER));
uri = '/' + controllerName + '/' + actionName;
}
if(uri.endsWith("/"))
uri = uri.substring(0,uri.length() - 1);
// if the id is blank check if its a request parameter
if(StringUtils.isBlank(id) && request.getParameter(ID_PARAMETER) != null) {
id = request.getParameter(ID_PARAMETER);
}
if(LOG.isDebugEnabled()) {
LOG.debug("Processing request for controller ["+controllerName+"], action ["+actionName+"], and id ["+id+"]");
}
if(LOG.isTraceEnabled()) {
LOG.trace("Extra params from uri ["+extraParams+"] ");
}
// Step 2: lookup the controller in the application.
GrailsControllerClass controllerClass = getControllerClassByURI(uri);
if (controllerClass == null) {
throw new UnknownControllerException("No controller found for URI [" + uri + "]!");
}
// parse the uri in its individual tokens
controllerName = WordUtils.uncapitalize(controllerClass.getName());
// Step 3: load controller from application context.
GroovyObject controller = getControllerInstance(controllerClass);
if(!controllerClass.isHttpMethodAllowedForAction(controller, request.getMethod(), actionName)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 403 error",e);
}
}
request.setAttribute( GrailsApplicationAttributes.CONTROLLER, controller );
// Step 3: if scaffolding retrieve scaffolder
if(controllerClass.isScaffolding()) {
this.scaffolder = (GrailsScaffolder)applicationContext.getBean( controllerClass.getFullName() + SCAFFOLDER );
if(this.scaffolder == null)
throw new IllegalStateException("Scaffolding set to true for controller ["+controllerClass.getFullName()+"] but no scaffolder available!");
}
// Step 4: get closure property name for URI.
if(StringUtils.isBlank(actionName))
actionName = controllerClass.getClosurePropertyName(uri);
if (StringUtils.isBlank(actionName)) {
// Step 4a: Check if scaffolding
if( controllerClass.isScaffolding() && !scaffolder.supportsAction(actionName))
throw new NoClosurePropertyForURIException("Could not find closure property for URI [" + uri + "] for controller [" + controllerClass.getFullName() + "]!");
}
// Step 4a: Set the action and controller name of the web request
webRequest.setActionName(actionName);
webRequest.setControllerName(controllerName);
// populate additional params from url
Map controllerParams = (Map)controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME);
request.setControllerParams(controllerParams);
if(!StringUtils.isBlank(id)) {
controllerParams.put(GrailsApplicationAttributes.ID_PARAM, id);
}
if(!extraParams.isEmpty()) {
for (Iterator i = extraParams.keySet().iterator(); i.hasNext();) {
String name = (String) i.next();
controllerParams.put(name,extraParams.get(name));
}
}
// set the flash scope instance to its next state and set on controller
FlashScope fs = this.grailsAttributes.getFlashScope(request);
fs.next();
// Step 4b: Set grails attributes in request scope
request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID,this.grailsAttributes);
// Step 5: get the view name for this URI.
String viewName = controllerClass.getViewByURI(uri);
// Step 5a: Check if there is a before interceptor if there is execute it
boolean executeAction = true;
if(controllerClass.isInterceptedBefore(controller,actionName)) {
Closure beforeInterceptor = controllerClass.getBeforeInterceptor(controller);
if(beforeInterceptor!= null) {
Object interceptorResult = beforeInterceptor.call();
if(interceptorResult instanceof Boolean) {
executeAction = ((Boolean)interceptorResult).booleanValue();
}
}
}
// if the interceptor returned false don't execute the action
if(!executeAction)
return null;
// Step 6: get closure from closure property
Closure action;
try {
action = (Closure)controller.getProperty(actionName);
// Step 7: process the action
Object returnValue = handleAction( controller,action,request,response,params );
// Step 8: determine return value type and handle accordingly
initChainModel(controller);
if(response.isRedirected()) {
return null;
}
ModelAndView mv = handleActionResponse(controller,returnValue,actionName,viewName);
// Step 9: Check if there is after interceptor
if(controllerClass.isInterceptedAfter(controller,actionName)) {
Closure afterInterceptor = controllerClass.getAfterInterceptor(controller);
Map model = mv.getModel() != null ? mv.getModel() : Collections.EMPTY_MAP;
afterInterceptor.call(new Object[]{ model });
}
return mv;
}
catch(MissingPropertyException mpe) {
if(controllerClass.isScaffolding())
throw new IllegalStateException("Scaffolder supports action ["+actionName +"] for controller ["+controllerClass.getFullName()+"] but getAction returned null!");
else {
try {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return null;
} catch (IOException e) {
throw new ControllerExecutionException("I/O error sending 404 error",e);
}
}
}
}
|
diff --git a/src/main/java/eu/serscis/sam/gui/DebugViewer.java b/src/main/java/eu/serscis/sam/gui/DebugViewer.java
index db230df..49b02f8 100644
--- a/src/main/java/eu/serscis/sam/gui/DebugViewer.java
+++ b/src/main/java/eu/serscis/sam/gui/DebugViewer.java
@@ -1,368 +1,368 @@
/////////////////////////////////////////////////////////////////////////
//
// © University of Southampton IT Innovation Centre, 2011
//
// Copyright in this library belongs to the University of Southampton
// University Road, Highfield, Southampton, UK, SO17 1BJ
//
// This software may not be used, sold, licensed, transferred, copied
// or reproduced in whole or in part in any manner or form or in or
// on any media by any person other than in accordance with the terms
// of the Licence Agreement supplied with the software, or otherwise
// without the prior written consent of the copyright owners.
//
// This software is distributed WITHOUT ANY WARRANTY, without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE, except where stated in the Licence Agreement supplied with
// the software.
//
// Created By : Thomas Leonard
// Created Date : 2011-11-03
// Created for Project : SERSCIS
//
/////////////////////////////////////////////////////////////////////////
//
// License : GNU Lesser General Public License, version 2.1
//
/////////////////////////////////////////////////////////////////////////
package eu.serscis.sam.gui;
import org.deri.iris.api.basics.IAtom;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionAdapter;
import java.util.HashMap;
import java.util.Map;
import org.deri.iris.api.basics.IRule;
import eu.serscis.sam.Reporter;
import eu.serscis.sam.Model;
import eu.serscis.sam.Constants;
import org.deri.iris.api.basics.IQuery;
import org.deri.iris.api.basics.ILiteral;
import org.deri.iris.storage.IRelation;
import org.deri.iris.api.basics.ITuple;
import org.deri.iris.api.basics.IPredicate;
import java.util.Arrays;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.layout.RowLayout;
import static org.deri.iris.factory.Factory.*;
import eu.serscis.sam.Debugger;
public class DebugViewer implements Updatable {
private final Shell myShell;
private final Tree myTree;
private final Text myText;
private final LiveResults myResults;
private final ILiteral myProblem;
private final Map<TreeItem,Details> extraData = new HashMap<TreeItem,Details>();
private final Color PRETTY_COLOUR = new Color(Display.getCurrent(), 0, 50, 150);
private final Color GREY = new Color(Display.getCurrent(), 100, 100, 100);
private boolean accessControlOn;
public DebugViewer(final Shell parent, final LiveResults results, ILiteral problem) throws Exception {
myShell = new Shell(parent, SWT.BORDER | SWT.CLOSE | SWT.MIN | SWT.MAX | SWT.RESIZE | SWT.TITLE);
myShell.setText("Debug: " + problem);
myResults = results;
myProblem = problem;
myTree = new Tree(myShell, 0);
myText = new Text(myShell, SWT.MULTI | SWT.READ_ONLY);
GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.verticalSpacing = 0;
GridData tableLayoutData = new GridData();
tableLayoutData.horizontalAlignment = GridData.FILL;
tableLayoutData.verticalAlignment = GridData.FILL;
tableLayoutData.grabExcessHorizontalSpace = true;
tableLayoutData.grabExcessVerticalSpace = true;
myTree.setLayoutData(tableLayoutData);
GridData textLayoutData = new GridData();
textLayoutData.horizontalAlignment = GridData.FILL;
textLayoutData.verticalAlignment = GridData.FILL;
textLayoutData.grabExcessHorizontalSpace = true;
textLayoutData.grabExcessVerticalSpace = false;
myText.setLayoutData(textLayoutData);
myTree.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
TreeItem item = (TreeItem) e.item;
Details details = extraData.get(item);
myText.setText(details != null ? details.notes : "");
myShell.layout();
}
public void widgetDefaultSelected(SelectionEvent e) {
TreeItem item = (TreeItem) e.item;
Details details = extraData.get(item);
if (details != null && details.lit != null) {
try {
new DebugViewer(parent, results, details.lit);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
myShell.setLayout(gridLayout);
myShell.open();
update();
}
public void update() throws Exception {
if (myShell.isDisposed()) {
return;
}
//System.out.println("refresh " + myShell.getText());
myTree.removeAll();
Model model = myResults.getResults().model;
accessControlOn = checkAccessControl(model);
GUIReporter reporter = new GUIReporter();
Debugger debugger = new Debugger(model);
debugger.debug(myProblem, reporter);
Display.getCurrent().timerExec(0, new Runnable() {
public void run() {
for (TreeItem item : myTree.getItems()) {
item.setExpanded(true);
for (TreeItem child : item.getItems()) {
child.setExpanded(true);
}
}
}
});
myResults.whenUpdated(this);
}
private boolean checkAccessControl(Model model) throws Exception {
ILiteral lit = BASIC.createLiteral(true, Constants.accessControlOnP, BASIC.createTuple());
IQuery query = BASIC.createQuery(lit);
IRelation rel = myResults.getResults().finalKnowledgeBase.execute(query);
return rel.size() > 0;
}
private static String getInvocation(ITuple tuple, int i) {
String object = tuple.get(i).getValue().toString();
if ("_testDriver".equals(object)) {
return "config";
}
return object;
}
/* Produce a friendly description of literal */
private String getPrettyText(ILiteral literal) {
if (!literal.isPositive()) {
return null;
}
IAtom atom = literal.getAtom();
ITuple tuple = atom.getTuple();
IPredicate p = atom.getPredicate();
if (p.getPredicateSymbol().equals("maySend")) {
String target = tuple.get(0).getValue().toString();
String method = tuple.get(2).getValue().toString();
String arg;
if (tuple.size() == 4) {
arg = tuple.get(3).getValue().toString();
} else {
arg = tuple.get(4).getValue().toString();
}
String msg = target + " received " + arg;
if (!method.equals("Unknown.invoke")) {
msg += " (arg to " + method + ")";
} else {
msg += " (as an argument)";
}
return msg;
} else if (p.equals(Constants.mayStoreP)) {
String callSite = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
return "(" + callSite + " may store result in " + target + ")";
} else if (p.equals(Constants.didCall3P)) {
String caller = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
String method = tuple.get(2).getValue().toString();
int i = method.indexOf('.');
method = method.substring(i + 1);
return caller + " called " + target + "." + method + "()";
} else if (p.equals(Constants.didCallP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String target = getInvocation(tuple, 3);
String method = tuple.get(5).getValue().toString();
//String method = tuple.get(4).getValue().toString();
//String arg = tuple.get(5).getValue().toString();
//String result = tuple.get(6).getValue().toString();
//msg = caller + "@" + callSite + " calls " + target + "." + method;
int i = method.indexOf('.');
method = method.substring(i + 1);
String msg = caller + " called " + target + "." + method + "()";
String callerInvocation = tuple.get(1).getValue().toString();
String targetInvocation = tuple.get(4).getValue().toString();
if (callerInvocation.equals("") && targetInvocation.equals("")) {
return msg;
} else if (callerInvocation.equals(targetInvocation)) {
return msg + " [" + callerInvocation + "]";
} else {
return msg + " [" + callerInvocation + " -> " + targetInvocation + "]";
}
} else if (p.equals(Constants.didGetP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String result = tuple.get(3).getValue().toString();
return "" + caller + " got " + result;
} else if (p.equals(Constants.didGetExceptionP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String result = tuple.get(3).getValue().toString();
return "" + caller + " got exception " + result;
} else if (p.equals(Constants.isAP)) {
String name = tuple.get(0).getValue().toString();
String type = tuple.get(1).getValue().toString();
return type + " '" + name + "' exists";
} else if (p.equals(Constants.accessAllowedP)) {
if (!accessControlOn) {
return null; // Not interesting then
}
String caller = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
String[] method = tuple.get(2).getValue().toString().split("\\.");
return "Access control: " + caller + " may call " + target + "." + method[1];
} else if (p.equals(Constants.fieldP)) {
String actor = tuple.get(0).getValue().toString();
String name = tuple.get(1).getValue().toString();
String value = tuple.get(2).getValue().toString();
return actor + "." + name + " = " + value;
} else if (p.equals(Constants.localP)) {
String actor = getInvocation(tuple, 0);
String[] name = tuple.get(2).getValue().toString().split("\\.");
String value = tuple.get(3).getValue().toString();
return actor + "." + name[1] + "()'s " + name[2] + " = " + value;
} else if (p.equals(Constants.mayCallObjectP)) {
String actor = getInvocation(tuple, 0);
String method = tuple.get(2).getValue().toString().split("\\.")[1].split("-")[0];
String target = tuple.get(3).getValue().toString();
- return actor + " may call " + target + "." + method;
+ return actor + "." + method + " may call " + target;
} else if (p.equals(Constants.didCreateP)) {
String actor = getInvocation(tuple, 0);
//String resultVar = tuple.get(2).getValue().toString();
String type = tuple.get(3).getValue().toString();
return actor + " created " + type;
}
return null;
}
private class GUIReporter implements Reporter {
private ILiteral optNegativeNeedHeader;
private TreeItem currentItem;
public void enter(ILiteral literal) {
//System.out.println("enter " + literal + ", " + currentItem);
TreeItem item;
if (currentItem == null) {
item = new TreeItem(myTree, 0);
} else {
item = new TreeItem(currentItem, 0);
}
Details details = new Details(literal);
String prettyText = getPrettyText(literal);
if (prettyText == null) {
item.setText("" + literal);
item.setForeground(GREY);
} else {
item.setText(prettyText);
item.setForeground(PRETTY_COLOUR);
FontData fontData = item.getFont().getFontData()[0];
item.setFont(new Font(Display.getCurrent(), fontData.getName(), fontData.getHeight(), SWT.BOLD));
details.notes += literal + "\n";
}
extraData.put(item, details);
currentItem = item;
}
public void leave(ILiteral literal) {
currentItem = currentItem.getParentItem();
}
public void noteNewProblem(ILiteral problem) {
}
public void noteQuery(IQuery ruleQ) {
String msg = "Rule body:\n";
for (ILiteral literal : ruleQ.getLiterals()) {
msg += literal + "\n";
}
extraData.get(currentItem).notes += msg;
}
/* We are about to explain why literal is false. */
public void enterNegative(ILiteral literal) {
optNegativeNeedHeader = literal;
currentItem = new TreeItem(currentItem, 0);
currentItem.setForeground(GREY);
currentItem.setText("" + literal + "; none of these was true:");
extraData.put(currentItem, new Details(literal));
}
public void leaveNegative() {
if (optNegativeNeedHeader != null) {
currentItem.setText("" + optNegativeNeedHeader + "; no rules for this predicate");
}
currentItem = currentItem.getParentItem();
}
/* This rule might have been intended to fire, but there was no match. */
public void noteNegative(IRule rule, IQuery unified) {
optNegativeNeedHeader = null;
TreeItem ruleItem = new TreeItem(currentItem, 0);
ruleItem.setText("" + rule);
ruleItem.setForeground(GREY);
Details details = new Details(null);
details.notes += unified;
extraData.put(ruleItem, details);
}
}
private class Details {
private ILiteral lit;
private String notes = "";
private Details(ILiteral lit) {
this.lit = lit;
}
}
}
| true | true | private String getPrettyText(ILiteral literal) {
if (!literal.isPositive()) {
return null;
}
IAtom atom = literal.getAtom();
ITuple tuple = atom.getTuple();
IPredicate p = atom.getPredicate();
if (p.getPredicateSymbol().equals("maySend")) {
String target = tuple.get(0).getValue().toString();
String method = tuple.get(2).getValue().toString();
String arg;
if (tuple.size() == 4) {
arg = tuple.get(3).getValue().toString();
} else {
arg = tuple.get(4).getValue().toString();
}
String msg = target + " received " + arg;
if (!method.equals("Unknown.invoke")) {
msg += " (arg to " + method + ")";
} else {
msg += " (as an argument)";
}
return msg;
} else if (p.equals(Constants.mayStoreP)) {
String callSite = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
return "(" + callSite + " may store result in " + target + ")";
} else if (p.equals(Constants.didCall3P)) {
String caller = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
String method = tuple.get(2).getValue().toString();
int i = method.indexOf('.');
method = method.substring(i + 1);
return caller + " called " + target + "." + method + "()";
} else if (p.equals(Constants.didCallP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String target = getInvocation(tuple, 3);
String method = tuple.get(5).getValue().toString();
//String method = tuple.get(4).getValue().toString();
//String arg = tuple.get(5).getValue().toString();
//String result = tuple.get(6).getValue().toString();
//msg = caller + "@" + callSite + " calls " + target + "." + method;
int i = method.indexOf('.');
method = method.substring(i + 1);
String msg = caller + " called " + target + "." + method + "()";
String callerInvocation = tuple.get(1).getValue().toString();
String targetInvocation = tuple.get(4).getValue().toString();
if (callerInvocation.equals("") && targetInvocation.equals("")) {
return msg;
} else if (callerInvocation.equals(targetInvocation)) {
return msg + " [" + callerInvocation + "]";
} else {
return msg + " [" + callerInvocation + " -> " + targetInvocation + "]";
}
} else if (p.equals(Constants.didGetP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String result = tuple.get(3).getValue().toString();
return "" + caller + " got " + result;
} else if (p.equals(Constants.didGetExceptionP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String result = tuple.get(3).getValue().toString();
return "" + caller + " got exception " + result;
} else if (p.equals(Constants.isAP)) {
String name = tuple.get(0).getValue().toString();
String type = tuple.get(1).getValue().toString();
return type + " '" + name + "' exists";
} else if (p.equals(Constants.accessAllowedP)) {
if (!accessControlOn) {
return null; // Not interesting then
}
String caller = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
String[] method = tuple.get(2).getValue().toString().split("\\.");
return "Access control: " + caller + " may call " + target + "." + method[1];
} else if (p.equals(Constants.fieldP)) {
String actor = tuple.get(0).getValue().toString();
String name = tuple.get(1).getValue().toString();
String value = tuple.get(2).getValue().toString();
return actor + "." + name + " = " + value;
} else if (p.equals(Constants.localP)) {
String actor = getInvocation(tuple, 0);
String[] name = tuple.get(2).getValue().toString().split("\\.");
String value = tuple.get(3).getValue().toString();
return actor + "." + name[1] + "()'s " + name[2] + " = " + value;
} else if (p.equals(Constants.mayCallObjectP)) {
String actor = getInvocation(tuple, 0);
String method = tuple.get(2).getValue().toString().split("\\.")[1].split("-")[0];
String target = tuple.get(3).getValue().toString();
return actor + " may call " + target + "." + method;
} else if (p.equals(Constants.didCreateP)) {
String actor = getInvocation(tuple, 0);
//String resultVar = tuple.get(2).getValue().toString();
String type = tuple.get(3).getValue().toString();
return actor + " created " + type;
}
return null;
}
| private String getPrettyText(ILiteral literal) {
if (!literal.isPositive()) {
return null;
}
IAtom atom = literal.getAtom();
ITuple tuple = atom.getTuple();
IPredicate p = atom.getPredicate();
if (p.getPredicateSymbol().equals("maySend")) {
String target = tuple.get(0).getValue().toString();
String method = tuple.get(2).getValue().toString();
String arg;
if (tuple.size() == 4) {
arg = tuple.get(3).getValue().toString();
} else {
arg = tuple.get(4).getValue().toString();
}
String msg = target + " received " + arg;
if (!method.equals("Unknown.invoke")) {
msg += " (arg to " + method + ")";
} else {
msg += " (as an argument)";
}
return msg;
} else if (p.equals(Constants.mayStoreP)) {
String callSite = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
return "(" + callSite + " may store result in " + target + ")";
} else if (p.equals(Constants.didCall3P)) {
String caller = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
String method = tuple.get(2).getValue().toString();
int i = method.indexOf('.');
method = method.substring(i + 1);
return caller + " called " + target + "." + method + "()";
} else if (p.equals(Constants.didCallP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String target = getInvocation(tuple, 3);
String method = tuple.get(5).getValue().toString();
//String method = tuple.get(4).getValue().toString();
//String arg = tuple.get(5).getValue().toString();
//String result = tuple.get(6).getValue().toString();
//msg = caller + "@" + callSite + " calls " + target + "." + method;
int i = method.indexOf('.');
method = method.substring(i + 1);
String msg = caller + " called " + target + "." + method + "()";
String callerInvocation = tuple.get(1).getValue().toString();
String targetInvocation = tuple.get(4).getValue().toString();
if (callerInvocation.equals("") && targetInvocation.equals("")) {
return msg;
} else if (callerInvocation.equals(targetInvocation)) {
return msg + " [" + callerInvocation + "]";
} else {
return msg + " [" + callerInvocation + " -> " + targetInvocation + "]";
}
} else if (p.equals(Constants.didGetP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String result = tuple.get(3).getValue().toString();
return "" + caller + " got " + result;
} else if (p.equals(Constants.didGetExceptionP)) {
String caller = getInvocation(tuple, 0);
String callSite = tuple.get(2).getValue().toString();
String result = tuple.get(3).getValue().toString();
return "" + caller + " got exception " + result;
} else if (p.equals(Constants.isAP)) {
String name = tuple.get(0).getValue().toString();
String type = tuple.get(1).getValue().toString();
return type + " '" + name + "' exists";
} else if (p.equals(Constants.accessAllowedP)) {
if (!accessControlOn) {
return null; // Not interesting then
}
String caller = tuple.get(0).getValue().toString();
String target = tuple.get(1).getValue().toString();
String[] method = tuple.get(2).getValue().toString().split("\\.");
return "Access control: " + caller + " may call " + target + "." + method[1];
} else if (p.equals(Constants.fieldP)) {
String actor = tuple.get(0).getValue().toString();
String name = tuple.get(1).getValue().toString();
String value = tuple.get(2).getValue().toString();
return actor + "." + name + " = " + value;
} else if (p.equals(Constants.localP)) {
String actor = getInvocation(tuple, 0);
String[] name = tuple.get(2).getValue().toString().split("\\.");
String value = tuple.get(3).getValue().toString();
return actor + "." + name[1] + "()'s " + name[2] + " = " + value;
} else if (p.equals(Constants.mayCallObjectP)) {
String actor = getInvocation(tuple, 0);
String method = tuple.get(2).getValue().toString().split("\\.")[1].split("-")[0];
String target = tuple.get(3).getValue().toString();
return actor + "." + method + " may call " + target;
} else if (p.equals(Constants.didCreateP)) {
String actor = getInvocation(tuple, 0);
//String resultVar = tuple.get(2).getValue().toString();
String type = tuple.get(3).getValue().toString();
return actor + " created " + type;
}
return null;
}
|
diff --git a/src/manager/impl/RessourceManagerImpl.java b/src/manager/impl/RessourceManagerImpl.java
index 36e59fc..2265d48 100644
--- a/src/manager/impl/RessourceManagerImpl.java
+++ b/src/manager/impl/RessourceManagerImpl.java
@@ -1,126 +1,127 @@
package manager.impl;
import java.util.Date;
import java.util.List;
import java.util.SortedSet;
import java.util.concurrent.ConcurrentSkipListSet;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import manager.GestionnaireRessource;
import manager.Ressources;
import modele.Artiste;
import modele.Evenement;
import modele.Utilisateur;
import org.apache.log4j.Logger;
import clientrest.deezer.DeezerRestService;
import clientrest.lastFM.LastFMRestService;
import dao.DAOArtistService;
import dao.DAOUserService;
/**
* Implementation du gestionnaire de ressource
* Dispatch les ressources en fonction des besoins de l'application web
* @author nicolas
*
*/
@Stateless
public class RessourceManagerImpl implements GestionnaireRessource {
private final Logger log = Logger.getLogger(RessourceManagerImpl.class);
@EJB
private DAOArtistService unDaoArtiste;
@EJB
private DAOUserService daoUser;
@EJB
private LastFMRestService api;
@EJB
private DeezerRestService apiDeezer;
public Object get(Ressources r,String... params) {
String param = params[0];
if(r.equals(Ressources.artiste)){
Artiste a = unDaoArtiste.getUnArtiste(param);
if(a !=null ){
- a.incrementPopularity();
+ if(params.length==2 && params[1]=="view")
+ a.incrementPopularity();
unDaoArtiste.update(a);
return a;
}
else{
a = api.getDetailArtistInfo(param);
a = apiDeezer.getTrackStream(a);
SortedSet<Evenement> events = api.getArtistEvent(param);
for(Evenement event : events)
a.addEvenement(event);
unDaoArtiste.ajouterArtiste(a);
return a;
}
}
else if(r.equals(Ressources.topArtistes)){
return unDaoArtiste.topArtistes(Integer.parseInt(param));
}
else if(r.equals(Ressources.utilisateur)){
return daoUser.get(param);
}
else if(r.equals(Ressources.artistesToString)){
List<String> artistesToString = unDaoArtiste.list();
return artistesToString;
}
else if(r.equals(Ressources.evenement)){
SortedSet<Evenement> evenements = api.getArtistEvent(param);
if(evenements!=null){
return evenements;
}
else{
return new ConcurrentSkipListSet<Evenement>();
}
}
else{
return "Erreur : je n'ai pas compris ce que vous recherchiez";
}
}
public Object update(Ressources r, Object param) {
if(r.equals(Ressources.utilisateur)){
daoUser.update((Utilisateur)param);
}
return null;
}
@Override
public void add(Ressources r, Object o) {
if(r.equals(Ressources.utilisateur)){
Utilisateur uti = (Utilisateur)o;
Utilisateur user = daoUser.get(uti.getIpAdresse());
if(user==null){
user = new Utilisateur();
user.setDateDerniereConnection(new Date());
user.setIpAdresse(uti.getIpAdresse());
daoUser.add(user);
}
else{
user.setDateDerniereConnection(new Date());
daoUser.update(user);
}
}
}
}
| true | true | public Object get(Ressources r,String... params) {
String param = params[0];
if(r.equals(Ressources.artiste)){
Artiste a = unDaoArtiste.getUnArtiste(param);
if(a !=null ){
a.incrementPopularity();
unDaoArtiste.update(a);
return a;
}
else{
a = api.getDetailArtistInfo(param);
a = apiDeezer.getTrackStream(a);
SortedSet<Evenement> events = api.getArtistEvent(param);
for(Evenement event : events)
a.addEvenement(event);
unDaoArtiste.ajouterArtiste(a);
return a;
}
}
else if(r.equals(Ressources.topArtistes)){
return unDaoArtiste.topArtistes(Integer.parseInt(param));
}
else if(r.equals(Ressources.utilisateur)){
return daoUser.get(param);
}
else if(r.equals(Ressources.artistesToString)){
List<String> artistesToString = unDaoArtiste.list();
return artistesToString;
}
else if(r.equals(Ressources.evenement)){
SortedSet<Evenement> evenements = api.getArtistEvent(param);
if(evenements!=null){
return evenements;
}
else{
return new ConcurrentSkipListSet<Evenement>();
}
}
else{
return "Erreur : je n'ai pas compris ce que vous recherchiez";
}
}
| public Object get(Ressources r,String... params) {
String param = params[0];
if(r.equals(Ressources.artiste)){
Artiste a = unDaoArtiste.getUnArtiste(param);
if(a !=null ){
if(params.length==2 && params[1]=="view")
a.incrementPopularity();
unDaoArtiste.update(a);
return a;
}
else{
a = api.getDetailArtistInfo(param);
a = apiDeezer.getTrackStream(a);
SortedSet<Evenement> events = api.getArtistEvent(param);
for(Evenement event : events)
a.addEvenement(event);
unDaoArtiste.ajouterArtiste(a);
return a;
}
}
else if(r.equals(Ressources.topArtistes)){
return unDaoArtiste.topArtistes(Integer.parseInt(param));
}
else if(r.equals(Ressources.utilisateur)){
return daoUser.get(param);
}
else if(r.equals(Ressources.artistesToString)){
List<String> artistesToString = unDaoArtiste.list();
return artistesToString;
}
else if(r.equals(Ressources.evenement)){
SortedSet<Evenement> evenements = api.getArtistEvent(param);
if(evenements!=null){
return evenements;
}
else{
return new ConcurrentSkipListSet<Evenement>();
}
}
else{
return "Erreur : je n'ai pas compris ce que vous recherchiez";
}
}
|
diff --git a/src/RelationalOperatorNode.java b/src/RelationalOperatorNode.java
index 3997556..262c1d2 100644
--- a/src/RelationalOperatorNode.java
+++ b/src/RelationalOperatorNode.java
@@ -1,52 +1,52 @@
/*
* Implements Semantic checking and code output generation for
* EqualityOperands
*
* Example - a LT 3
* b LT 5
*/
class RelationalOperatorNode extends ASTNode {
/*
* Instantiates EqualityOperator invoked by this grammar:
* equality_operand LT relational_operand
* equality_operand GT relational_operand
*
*
* @param op specifies the type of operator
* @param lcNode,rcNode represents nodes of operand
* @param yyline,yycolumn represents nodes line number and column number
*/
public RelationalOperatorNode(String op, ASTNode lcNode, ASTNode rcNode,
int yyline, int yycolumn) {
super(yyline, yycolumn);
this.addChild(lcNode);
this.addChild(rcNode);
}
/*
* symnatic check
*
*/
@Override
public void checkSemantics() throws Exception{
//symantic check for children
this.getChildAt(0).checkSemantics();
this.getChildAt(1).checkSemantics();
//type check
if (!this.getChildAt(0).getType().equals(this.getChildAt(1).getType())) {
throw new Exception("Type Mismatch : Cannot Add" + this.getChildAt(0).getType()
+ " and " + this.getChildAt(1).getType()+ "-- at "
+ this.getChildAt(0).getYyline() + ":" + this.getChildAt(0).getYycolumn());
}
- this.setType(this.getChildAt(0).getType());
+ this.setType("boolean");
return;
}
@Override
public String generateCode() {
// TODO Auto-generated method stub
return null;
}
}
| true | true | public void checkSemantics() throws Exception{
//symantic check for children
this.getChildAt(0).checkSemantics();
this.getChildAt(1).checkSemantics();
//type check
if (!this.getChildAt(0).getType().equals(this.getChildAt(1).getType())) {
throw new Exception("Type Mismatch : Cannot Add" + this.getChildAt(0).getType()
+ " and " + this.getChildAt(1).getType()+ "-- at "
+ this.getChildAt(0).getYyline() + ":" + this.getChildAt(0).getYycolumn());
}
this.setType(this.getChildAt(0).getType());
return;
}
| public void checkSemantics() throws Exception{
//symantic check for children
this.getChildAt(0).checkSemantics();
this.getChildAt(1).checkSemantics();
//type check
if (!this.getChildAt(0).getType().equals(this.getChildAt(1).getType())) {
throw new Exception("Type Mismatch : Cannot Add" + this.getChildAt(0).getType()
+ " and " + this.getChildAt(1).getType()+ "-- at "
+ this.getChildAt(0).getYyline() + ":" + this.getChildAt(0).getYycolumn());
}
this.setType("boolean");
return;
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java b/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java
index 6447729b..fa622f3c 100644
--- a/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java
+++ b/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java
@@ -1,346 +1,346 @@
/*
* Copyright (C) 2009.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 or
* 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.
*/
package uk.me.parabola.imgfmt.app.mdr;
import uk.me.parabola.imgfmt.app.BufferedImgFileReader;
import uk.me.parabola.imgfmt.app.BufferedImgFileWriter;
import uk.me.parabola.imgfmt.app.ImgFile;
import uk.me.parabola.imgfmt.app.ImgFileWriter;
import uk.me.parabola.imgfmt.app.Label;
import uk.me.parabola.imgfmt.app.lbl.Country;
import uk.me.parabola.imgfmt.app.lbl.Region;
import uk.me.parabola.imgfmt.app.lbl.Zip;
import uk.me.parabola.imgfmt.app.net.RoadDef;
import uk.me.parabola.imgfmt.app.srt.Sort;
import uk.me.parabola.imgfmt.app.trergn.Point;
import uk.me.parabola.imgfmt.fs.ImgChannel;
/**
* The MDR file. This is embedded into a .img file, either its own
* separate one, or as one file in the gmapsupp.img.
*
* @author Steve Ratcliffe
*/
public class MDRFile extends ImgFile {
private final MDRHeader mdrHeader;
// The sections
private final Mdr1 mdr1;
private final Mdr4 mdr4;
private final Mdr5 mdr5;
private final Mdr6 mdr6;
private final Mdr7 mdr7;
private final Mdr8 mdr8;
private final Mdr9 mdr9;
private final Mdr10 mdr10;
private final Mdr11 mdr11;
private final Mdr12 mdr12;
private final Mdr13 mdr13;
private final Mdr14 mdr14;
private final Mdr15 mdr15;
private final Mdr20 mdr20;
private final Mdr21 mdr21;
private final Mdr22 mdr22;
private final Mdr23 mdr23;
private final Mdr24 mdr24;
private final Mdr25 mdr25;
private final Mdr26 mdr26;
private final Mdr27 mdr27;
private final Mdr28 mdr28;
private final Mdr29 mdr29;
private int currentMap;
private final MdrSection[] sections;
private MdrSection.PointerSizes sizes;
public MDRFile(ImgChannel chan, MdrConfig config) {
Sort sort = config.getSort();
mdrHeader = new MDRHeader(config.getHeaderLen());
mdrHeader.setSort(sort);
setHeader(mdrHeader);
if (config.isWritable()) {
BufferedImgFileWriter fileWriter = new BufferedImgFileWriter(chan);
fileWriter.setMaxSize(Long.MAX_VALUE);
setWriter(fileWriter);
// Position at the start of the writable area.
position(mdrHeader.getHeaderLength());
} else {
setReader(new BufferedImgFileReader(chan));
mdrHeader.readHeader(getReader());
}
// Initialise the sections
mdr1 = new Mdr1(config);
mdr4 = new Mdr4(config);
mdr5 = new Mdr5(config);
mdr6 = new Mdr6(config);
mdr7 = new Mdr7(config);
mdr8 = new Mdr8(config);
mdr9 = new Mdr9(config);
mdr10 = new Mdr10(config);
mdr11 = new Mdr11(config);
mdr12 = new Mdr12(config);
mdr13 = new Mdr13(config);
mdr14 = new Mdr14(config);
mdr15 = new Mdr15(config);
mdr20 = new Mdr20(config);
mdr21 = new Mdr21(config);
mdr22 = new Mdr22(config);
mdr23 = new Mdr23(config);
mdr24 = new Mdr24(config);
mdr25 = new Mdr25(config);
mdr26 = new Mdr26(config);
mdr27 = new Mdr27(config);
mdr28 = new Mdr28(config);
mdr29 = new Mdr29(config);
this.sections = new MdrSection[]{
null,
mdr1, null, null, mdr4, mdr5, mdr6,
mdr7, mdr8, mdr9, mdr10, mdr11, mdr12,
mdr13, mdr14, mdr15, null, null, null, null,
mdr20, mdr21, mdr22, mdr23, mdr24, mdr25,
mdr26, mdr27, mdr28, mdr29,
};
mdr11.setMdr10(mdr10);
}
/**
* Add a map to the index. You must add the map, then all of the items
* that belong to it, before adding the next map.
* @param mapName The numeric name of the map.
*/
public void addMap(int mapName) {
currentMap++;
mdr1.addMap(mapName);
}
public Mdr14Record addCountry(Country country) {
Mdr14Record record = new Mdr14Record();
String name = country.getLabel().getText();
record.setMapIndex(currentMap);
record.setCountryIndex((int) country.getIndex());
record.setLblOffset(country.getLabel().getOffset());
record.setName(name);
record.setStrOff(createString(name));
mdr14.addCountry(record);
return record;
}
public Mdr13Record addRegion(Region region, Mdr14Record country) {
Mdr13Record record = new Mdr13Record();
String name = region.getLabel().getText();
record.setMapIndex(currentMap);
record.setLblOffset(region.getLabel().getOffset());
record.setCountryIndex(region.getCountry().getIndex());
record.setRegionIndex(region.getIndex());
record.setName(name);
record.setStrOffset(createString(name));
record.setMdr14(country);
mdr13.addRegion(record);
return record;
}
public void addCity(Mdr5Record city) {
int labelOffset = city.getLblOffset();
if (labelOffset != 0) {
String name = city.getName();
assert name != null : "off=" + labelOffset;
city.setMapIndex(currentMap);
city.setStringOffset(createString(name));
mdr5.addCity(city);
}
}
public void addZip(Zip zip) {
int strOff = createString(zip.getLabel().getText());
mdr6.addZip(currentMap, zip, strOff);
}
public void addPoint(Point point, Mdr5Record city, boolean isCity) {
assert currentMap > 0;
int fullType = point.getType();
if (!MdrUtils.canBeIndexed(fullType))
return;
Label label = point.getLabel();
String name = label.getText();
int strOff = createString(name);
Mdr11Record poi = mdr11.addPoi(currentMap, point, name, strOff);
poi.setCity(city);
poi.setIsCity(isCity);
poi.setType(fullType);
mdr4.addType(point.getType());
}
public void addStreet(RoadDef street, Mdr5Record mdrCity) {
// Add a separate record for each name
for (Label lab : street.getLabels()) {
if (lab == null)
break;
String name = lab.getText();
String cleanName = cleanUpName(name);
int strOff = createString(cleanName);
// XXX not sure: we sort on the dirty name (ie with the Garmin shield codes).
mdr7.addStreet(currentMap, name, lab.getOffset(), strOff, mdrCity);
}
}
/**
* Remove shields and other kinds of strange characters. Perform any
* rearrangement of the name to make it searchable.
* @param name The street name as read from the img file.
* @return The name as it will go into the index.
*/
private String cleanUpName(String name) {
return Label.stripGarminCodes(name);
}
public void write() {
for (MdrSection s : sections) {
if (s != null)
s.finish();
}
ImgFileWriter writer = getWriter();
writeSections(writer);
// Now refresh the header
position(0);
getHeader().writeHeader(writer);
}
/**
* Write all the sections out.
*
* The order of all the operations in this method is important. The order
* of the sections in the actual
* @param writer File is written here.
*/
private void writeSections(ImgFileWriter writer) {
sizes = new MdrMapSection.PointerSizes(sections);
// Deal with the dependencies between the sections. The order of the following
// statements is sometimes important.
mdr10.setNumberOfPois(mdr11.getNumberOfPois());
mdr28.buildFromRegions(mdr13.getRegions());
mdr23.sortRegions(mdr13.getRegions());
mdr29.buildFromCountries(mdr14.getCountries());
mdr24.sortCountries(mdr14.getCountries());
mdr20.buildFromStreets(mdr7.getStreets(), mdr5);
mdr21.buildFromStreets(mdr7.getStreets());
mdr22.buildFromStreets(mdr7.getStreets());
mdr8.setIndex(mdr7.getIndex());
mdr9.setGroups(mdr10.getGroupSizes());
mdr12.setIndex(mdr11.getIndex());
mdr25.sortCities(mdr5.getCities());
mdr27.sortCities(mdr5.getCities());
mdr26.sortMdr28(mdr28.getIndex());
writeSection(writer, 4, mdr4);
// We write the following sections that contain per-map data, in the
// order of the subsections of the reverse index that they are associated
// with.
writeSection(writer, 11, mdr11);
writeSection(writer, 10, mdr10);
writeSection(writer, 7, mdr7);
writeSection(writer, 5, mdr5);
writeSection(writer, 6, mdr6);
writeSection(writer, 20, mdr20);
writeSection(writer, 21, mdr21);
writeSection(writer, 22, mdr22);
// There is no ordering constraint on the following
- writeSection(writer, 8, mdr8);
+ //writeSection(writer, 8, mdr8);
writeSection(writer, 9, mdr9);
writeSection(writer, 12, mdr12);
writeSection(writer, 13, mdr13);
writeSection(writer, 14, mdr14);
writeSection(writer, 15, mdr15);
writeSection(writer, 23, mdr23);
writeSection(writer, 24, mdr24);
writeSection(writer, 25, mdr25);
writeSection(writer, 26, mdr26);
writeSection(writer, 27, mdr27);
writeSection(writer, 28, mdr28);
writeSection(writer, 29, mdr29);
// write the reverse index last.
mdr1.writeSubSections(writer);
mdrHeader.setPosition(1, writer.position());
mdr1.writeSectData(writer);
mdrHeader.setItemSize(1, mdr1.getItemSize());
mdrHeader.setEnd(1, writer.position());
mdrHeader.setExtraValue(1, mdr1.getExtraValue());
}
/**
* Write out the given single section.
*/
private void writeSection(ImgFileWriter writer, int sectionNumber, MdrSection section) {
section.setSizes(sizes);
mdrHeader.setPosition(sectionNumber, writer.position());
mdr1.setStartPosition(sectionNumber);
if (section instanceof MdrMapSection) {
MdrMapSection mapSection = (MdrMapSection) section;
mapSection.setMapIndex(mdr1);
mapSection.initIndex(sectionNumber);
}
if (section instanceof HasHeaderFlags)
mdrHeader.setExtraValue(sectionNumber, ((HasHeaderFlags) section).getExtraValue());
section.writeSectData(writer);
int itemSize = section.getItemSize();
if (itemSize > 0)
mdrHeader.setItemSize(sectionNumber, itemSize);
mdrHeader.setEnd(sectionNumber, writer.position());
mdr1.setEndPosition(sectionNumber);
}
/**
* Creates a string in MDR 15 and returns an offset value that can be
* used to refer to it in the other sections.
* @param str The text of the string.
* @return An offset value.
*/
private int createString(String str) {
return mdr15.createString(str.toUpperCase());
}
}
| true | true | private void writeSections(ImgFileWriter writer) {
sizes = new MdrMapSection.PointerSizes(sections);
// Deal with the dependencies between the sections. The order of the following
// statements is sometimes important.
mdr10.setNumberOfPois(mdr11.getNumberOfPois());
mdr28.buildFromRegions(mdr13.getRegions());
mdr23.sortRegions(mdr13.getRegions());
mdr29.buildFromCountries(mdr14.getCountries());
mdr24.sortCountries(mdr14.getCountries());
mdr20.buildFromStreets(mdr7.getStreets(), mdr5);
mdr21.buildFromStreets(mdr7.getStreets());
mdr22.buildFromStreets(mdr7.getStreets());
mdr8.setIndex(mdr7.getIndex());
mdr9.setGroups(mdr10.getGroupSizes());
mdr12.setIndex(mdr11.getIndex());
mdr25.sortCities(mdr5.getCities());
mdr27.sortCities(mdr5.getCities());
mdr26.sortMdr28(mdr28.getIndex());
writeSection(writer, 4, mdr4);
// We write the following sections that contain per-map data, in the
// order of the subsections of the reverse index that they are associated
// with.
writeSection(writer, 11, mdr11);
writeSection(writer, 10, mdr10);
writeSection(writer, 7, mdr7);
writeSection(writer, 5, mdr5);
writeSection(writer, 6, mdr6);
writeSection(writer, 20, mdr20);
writeSection(writer, 21, mdr21);
writeSection(writer, 22, mdr22);
// There is no ordering constraint on the following
writeSection(writer, 8, mdr8);
writeSection(writer, 9, mdr9);
writeSection(writer, 12, mdr12);
writeSection(writer, 13, mdr13);
writeSection(writer, 14, mdr14);
writeSection(writer, 15, mdr15);
writeSection(writer, 23, mdr23);
writeSection(writer, 24, mdr24);
writeSection(writer, 25, mdr25);
writeSection(writer, 26, mdr26);
writeSection(writer, 27, mdr27);
writeSection(writer, 28, mdr28);
writeSection(writer, 29, mdr29);
// write the reverse index last.
mdr1.writeSubSections(writer);
mdrHeader.setPosition(1, writer.position());
mdr1.writeSectData(writer);
mdrHeader.setItemSize(1, mdr1.getItemSize());
mdrHeader.setEnd(1, writer.position());
mdrHeader.setExtraValue(1, mdr1.getExtraValue());
}
| private void writeSections(ImgFileWriter writer) {
sizes = new MdrMapSection.PointerSizes(sections);
// Deal with the dependencies between the sections. The order of the following
// statements is sometimes important.
mdr10.setNumberOfPois(mdr11.getNumberOfPois());
mdr28.buildFromRegions(mdr13.getRegions());
mdr23.sortRegions(mdr13.getRegions());
mdr29.buildFromCountries(mdr14.getCountries());
mdr24.sortCountries(mdr14.getCountries());
mdr20.buildFromStreets(mdr7.getStreets(), mdr5);
mdr21.buildFromStreets(mdr7.getStreets());
mdr22.buildFromStreets(mdr7.getStreets());
mdr8.setIndex(mdr7.getIndex());
mdr9.setGroups(mdr10.getGroupSizes());
mdr12.setIndex(mdr11.getIndex());
mdr25.sortCities(mdr5.getCities());
mdr27.sortCities(mdr5.getCities());
mdr26.sortMdr28(mdr28.getIndex());
writeSection(writer, 4, mdr4);
// We write the following sections that contain per-map data, in the
// order of the subsections of the reverse index that they are associated
// with.
writeSection(writer, 11, mdr11);
writeSection(writer, 10, mdr10);
writeSection(writer, 7, mdr7);
writeSection(writer, 5, mdr5);
writeSection(writer, 6, mdr6);
writeSection(writer, 20, mdr20);
writeSection(writer, 21, mdr21);
writeSection(writer, 22, mdr22);
// There is no ordering constraint on the following
//writeSection(writer, 8, mdr8);
writeSection(writer, 9, mdr9);
writeSection(writer, 12, mdr12);
writeSection(writer, 13, mdr13);
writeSection(writer, 14, mdr14);
writeSection(writer, 15, mdr15);
writeSection(writer, 23, mdr23);
writeSection(writer, 24, mdr24);
writeSection(writer, 25, mdr25);
writeSection(writer, 26, mdr26);
writeSection(writer, 27, mdr27);
writeSection(writer, 28, mdr28);
writeSection(writer, 29, mdr29);
// write the reverse index last.
mdr1.writeSubSections(writer);
mdrHeader.setPosition(1, writer.position());
mdr1.writeSectData(writer);
mdrHeader.setItemSize(1, mdr1.getItemSize());
mdrHeader.setEnd(1, writer.position());
mdrHeader.setExtraValue(1, mdr1.getExtraValue());
}
|
diff --git a/src/com/jidesoft/swing/MultilineLabel.java b/src/com/jidesoft/swing/MultilineLabel.java
index cbaa08ab..2924678a 100644
--- a/src/com/jidesoft/swing/MultilineLabel.java
+++ b/src/com/jidesoft/swing/MultilineLabel.java
@@ -1,69 +1,70 @@
/*
* @(#)MultilineLabel.java
*
* Copyright 2002 JIDE Software. All rights reserved.
*/
package com.jidesoft.swing;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
import java.awt.*;
/**
* Normal JLabel cannot have multiple lines. If you want to multiple label, you can use this class.
*/
public class MultilineLabel extends JTextArea {
public MultilineLabel() {
initComponents();
}
public MultilineLabel(String s) {
super(s);
initComponents();
}
private void initComponents() {
adjustUI();
}
/**
* Reloads the pluggable UI. The key used to fetch the new interface is <code>getUIClassID()</code>. The type of
* the UI is <code>TextUI</code>. <code>invalidate</code> is called after setting the UI.
*/
@Override
public void updateUI() {
super.updateUI();
adjustUI();
}
/**
* Adjusts UI to make sure it looks like a label instead of a text area.
*/
protected void adjustUI() {
setLineWrap(true);
setWrapStyleWord(true);
setEditable(false);
setRequestFocusEnabled(false);
setFocusable(false);
setOpaque(false);
+ putClientProperty("Synthetica.opaque", false);
setCaret(new DefaultCaret() {
@Override
protected void adjustVisibility(Rectangle nloc) {
}
});
LookAndFeel.installBorder(this, "Label.border");
LookAndFeel.installColorsAndFont(this, "Label.background", "Label.foreground", "Label.font");
}
/**
* Overrides <code>getMinimumSize</code> to return <code>getPreferredSize()</code> instead. We did this because of a
* bug at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4824261.
*
* @return the preferred size as minimum size.
*/
@Override
public Dimension getMinimumSize() {
return getPreferredSize();
}
}
| true | true | protected void adjustUI() {
setLineWrap(true);
setWrapStyleWord(true);
setEditable(false);
setRequestFocusEnabled(false);
setFocusable(false);
setOpaque(false);
setCaret(new DefaultCaret() {
@Override
protected void adjustVisibility(Rectangle nloc) {
}
});
LookAndFeel.installBorder(this, "Label.border");
LookAndFeel.installColorsAndFont(this, "Label.background", "Label.foreground", "Label.font");
}
| protected void adjustUI() {
setLineWrap(true);
setWrapStyleWord(true);
setEditable(false);
setRequestFocusEnabled(false);
setFocusable(false);
setOpaque(false);
putClientProperty("Synthetica.opaque", false);
setCaret(new DefaultCaret() {
@Override
protected void adjustVisibility(Rectangle nloc) {
}
});
LookAndFeel.installBorder(this, "Label.border");
LookAndFeel.installColorsAndFont(this, "Label.background", "Label.foreground", "Label.font");
}
|
diff --git a/src/main/java/com/ardublock/translator/block/EqualPolyBlock.java b/src/main/java/com/ardublock/translator/block/EqualPolyBlock.java
index 5add869..5009694 100644
--- a/src/main/java/com/ardublock/translator/block/EqualPolyBlock.java
+++ b/src/main/java/com/ardublock/translator/block/EqualPolyBlock.java
@@ -1,25 +1,25 @@
package com.ardublock.translator.block;
import com.ardublock.translator.Translator;
import com.ardublock.translator.block.exception.SocketNullException;
import com.ardublock.translator.block.exception.SubroutineNotDeclaredException;
public class EqualPolyBlock extends TranslatorBlock
{
public EqualPolyBlock(Long blockId, Translator translator, String codePrefix, String codeSuffix, String label)
{
super(blockId, translator, codePrefix, codeSuffix, label);
}
public String toCode() throws SocketNullException, SubroutineNotDeclaredException
{
String ret = "( ( ";
TranslatorBlock tb = this.getRequiredTranslatorBlockAtSocket(0);
ret = ret + tb.toCode();
- ret = ret + " ) == ( ";
+ ret = ret + " ) == (\'";
tb = this.getRequiredTranslatorBlockAtSocket(1);
- ret = ret + tb.toCode();
- ret = ret + " ) )";
+ ret = ret + tb.toCode().replace("\"","");
+ ret = ret + "\') )";
return codePrefix + ret + codeSuffix;
}
}
| false | true | public String toCode() throws SocketNullException, SubroutineNotDeclaredException
{
String ret = "( ( ";
TranslatorBlock tb = this.getRequiredTranslatorBlockAtSocket(0);
ret = ret + tb.toCode();
ret = ret + " ) == ( ";
tb = this.getRequiredTranslatorBlockAtSocket(1);
ret = ret + tb.toCode();
ret = ret + " ) )";
return codePrefix + ret + codeSuffix;
}
| public String toCode() throws SocketNullException, SubroutineNotDeclaredException
{
String ret = "( ( ";
TranslatorBlock tb = this.getRequiredTranslatorBlockAtSocket(0);
ret = ret + tb.toCode();
ret = ret + " ) == (\'";
tb = this.getRequiredTranslatorBlockAtSocket(1);
ret = ret + tb.toCode().replace("\"","");
ret = ret + "\') )";
return codePrefix + ret + codeSuffix;
}
|
diff --git a/src/web/org/appfuse/webapp/action/UploadAction.java b/src/web/org/appfuse/webapp/action/UploadAction.java
index 01055026..b721bbd8 100644
--- a/src/web/org/appfuse/webapp/action/UploadAction.java
+++ b/src/web/org/appfuse/webapp/action/UploadAction.java
@@ -1,123 +1,122 @@
package org.appfuse.webapp.action;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.appfuse.Constants;
import org.appfuse.webapp.form.UploadForm;
/**
* This class handles the uploading of a resume (or any file) and writing it to
* the filesystem. Eventually, it will also add support for persisting the
* files information into the database.
*
* <p>
* <a href="UploadAction.java.html"><i>View Source</i></a>
* </p>
*
* @author <a href="mailto:[email protected]">Matt Raible</a>
*
* @struts.action name="uploadForm" path="/uploadFile" scope="request"
* validate="true" input="failure"
*
* @struts.action-forward name="failure" path="/WEB-INF/pages/uploadForm.jsp"
* @struts.action-forward name="success" path="/WEB-INF/pages/uploadDisplay.jsp"
*/
public class UploadAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// Did the user click the cancel button?
if (isCancelled(request)) {
request.removeAttribute(mapping.getAttribute());
return (mapping.findForward("mainMenu"));
}
//this line is here for when the input page is upload-utf8.jsp,
//it sets the correct character encoding for the response
String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
response.setContentType("text/html; charset=utf-8");
}
UploadForm theForm = (UploadForm) form;
//retrieve the name
String name = theForm.getName();
//retrieve the file representation
FormFile file = theForm.getFile();
//retrieve the file name
String fileName = file.getFileName();
//retrieve the content type
String contentType = file.getContentType();
//retrieve the file size
String size = (file.getFileSize() + " bytes");
String data = null;
String location = null;
// the directory to upload to
String uploadDir =
servlet.getServletContext().getRealPath("/resources") + "/"
+ request.getRemoteUser() + "/";
//write the file to the file specified
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
//retrieve the file data
InputStream stream = file.getInputStream();
//write the file to the file specified
OutputStream bos = new FileOutputStream(uploadDir + fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
- location =
- "The file has been written to <br />\"" + dirPath.getAbsolutePath()
- + Constants.FILE_SEP + file.getFileName() + "\"";
+ location = dirPath.getAbsolutePath()
+ + Constants.FILE_SEP + file.getFileName();
//close the stream
stream.close();
// place the data into the request for retrieval on next page
request.setAttribute("friendlyName", name);
request.setAttribute("fileName", fileName);
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("data", data);
request.setAttribute("location", location);
//destroy the temporary file created
file.destroy();
//return a forward to display.jsp
return mapping.findForward("success");
}
}
| true | true | public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// Did the user click the cancel button?
if (isCancelled(request)) {
request.removeAttribute(mapping.getAttribute());
return (mapping.findForward("mainMenu"));
}
//this line is here for when the input page is upload-utf8.jsp,
//it sets the correct character encoding for the response
String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
response.setContentType("text/html; charset=utf-8");
}
UploadForm theForm = (UploadForm) form;
//retrieve the name
String name = theForm.getName();
//retrieve the file representation
FormFile file = theForm.getFile();
//retrieve the file name
String fileName = file.getFileName();
//retrieve the content type
String contentType = file.getContentType();
//retrieve the file size
String size = (file.getFileSize() + " bytes");
String data = null;
String location = null;
// the directory to upload to
String uploadDir =
servlet.getServletContext().getRealPath("/resources") + "/"
+ request.getRemoteUser() + "/";
//write the file to the file specified
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
//retrieve the file data
InputStream stream = file.getInputStream();
//write the file to the file specified
OutputStream bos = new FileOutputStream(uploadDir + fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
location =
"The file has been written to <br />\"" + dirPath.getAbsolutePath()
+ Constants.FILE_SEP + file.getFileName() + "\"";
//close the stream
stream.close();
// place the data into the request for retrieval on next page
request.setAttribute("friendlyName", name);
request.setAttribute("fileName", fileName);
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("data", data);
request.setAttribute("location", location);
//destroy the temporary file created
file.destroy();
//return a forward to display.jsp
return mapping.findForward("success");
}
| public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
// Did the user click the cancel button?
if (isCancelled(request)) {
request.removeAttribute(mapping.getAttribute());
return (mapping.findForward("mainMenu"));
}
//this line is here for when the input page is upload-utf8.jsp,
//it sets the correct character encoding for the response
String encoding = request.getCharacterEncoding();
if ((encoding != null) && (encoding.equalsIgnoreCase("utf-8"))) {
response.setContentType("text/html; charset=utf-8");
}
UploadForm theForm = (UploadForm) form;
//retrieve the name
String name = theForm.getName();
//retrieve the file representation
FormFile file = theForm.getFile();
//retrieve the file name
String fileName = file.getFileName();
//retrieve the content type
String contentType = file.getContentType();
//retrieve the file size
String size = (file.getFileSize() + " bytes");
String data = null;
String location = null;
// the directory to upload to
String uploadDir =
servlet.getServletContext().getRealPath("/resources") + "/"
+ request.getRemoteUser() + "/";
//write the file to the file specified
File dirPath = new File(uploadDir);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
//retrieve the file data
InputStream stream = file.getInputStream();
//write the file to the file specified
OutputStream bos = new FileOutputStream(uploadDir + fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
bos.close();
location = dirPath.getAbsolutePath()
+ Constants.FILE_SEP + file.getFileName();
//close the stream
stream.close();
// place the data into the request for retrieval on next page
request.setAttribute("friendlyName", name);
request.setAttribute("fileName", fileName);
request.setAttribute("contentType", contentType);
request.setAttribute("size", size);
request.setAttribute("data", data);
request.setAttribute("location", location);
//destroy the temporary file created
file.destroy();
//return a forward to display.jsp
return mapping.findForward("success");
}
|
diff --git a/core/src/main/java/juzu/impl/bridge/spi/portlet/PortletRenderBridge.java b/core/src/main/java/juzu/impl/bridge/spi/portlet/PortletRenderBridge.java
index 8b92d75b..1f4acab3 100644
--- a/core/src/main/java/juzu/impl/bridge/spi/portlet/PortletRenderBridge.java
+++ b/core/src/main/java/juzu/impl/bridge/spi/portlet/PortletRenderBridge.java
@@ -1,186 +1,185 @@
/*
* Copyright (C) 2012 eXo Platform SAS.
*
* This 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 software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package juzu.impl.bridge.spi.portlet;
import juzu.Response;
import juzu.asset.Asset;
import juzu.impl.application.ApplicationContext;
import juzu.impl.bridge.Bridge;
import juzu.impl.inject.ScopedContext;
import juzu.impl.bridge.spi.RenderBridge;
import juzu.request.Phase;
import org.w3c.dom.Comment;
import org.w3c.dom.Element;
import javax.portlet.MimeResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceURL;
import java.io.IOException;
import java.util.LinkedList;
/** @author <a href="mailto:[email protected]">Julien Viet</a> */
public class PortletRenderBridge extends PortletMimeBridge<RenderRequest, RenderResponse> implements RenderBridge {
/** . */
private final Bridge bridge;
/** . */
private String title;
/** . */
private LinkedList<Element> headers = new LinkedList<Element>();
public PortletRenderBridge(ApplicationContext application, Bridge bridge, RenderRequest request, RenderResponse response, boolean prod) {
super(application, request, response, prod);
//
this.bridge = bridge;
}
@Override
protected Phase getPhase() {
return Phase.RENDER;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public void setResponse(Response response) throws IllegalStateException, IOException {
super.setResponse(response);
if (response instanceof Response.Content) {
Response.Content content = (Response.Content)response;
//
if (content instanceof Response.Render) {
Response.Render render = (Response.Render)response;
Iterable<Asset.Value> scripts = bridge.runtime.getScriptManager().resolveAssets(render.getScripts());
Iterable<Asset.Value> stylesheets = bridge.runtime.getStylesheetManager().resolveAssets(render.getStylesheets());
//
for (Asset.Value stylesheet : stylesheets) {
int pos = stylesheet.getURI().lastIndexOf('.');
String ext = pos == -1 ? "css" : stylesheet.getURI().substring(pos + 1);
Element elt = this.resp.createElement("link");
elt.setAttribute("media", "screen");
elt.setAttribute("rel", "stylesheet");
elt.setAttribute("type", "text/" + ext);
elt.setAttribute("href", getAssetURL(stylesheet));
headers.add(elt);
- this.resp.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, elt);
}
//
for (Asset.Value script : scripts) {
String url = getAssetURL(script);
Element elt = this.resp.createElement("script");
elt.setAttribute("type", "text/javascript");
elt.setAttribute("src", url);
// This comment is needed for liferay to make the script pass the minifier
// it forces to have a <script></script> tag
Comment comment = elt.getOwnerDocument().createComment(request.getApplication().getName() + " script ");
elt.appendChild(comment);
headers.add(elt);
}
//
String title = render.getTitle();
if (title != null) {
this.title = title;
}
}
//
super.setResponse(response);
} else {
throw new IllegalArgumentException();
}
}
private String getAssetURL(Asset.Value asset) {
StringBuilder sb;
String url;
String uri = asset.getURI();
switch (asset.getLocation()) {
case SERVER:
sb = new StringBuilder();
if (!uri.startsWith("/")) {
sb.append(req.getContextPath());
sb.append('/');
}
sb.append(uri);
url = sb.toString();
break;
case CLASSPATH:
if (prod) {
sb = new StringBuilder();
sb.append(req.getContextPath()).append("/assets");
if (!uri.startsWith("/")) {
sb.append('/');
}
sb.append(uri);
url = sb.toString();
}
else {
ResourceURL r = resp.createResourceURL();
r.setParameter("juzu.request", "assets");
r.setResourceID(uri);
url = r.toString();
}
break;
case EXTERNAL:
url = uri;
break;
default:
throw new AssertionError();
}
return url;
}
@Override
public void end() {
super.end();
//
ScopedContext context = getFlashContext(false);
if (context != null) {
context.close();
}
}
@Override
public void send() throws IOException {
// Set title
if (title != null) {
resp.setTitle(title);
}
// Add elements
for (Element elt : headers) {
resp.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, elt);
}
//
super.send();
}
}
| true | true | public void setResponse(Response response) throws IllegalStateException, IOException {
super.setResponse(response);
if (response instanceof Response.Content) {
Response.Content content = (Response.Content)response;
//
if (content instanceof Response.Render) {
Response.Render render = (Response.Render)response;
Iterable<Asset.Value> scripts = bridge.runtime.getScriptManager().resolveAssets(render.getScripts());
Iterable<Asset.Value> stylesheets = bridge.runtime.getStylesheetManager().resolveAssets(render.getStylesheets());
//
for (Asset.Value stylesheet : stylesheets) {
int pos = stylesheet.getURI().lastIndexOf('.');
String ext = pos == -1 ? "css" : stylesheet.getURI().substring(pos + 1);
Element elt = this.resp.createElement("link");
elt.setAttribute("media", "screen");
elt.setAttribute("rel", "stylesheet");
elt.setAttribute("type", "text/" + ext);
elt.setAttribute("href", getAssetURL(stylesheet));
headers.add(elt);
this.resp.addProperty(MimeResponse.MARKUP_HEAD_ELEMENT, elt);
}
//
for (Asset.Value script : scripts) {
String url = getAssetURL(script);
Element elt = this.resp.createElement("script");
elt.setAttribute("type", "text/javascript");
elt.setAttribute("src", url);
// This comment is needed for liferay to make the script pass the minifier
// it forces to have a <script></script> tag
Comment comment = elt.getOwnerDocument().createComment(request.getApplication().getName() + " script ");
elt.appendChild(comment);
headers.add(elt);
}
//
String title = render.getTitle();
if (title != null) {
this.title = title;
}
}
//
super.setResponse(response);
} else {
throw new IllegalArgumentException();
}
}
| public void setResponse(Response response) throws IllegalStateException, IOException {
super.setResponse(response);
if (response instanceof Response.Content) {
Response.Content content = (Response.Content)response;
//
if (content instanceof Response.Render) {
Response.Render render = (Response.Render)response;
Iterable<Asset.Value> scripts = bridge.runtime.getScriptManager().resolveAssets(render.getScripts());
Iterable<Asset.Value> stylesheets = bridge.runtime.getStylesheetManager().resolveAssets(render.getStylesheets());
//
for (Asset.Value stylesheet : stylesheets) {
int pos = stylesheet.getURI().lastIndexOf('.');
String ext = pos == -1 ? "css" : stylesheet.getURI().substring(pos + 1);
Element elt = this.resp.createElement("link");
elt.setAttribute("media", "screen");
elt.setAttribute("rel", "stylesheet");
elt.setAttribute("type", "text/" + ext);
elt.setAttribute("href", getAssetURL(stylesheet));
headers.add(elt);
}
//
for (Asset.Value script : scripts) {
String url = getAssetURL(script);
Element elt = this.resp.createElement("script");
elt.setAttribute("type", "text/javascript");
elt.setAttribute("src", url);
// This comment is needed for liferay to make the script pass the minifier
// it forces to have a <script></script> tag
Comment comment = elt.getOwnerDocument().createComment(request.getApplication().getName() + " script ");
elt.appendChild(comment);
headers.add(elt);
}
//
String title = render.getTitle();
if (title != null) {
this.title = title;
}
}
//
super.setResponse(response);
} else {
throw new IllegalArgumentException();
}
}
|
diff --git a/src/main/java/com/google/gwt/sample/stockwatcher/modules/stockreader/client/handlers/SubmitButtonClickHandler.java b/src/main/java/com/google/gwt/sample/stockwatcher/modules/stockreader/client/handlers/SubmitButtonClickHandler.java
index 177356d..62d8292 100644
--- a/src/main/java/com/google/gwt/sample/stockwatcher/modules/stockreader/client/handlers/SubmitButtonClickHandler.java
+++ b/src/main/java/com/google/gwt/sample/stockwatcher/modules/stockreader/client/handlers/SubmitButtonClickHandler.java
@@ -1,50 +1,48 @@
package com.google.gwt.sample.stockwatcher.modules.stockreader.client.handlers;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.sample.stockwatcher.modules.stockreader.client.callbacks.JSONRequestCallback;
import com.google.gwt.sample.stockwatcher.modules.stockreader.client.model.StockData;
import com.google.gwt.sample.stockwatcher.modules.stockreader.client.widgets.CurrenciesTextField;
import com.sencha.gxt.widget.core.client.box.AlertMessageBox;
import com.sencha.gxt.widget.core.client.info.Info;
/**
* Submit button click handler.
*/
public class SubmitButtonClickHandler implements ClickHandler {
private static final String JSON_URL = GWT.getHostPageBaseURL() + "stockPricesJSON";
private CurrenciesTextField currenciesTextField;
public SubmitButtonClickHandler(CurrenciesTextField currenciesTextField) {
this.currenciesTextField = currenciesTextField;
}
@Override
public void onClick(ClickEvent event) {
StringBuilder urlBuilder = new StringBuilder(JSON_URL);
- if (!currenciesTextField.getValue().isEmpty()) {
- urlBuilder.append("?q=")
- .append(currenciesTextField.getValue().replace(' ', '+'));
- }
+ urlBuilder.append("?q=")
+ .append(currenciesTextField.getValue().replace(' ', '+'));
String url = URL.encode(urlBuilder.toString());
// Send request to server and catch any errors.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
builder.sendRequest(null, new JSONRequestCallback());
} catch (RequestException e) {
AlertMessageBox msgBox = new AlertMessageBox("Request Error", e.getMessage());
msgBox.show();
}
}
}
| true | true | public void onClick(ClickEvent event) {
StringBuilder urlBuilder = new StringBuilder(JSON_URL);
if (!currenciesTextField.getValue().isEmpty()) {
urlBuilder.append("?q=")
.append(currenciesTextField.getValue().replace(' ', '+'));
}
String url = URL.encode(urlBuilder.toString());
// Send request to server and catch any errors.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
builder.sendRequest(null, new JSONRequestCallback());
} catch (RequestException e) {
AlertMessageBox msgBox = new AlertMessageBox("Request Error", e.getMessage());
msgBox.show();
}
}
| public void onClick(ClickEvent event) {
StringBuilder urlBuilder = new StringBuilder(JSON_URL);
urlBuilder.append("?q=")
.append(currenciesTextField.getValue().replace(' ', '+'));
String url = URL.encode(urlBuilder.toString());
// Send request to server and catch any errors.
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
try {
builder.sendRequest(null, new JSONRequestCallback());
} catch (RequestException e) {
AlertMessageBox msgBox = new AlertMessageBox("Request Error", e.getMessage());
msgBox.show();
}
}
|
diff --git a/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/runtimeinfo.java b/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/runtimeinfo.java
index d4e25a4de..202532f79 100644
--- a/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/runtimeinfo.java
+++ b/java/testing/org/apache/derbyTesting/functionTests/tests/derbynet/runtimeinfo.java
@@ -1,182 +1,184 @@
/*
Derby - Class org.apache.derbyTesting.functionTests.tests.derbynet.runtimeinfo
Copyright 2004 The Apache Software Foundation or its licensors, as applicable.
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.derbyTesting.functionTests.tests.derbynet;
import java.net.InetAddress;
import java.sql.*;
import java.util.Vector;
import java.util.Properties;
import java.io.File;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import org.apache.derbyTesting.functionTests.harness.jvm;
import org.apache.derbyTesting.functionTests.harness.ProcessStreamResult;
import org.apache.derby.drda.NetworkServerControl;
import org.apache.derby.tools.ij;
import org.apache.derbyTesting.functionTests.util.TestUtil;
import org.apache.derby.tools.JDBCDisplayUtil;
/**
This tests the runtimeinfo command
*/
public class runtimeinfo
{
private static Properties properties = new java.util.Properties();
private static jvm jvm;
private static Vector vCmd;
private static BufferedOutputStream bos;
private static String[] RuntimeinfoCmd = new String[] {"org.apache.derby.drda.NetworkServerControl",
"runtimeinfo"};
private static String[] RuntimeinfoLocaleCmd = new String[] {"-Duser.language=err",
"-Duser.country=DE", "org.apache.derby.drda.NetworkServerControl", "runtimeinfo"};
/**
* Execute the given command and dump the results to standard out
*
* @param args command and arguments
* @exception Exception
*/
private static void execCmdDumpResults (String[] args) throws Exception
{
// We need the process inputstream and errorstream
ProcessStreamResult prout = null;
ProcessStreamResult prerr = null;
bos = null;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < args.length; i++)
{
sb.append(args[i] + " ");
}
System.out.println(sb.toString());
int totalSize = vCmd.size() + args.length;
String serverCmd[] = new String[totalSize];
int i;
for (i = 0; i < vCmd.size(); i++)
{
serverCmd[i] = (String)vCmd.elementAt(i);
// System.out.println("serverCmd["+i+"]: "+serverCmd[i]);
}
int j = 0;
for (; i < totalSize; i++)
{
serverCmd[i] = args[j++];
// System.out.println("serverCmd["+i+"]: "+serverCmd[i]);
}
// Start a process to run the command
Process pr = Runtime.getRuntime().exec(serverCmd);
bos = new BufferedOutputStream(System.out, 1024);
prout = new ProcessStreamResult(pr.getInputStream(), bos, null);
prerr = new ProcessStreamResult(pr.getErrorStream(), bos, null);
// wait until all the results have been processed
prout.Wait();
prerr.Wait();
}
public static void main (String args[]) throws Exception
{
if ((System.getProperty("java.vm.name") != null) && System.getProperty("java.vm.name").equals("J9"))
jvm = jvm.getJvm("j9_13");
else
jvm = jvm.getJvm("currentjvm"); // ensure compatibility
vCmd = jvm.getCommandLine();
try
{
ij.getPropertyArg(args);
Connection conn1 = ij.startJBMS();
/************************************************************
* Test runtimeinfo
************************************************************/
System.out.println("Testing Runtimeinfo");
execCmdDumpResults(RuntimeinfoCmd);
System.out.println("End test");
// Now get a couple of connections with some prepared statements
Connection conn2 = ij.startJBMS();
PreparedStatement ps = prepareAndExecuteQuery(conn1,"SELECT count(*) from sys.systables");
PreparedStatement ps2 = prepareAndExecuteQuery(conn1,"VALUES(1)");
Connection conn3 = ij.startJBMS();
PreparedStatement ps3 = prepareAndExecuteQuery(conn2,"SELECT count(*) from sys.systables");
PreparedStatement ps4 = prepareAndExecuteQuery(conn2,"VALUES(2)");
/************************************************************
* Test runtimeinfo w/ foreign (non-English) locale
************************************************************/
System.out.println("Testing Runtimeinfo (locale)");
execCmdDumpResults(RuntimeinfoLocaleCmd);
System.out.println("End test (locale)");
ps.close();
ps2.close();
ps3.close();
ps4.close();
conn1.close();
conn2.close();
conn3.close();
/** once more after closing the connections
* - by calling NetworkServerControl.getRuntimeInfo
*/
System.out.println("Testing Runtimeinfo after closing connectiosn");
+ // give the network server a second to clean up (DERBY-1455)
+ Thread.sleep(1000);
NetworkServerControl derbyServer =
new NetworkServerControl( InetAddress.getByName("localhost"),
NetworkServerControl.DEFAULT_PORTNUMBER);
System.out.println(derbyServer.getRuntimeInfo());
System.out.println("End test");
bos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static PreparedStatement prepareAndExecuteQuery(Connection conn,
String sql)
throws SQLException
{
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
rs.next();
return ps;
}
}
| true | true | public static void main (String args[]) throws Exception
{
if ((System.getProperty("java.vm.name") != null) && System.getProperty("java.vm.name").equals("J9"))
jvm = jvm.getJvm("j9_13");
else
jvm = jvm.getJvm("currentjvm"); // ensure compatibility
vCmd = jvm.getCommandLine();
try
{
ij.getPropertyArg(args);
Connection conn1 = ij.startJBMS();
/************************************************************
* Test runtimeinfo
************************************************************/
System.out.println("Testing Runtimeinfo");
execCmdDumpResults(RuntimeinfoCmd);
System.out.println("End test");
// Now get a couple of connections with some prepared statements
Connection conn2 = ij.startJBMS();
PreparedStatement ps = prepareAndExecuteQuery(conn1,"SELECT count(*) from sys.systables");
PreparedStatement ps2 = prepareAndExecuteQuery(conn1,"VALUES(1)");
Connection conn3 = ij.startJBMS();
PreparedStatement ps3 = prepareAndExecuteQuery(conn2,"SELECT count(*) from sys.systables");
PreparedStatement ps4 = prepareAndExecuteQuery(conn2,"VALUES(2)");
/************************************************************
* Test runtimeinfo w/ foreign (non-English) locale
************************************************************/
System.out.println("Testing Runtimeinfo (locale)");
execCmdDumpResults(RuntimeinfoLocaleCmd);
System.out.println("End test (locale)");
ps.close();
ps2.close();
ps3.close();
ps4.close();
conn1.close();
conn2.close();
conn3.close();
/** once more after closing the connections
* - by calling NetworkServerControl.getRuntimeInfo
*/
System.out.println("Testing Runtimeinfo after closing connectiosn");
NetworkServerControl derbyServer =
new NetworkServerControl( InetAddress.getByName("localhost"),
NetworkServerControl.DEFAULT_PORTNUMBER);
System.out.println(derbyServer.getRuntimeInfo());
System.out.println("End test");
bos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
| public static void main (String args[]) throws Exception
{
if ((System.getProperty("java.vm.name") != null) && System.getProperty("java.vm.name").equals("J9"))
jvm = jvm.getJvm("j9_13");
else
jvm = jvm.getJvm("currentjvm"); // ensure compatibility
vCmd = jvm.getCommandLine();
try
{
ij.getPropertyArg(args);
Connection conn1 = ij.startJBMS();
/************************************************************
* Test runtimeinfo
************************************************************/
System.out.println("Testing Runtimeinfo");
execCmdDumpResults(RuntimeinfoCmd);
System.out.println("End test");
// Now get a couple of connections with some prepared statements
Connection conn2 = ij.startJBMS();
PreparedStatement ps = prepareAndExecuteQuery(conn1,"SELECT count(*) from sys.systables");
PreparedStatement ps2 = prepareAndExecuteQuery(conn1,"VALUES(1)");
Connection conn3 = ij.startJBMS();
PreparedStatement ps3 = prepareAndExecuteQuery(conn2,"SELECT count(*) from sys.systables");
PreparedStatement ps4 = prepareAndExecuteQuery(conn2,"VALUES(2)");
/************************************************************
* Test runtimeinfo w/ foreign (non-English) locale
************************************************************/
System.out.println("Testing Runtimeinfo (locale)");
execCmdDumpResults(RuntimeinfoLocaleCmd);
System.out.println("End test (locale)");
ps.close();
ps2.close();
ps3.close();
ps4.close();
conn1.close();
conn2.close();
conn3.close();
/** once more after closing the connections
* - by calling NetworkServerControl.getRuntimeInfo
*/
System.out.println("Testing Runtimeinfo after closing connectiosn");
// give the network server a second to clean up (DERBY-1455)
Thread.sleep(1000);
NetworkServerControl derbyServer =
new NetworkServerControl( InetAddress.getByName("localhost"),
NetworkServerControl.DEFAULT_PORTNUMBER);
System.out.println(derbyServer.getRuntimeInfo());
System.out.println("End test");
bos.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
|
diff --git a/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java
index 9493a4770..717dfbb52 100644
--- a/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java
+++ b/seam/plugins/org.jboss.tools.seam.core/src/org/jboss/tools/seam/internal/core/project/facet/SeamFacetPreferenceInitializer.java
@@ -1,108 +1,109 @@
/*******************************************************************************
* Copyright (c) 2007 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.seam.internal.core.project.facet;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
import org.eclipse.core.runtime.preferences.DefaultScope;
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
import org.jboss.tools.seam.core.SeamCorePlugin;
import org.jboss.tools.seam.core.project.facet.SeamProjectPreferences;
import org.jboss.tools.seam.core.project.facet.SeamRuntime;
import org.jboss.tools.seam.core.project.facet.SeamRuntimeListConverter;
import org.jboss.tools.seam.core.project.facet.SeamVersion;
import org.osgi.service.prefs.BackingStoreException;
/**
* @author eskimo
*
*/
public class SeamFacetPreferenceInitializer extends
AbstractPreferenceInitializer {
public static String RUNTIME_CONFIG_FORMAT_VERSION = "1.0"; //$NON-NLS-1$
public static final String SEAM_1_2_HOME = "../../../../jboss-eap/seam"; //$NON-NLS-1$
public static final String SEAM_2_0_HOME = "../../../../jboss-eap/seamfp"; //$NON-NLS-1$
/**
*
*/
public SeamFacetPreferenceInitializer() {}
@Override
public void initializeDefaultPreferences() {
IEclipsePreferences node = (IEclipsePreferences)
Platform.getPreferencesService()
.getRootNode()
.node(DefaultScope.SCOPE)
.node(SeamCorePlugin.PLUGIN_ID);
node.put(SeamProjectPreferences.RUNTIME_CONFIG_FORMAT_VERSION, RUNTIME_CONFIG_FORMAT_VERSION);
node.put(SeamProjectPreferences.JBOSS_AS_DEFAULT_DEPLOY_AS, "war"); //$NON-NLS-1$
node.put(SeamProjectPreferences.HIBERNATE_DEFAULT_DB_TYPE, "HSQL"); //$NON-NLS-1$
+ node.put(SeamProjectPreferences.SEAM_DEFAULT_CONNECTION_PROFILE, "DefaultDS"); //$NON-NLS-1$
Map<String, SeamRuntime> map = new HashMap<String,SeamRuntime>();
// Initialize Seam 1.2 Runtime from JBoss EAP
String seamGenBuildPath = getSeamGenBuildPath(SEAM_1_2_HOME);
File seamFolder = new File(seamGenBuildPath);
if(seamFolder.exists() && seamFolder.isDirectory()) {
SeamRuntime rt = new SeamRuntime();
rt.setHomeDir(seamGenBuildPath);
rt.setName("Seam " + SeamVersion.SEAM_1_2 + ".AP"); //$NON-NLS-1$ //$NON-NLS-2$
rt.setDefault(true);
rt.setVersion(SeamVersion.SEAM_1_2);
map.put(rt.getName(), rt);
}
// Initialize Seam 2.0 Runtime from JBoss EAP
seamGenBuildPath = getSeamGenBuildPath(SEAM_2_0_HOME);
seamFolder = new File(seamGenBuildPath);
if(seamFolder.exists() && seamFolder.isDirectory()) {
SeamRuntime rt = new SeamRuntime();
rt.setHomeDir(seamGenBuildPath);
rt.setName("Seam " + SeamVersion.SEAM_2_0 + ".FP"); //$NON-NLS-1$ //$NON-NLS-2$
rt.setDefault(true);
rt.setVersion(SeamVersion.SEAM_2_0);
map.put(rt.getName(), rt);
}
node.put(SeamProjectPreferences.RUNTIME_LIST, new SeamRuntimeListConverter().getString(map));
try {
node.flush();
} catch (BackingStoreException e) {
SeamCorePlugin.getPluginLog().logError(e);
}
}
private String getSeamGenBuildPath(String seamHomePath) {
String pluginLocation=null;
try {
pluginLocation = FileLocator.resolve(SeamCorePlugin.getDefault().getBundle().getEntry("/")).getFile(); //$NON-NLS-1$
} catch (IOException e) {
SeamCorePlugin.getPluginLog().logError(e);
};
File seamGenDir = new File(pluginLocation, seamHomePath);
Path p = new Path(seamGenDir.getPath());
p.makeAbsolute();
if(p.toFile().exists()) {
return p.toOSString();
} else {
return ""; //$NON-NLS-1$
}
}
}
| true | true | public void initializeDefaultPreferences() {
IEclipsePreferences node = (IEclipsePreferences)
Platform.getPreferencesService()
.getRootNode()
.node(DefaultScope.SCOPE)
.node(SeamCorePlugin.PLUGIN_ID);
node.put(SeamProjectPreferences.RUNTIME_CONFIG_FORMAT_VERSION, RUNTIME_CONFIG_FORMAT_VERSION);
node.put(SeamProjectPreferences.JBOSS_AS_DEFAULT_DEPLOY_AS, "war"); //$NON-NLS-1$
node.put(SeamProjectPreferences.HIBERNATE_DEFAULT_DB_TYPE, "HSQL"); //$NON-NLS-1$
Map<String, SeamRuntime> map = new HashMap<String,SeamRuntime>();
// Initialize Seam 1.2 Runtime from JBoss EAP
String seamGenBuildPath = getSeamGenBuildPath(SEAM_1_2_HOME);
File seamFolder = new File(seamGenBuildPath);
if(seamFolder.exists() && seamFolder.isDirectory()) {
SeamRuntime rt = new SeamRuntime();
rt.setHomeDir(seamGenBuildPath);
rt.setName("Seam " + SeamVersion.SEAM_1_2 + ".AP"); //$NON-NLS-1$ //$NON-NLS-2$
rt.setDefault(true);
rt.setVersion(SeamVersion.SEAM_1_2);
map.put(rt.getName(), rt);
}
// Initialize Seam 2.0 Runtime from JBoss EAP
seamGenBuildPath = getSeamGenBuildPath(SEAM_2_0_HOME);
seamFolder = new File(seamGenBuildPath);
if(seamFolder.exists() && seamFolder.isDirectory()) {
SeamRuntime rt = new SeamRuntime();
rt.setHomeDir(seamGenBuildPath);
rt.setName("Seam " + SeamVersion.SEAM_2_0 + ".FP"); //$NON-NLS-1$ //$NON-NLS-2$
rt.setDefault(true);
rt.setVersion(SeamVersion.SEAM_2_0);
map.put(rt.getName(), rt);
}
node.put(SeamProjectPreferences.RUNTIME_LIST, new SeamRuntimeListConverter().getString(map));
try {
node.flush();
} catch (BackingStoreException e) {
SeamCorePlugin.getPluginLog().logError(e);
}
}
| public void initializeDefaultPreferences() {
IEclipsePreferences node = (IEclipsePreferences)
Platform.getPreferencesService()
.getRootNode()
.node(DefaultScope.SCOPE)
.node(SeamCorePlugin.PLUGIN_ID);
node.put(SeamProjectPreferences.RUNTIME_CONFIG_FORMAT_VERSION, RUNTIME_CONFIG_FORMAT_VERSION);
node.put(SeamProjectPreferences.JBOSS_AS_DEFAULT_DEPLOY_AS, "war"); //$NON-NLS-1$
node.put(SeamProjectPreferences.HIBERNATE_DEFAULT_DB_TYPE, "HSQL"); //$NON-NLS-1$
node.put(SeamProjectPreferences.SEAM_DEFAULT_CONNECTION_PROFILE, "DefaultDS"); //$NON-NLS-1$
Map<String, SeamRuntime> map = new HashMap<String,SeamRuntime>();
// Initialize Seam 1.2 Runtime from JBoss EAP
String seamGenBuildPath = getSeamGenBuildPath(SEAM_1_2_HOME);
File seamFolder = new File(seamGenBuildPath);
if(seamFolder.exists() && seamFolder.isDirectory()) {
SeamRuntime rt = new SeamRuntime();
rt.setHomeDir(seamGenBuildPath);
rt.setName("Seam " + SeamVersion.SEAM_1_2 + ".AP"); //$NON-NLS-1$ //$NON-NLS-2$
rt.setDefault(true);
rt.setVersion(SeamVersion.SEAM_1_2);
map.put(rt.getName(), rt);
}
// Initialize Seam 2.0 Runtime from JBoss EAP
seamGenBuildPath = getSeamGenBuildPath(SEAM_2_0_HOME);
seamFolder = new File(seamGenBuildPath);
if(seamFolder.exists() && seamFolder.isDirectory()) {
SeamRuntime rt = new SeamRuntime();
rt.setHomeDir(seamGenBuildPath);
rt.setName("Seam " + SeamVersion.SEAM_2_0 + ".FP"); //$NON-NLS-1$ //$NON-NLS-2$
rt.setDefault(true);
rt.setVersion(SeamVersion.SEAM_2_0);
map.put(rt.getName(), rt);
}
node.put(SeamProjectPreferences.RUNTIME_LIST, new SeamRuntimeListConverter().getString(map));
try {
node.flush();
} catch (BackingStoreException e) {
SeamCorePlugin.getPluginLog().logError(e);
}
}
|
diff --git a/project/gncandroid/src/rednus/gncandroid/MainView.java b/project/gncandroid/src/rednus/gncandroid/MainView.java
index b94b8bc..f357d1f 100644
--- a/project/gncandroid/src/rednus/gncandroid/MainView.java
+++ b/project/gncandroid/src/rednus/gncandroid/MainView.java
@@ -1,230 +1,232 @@
/**
* Copyright (C) 2010 Rednus Limited http://www.rednus.co.uk
*
* #TODO License
*/
package rednus.gncandroid;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TabHost;
/**
* @author shyam.avvari
*
*/
public class MainView extends TabActivity {
private static final String TAG = "MainView"; // TAG for this activity
private GNCAndroid app; // Application Reference
private ProgressDialog pd; // progress bar
/*
* Start of activity. Check if data file can be read, if not show dialog and
* navigate to preferences. Also add sub activities as tabs to self.
*
* @see android.app.ActivityGroup#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get application
app = (GNCAndroid) getApplication();
// first check if data file is set otherwise show preferences
// Read data if has
if (app.canReadData()) {
if (app.isReloadFile()) // The data may already be read
new ReadDataTask().execute();
else
showScreen();
} else {
if (app.localLOGV)
Log.i(TAG, "No Data file set.. Forcing preferences...");
forcePreferences(app.res.getString(R.string.message_set_data_file));
}
}
private void forcePreferences(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setCancelable(false).setPositiveButton(
app.res.getString(R.string.button_text_ok),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// show prefs
Intent i = new Intent(getBaseContext(),
Preferences.class);
startActivity(i);
return;
}
});
builder.create().show();
}
/**
* This method is called once read data activity is finished so that the sub
* activities are initiated.
*/
private void showScreen() {
if (app.localLOGV)
Log.i(TAG, "Showing main screen...");
if (!app.gncDataHandler.dataValid) {
if (app.localLOGV)
Log.i(TAG, "GNCDataHandler failed to initialise.. Forcing preferences...");
forcePreferences(app.res
.getString(R.string.message_failed_to_read_data_file));
return;
}
// The activity TabHost
final TabHost tabHost = getTabHost();
+ // Clear the tabs to show the new data
+ tabHost.clearAllTabs();
// Reusable TabSpec for each tab
TabHost.TabSpec spec;
// Reusable Intent for each tab
Intent intent;
// add accounts tab
intent = new Intent().setClass(this, AccountsActivity.class);
spec = tabHost.newTabSpec("accounts").setIndicator(
getString(R.string.ic_tab_accounts),
app.res.getDrawable(R.drawable.ic_tab_accounts)).setContent(
intent);
tabHost.addTab(spec);
// add quick tab
intent = new Intent().setClass(this, QuickEntryActivity.class);
spec = tabHost.newTabSpec("quick").setIndicator(
getString(R.string.ic_tab_quick),
app.res.getDrawable(R.drawable.ic_tab_actions)).setContent(
intent);
tabHost.addTab(spec);
// #TODO add third tab
// // // add actions tab
// // intent = new Intent().setClass(this, ActionsActivity.class);
// // spec = tabHost
// // .newTabSpec("actions")
// // .setIndicator(getString(R.string.ic_tab_actions),
// // app.res.getDrawable(R.drawable.ic_tab_actions))
// // .setContent(intent);
// // tabHost.addTab(spec);
// set default tab
tabHost.setCurrentTab(0);
if (app.localLOGV)
Log.i(TAG, "Showing main screen...Done");
}
/*
* When menu is selected on this app, show options.
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
/*
* When any menu item is selected, perform specific action
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_prefs:
// show preferences
startActivity(new Intent(getBaseContext(), Preferences.class));
return true;
case R.id.menu_book:
// Start intent to show book details
startActivity(new Intent(getBaseContext(),
BookDetailsActivity.class));
return true;
case R.id.menu_save:
// Save data
// #TODO Save data
return true;
case R.id.menu_discard:
// cancel changes and reload - but ask before doing
// #TODO discard changes
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/*
* When the view is restarted when returned from preferences screen, check
* if the reload file flag is set and read data again if it does
*
* @see android.app.Activity#onRestart()
*/
@Override
protected void onRestart() {
super.onRestart();
// add log entry
if (app.localLOGV)
Log.i(TAG, "Activity Restarted.. Checking if data file changed...");
// check if reload flag is set then read data again
if (app.isReloadFile() && app.canReadData())
// read data
new ReadDataTask().execute();
}
/**
* This class implements AsynTask and reads the data file in a new thread so
* that the Time Out trigger does not happen.
*
* @author John Gray
*
*/
private class ReadDataTask extends AsyncTask<Void, Void, Boolean> {
/*
* Show progress dialog before execution
*
* @see android.os.AsyncTask#onPreExecute()
*/
@Override
protected void onPreExecute() {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
if (pd == null)
pd = ProgressDialog.show(MainView.this, "Please Wait...",
"Loading...", true);
else
pd.show();
}
/*
* Call method readData of GNCAndroid in background task
*
* @see android.os.AsyncTask#doInBackground(Params[])
*/
@Override
protected Boolean doInBackground(Void... voids) {
return app.readData();
}
/*
* Close progress dialog after execution
*
* @see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
@Override
protected void onPostExecute(Boolean result) {
// Refresh View here
pd.dismiss();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
showScreen();
}
}
}
| true | true | private void showScreen() {
if (app.localLOGV)
Log.i(TAG, "Showing main screen...");
if (!app.gncDataHandler.dataValid) {
if (app.localLOGV)
Log.i(TAG, "GNCDataHandler failed to initialise.. Forcing preferences...");
forcePreferences(app.res
.getString(R.string.message_failed_to_read_data_file));
return;
}
// The activity TabHost
final TabHost tabHost = getTabHost();
// Reusable TabSpec for each tab
TabHost.TabSpec spec;
// Reusable Intent for each tab
Intent intent;
// add accounts tab
intent = new Intent().setClass(this, AccountsActivity.class);
spec = tabHost.newTabSpec("accounts").setIndicator(
getString(R.string.ic_tab_accounts),
app.res.getDrawable(R.drawable.ic_tab_accounts)).setContent(
intent);
tabHost.addTab(spec);
// add quick tab
intent = new Intent().setClass(this, QuickEntryActivity.class);
spec = tabHost.newTabSpec("quick").setIndicator(
getString(R.string.ic_tab_quick),
app.res.getDrawable(R.drawable.ic_tab_actions)).setContent(
intent);
tabHost.addTab(spec);
// #TODO add third tab
// // // add actions tab
// // intent = new Intent().setClass(this, ActionsActivity.class);
// // spec = tabHost
// // .newTabSpec("actions")
// // .setIndicator(getString(R.string.ic_tab_actions),
// // app.res.getDrawable(R.drawable.ic_tab_actions))
// // .setContent(intent);
// // tabHost.addTab(spec);
// set default tab
tabHost.setCurrentTab(0);
if (app.localLOGV)
Log.i(TAG, "Showing main screen...Done");
}
| private void showScreen() {
if (app.localLOGV)
Log.i(TAG, "Showing main screen...");
if (!app.gncDataHandler.dataValid) {
if (app.localLOGV)
Log.i(TAG, "GNCDataHandler failed to initialise.. Forcing preferences...");
forcePreferences(app.res
.getString(R.string.message_failed_to_read_data_file));
return;
}
// The activity TabHost
final TabHost tabHost = getTabHost();
// Clear the tabs to show the new data
tabHost.clearAllTabs();
// Reusable TabSpec for each tab
TabHost.TabSpec spec;
// Reusable Intent for each tab
Intent intent;
// add accounts tab
intent = new Intent().setClass(this, AccountsActivity.class);
spec = tabHost.newTabSpec("accounts").setIndicator(
getString(R.string.ic_tab_accounts),
app.res.getDrawable(R.drawable.ic_tab_accounts)).setContent(
intent);
tabHost.addTab(spec);
// add quick tab
intent = new Intent().setClass(this, QuickEntryActivity.class);
spec = tabHost.newTabSpec("quick").setIndicator(
getString(R.string.ic_tab_quick),
app.res.getDrawable(R.drawable.ic_tab_actions)).setContent(
intent);
tabHost.addTab(spec);
// #TODO add third tab
// // // add actions tab
// // intent = new Intent().setClass(this, ActionsActivity.class);
// // spec = tabHost
// // .newTabSpec("actions")
// // .setIndicator(getString(R.string.ic_tab_actions),
// // app.res.getDrawable(R.drawable.ic_tab_actions))
// // .setContent(intent);
// // tabHost.addTab(spec);
// set default tab
tabHost.setCurrentTab(0);
if (app.localLOGV)
Log.i(TAG, "Showing main screen...Done");
}
|
diff --git a/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java b/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java
index 16d64013..08e96d11 100644
--- a/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java
+++ b/src/plugin/feed/src/test/org/apache/nutch/parse/feed/TestFeedParser.java
@@ -1,133 +1,134 @@
/**
* 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.nutch.parse.feed;
// JDK imports
import java.util.Iterator;
import java.util.Map;
// APACHE imports
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.parse.Parse;
import org.apache.nutch.parse.ParseException;
import org.apache.nutch.parse.ParseResult;
import org.apache.nutch.parse.ParseUtil;
import org.apache.nutch.protocol.Content;
import org.apache.nutch.protocol.Protocol;
import org.apache.nutch.protocol.ProtocolFactory;
import org.apache.nutch.protocol.ProtocolNotFound;
import org.apache.nutch.util.NutchConfiguration;
// Junit imports
import junit.framework.TestCase;
/**
*
* @author mattmann
*
* Test Suite for the {@link FeedParser}.
*
*/
public class TestFeedParser extends TestCase {
private String fileSeparator = System.getProperty("file.separator");
// This system property is defined in ./src/plugin/build-plugin.xml
private String sampleDir = System.getProperty("test.data", ".");
// Make sure sample files are copied to "test.data" as specified in
// ./src/plugin/feed/build.xml during plugin compilation.
private String[] sampleFiles = { "rsstest.rss" };
public static final Log LOG = LogFactory.getLog(TestFeedParser.class
.getName());
/**
* Default Constructor.
*
* @param name
* The name of this {@link TestCase}.
*/
public TestFeedParser(String name) {
super(name);
}
/**
* Calls the {@link FeedParser} on a sample RSS file and checks that there are
* 3 {@link ParseResult} entries including the below 2 links:
* <ul>
* <li>http://www-scf.usc.edu/~mattmann/</li>
* <li>http://www.nutch.org</li>
* </ul>
*
*
* @throws ProtocolNotFound
* If the {@link Protocol}Layer cannot be loaded (required to fetch
* the {@link Content} for the RSS file).
* @throws ParseException
* If the {@link Parser}Layer cannot be loaded.
*/
public void testParseFetchChannel() throws ProtocolNotFound, ParseException {
String urlString;
Protocol protocol;
Content content;
ParseResult parseResult;
Configuration conf = NutchConfiguration.create();
for (int i = 0; i < sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
+ urlString = urlString.replace('\\', '/');
protocol = new ProtocolFactory(conf).getProtocol(urlString);
content = protocol.getProtocolOutput(new Text(urlString),
new CrawlDatum()).getContent();
parseResult = new ParseUtil(conf).parseByExtensionId("feed", content);
assertEquals(3, parseResult.size());
boolean hasLink1 = false, hasLink2 = false, hasLink3=false;
for (Iterator<Map.Entry<Text, Parse>> j = parseResult.iterator(); j
.hasNext();) {
Map.Entry<Text, Parse> entry = j.next();
if (entry.getKey().toString().equals(
"http://www-scf.usc.edu/~mattmann/")) {
hasLink1 = true;
} else if (entry.getKey().toString().equals("http://www.nutch.org/")) {
hasLink2 = true;
}
else if(entry.getKey().toString().equals(urlString)){
hasLink3 = true;
}
assertNotNull(entry.getValue());
assertNotNull(entry.getValue().getData());
}
if (!hasLink1 || !hasLink2 || !hasLink3) {
fail("Outlinks read from sample rss file are not correct!");
}
}
}
}
| true | true | public void testParseFetchChannel() throws ProtocolNotFound, ParseException {
String urlString;
Protocol protocol;
Content content;
ParseResult parseResult;
Configuration conf = NutchConfiguration.create();
for (int i = 0; i < sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
protocol = new ProtocolFactory(conf).getProtocol(urlString);
content = protocol.getProtocolOutput(new Text(urlString),
new CrawlDatum()).getContent();
parseResult = new ParseUtil(conf).parseByExtensionId("feed", content);
assertEquals(3, parseResult.size());
boolean hasLink1 = false, hasLink2 = false, hasLink3=false;
for (Iterator<Map.Entry<Text, Parse>> j = parseResult.iterator(); j
.hasNext();) {
Map.Entry<Text, Parse> entry = j.next();
if (entry.getKey().toString().equals(
"http://www-scf.usc.edu/~mattmann/")) {
hasLink1 = true;
} else if (entry.getKey().toString().equals("http://www.nutch.org/")) {
hasLink2 = true;
}
else if(entry.getKey().toString().equals(urlString)){
hasLink3 = true;
}
assertNotNull(entry.getValue());
assertNotNull(entry.getValue().getData());
}
if (!hasLink1 || !hasLink2 || !hasLink3) {
fail("Outlinks read from sample rss file are not correct!");
}
}
}
| public void testParseFetchChannel() throws ProtocolNotFound, ParseException {
String urlString;
Protocol protocol;
Content content;
ParseResult parseResult;
Configuration conf = NutchConfiguration.create();
for (int i = 0; i < sampleFiles.length; i++) {
urlString = "file:" + sampleDir + fileSeparator + sampleFiles[i];
urlString = urlString.replace('\\', '/');
protocol = new ProtocolFactory(conf).getProtocol(urlString);
content = protocol.getProtocolOutput(new Text(urlString),
new CrawlDatum()).getContent();
parseResult = new ParseUtil(conf).parseByExtensionId("feed", content);
assertEquals(3, parseResult.size());
boolean hasLink1 = false, hasLink2 = false, hasLink3=false;
for (Iterator<Map.Entry<Text, Parse>> j = parseResult.iterator(); j
.hasNext();) {
Map.Entry<Text, Parse> entry = j.next();
if (entry.getKey().toString().equals(
"http://www-scf.usc.edu/~mattmann/")) {
hasLink1 = true;
} else if (entry.getKey().toString().equals("http://www.nutch.org/")) {
hasLink2 = true;
}
else if(entry.getKey().toString().equals(urlString)){
hasLink3 = true;
}
assertNotNull(entry.getValue());
assertNotNull(entry.getValue().getData());
}
if (!hasLink1 || !hasLink2 || !hasLink3) {
fail("Outlinks read from sample rss file are not correct!");
}
}
}
|
diff --git a/src/main/java/com/anjuke/romar/http/jetty/RomarRESTMain.java b/src/main/java/com/anjuke/romar/http/jetty/RomarRESTMain.java
index 3147636..5e68370 100644
--- a/src/main/java/com/anjuke/romar/http/jetty/RomarRESTMain.java
+++ b/src/main/java/com/anjuke/romar/http/jetty/RomarRESTMain.java
@@ -1,38 +1,38 @@
package com.anjuke.romar.http.jetty;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import com.anjuke.romar.core.RomarConfig;
import com.sun.jersey.spi.container.servlet.ServletContainer;
public final class RomarRESTMain {
private RomarRESTMain() {
}
public static void main(String[] args) throws Exception {
java.util.logging.Logger rootLogger = java.util.logging.LogManager
.getLogManager().getLogger("");
java.util.logging.Handler[] handlers = rootLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
rootLogger.removeHandler(handlers[i]);
}
org.slf4j.bridge.SLF4JBridgeHandler.install();
RomarConfig config = RomarConfig.getInstance();
Server server = new Server(config.getServerPort());
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.NO_SESSIONS);
ServletHolder servletHolder = new ServletHolder(new ServletContainer());
servletHolder.setInitParameter("com.sun.jersey.config.property.packages",
- "com.anjuke.romar.http.rest");
+ "com.anjuke.romar.http.rest;org.codehaus.jackson.jaxrs");
servletHolder.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature",
"true");
context.addServlet(servletHolder, "/*");
server.setHandler(context);
server.start();
server.join();
}
}
| true | true | public static void main(String[] args) throws Exception {
java.util.logging.Logger rootLogger = java.util.logging.LogManager
.getLogManager().getLogger("");
java.util.logging.Handler[] handlers = rootLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
rootLogger.removeHandler(handlers[i]);
}
org.slf4j.bridge.SLF4JBridgeHandler.install();
RomarConfig config = RomarConfig.getInstance();
Server server = new Server(config.getServerPort());
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.NO_SESSIONS);
ServletHolder servletHolder = new ServletHolder(new ServletContainer());
servletHolder.setInitParameter("com.sun.jersey.config.property.packages",
"com.anjuke.romar.http.rest");
servletHolder.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature",
"true");
context.addServlet(servletHolder, "/*");
server.setHandler(context);
server.start();
server.join();
}
| public static void main(String[] args) throws Exception {
java.util.logging.Logger rootLogger = java.util.logging.LogManager
.getLogManager().getLogger("");
java.util.logging.Handler[] handlers = rootLogger.getHandlers();
for (int i = 0; i < handlers.length; i++) {
rootLogger.removeHandler(handlers[i]);
}
org.slf4j.bridge.SLF4JBridgeHandler.install();
RomarConfig config = RomarConfig.getInstance();
Server server = new Server(config.getServerPort());
ServletContextHandler context = new ServletContextHandler(
ServletContextHandler.NO_SESSIONS);
ServletHolder servletHolder = new ServletHolder(new ServletContainer());
servletHolder.setInitParameter("com.sun.jersey.config.property.packages",
"com.anjuke.romar.http.rest;org.codehaus.jackson.jaxrs");
servletHolder.setInitParameter("com.sun.jersey.api.json.POJOMappingFeature",
"true");
context.addServlet(servletHolder, "/*");
server.setHandler(context);
server.start();
server.join();
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/quicksettings/quicktile/UserTile.java b/packages/SystemUI/src/com/android/systemui/statusbar/quicksettings/quicktile/UserTile.java
index d82fdcdf..9bef7f25 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/quicksettings/quicktile/UserTile.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/quicksettings/quicktile/UserTile.java
@@ -1,119 +1,121 @@
package com.android.systemui.statusbar.quicksettings.quicktile;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.android.systemui.R;
import com.android.systemui.statusbar.cmcustom.SmsHelper;
import com.android.systemui.statusbar.quicksettings.QuickSettingsContainerView;
import com.android.systemui.statusbar.quicksettings.QuickSettingsController;
public class UserTile extends QuickSettingsTile {
private static final String TAG = "UserTile";
private Drawable userAvatar;
public UserTile(Context context, LayoutInflater inflater,
QuickSettingsContainerView container, QuickSettingsController qsc) {
super(context, inflater, container, qsc);
mTileLayout = R.layout.quick_settings_tile_user;
mOnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
queryForUserInformation();
}
};
mOnLongClick = new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setClassName("com.cyanogenmod.cmparts", "com.cyanogenmod.cmparts.activities.TileViewActivity");
startSettingsActivity(intent);
return true;
}
};
qsc.registerAction(Intent.ACTION_BATTERY_CHANGED, this);
qsc.registerAction(Intent.ACTION_CONFIGURATION_CHANGED, this);
qsc.registerAction(Intent.ACTION_TIME_CHANGED, this);
qsc.registerAction(Intent.ACTION_TIMEZONE_CHANGED, this);
qsc.registerObservedContent(Settings.System.getUriFor(Settings.System.USER_MY_NUMBERS)
, this);
}
@Override
public void onChangeUri(ContentResolver resolver, Uri uri) {
queryForUserInformation();
}
@Override
public void onReceive(Context context, Intent intent) {
queryForUserInformation();
}
@Override
void onPostCreate() {
queryForUserInformation();
super.onPostCreate();
}
@Override
void updateQuickSettings() {
ImageView iv = (ImageView) mTile.findViewById(R.id.user_imageview);
TextView tv = (TextView) mTile.findViewById(R.id.user_textview);
tv.setText(mLabel);
iv.setImageDrawable(userAvatar);
flipTile();
}
private void queryForUserInformation() {
ContentResolver resolver = mContext.getContentResolver();
String numbers = Settings.System.getString(resolver, Settings.System.USER_MY_NUMBERS);
- String numberes;
+ String numberes = null;
Drawable avatar = null;
- if (numbers.equals("000000000") || numbers.equals("") || TextUtils.isEmpty(numbers)) {
- numberes = null;
- } else {
- numberes = numbers;
+ if (numbers != null) {
+ if (numbers.equals("000000000") || numbers.equals("") || TextUtils.isEmpty(numbers)) {
+ numberes = null;
+ } else {
+ numberes = numbers;
+ }
}
if (numberes != null) {
String name = SmsHelper.getName(mContext, numberes);
Bitmap rawAvatar = SmsHelper.getContactPicture(mContext, numberes);
if (rawAvatar != null) {
avatar = new BitmapDrawable(mContext.getResources(), rawAvatar);
} else {
avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user);
}
if (name != null) {
setUserTileInfo(name, avatar);
} else {
String names = mContext.getString(R.string.quick_settings_user_label);
setUserTileInfo(names, avatar);
}
} else {
String named = mContext.getString(R.string.quick_settings_user_label);
avatar = mContext.getResources().getDrawable(com.android.internal.R.drawable.ic_contact_picture);
setUserTileInfo(named, avatar);
}
}
void setUserTileInfo(String name, Drawable avatar) {
mLabel = name;
userAvatar = avatar;
updateQuickSettings();
}
}
| false | true | private void queryForUserInformation() {
ContentResolver resolver = mContext.getContentResolver();
String numbers = Settings.System.getString(resolver, Settings.System.USER_MY_NUMBERS);
String numberes;
Drawable avatar = null;
if (numbers.equals("000000000") || numbers.equals("") || TextUtils.isEmpty(numbers)) {
numberes = null;
} else {
numberes = numbers;
}
if (numberes != null) {
String name = SmsHelper.getName(mContext, numberes);
Bitmap rawAvatar = SmsHelper.getContactPicture(mContext, numberes);
if (rawAvatar != null) {
avatar = new BitmapDrawable(mContext.getResources(), rawAvatar);
} else {
avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user);
}
if (name != null) {
setUserTileInfo(name, avatar);
} else {
String names = mContext.getString(R.string.quick_settings_user_label);
setUserTileInfo(names, avatar);
}
} else {
String named = mContext.getString(R.string.quick_settings_user_label);
avatar = mContext.getResources().getDrawable(com.android.internal.R.drawable.ic_contact_picture);
setUserTileInfo(named, avatar);
}
}
| private void queryForUserInformation() {
ContentResolver resolver = mContext.getContentResolver();
String numbers = Settings.System.getString(resolver, Settings.System.USER_MY_NUMBERS);
String numberes = null;
Drawable avatar = null;
if (numbers != null) {
if (numbers.equals("000000000") || numbers.equals("") || TextUtils.isEmpty(numbers)) {
numberes = null;
} else {
numberes = numbers;
}
}
if (numberes != null) {
String name = SmsHelper.getName(mContext, numberes);
Bitmap rawAvatar = SmsHelper.getContactPicture(mContext, numberes);
if (rawAvatar != null) {
avatar = new BitmapDrawable(mContext.getResources(), rawAvatar);
} else {
avatar = mContext.getResources().getDrawable(R.drawable.ic_qs_default_user);
}
if (name != null) {
setUserTileInfo(name, avatar);
} else {
String names = mContext.getString(R.string.quick_settings_user_label);
setUserTileInfo(names, avatar);
}
} else {
String named = mContext.getString(R.string.quick_settings_user_label);
avatar = mContext.getResources().getDrawable(com.android.internal.R.drawable.ic_contact_picture);
setUserTileInfo(named, avatar);
}
}
|
diff --git a/src/jp/shuri/android/SDCardSender/SDCardSender.java b/src/jp/shuri/android/SDCardSender/SDCardSender.java
index a74ae50..b443ece 100644
--- a/src/jp/shuri/android/SDCardSender/SDCardSender.java
+++ b/src/jp/shuri/android/SDCardSender/SDCardSender.java
@@ -1,37 +1,36 @@
package jp.shuri.android.SDCardSender;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import org.acra.collector.CrashReportData;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import android.os.Environment;
public class SDCardSender implements ReportSender {
@Override
public void send(CrashReportData report) throws ReportSenderException {
String sdcard = Environment.getExternalStorageDirectory().getPath();
String path = sdcard + File.separator + "bug.txt";
File file = new File(path);
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new ReportSenderException("Error file not found " + path, e);
}
for (final Object key : report.keySet()) {
- //final Object preliminaryValue = finalReport.get(key);
final Object preliminaryValue = report.get(key);
final Object value = (preliminaryValue == null) ? "" : preliminaryValue;
pw.println(key.toString() + " : " + value.toString());
}
pw.close();
}
}
| true | true | public void send(CrashReportData report) throws ReportSenderException {
String sdcard = Environment.getExternalStorageDirectory().getPath();
String path = sdcard + File.separator + "bug.txt";
File file = new File(path);
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new ReportSenderException("Error file not found " + path, e);
}
for (final Object key : report.keySet()) {
//final Object preliminaryValue = finalReport.get(key);
final Object preliminaryValue = report.get(key);
final Object value = (preliminaryValue == null) ? "" : preliminaryValue;
pw.println(key.toString() + " : " + value.toString());
}
pw.close();
}
| public void send(CrashReportData report) throws ReportSenderException {
String sdcard = Environment.getExternalStorageDirectory().getPath();
String path = sdcard + File.separator + "bug.txt";
File file = new File(path);
PrintWriter pw = null;
try {
pw = new PrintWriter(new FileOutputStream(file));
} catch (FileNotFoundException e) {
throw new ReportSenderException("Error file not found " + path, e);
}
for (final Object key : report.keySet()) {
final Object preliminaryValue = report.get(key);
final Object value = (preliminaryValue == null) ? "" : preliminaryValue;
pw.println(key.toString() + " : " + value.toString());
}
pw.close();
}
|
diff --git a/contrib/piggybank/java/src/test/java/org/apache/pig/piggybank/test/storage/TestHiveColumnarLoader.java b/contrib/piggybank/java/src/test/java/org/apache/pig/piggybank/test/storage/TestHiveColumnarLoader.java
index b00cf245..c7a66827 100644
--- a/contrib/piggybank/java/src/test/java/org/apache/pig/piggybank/test/storage/TestHiveColumnarLoader.java
+++ b/contrib/piggybank/java/src/test/java/org/apache/pig/piggybank/test/storage/TestHiveColumnarLoader.java
@@ -1,575 +1,576 @@
/**
* 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.pig.piggybank.test.storage;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.RCFile;
import org.apache.hadoop.hive.ql.io.RCFileOutputFormat;
import org.apache.hadoop.hive.serde2.SerDeException;
import org.apache.hadoop.hive.serde2.columnar.BytesRefArrayWritable;
import org.apache.hadoop.hive.serde2.columnar.BytesRefWritable;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.DefaultCodec;
import org.apache.pig.ExecType;
import org.apache.pig.FuncSpec;
import org.apache.pig.PigServer;
import org.apache.pig.data.DataType;
import org.apache.pig.data.Tuple;
import org.apache.pig.test.Util;
import org.junit.Assert;
import org.junit.Test;
/**
*
* Tests that the HiveColumnLoader can:
* <ul>
* <li>Load files without partitioning</li>
* <li>Load files with partitioning and dates defined in constructor, or as a
* filter</li>
* <li>Load files using pig's push down loader capabilities.</li>
* </ul>
*
*/
public class TestHiveColumnarLoader extends TestCase {
static Configuration conf = null;
// for single non partitioned file testing
static File simpleDataFile = null;
// for multiple non partitioned file testing
static File simpleDataDir = null;
static File datePartitionedDir = null;
static File yearMonthDayHourPartitionedDir = null;
// used for cleanup
static List<String> datePartitionedRCFiles;
static List<String> datePartitionedDirs;
static private FileSystem fs;
static int columnMaxSize = 30;
static int columnCount = 3;
static int simpleDirFileCount = 3;
static int simpleRowCount = 10;
static String endingDate = null;
static String startingDate = null;
static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
static Calendar calendar = null;
static int datePartitionedRowCount;
private static Calendar yearMonthDayHourcalendar;
@Override
public synchronized void setUp() throws Exception {
conf = new Configuration();
fs = LocalFileSystem.getLocal(conf);
produceSimpleData();
produceDatePartitionedData();
produceYearMonthDayHourPartitionedData();
}
@Override
public void tearDown() {
Util.deleteDirectory(datePartitionedDir);
Util.deleteDirectory(yearMonthDayHourPartitionedDir);
Util.deleteDirectory(simpleDataDir);
simpleDataFile.delete();
}
@Test
public void testReadingSingleFileNoProjections() throws IOException {
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string')";
String singlePartitionedFile = simpleDataFile.getAbsolutePath();
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '" + singlePartitionedFile + "' using "
+ funcSpecString + ";");
Iterator<Tuple> result = server.openIterator("a");
int count = 0;
Tuple t = null;
while ((t = result.next()) != null) {
assertEquals(3, t.size());
assertEquals(DataType.CHARARRAY, t.getType(0));
count++;
}
Assert.assertEquals(simpleRowCount, count);
}
@Test
public void testReadingMultipleNonPartitionedFiles() throws IOException {
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string')";
String singlePartitionedDir = simpleDataDir.getAbsolutePath();
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '" + singlePartitionedDir + "' using "
+ funcSpecString + ";");
server.registerQuery("b = foreach a generate f1;");
Iterator<Tuple> result = server.openIterator("b");
int count = 0;
Tuple t = null;
while ((t = result.next()) != null) {
assertEquals(1, t.size());
assertEquals(DataType.CHARARRAY, t.getType(0));
count++;
}
Assert.assertEquals(simpleDirFileCount * simpleRowCount, count);
}
@Test
public void testReadingSingleFile() throws IOException {
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string')";
String singlePartitionedFile = simpleDataFile.getAbsolutePath();
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '" + singlePartitionedFile + "' using "
+ funcSpecString + ";");
server.registerQuery("b = foreach a generate f1;");
Iterator<Tuple> result = server.openIterator("b");
int count = 0;
Tuple t = null;
while ((t = result.next()) != null) {
assertEquals(1, t.size());
assertEquals(DataType.CHARARRAY, t.getType(0));
count++;
}
Assert.assertEquals(simpleRowCount, count);
}
@Test
public void testYearMonthDayHourPartitionedFilesWithProjection()
throws IOException {
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string')";
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '"
+ yearMonthDayHourPartitionedDir.getAbsolutePath() + "' using "
+ funcSpecString + ";");
server.registerQuery("f = FILTER a by year=='2010';");
server.registerQuery("b = foreach f generate f1;");
Iterator<Tuple> result = server.openIterator("b");
Tuple t = null;
while ((t = result.next()) != null) {
assertEquals(1, t.size());
assertEquals(DataType.CHARARRAY, t.getType(0));
count++;
}
Assert.assertEquals(240, count);
}
@Test
public void testYearMonthDayHourPartitionedFilesWithProjectionAndPartitionColumns()
throws IOException {
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string')";
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '"
+ yearMonthDayHourPartitionedDir.getAbsolutePath() + "' using "
+ funcSpecString + ";");
server.registerQuery("f = FILTER a by year=='2010';");
server.registerQuery("r = foreach f generate year, f2, f3, month, day, hour;");
server.registerQuery("b = ORDER r BY year, month, day, hour;");
Iterator<Tuple> result = server.openIterator("b");
Tuple t = null;
while ((t = result.next()) != null) {
System.out.println("Tuple: " + t);
assertEquals(6, t.size());
count++;
}
System.out.println("Count: " + count);
Assert.assertEquals(240, count);
}
@Test
public void test1DayDatePartitionedFilesWithProjection() throws IOException {
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string'"
+ ", '" + startingDate + ":" + startingDate + "')";
System.out.println(funcSpecString);
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '"
+ datePartitionedDir.getAbsolutePath() + "' using "
+ funcSpecString + ";");
server.registerQuery("b = FOREACH a GENERATE f2 as p;");
Iterator<Tuple> result = server.openIterator("b");
Tuple t = null;
while ((t = result.next()) != null) {
assertEquals(1, t.size());
assertEquals(DataType.CHARARRAY, t.getType(0));
count++;
}
Assert.assertEquals(50, count);
}
@Test
public void test1DayDatePartitionedFiles() throws IOException {
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string'"
+ ", '" + startingDate + ":" + startingDate + "')";
System.out.println(funcSpecString);
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '"
+ datePartitionedDir.getAbsolutePath() + "' using "
+ funcSpecString + ";");
Iterator<Tuple> result = server.openIterator("a");
while ((result.next()) != null) {
count++;
}
Assert.assertEquals(50, count);
}
@Test
public void testDatePartitionedFiles() throws IOException {
int count = 0;
String funcSpecString = "org.apache.pig.piggybank.storage.HiveColumnarLoader('f1 string,f2 string,f3 string'"
+ ", '" + startingDate + ":" + endingDate + "')";
System.out.println(funcSpecString);
PigServer server = new PigServer(ExecType.LOCAL);
server.setBatchOn();
server.registerFunction(
"org.apache.pig.piggybank.storage.HiveColumnarLoader",
new FuncSpec(funcSpecString));
server.registerQuery("a = LOAD '"
+ datePartitionedDir.getAbsolutePath() + "' using "
+ funcSpecString + ";");
Iterator<Tuple> result = server.openIterator("a");
while ((result.next()) != null) {
count++;
}
Assert.assertEquals(datePartitionedRowCount, count);
}
private static void produceDatePartitionedData() throws IOException {
datePartitionedRowCount = 0;
datePartitionedDir = new File("testhiveColumnarLoader-dateDir-"
+ System.currentTimeMillis());
datePartitionedDir.mkdir();
datePartitionedDir.deleteOnExit();
int dates = 4;
calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
calendar.set(Calendar.MONTH, Calendar.JANUARY);
startingDate = dateFormat.format(calendar.getTime());
datePartitionedRCFiles = new ArrayList<String>();
datePartitionedDirs = new ArrayList<String>();
for (int i = 0; i < dates; i++) {
File file = new File(datePartitionedDir, "daydate="
+ dateFormat.format(calendar.getTime()));
calendar.add(Calendar.DAY_OF_MONTH, 1);
file.mkdir();
file.deleteOnExit();
// for each daydate write 5 partitions
for (int pi = 0; pi < 5; pi++) {
Path path = new Path(new Path(file.getAbsolutePath()),
"parition" + pi);
datePartitionedRowCount += writeRCFileTest(fs, simpleRowCount,
path, columnCount, new DefaultCodec(), columnCount);
new File(path.toString()).deleteOnExit();
datePartitionedRCFiles.add(path.toString());
datePartitionedDirs.add(file.toString());
}
}
endingDate = dateFormat.format(calendar.getTime());
}
private static void produceYearMonthDayHourPartitionedData()
throws IOException {
yearMonthDayHourPartitionedDir = new File(
"testhiveColumnarLoader-yearMonthDayHourDir-"
+ System.currentTimeMillis());
yearMonthDayHourPartitionedDir.mkdir();
yearMonthDayHourPartitionedDir.deleteOnExit();
int years = 1;
int months = 2;
int days = 3;
int hours = 4;
yearMonthDayHourcalendar = Calendar.getInstance();
+ yearMonthDayHourcalendar.set(Calendar.YEAR, 2010);
yearMonthDayHourcalendar.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
yearMonthDayHourcalendar.set(Calendar.MONTH, Calendar.JANUARY);
for (int i = 0; i < years; i++) {
File file = new File(yearMonthDayHourPartitionedDir, "year="
+ yearMonthDayHourcalendar.get(Calendar.YEAR));
file.mkdir();
file.deleteOnExit();
for (int monthIndex = 0; monthIndex < months; monthIndex++) {
File monthFile = new File(file, "month="
+ yearMonthDayHourcalendar.get(Calendar.MONTH));
monthFile.mkdir();
monthFile.deleteOnExit();
for (int dayIndex = 0; dayIndex < days; dayIndex++) {
File dayFile = new File(monthFile,
"day="
+ yearMonthDayHourcalendar
.get(Calendar.DAY_OF_MONTH));
dayFile.mkdir();
dayFile.deleteOnExit();
for (int hourIndex = 0; hourIndex < hours; hourIndex++) {
File hourFile = new File(dayFile,
"hour="
+ yearMonthDayHourcalendar
.get(Calendar.HOUR_OF_DAY));
hourFile.mkdir();
hourFile.deleteOnExit();
File rcFile = new File(hourFile.getAbsolutePath()
+ "/attempt-00000");
Path hourFilePath = new Path(rcFile.getAbsolutePath());
rcFile.deleteOnExit();
writeRCFileTest(fs, simpleRowCount, hourFilePath,
columnCount, new DefaultCodec(), columnCount);
yearMonthDayHourcalendar.add(Calendar.HOUR_OF_DAY, 1);
}
yearMonthDayHourcalendar.add(Calendar.DAY_OF_MONTH, 1);
}
yearMonthDayHourcalendar.add(Calendar.MONTH, 1);
}
}
endingDate = dateFormat.format(calendar.getTime());
}
/**
* Writes out a simple temporary file with 5 columns and 100 rows.<br/>
* Data is random numbers.
*
* @throws SerDeException
* @throws IOException
*/
private static final void produceSimpleData() throws SerDeException,
IOException {
// produce on single file
simpleDataFile = File.createTempFile("testhiveColumnarLoader", ".txt");
simpleDataFile.deleteOnExit();
Path path = new Path(simpleDataFile.getPath());
writeRCFileTest(fs, simpleRowCount, path, columnCount,
new DefaultCodec(), columnCount);
// produce a folder of simple data
simpleDataDir = new File("simpleDataDir" + System.currentTimeMillis());
simpleDataDir.mkdir();
for (int i = 0; i < simpleDirFileCount; i++) {
simpleDataFile = new File(simpleDataDir, "testhiveColumnarLoader-"
+ i + ".txt");
Path filePath = new Path(simpleDataFile.getPath());
writeRCFileTest(fs, simpleRowCount, filePath, columnCount,
new DefaultCodec(), columnCount);
}
}
static Random randomCharGenerator = new Random(3);
static Random randColLenGenerator = new Random(20);
private static void resetRandomGenerators() {
randomCharGenerator = new Random(3);
randColLenGenerator = new Random(20);
}
private static int writeRCFileTest(FileSystem fs, int rowCount, Path file,
int columnNum, CompressionCodec codec, int columnCount)
throws IOException {
fs.delete(file, true);
int rowsWritten = 0;
resetRandomGenerators();
RCFileOutputFormat.setColumnNumber(conf, columnNum);
RCFile.Writer writer = new RCFile.Writer(fs, conf, file, null, codec);
byte[][] columnRandom;
BytesRefArrayWritable bytes = new BytesRefArrayWritable(columnNum);
columnRandom = new byte[columnNum][];
for (int i = 0; i < columnNum; i++) {
BytesRefWritable cu = new BytesRefWritable();
bytes.set(i, cu);
}
for (int i = 0; i < rowCount; i++) {
nextRandomRow(columnRandom, bytes, columnCount);
rowsWritten++;
writer.append(bytes);
}
writer.close();
return rowsWritten;
}
private static void nextRandomRow(byte[][] row,
BytesRefArrayWritable bytes, int columnCount) {
bytes.resetValid(row.length);
for (int i = 0; i < row.length; i++) {
row[i] = new byte[columnCount];
for (int j = 0; j < columnCount; j++)
row[i][j] = getRandomChar(randomCharGenerator);
bytes.get(i).set(row[i], 0, columnCount);
}
}
private static int CHAR_END = 122 - 7;
private static byte getRandomChar(Random random) {
byte b = 0;
do {
b = (byte) random.nextInt(CHAR_END);
} while ((b < 65));
if (b > 90) {
b = 7;
}
return b;
}
}
| true | true | private static void produceYearMonthDayHourPartitionedData()
throws IOException {
yearMonthDayHourPartitionedDir = new File(
"testhiveColumnarLoader-yearMonthDayHourDir-"
+ System.currentTimeMillis());
yearMonthDayHourPartitionedDir.mkdir();
yearMonthDayHourPartitionedDir.deleteOnExit();
int years = 1;
int months = 2;
int days = 3;
int hours = 4;
yearMonthDayHourcalendar = Calendar.getInstance();
yearMonthDayHourcalendar.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
yearMonthDayHourcalendar.set(Calendar.MONTH, Calendar.JANUARY);
for (int i = 0; i < years; i++) {
File file = new File(yearMonthDayHourPartitionedDir, "year="
+ yearMonthDayHourcalendar.get(Calendar.YEAR));
file.mkdir();
file.deleteOnExit();
for (int monthIndex = 0; monthIndex < months; monthIndex++) {
File monthFile = new File(file, "month="
+ yearMonthDayHourcalendar.get(Calendar.MONTH));
monthFile.mkdir();
monthFile.deleteOnExit();
for (int dayIndex = 0; dayIndex < days; dayIndex++) {
File dayFile = new File(monthFile,
"day="
+ yearMonthDayHourcalendar
.get(Calendar.DAY_OF_MONTH));
dayFile.mkdir();
dayFile.deleteOnExit();
for (int hourIndex = 0; hourIndex < hours; hourIndex++) {
File hourFile = new File(dayFile,
"hour="
+ yearMonthDayHourcalendar
.get(Calendar.HOUR_OF_DAY));
hourFile.mkdir();
hourFile.deleteOnExit();
File rcFile = new File(hourFile.getAbsolutePath()
+ "/attempt-00000");
Path hourFilePath = new Path(rcFile.getAbsolutePath());
rcFile.deleteOnExit();
writeRCFileTest(fs, simpleRowCount, hourFilePath,
columnCount, new DefaultCodec(), columnCount);
yearMonthDayHourcalendar.add(Calendar.HOUR_OF_DAY, 1);
}
yearMonthDayHourcalendar.add(Calendar.DAY_OF_MONTH, 1);
}
yearMonthDayHourcalendar.add(Calendar.MONTH, 1);
}
}
endingDate = dateFormat.format(calendar.getTime());
}
| private static void produceYearMonthDayHourPartitionedData()
throws IOException {
yearMonthDayHourPartitionedDir = new File(
"testhiveColumnarLoader-yearMonthDayHourDir-"
+ System.currentTimeMillis());
yearMonthDayHourPartitionedDir.mkdir();
yearMonthDayHourPartitionedDir.deleteOnExit();
int years = 1;
int months = 2;
int days = 3;
int hours = 4;
yearMonthDayHourcalendar = Calendar.getInstance();
yearMonthDayHourcalendar.set(Calendar.YEAR, 2010);
yearMonthDayHourcalendar.set(Calendar.DAY_OF_MONTH, Calendar.MONDAY);
yearMonthDayHourcalendar.set(Calendar.MONTH, Calendar.JANUARY);
for (int i = 0; i < years; i++) {
File file = new File(yearMonthDayHourPartitionedDir, "year="
+ yearMonthDayHourcalendar.get(Calendar.YEAR));
file.mkdir();
file.deleteOnExit();
for (int monthIndex = 0; monthIndex < months; monthIndex++) {
File monthFile = new File(file, "month="
+ yearMonthDayHourcalendar.get(Calendar.MONTH));
monthFile.mkdir();
monthFile.deleteOnExit();
for (int dayIndex = 0; dayIndex < days; dayIndex++) {
File dayFile = new File(monthFile,
"day="
+ yearMonthDayHourcalendar
.get(Calendar.DAY_OF_MONTH));
dayFile.mkdir();
dayFile.deleteOnExit();
for (int hourIndex = 0; hourIndex < hours; hourIndex++) {
File hourFile = new File(dayFile,
"hour="
+ yearMonthDayHourcalendar
.get(Calendar.HOUR_OF_DAY));
hourFile.mkdir();
hourFile.deleteOnExit();
File rcFile = new File(hourFile.getAbsolutePath()
+ "/attempt-00000");
Path hourFilePath = new Path(rcFile.getAbsolutePath());
rcFile.deleteOnExit();
writeRCFileTest(fs, simpleRowCount, hourFilePath,
columnCount, new DefaultCodec(), columnCount);
yearMonthDayHourcalendar.add(Calendar.HOUR_OF_DAY, 1);
}
yearMonthDayHourcalendar.add(Calendar.DAY_OF_MONTH, 1);
}
yearMonthDayHourcalendar.add(Calendar.MONTH, 1);
}
}
endingDate = dateFormat.format(calendar.getTime());
}
|
diff --git a/DND/src/edu/teco/dnd/module/Application.java b/DND/src/edu/teco/dnd/module/Application.java
index 96d9efe..c7b3b0b 100644
--- a/DND/src/edu/teco/dnd/module/Application.java
+++ b/DND/src/edu/teco/dnd/module/Application.java
@@ -1,635 +1,635 @@
package edu.teco.dnd.module;
import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import edu.teco.dnd.blocks.FunctionBlock;
import edu.teco.dnd.blocks.FunctionBlockID;
import edu.teco.dnd.blocks.Input;
import edu.teco.dnd.blocks.InputDescription;
import edu.teco.dnd.blocks.Output;
import edu.teco.dnd.blocks.OutputTarget;
import edu.teco.dnd.module.ModuleBlockManager.BlockTypeHolderFullException;
import edu.teco.dnd.module.ModuleBlockManager.NoSuchBlockTypeHolderException;
import edu.teco.dnd.network.ConnectionManager;
import edu.teco.dnd.util.HashStorage;
import edu.teco.dnd.util.ValueWithHash;
/**
* This class represents a single application running on a module.
*
* @author Marvin Marx
*
*/
public class Application {
private static final Logger LOGGER = LogManager.getLogger(Application.class);
/** Time all shutdown hooks of an application have to run before being killed. */
public static final int TIME_BEFORE_ATTEMPTED_SHUTDOWNHOOK_KILL = 2000;
/** Additional time granted, for shutdownhooks after kill attempt, before thread is forcefully stopped. */
public static final int ADDITIONAL_TIME_BEFORE_FORCEFULL_KILL = 500;
/**
* Current state of the application. Can only advance to the next state: the Application starts in CREATED, then
* goes to RUNNING and eventually transitions to STOPPED.
*
* @author Philipp Adolf
*/
private enum State {
CREATED, RUNNING, STOPPED
}
private final ApplicationID applicationID;
private final String name;
private final ScheduledThreadPoolExecutor scheduledThreadPool;
private final ConnectionManager connMan;
private final ModuleBlockManager moduleBlockManager;
private final HashStorage<byte[]> byteCodeStorage;
private State currentState = State.CREATED;
private final ReadWriteLock currentStateLock = new ReentrantReadWriteLock();
private final Set<FunctionBlockSecurityDecorator> scheduledToStart = new HashSet<FunctionBlockSecurityDecorator>();
private final Map<FunctionBlockSecurityDecorator, Map<String, String>> blockOptions =
new HashMap<FunctionBlockSecurityDecorator, Map<String, String>>();
/**
* A Map from FunctionBlock UUID to matching ValueSender. Not used for local FunctionBlocks.
*/
private final ConcurrentMap<FunctionBlockID, ValueSender> valueSenders =
new ConcurrentHashMap<FunctionBlockID, ValueSender>();
private final ApplicationClassLoader classLoader;
/** mapping of active blocks to their ID, used e.g. to pass values to inputs. */
private final ConcurrentMap<FunctionBlockID, FunctionBlockSecurityDecorator> functionBlocksById =
new ConcurrentHashMap<FunctionBlockID, FunctionBlockSecurityDecorator>();
/**
*
* @param applicationID
* UUID of this application
* @param name
* Human readable name of this application
* @param scheduledThreadPool
* a ThreadPool all tasks of this application will be sheduled in. Used to limit the amount of resources
* this App can allocate.
* @param connMan
* ConnectionManager to send/receive messages.
* @param classloader
* Class loader that will be used by this Application. Can be used to limit the privileges of this app.
* Also used to make loading classes over network possible.
* @param module
* The module ApplicationManager used for callbacks to de/increase allowedBlockmaps
*
*/
public Application(final ApplicationID applicationID, final String name, final ConnectionManager connMan,
final ThreadFactory threadFactory, final int maxThreadsPerApp, final ModuleBlockManager moduleBlockManager,
final HashStorage<byte[]> byteCodeStorage) {
this.applicationID = applicationID;
this.name = name;
this.byteCodeStorage = byteCodeStorage;
this.classLoader = new ApplicationClassLoader();
this.scheduledThreadPool =
new ScheduledThreadPoolExecutor(maxThreadsPerApp, new ContextClassLoaderThreadFactory(threadFactory));
this.connMan = connMan;
this.moduleBlockManager = moduleBlockManager;
}
/**
* Returns true if this Application is currently running.
*
* @return true if this Application is currently running.
*/
public boolean isRunning() {
currentStateLock.readLock().lock();
try {
return currentState == State.RUNNING;
} finally {
currentStateLock.readLock().unlock();
}
}
/**
* Returns true if this Application has been shut down.
*
* @return true if this Application has been shut down
*/
public boolean hasShutDown() {
currentStateLock.readLock().lock();
try {
return currentState == State.STOPPED;
} finally {
currentStateLock.readLock().unlock();
}
}
/**
* called from this app, when a value is supposed to be send to another block (potentially on another ModuleInfo).
*
*
* @param funcBlock
* the receiving functionBlock.
* @param input
* the input on the given block to receive the message.
* @param value
* the value to be send.
*/
private void sendValue(final FunctionBlockID funcBlock, final String input, final Serializable value) {
if (funcBlock == null) {
throw new IllegalArgumentException("funcBlock must not be null");
}
if (input == null) {
throw new IllegalArgumentException("input must not be null");
}
// sending null is allowed, as some FunctionBlocks may make use of it
if (hasFunctionBlockWithID(funcBlock)) { // block is local
try {
receiveValue(funcBlock, input, value);
} catch (NonExistentFunctionblockException e) {
// probably racecondition with app killing. Ignore.
LOGGER.trace(e);
} catch (NonExistentInputException e) {
LOGGER.trace("the given input {} does not exist on the local functionBlock {}", input, funcBlock);
}
} else {
getValueSender(funcBlock).sendValue(input, value);
}
}
/**
* Returns a ValueSender for the given target FunctionBlock. If no ValueSender for that FunctionBlock exists yet a
* new one is created. When called with the same UUID it will always return the same ValueSender, even if called
* concurrently in different Threads.
*
* @param funcBlock
* the UUID of the FunctionBlock for which a ValueSender should be returned
* @return the ValueSender for the given FunctionBlock
*/
// FIXME: Need a way to clean up old value senders
private ValueSender getValueSender(final FunctionBlockID funcBlock) {
ValueSender valueSender = valueSenders.get(funcBlock);
if (valueSender == null) {
valueSender = new ValueSender(applicationID, funcBlock, connMan);
// if between the get and this call another Thread put a ValueSender into the map, this call will return the
// ValueSender the other
// Thread put into the Map. We'll use that one instead of our new one so that only one ValueSender exists
// per target
ValueSender oldValueSender = valueSenders.putIfAbsent(funcBlock, valueSender);
if (oldValueSender != null) {
valueSender = oldValueSender;
}
}
return valueSender;
}
/**
* loads a class into this app.
*
* @param classname
* name of the class to load
* @param classData
* bytecode of the class to be loaded
*/
public void loadClass(String classname, byte[] classData) {
if (classname == null || classData == null) {
throw new IllegalArgumentException("classname and classdata must not be null.");
}
final ValueWithHash<byte[]> byteCode = byteCodeStorage.putIfAbsent(classData);
classLoader.addClass(classname, byteCode.getValue());
}
/**
* Schedules a block in this application to be executed, once Application.start() is called.
*
* @param blockDescription
* which block to schedule.
* @throws ClassNotFoundException
* if the class given is not known by the Classloader of this application
* @throws UserSuppliedCodeException
* if some part of the code of the functionBlock (e.g. constructor) does throw an exception or otherwise
* misbehave (e.g. System.exit(),...)
* @throws NoSuchBlockTypeHolderException
* @throws BlockTypeHolderFullException
* @throws IllegalArgumentException
* if blockDescription.blockClassName is not a function block.
*/
public void scheduleBlock(final BlockDescription blockDescription) throws ClassNotFoundException,
UserSuppliedCodeException, BlockTypeHolderFullException, NoSuchBlockTypeHolderException {
LOGGER.entry(blockDescription);
currentStateLock.readLock().lock();
try {
if (hasShutDown()) {
throw LOGGER.throwing(new IllegalStateException(this + " has already been stopped"));
}
final FunctionBlockSecurityDecorator securityDecorator =
createFunctionBlockSecurityDecorator(blockDescription.blockClassName);
LOGGER.trace("calling doInit on securityDecorator {}", securityDecorator);
securityDecorator.doInit(blockDescription.blockID, blockDescription.blockName);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("adding {} to ID {}", securityDecorator, blockDescription.blockTypeHolderId);
}
moduleBlockManager.addToBlockTypeHolders(applicationID, securityDecorator,
blockDescription.blockTypeHolderId);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("initializing outputs {} on {}", blockDescription.outputs, securityDecorator);
}
initializeOutputs(securityDecorator, blockDescription.outputs);
if (isRunning()) {
startBlock(securityDecorator, blockDescription.options);
} else {
synchronized (scheduledToStart) {
LOGGER.trace("adding {} to scheduledToStart");
scheduledToStart.add(securityDecorator);
LOGGER.trace("saving block options");
blockOptions.put(securityDecorator, blockDescription.options);
}
}
} finally {
currentStateLock.readLock().unlock();
}
}
/**
* Wraps a functionBlock (given by name) into a security decorator (see FunctionBlockSecurityDecorator) for the
* rationale.
*
* @param className
* name of the class to wrap
* @return a new FunctionBlockSecurityDecorator wrapping the given block.
* @throws ClassNotFoundException
* if the classloader can not find a class with this name.
* @throws UserSuppliedCodeException
* If the given class misbehaves during initialization (throws errors...)
* @throws IllegalArgumentException
* inf className is not a functionBlock.
*/
@SuppressWarnings("unchecked")
private FunctionBlockSecurityDecorator createFunctionBlockSecurityDecorator(final String className)
throws ClassNotFoundException, UserSuppliedCodeException, IllegalArgumentException {
Class<?> cls = null;
cls = classLoader.loadClass(className);
if (!FunctionBlock.class.isAssignableFrom(cls)) {
throw new IllegalArgumentException("class " + className + " is not a FunctionBlock");
}
return new FunctionBlockSecurityDecorator((Class<? extends FunctionBlock>) cls);
}
/**
* Initializes the outputs used for sending values on a functionBlock.
*
* @param securityDecorator
* the SecurityDecorator holding the block with the outputs to set.
* @param outputs
* the outputs to set on the Block.
*/
private void initializeOutputs(final FunctionBlockSecurityDecorator securityDecorator,
final Map<String, Set<InputDescription>> outputs) {
final Map<String, Output<? extends Serializable>> blockOutputs = securityDecorator.getOutputs();
for (final Entry<String, Set<InputDescription>> output : outputs.entrySet()) {
if (!blockOutputs.containsKey(output.getKey())) {
continue;
}
final Output<? extends Serializable> blockOutput = blockOutputs.get(output.getKey());
blockOutput.setTarget(new ApplicationOutputTarget(output.getValue()));
}
}
/**
* starts this application, as in: starts executing the previously scheduled blocks.
*/
public void start() {
currentStateLock.readLock().lock();
try {
if (currentState != State.CREATED) {
throw LOGGER.throwing(new IllegalStateException("Tried to start " + this + " while it was in State "
+ currentState));
}
} finally {
currentStateLock.readLock().unlock();
}
currentStateLock.writeLock().lock();
try {
if (currentState != State.CREATED) {
throw LOGGER.throwing(new IllegalStateException("Tried to start " + this + " while it was in State "
+ currentState));
}
currentState = State.RUNNING;
synchronized (scheduledToStart) {
for (final FunctionBlockSecurityDecorator func : scheduledToStart) {
startBlock(func, blockOptions.get(func));
}
scheduledToStart.clear();
blockOptions.clear();
}
} finally {
currentStateLock.writeLock().unlock();
}
}
/**
* starts the given function block on the Module. Also triggers removing it from runnable blocks
*
* @param block
* the block to be started.
*/
private void startBlock(final FunctionBlockSecurityDecorator block, final Map<String, String> options) {
currentStateLock.readLock().lock();
try {
if (hasShutDown()) {
throw LOGGER.throwing(new IllegalStateException(this + " has already been shut down"));
}
final Runnable initRunnable = new Runnable() {
@Override
public void run() {
try {
block.init(options);
} catch (UserSuppliedCodeException e) {
// TODO: handle malevolent block. Stop it, maybe?
}
}
};
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
block.update();
} catch (UserSuppliedCodeException e) {
// TODO: handle malevolent block. Stop it, maybe?
}
}
};
final Future<?> initFuture = scheduledThreadPool.submit(initRunnable);
- while (initFuture.isDone()) {
+ while (!initFuture.isDone()) {
try {
initFuture.get();
} catch (final InterruptedException e) {
LOGGER.debug("got interrupted waiting for init future of {}", block);
} catch (final ExecutionException e) {
LOGGER.catching(e);
return;
}
}
// FIXME: if two blocks share the UUID, blocks get lost
functionBlocksById.put(block.getBlockID(), block);
long period = block.getUpdateInterval();
try {
if (period < 0) {
scheduledThreadPool.schedule(updater, 0, TimeUnit.SECONDS);
} else {
scheduledThreadPool.scheduleAtFixedRate(updater, period, period, TimeUnit.MILLISECONDS);
}
} catch (RejectedExecutionException e) {
LOGGER.catching(e);
}
} finally {
currentStateLock.readLock().unlock();
}
}
/**
* passes a received value the given input of a local block.
*
* @param funcBlockId
* Id of the block to pass the message to.
* @param value
* the value to give to the input.
* @param inputName
* name of the input this value is directed to.
* @throws NonExistentFunctionblockException
* If the FunctionBlock is not being executed by this module.
* @throws NonExistentInputException
* If the FunctionBlock is being executed but does not have an input of said name.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void receiveValue(final FunctionBlockID funcBlockId, String inputName, Serializable value)
throws NonExistentFunctionblockException, NonExistentInputException {
currentStateLock.readLock().lock();
try {
if (isRunning()) {
throw new IllegalStateException(this + " is not running");
}
final FunctionBlockSecurityDecorator block = functionBlocksById.get(funcBlockId);
if (block == null) {
throw LOGGER.throwing(new NonExistentFunctionblockException(funcBlockId.toString()));
}
final Input input = block.getInputs().get(inputName);
if (input == null) {
throw LOGGER.throwing(new NonExistentInputException("FunctionBlock " + funcBlockId
+ " does not have an input called " + inputName));
}
input.setValue(value);
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
block.update();
} catch (UserSuppliedCodeException e) {
// TODO: handle malevolent block. Stop it, maybe?
}
}
};
try {
scheduledThreadPool.schedule(updater, 0, TimeUnit.SECONDS);
} catch (RejectedExecutionException e) {
LOGGER.catching(e);
}
} finally {
currentStateLock.readLock().unlock();
}
}
/**
* Called when this application is shut down. Will call the appropriate methods on the executed functionBlocks.
*/
@SuppressWarnings("deprecation")
public void shutdown() {
currentStateLock.readLock().lock();
try {
if (currentState != State.RUNNING) {
throw LOGGER.throwing(new IllegalArgumentException(this + " is not currently running"));
}
} finally {
currentStateLock.readLock().unlock();
}
currentStateLock.writeLock().lock();
try {
if (currentState != State.RUNNING) {
throw LOGGER.throwing(new IllegalArgumentException(this + " is not currently running"));
}
scheduledThreadPool.shutdown();
final Thread shutdownThread = new Thread() {
@Override
public void run() {
for (final FunctionBlockSecurityDecorator block : functionBlocksById.values()) {
if (Thread.interrupted()) {
LOGGER.warn("shutdownThread got interrupted, not shutting down remaining FunctionBlocks");
break;
}
try {
block.shutdown();
} catch (UserSuppliedCodeException e) {
LOGGER.catching(e);
}
}
}
};
shutdownThread.start();
sleepUninterrupted(TIME_BEFORE_ATTEMPTED_SHUTDOWNHOOK_KILL);
if (!shutdownThread.isAlive()) {
LOGGER.debug("shutdownThread finished in time");
return;
}
LOGGER.info("shutdownThread is taking too long. Interrupting it.");
shutdownThread.interrupt();
sleepUninterrupted(ADDITIONAL_TIME_BEFORE_FORCEFULL_KILL);
if (!shutdownThread.isAlive()) {
LOGGER.debug("shutdownThread finished in time after interrupting");
return;
}
LOGGER.warn("Shutdown thread hanging. Killing it.");
shutdownThread.stop();
// It's deprecated and dangerous to stop a thread like this, because it forcefully releases all locks,
// yet there is no alternative to it if the victim is refusing to cooperate.
} finally {
currentStateLock.writeLock().unlock();
}
}
/**
*
* @return the UUID of this application
*/
public ApplicationID getApplicationID() {
return applicationID;
}
/**
*
* @return the human readable name of this application.
*/
public String getName() {
return name;
}
/**
*
* @return the classloader this application uses.
*/
public ApplicationClassLoader getClassLoader() {
return classLoader;
}
/**
*
* @return the threadpool this application uses.
*/
public ScheduledThreadPoolExecutor getThreadPool() {
return scheduledThreadPool;
}
public Map<FunctionBlockID, FunctionBlockSecurityDecorator> getFunctionBlocksById() {
return new HashMap<FunctionBlockID, FunctionBlockSecurityDecorator>(functionBlocksById);
}
public boolean hasFunctionBlockWithID(FunctionBlockID blockId) {
return functionBlocksById.containsKey(blockId);
}
// TODO insert javadoc here.
class ApplicationOutputTarget implements OutputTarget<Serializable> {
private final Set<InputDescription> destinations;
/**
*
* @param destinations
* places connected to this output. Where values are supposed to be send when they are send.
*/
public ApplicationOutputTarget(final Collection<InputDescription> destinations) {
this.destinations = new HashSet<InputDescription>(destinations);
}
@Override
public void setValue(Serializable value) {
for (final InputDescription destination : destinations) {
sendValue(destination.getBlock(), destination.getInput(), value);
}
}
}
private class ContextClassLoaderThreadFactory implements ThreadFactory {
private final ThreadFactory internalFactory;
private ContextClassLoaderThreadFactory(final ThreadFactory internalFactory) {
this.internalFactory = internalFactory;
}
@Override
public Thread newThread(final Runnable r) {
final Thread thread = internalFactory.newThread(r);
thread.setContextClassLoader(classLoader);
return thread;
}
}
/**
* Behaves like a Thread.sleep(millisToSleep), with the exception, that all InterruptedExceptions are disregarded
* (=have no influence on sleep time and are dropped)
*
* @param millisToSleep
* time to sleep in milli seconds.
*/
private void sleepUninterrupted(long millisToSleep) {
long sleepTill = System.currentTimeMillis() + millisToSleep;
long timeLeftToSleep = millisToSleep;
while (timeLeftToSleep > 0) {
try {
Thread.sleep(timeLeftToSleep);
break;
} catch (InterruptedException e) {
timeLeftToSleep = sleepTill - System.currentTimeMillis();
}
}
}
}
| true | true | private void startBlock(final FunctionBlockSecurityDecorator block, final Map<String, String> options) {
currentStateLock.readLock().lock();
try {
if (hasShutDown()) {
throw LOGGER.throwing(new IllegalStateException(this + " has already been shut down"));
}
final Runnable initRunnable = new Runnable() {
@Override
public void run() {
try {
block.init(options);
} catch (UserSuppliedCodeException e) {
// TODO: handle malevolent block. Stop it, maybe?
}
}
};
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
block.update();
} catch (UserSuppliedCodeException e) {
// TODO: handle malevolent block. Stop it, maybe?
}
}
};
final Future<?> initFuture = scheduledThreadPool.submit(initRunnable);
while (initFuture.isDone()) {
try {
initFuture.get();
} catch (final InterruptedException e) {
LOGGER.debug("got interrupted waiting for init future of {}", block);
} catch (final ExecutionException e) {
LOGGER.catching(e);
return;
}
}
// FIXME: if two blocks share the UUID, blocks get lost
functionBlocksById.put(block.getBlockID(), block);
long period = block.getUpdateInterval();
try {
if (period < 0) {
scheduledThreadPool.schedule(updater, 0, TimeUnit.SECONDS);
} else {
scheduledThreadPool.scheduleAtFixedRate(updater, period, period, TimeUnit.MILLISECONDS);
}
} catch (RejectedExecutionException e) {
LOGGER.catching(e);
}
} finally {
currentStateLock.readLock().unlock();
}
}
| private void startBlock(final FunctionBlockSecurityDecorator block, final Map<String, String> options) {
currentStateLock.readLock().lock();
try {
if (hasShutDown()) {
throw LOGGER.throwing(new IllegalStateException(this + " has already been shut down"));
}
final Runnable initRunnable = new Runnable() {
@Override
public void run() {
try {
block.init(options);
} catch (UserSuppliedCodeException e) {
// TODO: handle malevolent block. Stop it, maybe?
}
}
};
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
block.update();
} catch (UserSuppliedCodeException e) {
// TODO: handle malevolent block. Stop it, maybe?
}
}
};
final Future<?> initFuture = scheduledThreadPool.submit(initRunnable);
while (!initFuture.isDone()) {
try {
initFuture.get();
} catch (final InterruptedException e) {
LOGGER.debug("got interrupted waiting for init future of {}", block);
} catch (final ExecutionException e) {
LOGGER.catching(e);
return;
}
}
// FIXME: if two blocks share the UUID, blocks get lost
functionBlocksById.put(block.getBlockID(), block);
long period = block.getUpdateInterval();
try {
if (period < 0) {
scheduledThreadPool.schedule(updater, 0, TimeUnit.SECONDS);
} else {
scheduledThreadPool.scheduleAtFixedRate(updater, period, period, TimeUnit.MILLISECONDS);
}
} catch (RejectedExecutionException e) {
LOGGER.catching(e);
}
} finally {
currentStateLock.readLock().unlock();
}
}
|
diff --git a/src/fortran/ofp/parser/java/FortranStream.java b/src/fortran/ofp/parser/java/FortranStream.java
index d8b2a3e..d243f09 100644
--- a/src/fortran/ofp/parser/java/FortranStream.java
+++ b/src/fortran/ofp/parser/java/FortranStream.java
@@ -1,97 +1,97 @@
/*******************************************************************************
* Copyright (c) 2005, 2006 Los Alamos National Security, LLC.
* This material was produced under U.S. Government contract DE-AC52-06NA25396
* for Los Alamos National Laboratory (LANL), which is operated by the Los Alamos
* National Security, LLC (LANS) for the U.S. Department of Energy. The U.S. Government has
* rights to use, reproduce, and distribute this software. NEITHER THE
* GOVERNMENT NOR LANS MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
* ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified
* to produce derivative works, such modified software should be clearly marked,
* so as not to confuse it with the version available from LANL.
*
* Additionally, 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 fortran.ofp.parser.java;
import java.io.*;
import org.antlr.runtime.*;
import fortran.ofp.FrontEnd;
public class FortranStream extends ANTLRFileStream {
private int sourceForm;
public FortranStream(String fileName) throws IOException {
super(fileName);
}
public FortranStream(String fileName, int sourceForm) throws IOException {
super(fileName);
this.sourceForm = sourceForm;
}
public int getSourceForm() {
return this.sourceForm;
}
public String getFileName() {
return getSourceName();
}
public int LA(int i) {
int letter_value = super.LA(i);
int char_pos = super.getCharPositionInLine();
// the letter is lower-case
if (Character.isLowerCase((char)letter_value)) {
// convert to upper-case
letter_value = (int) Character.toUpperCase((char)(letter_value));
}
if (this.sourceForm == FrontEnd.FIXED_FORM) {
if (char_pos == 0) {
if (letter_value == 'C' || letter_value == '*') {
// return '!' to signify a line comment so the lexer won't try
// and parse this line.
letter_value = (int) '!';
}
}
else {
// Look for continuation character. The convention we use
// is for TAB + (WS | '0') acts as ';'. TAB + other char is a
// continuation line. This follows DEC (I believe) but is
// non standard Fortran.
//
// location of continuation character
int continue_pos = 5; // 6th column
// check for tab formatting, note, this seems to work because LA always
// called with i==1, so getCharPositionInLine is always as expected
if (super.LA(-char_pos) == (int) '\t') {
// first character in line is a tab
continue_pos = 1;
}
if (char_pos == continue_pos) {
- // if neither '0' nor whitespace then a continuation character
+ // if TAB followed by a digit 1-9 then a continuation character
if (letter_value >= (int)'1' && letter_value <= (int)'9') {
letter_value = (int)'&';
}
}
}
}
return letter_value;
} // end LA()
} // end class FortranStream
| true | true | public int LA(int i) {
int letter_value = super.LA(i);
int char_pos = super.getCharPositionInLine();
// the letter is lower-case
if (Character.isLowerCase((char)letter_value)) {
// convert to upper-case
letter_value = (int) Character.toUpperCase((char)(letter_value));
}
if (this.sourceForm == FrontEnd.FIXED_FORM) {
if (char_pos == 0) {
if (letter_value == 'C' || letter_value == '*') {
// return '!' to signify a line comment so the lexer won't try
// and parse this line.
letter_value = (int) '!';
}
}
else {
// Look for continuation character. The convention we use
// is for TAB + (WS | '0') acts as ';'. TAB + other char is a
// continuation line. This follows DEC (I believe) but is
// non standard Fortran.
//
// location of continuation character
int continue_pos = 5; // 6th column
// check for tab formatting, note, this seems to work because LA always
// called with i==1, so getCharPositionInLine is always as expected
if (super.LA(-char_pos) == (int) '\t') {
// first character in line is a tab
continue_pos = 1;
}
if (char_pos == continue_pos) {
// if neither '0' nor whitespace then a continuation character
if (letter_value >= (int)'1' && letter_value <= (int)'9') {
letter_value = (int)'&';
}
}
}
}
return letter_value;
} // end LA()
| public int LA(int i) {
int letter_value = super.LA(i);
int char_pos = super.getCharPositionInLine();
// the letter is lower-case
if (Character.isLowerCase((char)letter_value)) {
// convert to upper-case
letter_value = (int) Character.toUpperCase((char)(letter_value));
}
if (this.sourceForm == FrontEnd.FIXED_FORM) {
if (char_pos == 0) {
if (letter_value == 'C' || letter_value == '*') {
// return '!' to signify a line comment so the lexer won't try
// and parse this line.
letter_value = (int) '!';
}
}
else {
// Look for continuation character. The convention we use
// is for TAB + (WS | '0') acts as ';'. TAB + other char is a
// continuation line. This follows DEC (I believe) but is
// non standard Fortran.
//
// location of continuation character
int continue_pos = 5; // 6th column
// check for tab formatting, note, this seems to work because LA always
// called with i==1, so getCharPositionInLine is always as expected
if (super.LA(-char_pos) == (int) '\t') {
// first character in line is a tab
continue_pos = 1;
}
if (char_pos == continue_pos) {
// if TAB followed by a digit 1-9 then a continuation character
if (letter_value >= (int)'1' && letter_value <= (int)'9') {
letter_value = (int)'&';
}
}
}
}
return letter_value;
} // end LA()
|
diff --git a/src-tools/org/seasr/meandre/components/tools/webservice/ExtractRequestContent.java b/src-tools/org/seasr/meandre/components/tools/webservice/ExtractRequestContent.java
index 6b5131af..ec731d7c 100644
--- a/src-tools/org/seasr/meandre/components/tools/webservice/ExtractRequestContent.java
+++ b/src-tools/org/seasr/meandre/components/tools/webservice/ExtractRequestContent.java
@@ -1,125 +1,130 @@
/**
* University of Illinois/NCSA
* Open Source License
*
* Copyright (c) 2008, Board of Trustees-University of Illinois.
* All rights reserved.
*
* Developed by:
*
* Automated Learning Group
* National Center for Supercomputing Applications
* http://www.seasr.org
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal with 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:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimers.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimers in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the names of Automated Learning Group, The National Center for
* Supercomputing Applications, or University of Illinois, nor the names of
* its contributors may be used to endorse or promote products derived from
* this Software without specific prior written permission.
*
* 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
* CONTRIBUTORS 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
* WITH THE SOFTWARE.
*/
package org.seasr.meandre.components.tools.webservice;
import java.io.InputStreamReader;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import org.meandre.annotations.Component;
import org.meandre.annotations.Component.Licenses;
import org.meandre.annotations.ComponentInput;
import org.meandre.annotations.ComponentOutput;
import org.meandre.core.ComponentContext;
import org.meandre.core.ComponentContextProperties;
import org.seasr.datatypes.core.BasicDataTypesTools;
import org.seasr.datatypes.core.Names;
import org.seasr.meandre.components.abstracts.AbstractExecutableComponent;
import org.seasr.meandre.support.generic.io.IOUtils;
/**
* @author Boris Capitanu
*/
@Component(
creator = "Boris Capitanu",
description = "Extracts the payload (body/content) of a request.",
name = "Extract Request Content",
tags = "webservice, request, content, extract",
rights = Licenses.UofINCSA,
baseURL = "meandre://seasr.org/components/foundry/",
dependency = {"protobuf-java-2.2.0.jar"}
)
public class ExtractRequestContent extends AbstractExecutableComponent {
//------------------------------ INPUTS ------------------------------------------------------
@ComponentInput(
name = "request_handler",
description = "The request object." +
"<br>TYPE: javax.servlet.http.HttpServletRequest"
)
protected static final String IN_REQUEST = "request_handler";
//------------------------------ OUTPUTS -----------------------------------------------------
@ComponentOutput(
name = Names.PORT_TEXT,
description = "The header value" +
"<br>TYPE: org.seasr.datatypes.BasicDataTypes.Strings"
)
protected static final String OUT_TEXT = Names.PORT_TEXT;
@ComponentOutput(
name = "request_handler",
description = "Same as input."
)
protected static final String OUT_REQUEST = "request_handler";
//--------------------------------------------------------------------------------------------
@Override
public void initializeCallBack(ComponentContextProperties ccp) throws Exception {
}
@Override
public void executeCallBack(ComponentContext cc) throws Exception {
HttpServletRequest request = (HttpServletRequest) cc.getDataComponentFromInput(IN_REQUEST);
+ String characterEncoding = request.getCharacterEncoding();
- if (console.isLoggable(Level.FINE)) {
+ if (console.isLoggable(Level.FINE)) {
console.fine("Content-Type: " + request.getContentType());
console.fine("Content-Length: " + request.getContentLength());
- console.fine("Content-Encoding: " + request.getCharacterEncoding());
+ console.fine("Content-Encoding: " + characterEncoding);
}
- String content = IOUtils.getTextFromReader(new InputStreamReader(request.getInputStream(), request.getCharacterEncoding()));
+ InputStreamReader reader =
+ characterEncoding != null ?
+ new InputStreamReader(request.getInputStream(), characterEncoding) :
+ new InputStreamReader(request.getInputStream());
+ String content = IOUtils.getTextFromReader(reader);
cc.pushDataComponentToOutput(OUT_REQUEST, request);
cc.pushDataComponentToOutput(OUT_TEXT, BasicDataTypesTools.stringToStrings(content));
}
@Override
public void disposeCallBack(ComponentContextProperties ccp) throws Exception {
}
}
| false | true | public void executeCallBack(ComponentContext cc) throws Exception {
HttpServletRequest request = (HttpServletRequest) cc.getDataComponentFromInput(IN_REQUEST);
if (console.isLoggable(Level.FINE)) {
console.fine("Content-Type: " + request.getContentType());
console.fine("Content-Length: " + request.getContentLength());
console.fine("Content-Encoding: " + request.getCharacterEncoding());
}
String content = IOUtils.getTextFromReader(new InputStreamReader(request.getInputStream(), request.getCharacterEncoding()));
cc.pushDataComponentToOutput(OUT_REQUEST, request);
cc.pushDataComponentToOutput(OUT_TEXT, BasicDataTypesTools.stringToStrings(content));
}
| public void executeCallBack(ComponentContext cc) throws Exception {
HttpServletRequest request = (HttpServletRequest) cc.getDataComponentFromInput(IN_REQUEST);
String characterEncoding = request.getCharacterEncoding();
if (console.isLoggable(Level.FINE)) {
console.fine("Content-Type: " + request.getContentType());
console.fine("Content-Length: " + request.getContentLength());
console.fine("Content-Encoding: " + characterEncoding);
}
InputStreamReader reader =
characterEncoding != null ?
new InputStreamReader(request.getInputStream(), characterEncoding) :
new InputStreamReader(request.getInputStream());
String content = IOUtils.getTextFromReader(reader);
cc.pushDataComponentToOutput(OUT_REQUEST, request);
cc.pushDataComponentToOutput(OUT_TEXT, BasicDataTypesTools.stringToStrings(content));
}
|
diff --git a/src/ExtraInfoParser.java b/src/ExtraInfoParser.java
index 1daf632..7cd4ba2 100644
--- a/src/ExtraInfoParser.java
+++ b/src/ExtraInfoParser.java
@@ -1,46 +1,45 @@
import java.io.*;
import java.util.*;
public class ExtraInfoParser {
private DirreqStatsFileHandler dsfh;
private SortedSet<String> countries;
private SortedMap<String, String> directories;
public ExtraInfoParser(DirreqStatsFileHandler dsfh,
SortedSet<String> countries,
SortedMap<String, String> directories) {
this.dsfh = dsfh;
this.countries = countries;
this.directories = directories;
}
public void parse(String dir, BufferedReader br) throws IOException {
String line = null, date = null, v3ips = null;
+ boolean skip = false;
while ((line = br.readLine()) != null) {
if (line.startsWith("dirreq-stats-end ")) {
date = line.split(" ")[1];
- if (dir.equals("8522EB98C91496E80EC238E732594D1509158E77")
- && (date.equals("2009-09-10") || date.equals("2009-09-11"))) {
- // trusted had very strange dirreq-v3-shares there...
- break;
- }
+ // trusted had very strange dirreq-v3-shares here...
+ skip = dir.equals("8522EB98C91496E80EC238E732594D1509158E77")
+ && (date.equals("2009-09-10") || date.equals("2009-09-11"));
} else if (line.startsWith("dirreq-v3-reqs ")
&& line.length() > "dirreq-v3-reqs ".length()) {
v3ips = line.split(" ")[1];
} else if (line.startsWith("dirreq-v3-share ")
- && v3ips != null) {
+ && v3ips != null && !skip) {
Map<String, String> obs = new HashMap<String, String>();
String[] parts = v3ips.split(",");
for (String p : parts) {
for (String c : this.countries) {
if (p.startsWith(c)) {
obs.put(c, p.substring(3));
}
}
}
String share = line.substring("dirreq-v3-share ".length(),
line.length() - 1);
dsfh.addObs(this.directories.get(dir), date, obs, share);
}
}
}
}
| false | true | public void parse(String dir, BufferedReader br) throws IOException {
String line = null, date = null, v3ips = null;
while ((line = br.readLine()) != null) {
if (line.startsWith("dirreq-stats-end ")) {
date = line.split(" ")[1];
if (dir.equals("8522EB98C91496E80EC238E732594D1509158E77")
&& (date.equals("2009-09-10") || date.equals("2009-09-11"))) {
// trusted had very strange dirreq-v3-shares there...
break;
}
} else if (line.startsWith("dirreq-v3-reqs ")
&& line.length() > "dirreq-v3-reqs ".length()) {
v3ips = line.split(" ")[1];
} else if (line.startsWith("dirreq-v3-share ")
&& v3ips != null) {
Map<String, String> obs = new HashMap<String, String>();
String[] parts = v3ips.split(",");
for (String p : parts) {
for (String c : this.countries) {
if (p.startsWith(c)) {
obs.put(c, p.substring(3));
}
}
}
String share = line.substring("dirreq-v3-share ".length(),
line.length() - 1);
dsfh.addObs(this.directories.get(dir), date, obs, share);
}
}
}
| public void parse(String dir, BufferedReader br) throws IOException {
String line = null, date = null, v3ips = null;
boolean skip = false;
while ((line = br.readLine()) != null) {
if (line.startsWith("dirreq-stats-end ")) {
date = line.split(" ")[1];
// trusted had very strange dirreq-v3-shares here...
skip = dir.equals("8522EB98C91496E80EC238E732594D1509158E77")
&& (date.equals("2009-09-10") || date.equals("2009-09-11"));
} else if (line.startsWith("dirreq-v3-reqs ")
&& line.length() > "dirreq-v3-reqs ".length()) {
v3ips = line.split(" ")[1];
} else if (line.startsWith("dirreq-v3-share ")
&& v3ips != null && !skip) {
Map<String, String> obs = new HashMap<String, String>();
String[] parts = v3ips.split(",");
for (String p : parts) {
for (String c : this.countries) {
if (p.startsWith(c)) {
obs.put(c, p.substring(3));
}
}
}
String share = line.substring("dirreq-v3-share ".length(),
line.length() - 1);
dsfh.addObs(this.directories.get(dir), date, obs, share);
}
}
}
|
diff --git a/src/java/org/jamwiki/utils/LinkUtil.java b/src/java/org/jamwiki/utils/LinkUtil.java
index d3665351..5c255dac 100644
--- a/src/java/org/jamwiki/utils/LinkUtil.java
+++ b/src/java/org/jamwiki/utils/LinkUtil.java
@@ -1,246 +1,246 @@
/**
* Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, version 2.1, dated February 1999.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the latest version of the GNU Lesser General
* Public License as published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program (LICENSE.txt); if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.jamwiki.utils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.jamwiki.Environment;
import org.jamwiki.WikiBase;
import org.jamwiki.model.WikiFile;
import org.springframework.util.StringUtils;
/**
*
*/
public class LinkUtil {
private static final Logger logger = Logger.getLogger(LinkUtil.class);
/**
*
*/
public static String buildEditLinkHtml(String context, String virtualWiki, String topic) throws Exception {
return buildEditLinkHtml(context, virtualWiki, topic, null, -1, null);
}
/**
*
*/
public static String buildEditLinkHtml(String context, String virtualWiki, String topic, String query, int section, String text) throws Exception {
String url = LinkUtil.buildEditLinkUrl(context, virtualWiki, topic, query, section);
if (!StringUtils.hasText(text)) {
text = topic;
int pos = topic.indexOf('?');
if (pos > 0) {
text = topic.substring(0, pos).trim();
}
pos = text.indexOf('#');
if (pos > 0) {
text = text.substring(0, pos).trim();
}
}
String css = "";
if (!WikiBase.exists(virtualWiki, topic)) {
// FIXME - hard coding
css = " class=\"edit\"";
}
url = "<a href=\"" + url + "\"" + css + ">" + Utilities.escapeHTML(text) + "</a>";
return url;
}
/**
*
*/
public static String buildEditLinkUrl(String context, String virtualWiki, String topic) throws Exception {
return LinkUtil.buildEditLinkUrl(context, virtualWiki, topic, null, -1);
}
/**
*
*/
public static String buildEditLinkUrl(String context, String virtualWiki, String topic, String query, int section) throws Exception {
if (StringUtils.hasText(query)) {
if (!query.startsWith("?")) query = "?" + query;
query += "&topic=" + Utilities.encodeURL(topic);
} else {
query = "?topic=" + Utilities.encodeURL(topic);
}
if (section > 0) {
query += "&section=" + section;
}
return LinkUtil.buildInternalLinkUrl(context, virtualWiki, "Special:Edit", null, query);
}
/**
*
*/
public static String buildImageLinkHtml(String context, String virtualWiki, String topicName) throws Exception {
return LinkUtil.buildImageLinkHtml(context, virtualWiki, topicName, false, false, null, null, true);
}
/**
*
*/
public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, boolean suppressLink) throws Exception {
WikiFile wikiFile = WikiBase.getHandler().lookupWikiFile(virtualWiki, topicName);
if (wikiFile == null) {
// doesn't exist, return topic name as text IF it's an image
return (topicName.startsWith(WikiBase.NAMESPACE_IMAGE)) ? topicName : "";
}
String html = "";
if (!suppressLink) html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
if (frame || thumb || StringUtils.hasText(align) || StringUtils.hasText(caption)) {
- html += "<div ";
+ html += "<div";
if (thumb) {
- html += "class=\"imgthumb\"";
+ html += " class=\"imgthumb\"";
} else if (align != null && align.equalsIgnoreCase("right")) {
- html += "class=\"imgright\"";
+ html += " class=\"imgright\"";
} else if (align != null && align.equalsIgnoreCase("left")) {
- html += "class=\"imgleft\"";
+ html += " class=\"imgleft\"";
} else if (frame) {
- html += "class=\"imgleft\"";
+ html += " class=\"imgleft\"";
}
- html += "\">";
+ html += ">";
}
html += "<img class=\"wikiimg\" src=\"";
if (!Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH).startsWith("/")) html += "/";
html += Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH);
String url = wikiFile.getUrl();
if (!html.endsWith("/") && !url.startsWith("/")) {
url = "/" + url;
} else if (html.endsWith("/") && url.startsWith("/")) {
url = url.substring(1);
}
html += url;
html += "\" />";
if (frame || thumb || StringUtils.hasText(align) || StringUtils.hasText(caption)) {
if (StringUtils.hasText(caption)) {
html += "<div class=\"imgcaption\">" + caption + "</div>";
}
html += "</div>";
}
if (!suppressLink) html += "</a>";
return html;
}
/**
*
*/
public static String buildInternalLinkHtml(String context, String virtualWiki, String topic, String text, String style) throws Exception {
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, parseTopic(topic), parseSection(topic), parseQuery(topic), text, style);
}
/**
*
*/
public static String buildInternalLinkHtml(String context, String virtualWiki, String topic, String section, String query, String text) throws Exception {
return LinkUtil.buildInternalLinkHtml(context, virtualWiki, topic, section, query, text, null);
}
/**
*
*/
public static String buildInternalLinkHtml(String context, String virtualWiki, String topic, String section, String query, String text, String style) throws Exception {
String url = LinkUtil.buildInternalLinkUrl(context, virtualWiki, topic, section, query);
if (!StringUtils.hasText(text)) text = topic;
if (!WikiBase.exists(virtualWiki, topic) && !StringUtils.hasText(style)) {
style = "edit";
}
if (StringUtils.hasText(style)) {
style = " class=\"" + style + "\"";
} else {
style = "";
}
return "<a title=\"" + Utilities.escapeHTML(text) + "\" href=\"" + url + "\"" + style + ">" + Utilities.escapeHTML(text) + "</a>";
}
/**
*
*/
public static String buildInternalLinkUrl(String context, String virtualWiki, String topic) throws Exception {
if (!StringUtils.hasText(topic)) {
return null;
}
return LinkUtil.buildInternalLinkUrl(context, virtualWiki, parseTopic(topic), parseSection(topic), parseQuery(topic));
}
/**
*
*/
public static String buildInternalLinkUrl(String context, String virtualWiki, String topic, String section, String query) throws Exception {
if (!WikiBase.exists(virtualWiki, topic)) {
return LinkUtil.buildEditLinkUrl(context, virtualWiki, topic, query, -1);
}
String url = context;
// context never ends with a "/" per servlet specification
url += "/";
// get the virtual wiki, which should have been set by the parent servlet
url += Utilities.encodeURL(virtualWiki);
url += "/";
url += Utilities.encodeURL(topic);
if (StringUtils.hasText(section)) {
if (!section.startsWith("#")) url += "#";
url += Utilities.encodeURL(section);
}
if (StringUtils.hasText(query)) {
if (!query.startsWith("?")) url += "?";
url += query;
}
return url;
}
/**
*
*/
private static String parseQuery(String text) {
String query = null;
int pos = text.indexOf('?');
if (pos > 0) {
if (text.length() > pos) {
query = text.substring(pos+1).trim();
}
}
return query;
}
/**
*
*/
private static String parseSection(String text) {
int pos = text.indexOf('#');
if (pos == -1 || text.length() <= pos) return null;
String section = text.substring(pos+1).trim();
return Utilities.encodeURL(section);
}
/**
*
*/
private static String parseTopic(String text) {
String topic = text;
int pos = text.indexOf('#');
if (pos > 0) {
topic = text.substring(0, pos).trim();
}
pos = text.indexOf('?');
if (pos > 0) {
topic = text.substring(0, pos).trim();
}
return topic;
}
}
| false | true | public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, boolean suppressLink) throws Exception {
WikiFile wikiFile = WikiBase.getHandler().lookupWikiFile(virtualWiki, topicName);
if (wikiFile == null) {
// doesn't exist, return topic name as text IF it's an image
return (topicName.startsWith(WikiBase.NAMESPACE_IMAGE)) ? topicName : "";
}
String html = "";
if (!suppressLink) html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
if (frame || thumb || StringUtils.hasText(align) || StringUtils.hasText(caption)) {
html += "<div ";
if (thumb) {
html += "class=\"imgthumb\"";
} else if (align != null && align.equalsIgnoreCase("right")) {
html += "class=\"imgright\"";
} else if (align != null && align.equalsIgnoreCase("left")) {
html += "class=\"imgleft\"";
} else if (frame) {
html += "class=\"imgleft\"";
}
html += "\">";
}
html += "<img class=\"wikiimg\" src=\"";
if (!Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH).startsWith("/")) html += "/";
html += Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH);
String url = wikiFile.getUrl();
if (!html.endsWith("/") && !url.startsWith("/")) {
url = "/" + url;
} else if (html.endsWith("/") && url.startsWith("/")) {
url = url.substring(1);
}
html += url;
html += "\" />";
if (frame || thumb || StringUtils.hasText(align) || StringUtils.hasText(caption)) {
if (StringUtils.hasText(caption)) {
html += "<div class=\"imgcaption\">" + caption + "</div>";
}
html += "</div>";
}
if (!suppressLink) html += "</a>";
return html;
}
| public static String buildImageLinkHtml(String context, String virtualWiki, String topicName, boolean frame, boolean thumb, String align, String caption, boolean suppressLink) throws Exception {
WikiFile wikiFile = WikiBase.getHandler().lookupWikiFile(virtualWiki, topicName);
if (wikiFile == null) {
// doesn't exist, return topic name as text IF it's an image
return (topicName.startsWith(WikiBase.NAMESPACE_IMAGE)) ? topicName : "";
}
String html = "";
if (!suppressLink) html += "<a class=\"wikiimg\" href=\"" + LinkUtil.buildInternalLinkUrl(context, virtualWiki, topicName) + "\">";
if (frame || thumb || StringUtils.hasText(align) || StringUtils.hasText(caption)) {
html += "<div";
if (thumb) {
html += " class=\"imgthumb\"";
} else if (align != null && align.equalsIgnoreCase("right")) {
html += " class=\"imgright\"";
} else if (align != null && align.equalsIgnoreCase("left")) {
html += " class=\"imgleft\"";
} else if (frame) {
html += " class=\"imgleft\"";
}
html += ">";
}
html += "<img class=\"wikiimg\" src=\"";
if (!Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH).startsWith("/")) html += "/";
html += Environment.getValue(Environment.PROP_FILE_DIR_RELATIVE_PATH);
String url = wikiFile.getUrl();
if (!html.endsWith("/") && !url.startsWith("/")) {
url = "/" + url;
} else if (html.endsWith("/") && url.startsWith("/")) {
url = url.substring(1);
}
html += url;
html += "\" />";
if (frame || thumb || StringUtils.hasText(align) || StringUtils.hasText(caption)) {
if (StringUtils.hasText(caption)) {
html += "<div class=\"imgcaption\">" + caption + "</div>";
}
html += "</div>";
}
if (!suppressLink) html += "</a>";
return html;
}
|
diff --git a/src/com/whicken/werecat/paw/PawParser.java b/src/com/whicken/werecat/paw/PawParser.java
index c0a8225..5692583 100644
--- a/src/com/whicken/werecat/paw/PawParser.java
+++ b/src/com/whicken/werecat/paw/PawParser.java
@@ -1,24 +1,24 @@
package com.whicken.werecat.paw;
import com.whicken.werecat.expr.Expression;
import com.whicken.werecat.parser.ExpressionParser;
/**
* The template just enforces that our PawExpression must be passed the
* right type of object to the getValue method.
*/
public class PawParser<T> {
PawFactory factory;
public PawParser(Class c) {
factory = new PawFactory(c);
}
- PawExpression<T> parse(String expr) {
+ public PawExpression<T> parse(String expr) {
try {
Expression e = ExpressionParser.parse(expr, factory);
if (e != null)
return new PawExpression(e);
} catch (Throwable t) {
}
return null;
}
}
| true | true | PawExpression<T> parse(String expr) {
try {
Expression e = ExpressionParser.parse(expr, factory);
if (e != null)
return new PawExpression(e);
} catch (Throwable t) {
}
return null;
}
| public PawExpression<T> parse(String expr) {
try {
Expression e = ExpressionParser.parse(expr, factory);
if (e != null)
return new PawExpression(e);
} catch (Throwable t) {
}
return null;
}
|
diff --git a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java
index 9c1dd599d..464d7086d 100644
--- a/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java
+++ b/org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/tags/form/FormTag.java
@@ -1,514 +1,514 @@
/*
* Copyright 2002-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.springframework.web.servlet.tags.form;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import org.springframework.beans.PropertyAccessor;
import org.springframework.core.Conventions;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.support.RequestDataValueProcessor;
import org.springframework.web.util.HtmlUtils;
/**
* Databinding-aware JSP tag for rendering an HTML '<code>form</code>' whose
* inner elements are bound to properties on a <em>form object</em>.
*
* <p>Users should place the form object into the
* {@link org.springframework.web.servlet.ModelAndView ModelAndView} when
* populating the data for their view. The name of this form object can be
* configured using the {@link #setModelAttribute "modelAttribute"} property.
*
* <p>The default value for the {@link #setModelAttribute "modelAttribute"}
* property is '<code>command</code>' which corresponds to the default name
* when using the
* {@link org.springframework.web.servlet.mvc.SimpleFormController SimpleFormController}.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @author Scott Andrews
* @since 2.0
* @see org.springframework.web.servlet.mvc.SimpleFormController
*/
public class FormTag extends AbstractHtmlElementTag {
/** The default HTTP method using which form values are sent to the server: "post" */
private static final String DEFAULT_METHOD = "post";
/** The default attribute name: "command" */
public static final String DEFAULT_COMMAND_NAME = "command";
/** The name of the '<code>modelAttribute</code>' setting */
private static final String MODEL_ATTRIBUTE = "modelAttribute";
/**
* The name of the {@link javax.servlet.jsp.PageContext} attribute under which the
* form object name is exposed.
*/
public static final String MODEL_ATTRIBUTE_VARIABLE_NAME =
Conventions.getQualifiedAttributeName(AbstractFormTag.class, MODEL_ATTRIBUTE);
/** Default method parameter, i.e. <code>_method</code>. */
private static final String DEFAULT_METHOD_PARAM = "_method";
private static final String FORM_TAG = "form";
private static final String INPUT_TAG = "input";
private static final String ACTION_ATTRIBUTE = "action";
private static final String METHOD_ATTRIBUTE = "method";
private static final String TARGET_ATTRIBUTE = "target";
private static final String ENCTYPE_ATTRIBUTE = "enctype";
private static final String ACCEPT_CHARSET_ATTRIBUTE = "accept-charset";
private static final String ONSUBMIT_ATTRIBUTE = "onsubmit";
private static final String ONRESET_ATTRIBUTE = "onreset";
private static final String AUTOCOMPLETE_ATTRIBUTE = "autocomplete";
private static final String NAME_ATTRIBUTE = "name";
private static final String VALUE_ATTRIBUTE = "value";
private static final String TYPE_ATTRIBUTE = "type";
private TagWriter tagWriter;
private String modelAttribute = DEFAULT_COMMAND_NAME;
private String name;
private String action;
private String method = DEFAULT_METHOD;
private String target;
private String enctype;
private String acceptCharset;
private String onsubmit;
private String onreset;
private String autocomplete;
private String methodParam = DEFAULT_METHOD_PARAM;
/** Caching a previous nested path, so that it may be reset */
private String previousNestedPath;
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
*/
public void setModelAttribute(String modelAttribute) {
this.modelAttribute = modelAttribute;
}
/**
* Get the name of the form attribute in the model.
*/
protected String getModelAttribute() {
return this.modelAttribute;
}
/**
* Set the name of the form attribute in the model.
* <p>May be a runtime expression.
* @see #setModelAttribute
*/
public void setCommandName(String commandName) {
this.modelAttribute = commandName;
}
/**
* Get the name of the form attribute in the model.
* @see #getModelAttribute
*/
protected String getCommandName() {
return this.modelAttribute;
}
/**
* Set the value of the '<code>name</code>' attribute.
* <p>May be a runtime expression.
* <p>Name is not a valid attribute for form on XHTML 1.0. However,
* it is sometimes needed for backward compatibility.
*/
public void setName(String name) {
this.name = name;
}
/**
* Get the value of the '<code>name</code>' attribute.
*/
@Override
protected String getName() throws JspException {
return this.name;
}
/**
* Set the value of the '<code>action</code>' attribute.
* <p>May be a runtime expression.
*/
public void setAction(String action) {
this.action = (action != null ? action : "");
}
/**
* Get the value of the '<code>action</code>' attribute.
*/
protected String getAction() {
return this.action;
}
/**
* Set the value of the '<code>method</code>' attribute.
* <p>May be a runtime expression.
*/
public void setMethod(String method) {
this.method = method;
}
/**
* Get the value of the '<code>method</code>' attribute.
*/
protected String getMethod() {
return this.method;
}
/**
* Set the value of the '<code>target</code>' attribute.
* <p>May be a runtime expression.
*/
public void setTarget(String target) {
this.target = target;
}
/**
* Get the value of the '<code>target</code>' attribute.
*/
public String getTarget() {
return this.target;
}
/**
* Set the value of the '<code>enctype</code>' attribute.
* <p>May be a runtime expression.
*/
public void setEnctype(String enctype) {
this.enctype = enctype;
}
/**
* Get the value of the '<code>enctype</code>' attribute.
*/
protected String getEnctype() {
return this.enctype;
}
/**
* Set the value of the '<code>acceptCharset</code>' attribute.
* <p>May be a runtime expression.
*/
public void setAcceptCharset(String acceptCharset) {
this.acceptCharset = acceptCharset;
}
/**
* Get the value of the '<code>acceptCharset</code>' attribute.
*/
protected String getAcceptCharset() {
return this.acceptCharset;
}
/**
* Set the value of the '<code>onsubmit</code>' attribute.
* <p>May be a runtime expression.
*/
public void setOnsubmit(String onsubmit) {
this.onsubmit = onsubmit;
}
/**
* Get the value of the '<code>onsubmit</code>' attribute.
*/
protected String getOnsubmit() {
return this.onsubmit;
}
/**
* Set the value of the '<code>onreset</code>' attribute.
* <p>May be a runtime expression.
*/
public void setOnreset(String onreset) {
this.onreset = onreset;
}
/**
* Get the value of the '<code>onreset</code>' attribute.
*/
protected String getOnreset() {
return this.onreset;
}
/**
* Set the value of the '<code>autocomplete</code>' attribute.
* May be a runtime expression.
*/
public void setAutocomplete(String autocomplete) {
this.autocomplete = autocomplete;
}
/**
* Get the value of the '<code>autocomplete</code>' attribute.
*/
protected String getAutocomplete() {
return this.autocomplete;
}
/**
* Set the name of the request param for non-browser supported HTTP methods.
*/
public void setMethodParam(String methodParam) {
this.methodParam = methodParam;
}
/**
* Get the name of the request param for non-browser supported HTTP methods.
*/
protected String getMethodParameter() {
return this.methodParam;
}
/**
* Determine if the HTTP method is supported by browsers (i.e. GET or POST).
*/
protected boolean isMethodBrowserSupported(String method) {
return ("get".equalsIgnoreCase(method) || "post".equalsIgnoreCase(method));
}
/**
* Writes the opening part of the block '<code>form</code>' tag and exposes
* the form object name in the {@link javax.servlet.jsp.PageContext}.
* @param tagWriter the {@link TagWriter} to which the form content is to be written
* @return {@link javax.servlet.jsp.tagext.Tag#EVAL_BODY_INCLUDE}
*/
@Override
protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE,
isMethodBrowserSupported(getMethod()) ? getMethod() : DEFAULT_METHOD);
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
String inputName = getMethodParameter();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
- writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(getName(), getMethod(), inputType));
+ writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(COMMAND_NAME_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
/**
* Autogenerated IDs correspond to the form object name.
*/
@Override
protected String autogenerateId() throws JspException {
return resolveModelAttribute();
}
/**
* {@link #evaluate Resolves} and returns the name of the form object.
* @throws IllegalArgumentException if the form object resolves to <code>null</code>
*/
protected String resolveModelAttribute() throws JspException {
Object resolvedModelAttribute = evaluate(MODEL_ATTRIBUTE, getModelAttribute());
if (resolvedModelAttribute == null) {
throw new IllegalArgumentException(MODEL_ATTRIBUTE + " must not be null");
}
return (String) resolvedModelAttribute;
}
/**
* Resolve the value of the '<code>action</code>' attribute.
* <p>If the user configured an '<code>action</code>' value then
* the result of evaluating this value is used. Otherwise, the
* {@link org.springframework.web.servlet.support.RequestContext#getRequestUri() originating URI}
* is used.
* @return the value that is to be used for the '<code>action</code>' attribute
*/
protected String resolveAction() throws JspException {
String action = getAction();
if (StringUtils.hasText(action)) {
action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action));
return processAction(action);
}
else {
String requestUri = getRequestContext().getRequestUri();
ServletResponse response = this.pageContext.getResponse();
if (response instanceof HttpServletResponse) {
requestUri = ((HttpServletResponse) response).encodeURL(requestUri);
String queryString = getRequestContext().getQueryString();
if (StringUtils.hasText(queryString)) {
requestUri += "?" + HtmlUtils.htmlEscape(queryString);
}
}
if (StringUtils.hasText(requestUri)) {
return processAction(requestUri);
}
else {
throw new IllegalArgumentException("Attribute 'action' is required. " +
"Attempted to resolve against current request URI but request URI was null.");
}
}
}
/**
* Process the action through a {@link RequestDataValueProcessor} instance
* if one is configured or otherwise returns the action unmodified.
*/
private String processAction(String action) {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest();
if ((processor != null) && (request instanceof HttpServletRequest)) {
action = processor.processAction((HttpServletRequest) request, action);
}
return action;
}
/**
* Closes the '<code>form</code>' block tag and removes the form object name
* from the {@link javax.servlet.jsp.PageContext}.
*/
@Override
public int doEndTag() throws JspException {
RequestDataValueProcessor processor = getRequestContext().getRequestDataValueProcessor();
ServletRequest request = this.pageContext.getRequest();
if ((processor != null) && (request instanceof HttpServletRequest)) {
writeHiddenFields(processor.getExtraHiddenFields((HttpServletRequest) request));
}
this.tagWriter.endTag();
return EVAL_PAGE;
}
/**
* Writes the given values as hidden fields.
*/
private void writeHiddenFields(Map<String, String> hiddenFields) throws JspException {
if (hiddenFields != null) {
for (String name : hiddenFields.keySet()) {
this.tagWriter.appendValue("<input type=\"hidden\" ");
this.tagWriter.appendValue("name=\"" + name + "\" value=\"" + hiddenFields.get(name) + "\">");
this.tagWriter.appendValue("</input>\n");
}
}
}
/**
* Clears the stored {@link TagWriter}.
*/
@Override
public void doFinally() {
super.doFinally();
this.pageContext.removeAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.removeAttribute(COMMAND_NAME_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
if (this.previousNestedPath != null) {
// Expose previous nestedPath value.
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME, this.previousNestedPath, PageContext.REQUEST_SCOPE);
}
else {
// Remove exposed nestedPath value.
this.pageContext.removeAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
}
this.tagWriter = null;
this.previousNestedPath = null;
}
/**
* Override resolve CSS class since error class is not supported.
*/
@Override
protected String resolveCssClass() throws JspException {
return ObjectUtils.getDisplayString(evaluate("cssClass", getCssClass()));
}
/**
* Unsupported for forms.
* @throws UnsupportedOperationException always
*/
@Override
public void setPath(String path) {
throw new UnsupportedOperationException("The 'path' attribute is not supported for forms");
}
/**
* Unsupported for forms.
* @throws UnsupportedOperationException always
*/
@Override
public void setCssErrorClass(String cssErrorClass) {
throw new UnsupportedOperationException("The 'cssErrorClass' attribute is not supported for forms");
}
}
| true | true | protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE,
isMethodBrowserSupported(getMethod()) ? getMethod() : DEFAULT_METHOD);
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
String inputName = getMethodParameter();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(getName(), getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(COMMAND_NAME_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
| protected int writeTagContent(TagWriter tagWriter) throws JspException {
this.tagWriter = tagWriter;
tagWriter.startTag(FORM_TAG);
writeDefaultAttributes(tagWriter);
tagWriter.writeAttribute(ACTION_ATTRIBUTE, resolveAction());
writeOptionalAttribute(tagWriter, METHOD_ATTRIBUTE,
isMethodBrowserSupported(getMethod()) ? getMethod() : DEFAULT_METHOD);
writeOptionalAttribute(tagWriter, TARGET_ATTRIBUTE, getTarget());
writeOptionalAttribute(tagWriter, ENCTYPE_ATTRIBUTE, getEnctype());
writeOptionalAttribute(tagWriter, ACCEPT_CHARSET_ATTRIBUTE, getAcceptCharset());
writeOptionalAttribute(tagWriter, ONSUBMIT_ATTRIBUTE, getOnsubmit());
writeOptionalAttribute(tagWriter, ONRESET_ATTRIBUTE, getOnreset());
writeOptionalAttribute(tagWriter, AUTOCOMPLETE_ATTRIBUTE, getAutocomplete());
tagWriter.forceBlock();
if (!isMethodBrowserSupported(getMethod())) {
String inputName = getMethodParameter();
String inputType = "hidden";
tagWriter.startTag(INPUT_TAG);
writeOptionalAttribute(tagWriter, TYPE_ATTRIBUTE, inputType);
writeOptionalAttribute(tagWriter, NAME_ATTRIBUTE, inputName);
writeOptionalAttribute(tagWriter, VALUE_ATTRIBUTE, processFieldValue(inputName, getMethod(), inputType));
tagWriter.endTag();
}
// Expose the form object name for nested tags...
String modelAttribute = resolveModelAttribute();
this.pageContext.setAttribute(MODEL_ATTRIBUTE_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(COMMAND_NAME_VARIABLE_NAME, modelAttribute, PageContext.REQUEST_SCOPE);
// Save previous nestedPath value, build and expose current nestedPath value.
// Use request scope to expose nestedPath to included pages too.
this.previousNestedPath =
(String) this.pageContext.getAttribute(NESTED_PATH_VARIABLE_NAME, PageContext.REQUEST_SCOPE);
this.pageContext.setAttribute(NESTED_PATH_VARIABLE_NAME,
modelAttribute + PropertyAccessor.NESTED_PROPERTY_SEPARATOR, PageContext.REQUEST_SCOPE);
return EVAL_BODY_INCLUDE;
}
|
diff --git a/services/src/main/java/org/fao/geonet/services/metadata/GetCategories.java b/services/src/main/java/org/fao/geonet/services/metadata/GetCategories.java
index 018abaaa2b..69878620ce 100644
--- a/services/src/main/java/org/fao/geonet/services/metadata/GetCategories.java
+++ b/services/src/main/java/org/fao/geonet/services/metadata/GetCategories.java
@@ -1,129 +1,129 @@
//=============================================================================
//=== Copyright (C) 2001-2007 Food and Agriculture Organization of the
//=== United Nations (FAO-UN), United Nations World Food Programme (WFP)
//=== and United Nations Environment Programme (UNEP)
//===
//=== This program is free software; you can redistribute it and/or modify
//=== it under the terms of the GNU General Public License as published by
//=== the Free Software Foundation; either version 2 of the License, or (at
//=== your option) any later version.
//===
//=== This program is distributed in the hope that it will be useful, but
//=== WITHOUT ANY WARRANTY; without even the implied warranty of
//=== MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//=== General Public License for more details.
//===
//=== You should have received a copy of the GNU General Public License
//=== along with this program; if not, write to the Free Software
//=== Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
//===
//=== Contact: Jeroen Ticheler - FAO - Viale delle Terme di Caracalla 2,
//=== Rome - Italy. email: [email protected]
//==============================================================================
package org.fao.geonet.services.metadata;
import jeeves.constants.Jeeves;
import jeeves.interfaces.Service;
import jeeves.server.ServiceConfig;
import jeeves.server.context.ServiceContext;
import org.fao.geonet.GeonetContext;
import org.fao.geonet.constants.Geonet;
import org.fao.geonet.domain.Metadata;
import org.fao.geonet.domain.MetadataCategory;
import org.fao.geonet.kernel.AccessManager;
import org.fao.geonet.kernel.DataManager;
import org.fao.geonet.repository.MetadataCategoryRepository;
import org.fao.geonet.repository.MetadataRepository;
import org.fao.geonet.services.Utils;
import org.jdom.Element;
import java.util.HashSet;
import java.util.List;
//=============================================================================
/** Given a metadata id returns all associated categories. Called by the
* metadata.category service
*/
public class GetCategories implements Service
{
//--------------------------------------------------------------------------
//---
//--- Init
//---
//--------------------------------------------------------------------------
public void init(String appPath, ServiceConfig params) throws Exception {}
//--------------------------------------------------------------------------
//---
//--- Service
//---
//--------------------------------------------------------------------------
public Element exec(Element params, ServiceContext context) throws Exception
{
AccessManager am = context.getBean(AccessManager.class);
String id = Utils.getIdentifierFromParameters(params, context);
//-----------------------------------------------------------------------
//--- check access
int iLocalId = Integer.parseInt(id);
final Metadata metadata = context.getBean(MetadataRepository.class).findOne(iLocalId);
if (metadata == null) {
throw new IllegalArgumentException("Metadata not found --> " + id);
}
Element isOwner = new Element("owner");
- if (am.isOwner(context,id)) {
+ if (am.isOwner(context, id)) {
isOwner.setText("true");
} else {
isOwner.setText("false");
}
//-----------------------------------------------------------------------
//--- retrieve metadata categories
HashSet<String> hsMetadataCat = new HashSet<String>();
for (MetadataCategory cat : metadata.getCategories()) {
hsMetadataCat.add(cat.getId() + "");
}
//-----------------------------------------------------------------------
//--- retrieve groups operations
final MetadataCategoryRepository categoryRepository = context.getBean(MetadataCategoryRepository.class);
Element elCateg = categoryRepository.findAllAsXml();
@SuppressWarnings("unchecked")
List<Element> list = elCateg.getChildren();
for (Element el : list) {
el.setName(Geonet.Elem.CATEGORY);
//--- get all operations that this group can do on given metadata
if (hsMetadataCat.contains(el.getChildText("id")))
el.addContent(new Element("on"));
}
//-----------------------------------------------------------------------
//--- put all together
Element elRes = new Element(Jeeves.Elem.RESPONSE)
.addContent(new Element(Geonet.Elem.ID).setText(id))
.addContent(elCateg)
.addContent(isOwner);
return elRes;
}
}
//=============================================================================
| true | true | public Element exec(Element params, ServiceContext context) throws Exception
{
AccessManager am = context.getBean(AccessManager.class);
String id = Utils.getIdentifierFromParameters(params, context);
//-----------------------------------------------------------------------
//--- check access
int iLocalId = Integer.parseInt(id);
final Metadata metadata = context.getBean(MetadataRepository.class).findOne(iLocalId);
if (metadata == null) {
throw new IllegalArgumentException("Metadata not found --> " + id);
}
Element isOwner = new Element("owner");
if (am.isOwner(context,id)) {
isOwner.setText("true");
} else {
isOwner.setText("false");
}
//-----------------------------------------------------------------------
//--- retrieve metadata categories
HashSet<String> hsMetadataCat = new HashSet<String>();
for (MetadataCategory cat : metadata.getCategories()) {
hsMetadataCat.add(cat.getId() + "");
}
//-----------------------------------------------------------------------
//--- retrieve groups operations
final MetadataCategoryRepository categoryRepository = context.getBean(MetadataCategoryRepository.class);
Element elCateg = categoryRepository.findAllAsXml();
@SuppressWarnings("unchecked")
List<Element> list = elCateg.getChildren();
for (Element el : list) {
el.setName(Geonet.Elem.CATEGORY);
//--- get all operations that this group can do on given metadata
if (hsMetadataCat.contains(el.getChildText("id")))
el.addContent(new Element("on"));
}
//-----------------------------------------------------------------------
//--- put all together
Element elRes = new Element(Jeeves.Elem.RESPONSE)
.addContent(new Element(Geonet.Elem.ID).setText(id))
.addContent(elCateg)
.addContent(isOwner);
return elRes;
}
| public Element exec(Element params, ServiceContext context) throws Exception
{
AccessManager am = context.getBean(AccessManager.class);
String id = Utils.getIdentifierFromParameters(params, context);
//-----------------------------------------------------------------------
//--- check access
int iLocalId = Integer.parseInt(id);
final Metadata metadata = context.getBean(MetadataRepository.class).findOne(iLocalId);
if (metadata == null) {
throw new IllegalArgumentException("Metadata not found --> " + id);
}
Element isOwner = new Element("owner");
if (am.isOwner(context, id)) {
isOwner.setText("true");
} else {
isOwner.setText("false");
}
//-----------------------------------------------------------------------
//--- retrieve metadata categories
HashSet<String> hsMetadataCat = new HashSet<String>();
for (MetadataCategory cat : metadata.getCategories()) {
hsMetadataCat.add(cat.getId() + "");
}
//-----------------------------------------------------------------------
//--- retrieve groups operations
final MetadataCategoryRepository categoryRepository = context.getBean(MetadataCategoryRepository.class);
Element elCateg = categoryRepository.findAllAsXml();
@SuppressWarnings("unchecked")
List<Element> list = elCateg.getChildren();
for (Element el : list) {
el.setName(Geonet.Elem.CATEGORY);
//--- get all operations that this group can do on given metadata
if (hsMetadataCat.contains(el.getChildText("id")))
el.addContent(new Element("on"));
}
//-----------------------------------------------------------------------
//--- put all together
Element elRes = new Element(Jeeves.Elem.RESPONSE)
.addContent(new Element(Geonet.Elem.ID).setText(id))
.addContent(elCateg)
.addContent(isOwner);
return elRes;
}
|
diff --git a/src/risk/game/Game.java b/src/risk/game/Game.java
index 32be728..5cabe35 100644
--- a/src/risk/game/Game.java
+++ b/src/risk/game/Game.java
@@ -1,417 +1,418 @@
package risk.game;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import risk.common.Logger;
public class Game implements GameView, GameController {
/**
* The map that represent the current state of the world.
*/
private Map map = new Map();
/**
* A list of players.
*/
private LinkedList<Player> players = new LinkedList<Player>();
private Iterator<Player> currentPlayerIterator;
private LinkedList<Player> roundPlayers;
/**
* A list of observers for the Observer design pattern.
*/
private ArrayList<Observer> observers=new ArrayList<Observer>();
private LinkedList<MessageListener> msgListeners = new LinkedList<MessageListener>();
/**
* Indicates in which phase the current round is. May be null.
* Eg. reinforcement phase, attack phase, regroup phase
*/
private RoundPhase currentRoundPhase;
/**
* Indicates the next RoundPhase. May be null.
*/
private RoundPhase nextRoundPhase;
/**
* The number of troops that can be assigned to countries at the beginning
* of a new round as reinforcement.
*/
private int availableReinforcement;
/**
* The player controlled by this client
*/
private Player myPlayer;
/**
* The player currently acting.
*/
private Player currentPlayer;
/**
* The current round number
*/
private int roundNumber;
/**
* The round phases in this current round
*/
private LinkedList<RoundPhase> roundPhases;
private Iterator<RoundPhase> roundPhasesIterator;
private Attack attack;
private Attack lastAttack;
private boolean gameStarted = false;
public void addPlayer(Player p) {
players.add(p);
modelChanged();
}
@Override
public void setMyPlayer(Player p) {
myPlayer = p;
modelChanged();
}
@Override
public Player getMyPlayer() {
return myPlayer;
}
public Collection<Player> getPlayers() {
return players;
}
public Player getPlayer(String Name) {
for (Player p : players) {
if (p.getName().compareTo(Name) == 0) {
return p;
}
}
return null;
}
@Override
public void setRoundPlayers(Collection<Player> players) {
this.currentPlayerIterator = null;
this.roundPlayers = new LinkedList<Player>();
for (Player p : players) {
this.roundPlayers.add(getPlayer(p.getName()));
}
}
@Override
public Country getCountry(String countryName) {
return map.getCountry(countryName);
}
@Override
public Collection<Continent> getContinents() {
return map.getContinents();
}
@Override
public Collection<Country> getCountries() {
ArrayList<Country> countries = new ArrayList<Country>();
Collection<Continent> continets = getContinents();
for (Continent c : continets) {
countries.addAll(c.getCountries());
}
return countries;
}
@Override
public void initCountry(String countryName, String ownerName, int troops) {
Country c = getCountry(countryName);
Player newOwner = getPlayer(ownerName);
c.setOwner(newOwner);
c.setTroops(troops);
modelChanged();
}
@Override
public void registerObserver(Observer o) {
observers.add(o);
modelChanged();
}
private void modelChanged(){
for(Observer o : observers){
o.refresh(this);
}
}
@Override
public void registerMsgListener(MessageListener listener) {
msgListeners.add(listener);
}
@Override
public Collection<MessageListener> getMessageListeners() {
return msgListeners;
}
@Override
public Color getCountryColor(String countryName) {
Country c = getCountry(countryName);
if (c != null && c.getOwner() != null) {
return c.getOwner().getColor();
}
return null;
}
@Override
public int getCountryTroops(String countryName) {
Country c = getCountry(countryName);
if (c != null) {
return c.getTroops();
}
return 0;
}
@Override
public void cancelCountrySelection(Country c) {
map.cancelCountrySelection(c);
modelChanged();
}
@Override
public void selectCountry(Country c) {
map.selectCountry(c);
modelChanged();
}
@Override
public boolean isCountrySelected(String name) {
Country c = getCountry(name);
return isCountrySelected(c);
}
@Override
public boolean isCountryNeighbourSelected(String name) {
Country c = getCountry(name);
return getSelectedCountryNeighbour(c) != null;
}
@Override
public boolean isCountrySelected(Country c) {
return map.isCountrySelected(c);
}
@Override
public Country getSelectedCountryNeighbour(Country c) {
return map.getSelectedCountryNeighbour(c);
}
@Override
public void cancelCountryNeighbourSelection(Country c) {
map.cancelCountryNeighbourSelection(c);
}
@Override
public RoundPhase getRoundPhase() {
return currentRoundPhase;
}
@Override
public RoundPhase getNextRoundPhase() {
return nextRoundPhase;
}
@Override
public int getAvailableReinforcement() {
return availableReinforcement;
}
@Override
public void setAvailableReinforcement(int availableReinforcement) {
this.availableReinforcement = availableReinforcement;
modelChanged();
}
@Override
public void addTroopsToCountry(Country country, int troops) {
country.setTroops(country.getTroops() + troops);
modelChanged();
}
@Override
public boolean switchToNextPlayer() {
if (currentPlayerIterator == null) {
currentPlayerIterator = roundPlayers.iterator();
}
if (currentPlayerIterator.hasNext()) {
currentPlayer = currentPlayerIterator.next();
} else {
currentPlayer = null;
}
modelChanged();
return currentPlayer != null;
}
@Override
public Player getCurrentPlayer() {
return currentPlayer;
}
@Override
public int getRoundNumber() {
return roundNumber;
}
@Override
public void setRoundNumber(int roundNumber) {
this.roundNumber = roundNumber;
modelChanged();
}
@Override
public Collection<RoundPhase> getRoundPhases() {
return roundPhases;
}
@Override
public void setRoundPhases(Collection<RoundPhase> roundPhases) {
this.roundPhases = new LinkedList<RoundPhase>(roundPhases);
this.currentRoundPhase = null;
this.roundPhasesIterator = null;
modelChanged();
}
@Override
public void resetPhases() {
roundPhasesIterator = null;
}
@Override
public boolean swicthToNextPhase() {
if (roundPhasesIterator == null) {
roundPhasesIterator = roundPhases.iterator();
if (roundPhasesIterator.hasNext()) {
nextRoundPhase = roundPhasesIterator.next();
} else {
nextRoundPhase = null;
}
}
currentRoundPhase = nextRoundPhase;
if (roundPhasesIterator.hasNext()) {
nextRoundPhase = roundPhasesIterator.next();
} else {
nextRoundPhase = null;
}
modelChanged();
return currentRoundPhase != null;
}
@Override
public void regroup(CountryPair countryPair, int troops) {
Country from = countryPair.From;
Country to = countryPair.To;
from.setTroops(from.getTroops() - troops);
to.setTroops(to.getTroops() + troops);
modelChanged();
}
@Override
public void setAttack(Attack attack) {
this.attack = attack;
modelChanged();
}
@Override
public Attack getAttack() {
return attack;
}
@Override
public Attack getLastAttack() {
return lastAttack;
}
private void accountAttackLosses() {
if (attack == null) {
Logger.logerror("Accounting attack losses when no attack is in progress");
return;
}
Country from = attack.getCountryPair().From;
Country to = attack.getCountryPair().To;
int[] losses = attack.calcLosses();
int aLosses = losses[0];
int dLosses = losses[1];
from.setTroops(from.getTroops() - aLosses);
to.setTroops(to.getTroops() - dLosses);
if (to.getTroops() < 1) {
to.setOwner(from.getOwner());
to.setTroops(attack.getAttackerDice());
+ from.setTroops(from.getTroops() - attack.getAttackerDice());
clearAttack();
}
if (from.getTroops() < 2) {
clearAttack();
}
}
@Override
public void setAttackDDice(int dice) {
if (attack == null) {
Logger.logerror("Adding adice when no attack is in progress");
return;
}
attack.setDefenderDice(dice);
modelChanged();
}
@Override
public void setAttackADice(int dice) {
if (attack == null) {
Logger.logerror("Adding ddice when no attack is in progress");
return;
}
attack.setAttackerDice(dice);
modelChanged();
}
@Override
public void clearAttack() {
lastAttack = attack;
attack = null;
modelChanged();
}
@Override
public void setAttackRoundResults(ArrayList<Integer> aDiceResults, ArrayList<Integer> dDiceResults) {
if (attack == null) {
Logger.logerror("Adding dice results when no attack is in progress");
return;
}
attack.setaDiceResults(aDiceResults);
attack.setdDiceResults(dDiceResults);
accountAttackLosses();
if (attack != null) {
attack.resetDice();
}
modelChanged();
}
@Override
public boolean isGameStarted() {
return gameStarted;
}
public void setGameStarted(boolean gameStarted) {
this.gameStarted = gameStarted;
}
}
| true | true | private void accountAttackLosses() {
if (attack == null) {
Logger.logerror("Accounting attack losses when no attack is in progress");
return;
}
Country from = attack.getCountryPair().From;
Country to = attack.getCountryPair().To;
int[] losses = attack.calcLosses();
int aLosses = losses[0];
int dLosses = losses[1];
from.setTroops(from.getTroops() - aLosses);
to.setTroops(to.getTroops() - dLosses);
if (to.getTroops() < 1) {
to.setOwner(from.getOwner());
to.setTroops(attack.getAttackerDice());
clearAttack();
}
if (from.getTroops() < 2) {
clearAttack();
}
}
| private void accountAttackLosses() {
if (attack == null) {
Logger.logerror("Accounting attack losses when no attack is in progress");
return;
}
Country from = attack.getCountryPair().From;
Country to = attack.getCountryPair().To;
int[] losses = attack.calcLosses();
int aLosses = losses[0];
int dLosses = losses[1];
from.setTroops(from.getTroops() - aLosses);
to.setTroops(to.getTroops() - dLosses);
if (to.getTroops() < 1) {
to.setOwner(from.getOwner());
to.setTroops(attack.getAttackerDice());
from.setTroops(from.getTroops() - attack.getAttackerDice());
clearAttack();
}
if (from.getTroops() < 2) {
clearAttack();
}
}
|
diff --git a/src/org/eclipse/core/internal/localstore/UnifiedTree.java b/src/org/eclipse/core/internal/localstore/UnifiedTree.java
index 0c4fbb69..d36f9ef6 100644
--- a/src/org/eclipse/core/internal/localstore/UnifiedTree.java
+++ b/src/org/eclipse/core/internal/localstore/UnifiedTree.java
@@ -1,404 +1,404 @@
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.internal.localstore;
import java.util.*;
import org.eclipse.core.filesystem.*;
import org.eclipse.core.internal.resources.*;
import org.eclipse.core.internal.utils.OldAssert;
import org.eclipse.core.internal.utils.Queue;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
/**
* Represents the workspace's tree merged with the file system's tree.
*/
public class UnifiedTree {
/** tree's root */
protected IResource root;
/** tree's actual level */
protected int level;
/**
* True if the level of the children of the current node are valid according
* to the requested refresh depth, false otherwise
*/
protected boolean childLevelValid = false;
/** our queue */
protected Queue queue;
/** Spare node objects available for reuse */
protected ArrayList freeNodes = new ArrayList();
/** special node to mark the beginning of a level in the tree */
protected static final UnifiedTreeNode levelMarker = new UnifiedTreeNode(null, null, null, null, false);
/** special node to mark the separation of a node's children */
protected static final UnifiedTreeNode childrenMarker = new UnifiedTreeNode(null, null, null, null, false);
/** Singleton to indicate no local children */
private static final IResource[] NO_RESOURCES = new IResource[0];
private static final IFileInfo[] NO_CHILDREN = new IFileInfo[0];
private static final Iterator EMPTY_ITERATOR = Collections.EMPTY_LIST.iterator();
/**
* The root must only be a file or a folder.
*/
public UnifiedTree(IResource root) {
setRoot(root);
}
public void accept(IUnifiedTreeVisitor visitor) throws CoreException {
accept(visitor, IResource.DEPTH_INFINITE);
}
public void accept(IUnifiedTreeVisitor visitor, int depth) throws CoreException {
OldAssert.isNotNull(root);
initializeQueue();
setLevel(0, depth);
while (!queue.isEmpty()) {
UnifiedTreeNode node = (UnifiedTreeNode) queue.remove();
if (isChildrenMarker(node))
continue;
if (isLevelMarker(node)) {
if (!setLevel(getLevel() + 1, depth))
break;
continue;
}
if (visitor.visit(node))
addNodeChildrenToQueue(node);
else
removeNodeChildrenFromQueue(node);
//allow reuse of the node
freeNodes.add(node);
}
}
protected void addChildren(UnifiedTreeNode node) {
Resource parent = (Resource) node.getResource();
// is there a possibility to have children?
int parentType = parent.getType();
if (parentType == IResource.FILE && !node.isFolder())
return;
//don't refresh resources in closed or non-existent projects
if (!parent.getProject().isAccessible())
return;
// get the list of resources in the file system
// don't ask for local children if we know it doesn't exist locally
IFileInfo[] list = node.existsInFileSystem() ? getLocalList(node) : NO_CHILDREN;
int localIndex = 0;
// See if the children of this resource have been computed before
ResourceInfo resourceInfo = parent.getResourceInfo(false, false);
int flags = parent.getFlags(resourceInfo);
boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN);
// get the list of resources in the workspace
if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) {
IResource target = null;
UnifiedTreeNode child = null;
IResource[] members;
try {
members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS);
} catch (CoreException e) {
members = NO_RESOURCES;
}
int workspaceIndex = 0;
//iterate simultaneously over file system and workspace members
while (workspaceIndex < members.length) {
target = members[workspaceIndex];
String name = target.getName();
String localName = localIndex < list.length ? list[localIndex].getName() : null;
int comp = localName != null ? name.compareTo(localName) : -1;
//special handling for linked resources
- if (parentType == IResource.PROJECT && target.isLinked()) {
+ if (target.isLinked()) {
//child will be null if location is undefined
child = createChildForLinkedResource(target);
workspaceIndex++;
//if there is a matching local file, skip it - it will be blocked by the linked resource
if (comp == 0)
localIndex++;
} else if (comp == 0) {
// resource exists in workspace and file system
child = createNode(target, null, list[localIndex], true);
localIndex++;
workspaceIndex++;
} else if (comp > 0) {
// resource exists only in file system
child = createChildNodeFromFileSystem(node, list[localIndex]);
localIndex++;
} else {
// resource exists only in the workspace
child = createNode(target, null, null, true);
workspaceIndex++;
}
if (child != null)
addChildToTree(node, child);
}
}
/* process any remaining resource from the file system */
addChildrenFromFileSystem(node, list, localIndex);
/* Mark the children as now known */
if (unknown) {
// Don't open the info - we might not be inside a workspace-modifying operation
resourceInfo = parent.getResourceInfo(false, false);
if (resourceInfo != null)
resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN);
}
/* if we added children, add the childMarker separator */
if (node.getFirstChild() != null)
addChildrenMarker();
}
/**
* Creates a tree node for a resource that is linked in a different file system location.
*/
protected UnifiedTreeNode createChildForLinkedResource(IResource target) {
IFileStore store = ((Resource) target).getStore();
return createNode(target, store, store.fetchInfo(), true);
}
protected void addChildrenFromFileSystem(UnifiedTreeNode node, IFileInfo[] childInfos, int index) {
if (childInfos == null)
return;
for (int i = index; i < childInfos.length; i++)
addChildToTree(node, createChildNodeFromFileSystem(node, childInfos[i]));
}
protected void addChildrenMarker() {
addElementToQueue(childrenMarker);
}
protected void addChildToTree(UnifiedTreeNode node, UnifiedTreeNode child) {
if (node.getFirstChild() == null)
node.setFirstChild(child);
addElementToQueue(child);
}
protected void addElementToQueue(UnifiedTreeNode target) {
queue.add(target);
}
protected void addNodeChildrenToQueue(UnifiedTreeNode node) {
/* if the first child is not null we already added the children */
/* If the children won't be at a valid level for the refresh depth, don't bother adding them */
if (!childLevelValid || node.getFirstChild() != null)
return;
addChildren(node);
if (queue.isEmpty())
return;
//if we're about to change levels, then the children just added
//are the last nodes for their level, so add a level marker to the queue
UnifiedTreeNode nextNode = (UnifiedTreeNode) queue.peek();
if (isChildrenMarker(nextNode))
queue.remove();
nextNode = (UnifiedTreeNode) queue.peek();
if (isLevelMarker(nextNode))
addElementToQueue(levelMarker);
}
protected void addRootToQueue() {
//don't refresh in closed projects
if (!root.getProject().isAccessible())
return;
IFileStore rootStore = ((Resource) root).getStore();
UnifiedTreeNode node = createNode(root, rootStore, rootStore.fetchInfo(), root.exists());
if (!node.existsInFileSystem() && !node.existsInWorkspace())
return;
addElementToQueue(node);
}
/**
* Creates a child node for a location in the file system. Does nothing and returns null if the location does not correspond to a valid file/folder.
*/
protected UnifiedTreeNode createChildNodeFromFileSystem(UnifiedTreeNode parent, IFileInfo info) {
IPath childPath = parent.getResource().getFullPath().append(info.getName());
int type = info.isDirectory() ? IResource.FOLDER : IResource.FILE;
IResource target = getWorkspace().newResource(childPath, type);
return createNode(target, null, info, false);
}
/**
* Factory method for creating a node for this tree. If the file exists on
* disk, either the parent store or child store can be provided. Providing
* only the parent store avoids creation of the child store in cases where
* it is not needed. The store object is only needed for directories for
* simple file system traversals, so this avoids creating store objects
* for all files.
*/
protected UnifiedTreeNode createNode(IResource resource, IFileStore store, IFileInfo info, boolean existsWorkspace) {
//first check for reusable objects
UnifiedTreeNode node = null;
int size = freeNodes.size();
if (size > 0) {
node = (UnifiedTreeNode) freeNodes.remove(size - 1);
node.reuse(this, resource, store, info, existsWorkspace);
return node;
}
//none available, so create a new one
return new UnifiedTreeNode(this, resource, store, info, existsWorkspace);
}
protected Iterator getChildren(UnifiedTreeNode node) {
/* if first child is null we need to add node's children to queue */
if (node.getFirstChild() == null)
addNodeChildrenToQueue(node);
/* if the first child is still null, the node does not have any children */
if (node.getFirstChild() == null)
return EMPTY_ITERATOR;
/* get the index of the first child */
int index = queue.indexOf(node.getFirstChild());
/* if we do not have children, just return an empty enumeration */
if (index == -1)
return EMPTY_ITERATOR;
/* create an enumeration with node's children */
List result = new ArrayList(10);
while (true) {
UnifiedTreeNode child = (UnifiedTreeNode) queue.elementAt(index);
if (isChildrenMarker(child))
break;
result.add(child);
index = queue.increment(index);
}
return result.iterator();
}
protected int getLevel() {
return level;
}
protected IFileInfo[] getLocalList(UnifiedTreeNode node) {
IFileInfo[] list;
try {
list = node.getStore().childInfos(EFS.NONE, null);
} catch (CoreException e) {
//treat failure to access the directory as a non-existent directory
return NO_CHILDREN;
}
if (list == null)
return NO_CHILDREN;
int size = list.length;
if (size > 1)
quickSort(list, 0, size - 1);
return list;
}
protected Workspace getWorkspace() {
return (Workspace) root.getWorkspace();
}
/**
* Increases the current tree level by one. Returns true if the new
* level is still valid for the given depth
*/
protected boolean setLevel(int newLevel, int depth) {
level = newLevel;
childLevelValid = isValidLevel(level + 1, depth);
return isValidLevel(level, depth);
}
protected void initializeQueue() {
//initialize the queue
if (queue == null)
queue = new Queue(100, false);
else
queue.reset();
//initialize the free nodes list
if (freeNodes == null)
freeNodes = new ArrayList(100);
else
freeNodes.clear();
addRootToQueue();
addElementToQueue(levelMarker);
}
protected boolean isChildrenMarker(UnifiedTreeNode node) {
return node == childrenMarker;
}
protected boolean isLevelMarker(UnifiedTreeNode node) {
return node == levelMarker;
}
protected boolean isValidLevel(int currentLevel, int depth) {
switch (depth) {
case IResource.DEPTH_INFINITE :
return true;
case IResource.DEPTH_ONE :
return currentLevel <= 1;
case IResource.DEPTH_ZERO :
return currentLevel == 0;
default :
return currentLevel + 1000 <= depth;
}
}
/**
* Remove from the last element of the queue to the first child of the
* given node.
*/
protected void removeNodeChildrenFromQueue(UnifiedTreeNode node) {
UnifiedTreeNode first = node.getFirstChild();
if (first == null)
return;
while (true) {
if (first.equals(queue.removeTail()))
break;
}
node.setFirstChild(null);
}
public void setRoot(IResource root) {
this.root = root;
}
/**
* Sorts the given array of strings in place. This is
* not using the sorting framework to avoid casting overhead.
*/
protected void quickSort(IFileInfo[] infos, int left, int right) {
int originalLeft = left;
int originalRight = right;
IFileInfo mid = infos[(left + right) / 2];
do {
while (mid.compareTo(infos[left]) > 0)
left++;
while (infos[right].compareTo(mid) > 0)
right--;
if (left <= right) {
IFileInfo tmp = infos[left];
infos[left] = infos[right];
infos[right] = tmp;
left++;
right--;
}
} while (left <= right);
if (originalLeft < right)
quickSort(infos, originalLeft, right);
if (left < originalRight)
quickSort(infos, left, originalRight);
return;
}
}
| true | true | protected void addChildren(UnifiedTreeNode node) {
Resource parent = (Resource) node.getResource();
// is there a possibility to have children?
int parentType = parent.getType();
if (parentType == IResource.FILE && !node.isFolder())
return;
//don't refresh resources in closed or non-existent projects
if (!parent.getProject().isAccessible())
return;
// get the list of resources in the file system
// don't ask for local children if we know it doesn't exist locally
IFileInfo[] list = node.existsInFileSystem() ? getLocalList(node) : NO_CHILDREN;
int localIndex = 0;
// See if the children of this resource have been computed before
ResourceInfo resourceInfo = parent.getResourceInfo(false, false);
int flags = parent.getFlags(resourceInfo);
boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN);
// get the list of resources in the workspace
if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) {
IResource target = null;
UnifiedTreeNode child = null;
IResource[] members;
try {
members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS);
} catch (CoreException e) {
members = NO_RESOURCES;
}
int workspaceIndex = 0;
//iterate simultaneously over file system and workspace members
while (workspaceIndex < members.length) {
target = members[workspaceIndex];
String name = target.getName();
String localName = localIndex < list.length ? list[localIndex].getName() : null;
int comp = localName != null ? name.compareTo(localName) : -1;
//special handling for linked resources
if (parentType == IResource.PROJECT && target.isLinked()) {
//child will be null if location is undefined
child = createChildForLinkedResource(target);
workspaceIndex++;
//if there is a matching local file, skip it - it will be blocked by the linked resource
if (comp == 0)
localIndex++;
} else if (comp == 0) {
// resource exists in workspace and file system
child = createNode(target, null, list[localIndex], true);
localIndex++;
workspaceIndex++;
} else if (comp > 0) {
// resource exists only in file system
child = createChildNodeFromFileSystem(node, list[localIndex]);
localIndex++;
} else {
// resource exists only in the workspace
child = createNode(target, null, null, true);
workspaceIndex++;
}
if (child != null)
addChildToTree(node, child);
}
}
/* process any remaining resource from the file system */
addChildrenFromFileSystem(node, list, localIndex);
/* Mark the children as now known */
if (unknown) {
// Don't open the info - we might not be inside a workspace-modifying operation
resourceInfo = parent.getResourceInfo(false, false);
if (resourceInfo != null)
resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN);
}
/* if we added children, add the childMarker separator */
if (node.getFirstChild() != null)
addChildrenMarker();
}
| protected void addChildren(UnifiedTreeNode node) {
Resource parent = (Resource) node.getResource();
// is there a possibility to have children?
int parentType = parent.getType();
if (parentType == IResource.FILE && !node.isFolder())
return;
//don't refresh resources in closed or non-existent projects
if (!parent.getProject().isAccessible())
return;
// get the list of resources in the file system
// don't ask for local children if we know it doesn't exist locally
IFileInfo[] list = node.existsInFileSystem() ? getLocalList(node) : NO_CHILDREN;
int localIndex = 0;
// See if the children of this resource have been computed before
ResourceInfo resourceInfo = parent.getResourceInfo(false, false);
int flags = parent.getFlags(resourceInfo);
boolean unknown = ResourceInfo.isSet(flags, ICoreConstants.M_CHILDREN_UNKNOWN);
// get the list of resources in the workspace
if (!unknown && (parentType == IResource.FOLDER || parentType == IResource.PROJECT) && parent.exists(flags, true)) {
IResource target = null;
UnifiedTreeNode child = null;
IResource[] members;
try {
members = ((IContainer) parent).members(IContainer.INCLUDE_TEAM_PRIVATE_MEMBERS);
} catch (CoreException e) {
members = NO_RESOURCES;
}
int workspaceIndex = 0;
//iterate simultaneously over file system and workspace members
while (workspaceIndex < members.length) {
target = members[workspaceIndex];
String name = target.getName();
String localName = localIndex < list.length ? list[localIndex].getName() : null;
int comp = localName != null ? name.compareTo(localName) : -1;
//special handling for linked resources
if (target.isLinked()) {
//child will be null if location is undefined
child = createChildForLinkedResource(target);
workspaceIndex++;
//if there is a matching local file, skip it - it will be blocked by the linked resource
if (comp == 0)
localIndex++;
} else if (comp == 0) {
// resource exists in workspace and file system
child = createNode(target, null, list[localIndex], true);
localIndex++;
workspaceIndex++;
} else if (comp > 0) {
// resource exists only in file system
child = createChildNodeFromFileSystem(node, list[localIndex]);
localIndex++;
} else {
// resource exists only in the workspace
child = createNode(target, null, null, true);
workspaceIndex++;
}
if (child != null)
addChildToTree(node, child);
}
}
/* process any remaining resource from the file system */
addChildrenFromFileSystem(node, list, localIndex);
/* Mark the children as now known */
if (unknown) {
// Don't open the info - we might not be inside a workspace-modifying operation
resourceInfo = parent.getResourceInfo(false, false);
if (resourceInfo != null)
resourceInfo.clear(ICoreConstants.M_CHILDREN_UNKNOWN);
}
/* if we added children, add the childMarker separator */
if (node.getFirstChild() != null)
addChildrenMarker();
}
|
diff --git a/src/mapred/org/apache/hadoop/mapred/jobcontrol/Job.java b/src/mapred/org/apache/hadoop/mapred/jobcontrol/Job.java
index 9801d2cf3..fd0957db9 100644
--- a/src/mapred/org/apache/hadoop/mapred/jobcontrol/Job.java
+++ b/src/mapred/org/apache/hadoop/mapred/jobcontrol/Job.java
@@ -1,387 +1,387 @@
/**
* 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.hadoop.mapred.jobcontrol;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.JobID;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.util.StringUtils;
/** This class encapsulates a MapReduce job and its dependency. It monitors
* the states of the depending jobs and updates the state of this job.
* A job starts in the WAITING state. If it does not have any depending jobs, or
* all of the depending jobs are in SUCCESS state, then the job state will become
* READY. If any depending jobs fail, the job will fail too.
* When in READY state, the job can be submitted to Hadoop for execution, with
* the state changing into RUNNING state. From RUNNING state, the job can get into
* SUCCESS or FAILED state, depending the status of the job execution.
*
*/
public class Job {
// A job will be in one of the following states
final public static int SUCCESS = 0;
final public static int WAITING = 1;
final public static int RUNNING = 2;
final public static int READY = 3;
final public static int FAILED = 4;
final public static int DEPENDENT_FAILED = 5;
private JobConf theJobConf;
private int state;
private String jobID; // assigned and used by JobControl class
private JobID mapredJobID; // the job ID assigned by map/reduce
private String jobName; // external name, assigned/used by client app
private String message; // some info for human consumption,
// e.g. the reason why the job failed
private ArrayList<Job> dependingJobs; // the jobs the current job depends on
private JobClient jc = null; // the map reduce job client
/**
* Construct a job.
* @param jobConf a mapred job configuration representing a job to be executed.
* @param dependingJobs an array of jobs the current job depends on
*/
public Job(JobConf jobConf, ArrayList<Job> dependingJobs) throws IOException {
this.theJobConf = jobConf;
this.dependingJobs = dependingJobs;
this.state = Job.WAITING;
this.jobID = "unassigned";
this.mapredJobID = null; //not yet assigned
this.jobName = "unassigned";
this.message = "just initialized";
this.jc = new JobClient(jobConf);
}
/**
* Construct a job.
*
* @param jobConf mapred job configuration representing a job to be executed.
* @throws IOException
*/
public Job(JobConf jobConf) throws IOException {
this(jobConf, null);
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("job name:\t").append(this.jobName).append("\n");
sb.append("job id:\t").append(this.jobID).append("\n");
sb.append("job state:\t").append(this.state).append("\n");
sb.append("job mapred id:\t").append(this.mapredJobID==null ? "unassigned"
: this.mapredJobID).append("\n");
sb.append("job message:\t").append(this.message).append("\n");
if (this.dependingJobs == null || this.dependingJobs.size() == 0) {
sb.append("job has no depending job:\t").append("\n");
} else {
sb.append("job has ").append(this.dependingJobs.size()).append(" dependeng jobs:\n");
for (int i = 0; i < this.dependingJobs.size(); i++) {
sb.append("\t depending job ").append(i).append(":\t");
sb.append((this.dependingJobs.get(i)).getJobName()).append("\n");
}
}
return sb.toString();
}
/**
* @return the job name of this job
*/
public String getJobName() {
return this.jobName;
}
/**
* Set the job name for this job.
* @param jobName the job name
*/
public void setJobName(String jobName) {
this.jobName = jobName;
}
/**
* @return the job ID of this job assigned by JobControl
*/
public String getJobID() {
return this.jobID;
}
/**
* Set the job ID for this job.
* @param id the job ID
*/
public void setJobID(String id) {
this.jobID = id;
}
/**
* @return the mapred ID of this job
* @deprecated use {@link #getAssignedJobID()} instead
*/
@Deprecated
public String getMapredJobID() {
return this.mapredJobID.toString();
}
/**
* Set the mapred ID for this job.
* @param mapredJobID the mapred job ID for this job.
* @deprecated use {@link #setAssignedJobID(JobID)} instead
*/
@Deprecated
public void setMapredJobID(String mapredJobID) {
this.mapredJobID = JobID.forName(mapredJobID);
}
/**
* @return the mapred ID of this job as assigned by the
* mapred framework.
*/
public JobID getAssignedJobID() {
return this.mapredJobID;
}
/**
* Set the mapred ID for this job as assigned by the
* mapred framework.
* @param mapredJobID the mapred job ID for this job.
*/
public void setAssignedJobID(JobID mapredJobID) {
this.mapredJobID = mapredJobID;
}
/**
* @return the mapred job conf of this job
*/
public JobConf getJobConf() {
return this.theJobConf;
}
/**
* Set the mapred job conf for this job.
* @param jobConf the mapred job conf for this job.
*/
public void setJobConf(JobConf jobConf) {
this.theJobConf = jobConf;
}
/**
* @return the state of this job
*/
public synchronized int getState() {
return this.state;
}
/**
* Set the state for this job.
* @param state the new state for this job.
*/
protected synchronized void setState(int state) {
this.state = state;
}
/**
* @return the message of this job
*/
public String getMessage() {
return this.message;
}
/**
* Set the message for this job.
* @param message the message for this job.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* @return the job client of this job
*/
public JobClient getJobClient(){
return this.jc;
}
/**
* @return the depending jobs of this job
*/
public ArrayList<Job> getDependingJobs() {
return this.dependingJobs;
}
/**
* Add a job to this jobs' dependency list. Dependent jobs can only be added while a Job
* is waiting to run, not during or afterwards.
*
* @param dependingJob Job that this Job depends on.
* @return <tt>true</tt> if the Job was added.
*/
public synchronized boolean addDependingJob(Job dependingJob) {
if (this.state == Job.WAITING) { //only allowed to add jobs when waiting
if (this.dependingJobs == null) {
this.dependingJobs = new ArrayList<Job>();
}
return this.dependingJobs.add(dependingJob);
} else {
return false;
}
}
/**
* @return true if this job is in a complete state
*/
public boolean isCompleted() {
return this.state == Job.FAILED ||
this.state == Job.DEPENDENT_FAILED ||
this.state == Job.SUCCESS;
}
/**
* @return true if this job is in READY state
*/
public boolean isReady() {
return this.state == Job.READY;
}
/**
* Check the state of this running job. The state may
* remain the same, become SUCCESS or FAILED.
*/
private void checkRunningState() {
RunningJob running = null;
try {
running = jc.getJob(this.mapredJobID);
if (running.isComplete()) {
if (running.isSuccessful()) {
this.state = Job.SUCCESS;
} else {
this.state = Job.FAILED;
- this.message = "Job failed!";
+ this.message = "Job failed! Error - " + running.getFailureInfo();
try {
running.killJob();
} catch (IOException e1) {
}
try {
this.jc.close();
} catch (IOException e2) {
}
}
}
} catch (IOException ioe) {
this.state = Job.FAILED;
this.message = StringUtils.stringifyException(ioe);
try {
if (running != null)
running.killJob();
} catch (IOException e1) {
}
try {
this.jc.close();
} catch (IOException e1) {
}
}
}
/**
* Check and update the state of this job. The state changes
* depending on its current state and the states of the depending jobs.
*/
synchronized int checkState() {
if (this.state == Job.RUNNING) {
checkRunningState();
}
if (this.state != Job.WAITING) {
return this.state;
}
if (this.dependingJobs == null || this.dependingJobs.size() == 0) {
this.state = Job.READY;
return this.state;
}
Job pred = null;
int n = this.dependingJobs.size();
for (int i = 0; i < n; i++) {
pred = this.dependingJobs.get(i);
int s = pred.checkState();
if (s == Job.WAITING || s == Job.READY || s == Job.RUNNING) {
break; // a pred is still not completed, continue in WAITING
// state
}
if (s == Job.FAILED || s == Job.DEPENDENT_FAILED) {
this.state = Job.DEPENDENT_FAILED;
this.message = "depending job " + i + " with jobID "
+ pred.getJobID() + " failed. " + pred.getMessage();
break;
}
// pred must be in success state
if (i == n - 1) {
this.state = Job.READY;
}
}
return this.state;
}
/**
* Submit this job to mapred. The state becomes RUNNING if submission
* is successful, FAILED otherwise.
*/
protected synchronized void submit() {
try {
if (theJobConf.getBoolean("create.empty.dir.if.nonexist", false)) {
FileSystem fs = FileSystem.get(theJobConf);
Path inputPaths[] = FileInputFormat.getInputPaths(theJobConf);
for (int i = 0; i < inputPaths.length; i++) {
if (!fs.exists(inputPaths[i])) {
try {
fs.mkdirs(inputPaths[i]);
} catch (IOException e) {
}
}
}
}
RunningJob running = jc.submitJob(theJobConf);
this.mapredJobID = running.getID();
this.state = Job.RUNNING;
} catch (IOException ioe) {
this.state = Job.FAILED;
this.message = StringUtils.stringifyException(ioe);
}
}
}
| true | true | private void checkRunningState() {
RunningJob running = null;
try {
running = jc.getJob(this.mapredJobID);
if (running.isComplete()) {
if (running.isSuccessful()) {
this.state = Job.SUCCESS;
} else {
this.state = Job.FAILED;
this.message = "Job failed!";
try {
running.killJob();
} catch (IOException e1) {
}
try {
this.jc.close();
} catch (IOException e2) {
}
}
}
} catch (IOException ioe) {
this.state = Job.FAILED;
this.message = StringUtils.stringifyException(ioe);
try {
if (running != null)
running.killJob();
} catch (IOException e1) {
}
try {
this.jc.close();
} catch (IOException e1) {
}
}
}
| private void checkRunningState() {
RunningJob running = null;
try {
running = jc.getJob(this.mapredJobID);
if (running.isComplete()) {
if (running.isSuccessful()) {
this.state = Job.SUCCESS;
} else {
this.state = Job.FAILED;
this.message = "Job failed! Error - " + running.getFailureInfo();
try {
running.killJob();
} catch (IOException e1) {
}
try {
this.jc.close();
} catch (IOException e2) {
}
}
}
} catch (IOException ioe) {
this.state = Job.FAILED;
this.message = StringUtils.stringifyException(ioe);
try {
if (running != null)
running.killJob();
} catch (IOException e1) {
}
try {
this.jc.close();
} catch (IOException e1) {
}
}
}
|
diff --git a/src/lmp/Simulator.java b/src/lmp/Simulator.java
index ad29d28..76b7e87 100644
--- a/src/lmp/Simulator.java
+++ b/src/lmp/Simulator.java
@@ -1,50 +1,49 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package lmp;
import java.util.ArrayList;
import java.util.ListIterator;
/**
*
* @author T-CATS
*/
public class Simulator {
private ArrayList<Node2> fred;
private Double lambda;
Simulator(int numOfStations, Double lambda)
{
fred = new ArrayList(); // Hello fred!
this.lambda = lambda;
for(int i=1;i<=numOfStations;i++)
fred.add(new Node2(lambda)); // Create new Nodes!
}
/**
* Attempts to send.
* @return Returns the time of the successful transmission, else, returns -1
*/
public Double send()
{
- ArrayList<Integer> trans = new ArrayList();
+ ArrayList<Node2> collision = new ArrayList();
for(int i=0;i<fred.size();i++)
{
- ArrayList<Node2> collision = new ArrayList();
fred.get(i).send(lambda); // Send!
for(int j= i+1;j<fred.size();j++)
{
fred.get(j).send(lambda); // Send!
- if(Math.abs(fred.get(i).getTime()-fred.get(j).getTime())<=1)
+ if(Math.abs(fred.get(i).getTime()-fred.get(j).getTime())<=1)
{
System.out.println("Collision!"); // Oh noes!
collision.add(fred.get(j)); // Add to a running list of collisions
}
}
if(collision.isEmpty())
return fred.get(i).getTime();
}
return -1.0;
}
}
| false | true | public Double send()
{
ArrayList<Integer> trans = new ArrayList();
for(int i=0;i<fred.size();i++)
{
ArrayList<Node2> collision = new ArrayList();
fred.get(i).send(lambda); // Send!
for(int j= i+1;j<fred.size();j++)
{
fred.get(j).send(lambda); // Send!
if(Math.abs(fred.get(i).getTime()-fred.get(j).getTime())<=1)
{
System.out.println("Collision!"); // Oh noes!
collision.add(fred.get(j)); // Add to a running list of collisions
}
}
if(collision.isEmpty())
return fred.get(i).getTime();
}
return -1.0;
}
| public Double send()
{
ArrayList<Node2> collision = new ArrayList();
for(int i=0;i<fred.size();i++)
{
fred.get(i).send(lambda); // Send!
for(int j= i+1;j<fred.size();j++)
{
fred.get(j).send(lambda); // Send!
if(Math.abs(fred.get(i).getTime()-fred.get(j).getTime())<=1)
{
System.out.println("Collision!"); // Oh noes!
collision.add(fred.get(j)); // Add to a running list of collisions
}
}
if(collision.isEmpty())
return fred.get(i).getTime();
}
return -1.0;
}
|
diff --git a/openstack-api/src/test/java/org/openstack/client/image/GlanceIntegrationTest.java b/openstack-api/src/test/java/org/openstack/client/image/GlanceIntegrationTest.java
index c3a357a..946eee4 100644
--- a/openstack-api/src/test/java/org/openstack/client/image/GlanceIntegrationTest.java
+++ b/openstack-api/src/test/java/org/openstack/client/image/GlanceIntegrationTest.java
@@ -1,20 +1,20 @@
package org.openstack.client.image;
import org.openstack.client.AbstractOpenStackTest;
import org.openstack.client.common.OpenstackImageClient;
import org.openstack.client.utils.RandomUtil;
import org.testng.SkipException;
public abstract class GlanceIntegrationTest extends AbstractOpenStackTest {
protected RandomUtil random = new RandomUtil();
protected OpenstackImageClient getImageClient() {
return context.session.getImageClient();
}
protected void skipIfNoGlance() {
- if (!context.haveGlance()) {
+ if (!context.isGlanceEnabled()) {
throw new SkipException("Skipping because glance not present / accessible");
}
}
}
| true | true | protected void skipIfNoGlance() {
if (!context.haveGlance()) {
throw new SkipException("Skipping because glance not present / accessible");
}
}
| protected void skipIfNoGlance() {
if (!context.isGlanceEnabled()) {
throw new SkipException("Skipping because glance not present / accessible");
}
}
|
diff --git a/miwotreff/src/main/java/de/micmun/android/miwotreff/utils/ProgramLoader.java b/miwotreff/src/main/java/de/micmun/android/miwotreff/utils/ProgramLoader.java
index 7c786be..4d9c703 100644
--- a/miwotreff/src/main/java/de/micmun/android/miwotreff/utils/ProgramLoader.java
+++ b/miwotreff/src/main/java/de/micmun/android/miwotreff/utils/ProgramLoader.java
@@ -1,208 +1,209 @@
/**
* Copyright 2013 MicMun
*
* 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 de.micmun.android.miwotreff.utils;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.view.MenuItem;
import com.devspark.appmsg.AppMsg;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import de.micmun.android.miwotreff.MainActivity;
import de.micmun.android.miwotreff.R;
/**
* Loads the program from the website and save it in the database.
*
* @author MicMun
* @version 1.0, 13.01.2013
*/
public class ProgramLoader extends AsyncTask<Void, Void, Integer> {
private final String TAG = "MiWoTreff.ProgramLoader";
private final Context mCtx;
Drawable btnRefresStaticDrawable = null;
private ArrayList<LoaderListener> listener = new ArrayList<LoaderListener>();
private ConnectivityManager mConManager;
private MenuItem btnRefresh = null;
private int counter;
public ProgramLoader(Context ctx, MenuItem mi) {
super();
mCtx = ctx;
btnRefresh = mi;
btnRefresStaticDrawable = btnRefresh.getIcon();
mConManager = (ConnectivityManager) ctx.getSystemService(Context
.CONNECTIVITY_SERVICE);
}
/**
* Returns <code>true</code>, if you are connected to the internet.
*
* @return <code>true</code>, if connected to the internet.
*/
private boolean isOnline() {
boolean ret = false;
NetworkInfo ni = mConManager.getActiveNetworkInfo();
if (ni != null && ni.isConnected() && !ni.isRoaming())
ret = true;
return ret;
}
/**
* @see android.os.AsyncTask#doInBackground(Object[])
*/
@Override
protected Integer doInBackground(Void... params) {
publishProgress();
if (!isOnline()) {
Log.e(TAG, "No Internet connection!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_noconnect, AppMsg.STYLE_ALERT).show();
return 1;
} else {
HtmlParser parser = new HtmlParser();
String table = parser
.getHtmlFromUrl("http://www.gemeinschaft-muenchen.de/index.php?id=7&no_cache=1");
if (table == null) {
Log.e(TAG, "Can't fetch program!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_fetch, AppMsg.STYLE_ALERT).show();
return 1;
} else {
ArrayList<HashMap<String, Object>> prog = parser.getProg(table);
if (prog == null) {
Log.e(TAG, "No data!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_nodata,
AppMsg.STYLE_ALERT).show();
return 1;
} else {
counter = 0;
for (HashMap<String, Object> m : prog) {
long date = ((Date) m.get(DBConstants.KEY_DATUM)).getTime();
String topic = (String) m.get(DBConstants.KEY_THEMA);
String person = (String) m.get(DBConstants.KEY_PERSON);
String[] selArgs = {String.valueOf(date)};
// Prepare values for insert or update
ContentValues values = new ContentValues();
values.put(DBConstants.KEY_DATUM, date);
values.put(DBConstants.KEY_THEMA, topic);
values.put(DBConstants.KEY_PERSON, person);
values.put(DBConstants.KEY_EDIT, 0);
// Query, if date exists
Uri uri = Uri.withAppendedPath(DBConstants
.TABLE_CONTENT_URI, DBConstants.DATE_QUERY);
Cursor c = mCtx.getContentResolver().query(uri, null, null,
selArgs, null);
if (c == null || c.getCount() <= 0) { // if not exists
// Insert
mCtx.getContentResolver()
.insert(DBConstants.TABLE_CONTENT_URI, values);
counter++;
} else { // exists
c.moveToFirst();
int edit = c.getInt(c.getColumnIndex(DBConstants
.KEY_EDIT));
int id = c.getInt(c.getColumnIndex(DBConstants._ID));
if (edit == 0) { // if not edited yet
// Update
uri = Uri.withAppendedPath(DBConstants
.TABLE_CONTENT_URI, String.valueOf(id));
mCtx.getContentResolver().update(uri, values,
null, null);
}
}
+ c.close();
}
}
}
}
return 0;
}
/**
* @see AsyncTask#onProgressUpdate(Object[])
*/
@Override
protected void onProgressUpdate(Void... progress) {
btnRefresh.setIcon((mCtx.getResources()
.getDrawable(R.drawable.ic_action_refresh_anim)));
btnRefresh.setEnabled(false);
AnimationDrawable frameAnimation = (AnimationDrawable) btnRefresh
.getIcon();
if (frameAnimation != null)
frameAnimation.start();
}
/**
* @see android.os.AsyncTask#onPostExecute
*/
@Override
protected void onPostExecute(Integer result) {
btnRefresh.setIcon(btnRefresStaticDrawable);
btnRefresh.setEnabled(true);
Log.d(TAG, "result = " + result);
if (result == 0) {
notifyLoaderListener();
}
}
/**
* Adds a LoaderListener to the list of listener.
*
* @param l {@link LoaderListener} to add.
*/
public void addLoaderListener(LoaderListener l) {
listener.add(l);
}
/**
* Removes a LoaderListener from the list of listener.
*
* @param l {@link LoaderListener} to remove.
*/
public void removeLoaderListener(LoaderListener l) {
listener.remove(l);
}
/**
* Notifies all listener.
*/
protected void notifyLoaderListener() {
for (LoaderListener l : listener) {
Log.d(TAG, l.toString());
l.update(counter);
}
}
}
| true | true | protected Integer doInBackground(Void... params) {
publishProgress();
if (!isOnline()) {
Log.e(TAG, "No Internet connection!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_noconnect, AppMsg.STYLE_ALERT).show();
return 1;
} else {
HtmlParser parser = new HtmlParser();
String table = parser
.getHtmlFromUrl("http://www.gemeinschaft-muenchen.de/index.php?id=7&no_cache=1");
if (table == null) {
Log.e(TAG, "Can't fetch program!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_fetch, AppMsg.STYLE_ALERT).show();
return 1;
} else {
ArrayList<HashMap<String, Object>> prog = parser.getProg(table);
if (prog == null) {
Log.e(TAG, "No data!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_nodata,
AppMsg.STYLE_ALERT).show();
return 1;
} else {
counter = 0;
for (HashMap<String, Object> m : prog) {
long date = ((Date) m.get(DBConstants.KEY_DATUM)).getTime();
String topic = (String) m.get(DBConstants.KEY_THEMA);
String person = (String) m.get(DBConstants.KEY_PERSON);
String[] selArgs = {String.valueOf(date)};
// Prepare values for insert or update
ContentValues values = new ContentValues();
values.put(DBConstants.KEY_DATUM, date);
values.put(DBConstants.KEY_THEMA, topic);
values.put(DBConstants.KEY_PERSON, person);
values.put(DBConstants.KEY_EDIT, 0);
// Query, if date exists
Uri uri = Uri.withAppendedPath(DBConstants
.TABLE_CONTENT_URI, DBConstants.DATE_QUERY);
Cursor c = mCtx.getContentResolver().query(uri, null, null,
selArgs, null);
if (c == null || c.getCount() <= 0) { // if not exists
// Insert
mCtx.getContentResolver()
.insert(DBConstants.TABLE_CONTENT_URI, values);
counter++;
} else { // exists
c.moveToFirst();
int edit = c.getInt(c.getColumnIndex(DBConstants
.KEY_EDIT));
int id = c.getInt(c.getColumnIndex(DBConstants._ID));
if (edit == 0) { // if not edited yet
// Update
uri = Uri.withAppendedPath(DBConstants
.TABLE_CONTENT_URI, String.valueOf(id));
mCtx.getContentResolver().update(uri, values,
null, null);
}
}
}
}
}
}
return 0;
}
| protected Integer doInBackground(Void... params) {
publishProgress();
if (!isOnline()) {
Log.e(TAG, "No Internet connection!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_noconnect, AppMsg.STYLE_ALERT).show();
return 1;
} else {
HtmlParser parser = new HtmlParser();
String table = parser
.getHtmlFromUrl("http://www.gemeinschaft-muenchen.de/index.php?id=7&no_cache=1");
if (table == null) {
Log.e(TAG, "Can't fetch program!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_fetch, AppMsg.STYLE_ALERT).show();
return 1;
} else {
ArrayList<HashMap<String, Object>> prog = parser.getProg(table);
if (prog == null) {
Log.e(TAG, "No data!");
AppMsg.makeText((MainActivity) mCtx, R.string.error_pl_nodata,
AppMsg.STYLE_ALERT).show();
return 1;
} else {
counter = 0;
for (HashMap<String, Object> m : prog) {
long date = ((Date) m.get(DBConstants.KEY_DATUM)).getTime();
String topic = (String) m.get(DBConstants.KEY_THEMA);
String person = (String) m.get(DBConstants.KEY_PERSON);
String[] selArgs = {String.valueOf(date)};
// Prepare values for insert or update
ContentValues values = new ContentValues();
values.put(DBConstants.KEY_DATUM, date);
values.put(DBConstants.KEY_THEMA, topic);
values.put(DBConstants.KEY_PERSON, person);
values.put(DBConstants.KEY_EDIT, 0);
// Query, if date exists
Uri uri = Uri.withAppendedPath(DBConstants
.TABLE_CONTENT_URI, DBConstants.DATE_QUERY);
Cursor c = mCtx.getContentResolver().query(uri, null, null,
selArgs, null);
if (c == null || c.getCount() <= 0) { // if not exists
// Insert
mCtx.getContentResolver()
.insert(DBConstants.TABLE_CONTENT_URI, values);
counter++;
} else { // exists
c.moveToFirst();
int edit = c.getInt(c.getColumnIndex(DBConstants
.KEY_EDIT));
int id = c.getInt(c.getColumnIndex(DBConstants._ID));
if (edit == 0) { // if not edited yet
// Update
uri = Uri.withAppendedPath(DBConstants
.TABLE_CONTENT_URI, String.valueOf(id));
mCtx.getContentResolver().update(uri, values,
null, null);
}
}
c.close();
}
}
}
}
return 0;
}
|
diff --git a/HeroesSkillTree/src/me/Whatshiywl/heroesskilltree/commands/SkillAdminCommand.java b/HeroesSkillTree/src/me/Whatshiywl/heroesskilltree/commands/SkillAdminCommand.java
index fbc6599..9dd63b4 100644
--- a/HeroesSkillTree/src/me/Whatshiywl/heroesskilltree/commands/SkillAdminCommand.java
+++ b/HeroesSkillTree/src/me/Whatshiywl/heroesskilltree/commands/SkillAdminCommand.java
@@ -1,158 +1,158 @@
package me.Whatshiywl.heroesskilltree.commands;
import com.herocraftonline.heroes.characters.Hero;
import me.Whatshiywl.heroesskilltree.HeroesSkillTree;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @author Multitallented
*/
public class SkillAdminCommand {
public static void skillAdmin(HeroesSkillTree hst, CommandSender sender, String[] args) {
if(args.length < 1) {
sender.sendMessage(ChatColor.RED + "Not enough arguments: /skilladmin <command> (amount) [sender]");
return;
}
if(args[0].equalsIgnoreCase("clear")) {
if(!sender.hasPermission("skilladmin.clear")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length == 2){
if(Bukkit.getPlayer(args[1]) != null) {
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[1]));
hst.setPlayerPoints(thero, 0);
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[1] + " is not online.");
return;
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, 0);
}
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have reset " + args[1] + "'s SkillPoints.");
return;
}
if(args[0].equalsIgnoreCase("reset")){
if(!sender.hasPermission("skilladmin.reset")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length == 2){
if(Bukkit.getPlayer(args[1]) != null){
hst.resetPlayer(Bukkit.getPlayer(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have reset " + args[1]);
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[1] + " is not online.");
}
} else{
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
hst.resetPlayer((Player) sender);
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have reset yourself.");
}
return;
}
- if(args.length > 1) {
+ if(args.length < 2) {
sender.sendMessage(ChatColor.RED + "/skilladmin (set/give/remove/clear/reset)");
return;
}
if(args[0].equalsIgnoreCase("set")){
if(!sender.hasPermission("skilladmin.set")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have set " +
args[2] + "'s SkillPoints to " + Integer.parseInt(args[1]) + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else{
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have set your SkillPoints to " + Integer.parseInt(args[1]) + ".");
}
return;
}
if(args[0].equalsIgnoreCase("give")){
if(!sender.hasPermission("skilladmin.give")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, hst.getPlayerPoints(thero) + Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have given " +
Integer.parseInt(args[1]) + " SkillPoint(s) to " + args[2] + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, hst.getPlayerPoints(hero) + Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) to yourself.");
}
return;
}
if(args[0].equalsIgnoreCase("remove")){
if(sender.hasPermission("skilladmin.remove")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, hst.getPlayerPoints(thero) - Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) from " + args[2] + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, hst.getPlayerPoints(hero) - Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) from yourself.");
}
}
}
}
| true | true | public static void skillAdmin(HeroesSkillTree hst, CommandSender sender, String[] args) {
if(args.length < 1) {
sender.sendMessage(ChatColor.RED + "Not enough arguments: /skilladmin <command> (amount) [sender]");
return;
}
if(args[0].equalsIgnoreCase("clear")) {
if(!sender.hasPermission("skilladmin.clear")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length == 2){
if(Bukkit.getPlayer(args[1]) != null) {
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[1]));
hst.setPlayerPoints(thero, 0);
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[1] + " is not online.");
return;
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, 0);
}
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have reset " + args[1] + "'s SkillPoints.");
return;
}
if(args[0].equalsIgnoreCase("reset")){
if(!sender.hasPermission("skilladmin.reset")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length == 2){
if(Bukkit.getPlayer(args[1]) != null){
hst.resetPlayer(Bukkit.getPlayer(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have reset " + args[1]);
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[1] + " is not online.");
}
} else{
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
hst.resetPlayer((Player) sender);
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have reset yourself.");
}
return;
}
if(args.length > 1) {
sender.sendMessage(ChatColor.RED + "/skilladmin (set/give/remove/clear/reset)");
return;
}
if(args[0].equalsIgnoreCase("set")){
if(!sender.hasPermission("skilladmin.set")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have set " +
args[2] + "'s SkillPoints to " + Integer.parseInt(args[1]) + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else{
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have set your SkillPoints to " + Integer.parseInt(args[1]) + ".");
}
return;
}
if(args[0].equalsIgnoreCase("give")){
if(!sender.hasPermission("skilladmin.give")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, hst.getPlayerPoints(thero) + Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have given " +
Integer.parseInt(args[1]) + " SkillPoint(s) to " + args[2] + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, hst.getPlayerPoints(hero) + Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) to yourself.");
}
return;
}
if(args[0].equalsIgnoreCase("remove")){
if(sender.hasPermission("skilladmin.remove")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, hst.getPlayerPoints(thero) - Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) from " + args[2] + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, hst.getPlayerPoints(hero) - Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) from yourself.");
}
}
}
| public static void skillAdmin(HeroesSkillTree hst, CommandSender sender, String[] args) {
if(args.length < 1) {
sender.sendMessage(ChatColor.RED + "Not enough arguments: /skilladmin <command> (amount) [sender]");
return;
}
if(args[0].equalsIgnoreCase("clear")) {
if(!sender.hasPermission("skilladmin.clear")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length == 2){
if(Bukkit.getPlayer(args[1]) != null) {
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[1]));
hst.setPlayerPoints(thero, 0);
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[1] + " is not online.");
return;
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, 0);
}
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have reset " + args[1] + "'s SkillPoints.");
return;
}
if(args[0].equalsIgnoreCase("reset")){
if(!sender.hasPermission("skilladmin.reset")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length == 2){
if(Bukkit.getPlayer(args[1]) != null){
hst.resetPlayer(Bukkit.getPlayer(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have reset " + args[1]);
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[1] + " is not online.");
}
} else{
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
hst.resetPlayer((Player) sender);
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have reset yourself.");
}
return;
}
if(args.length < 2) {
sender.sendMessage(ChatColor.RED + "/skilladmin (set/give/remove/clear/reset)");
return;
}
if(args[0].equalsIgnoreCase("set")){
if(!sender.hasPermission("skilladmin.set")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have set " +
args[2] + "'s SkillPoints to " + Integer.parseInt(args[1]) + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else{
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA +
"You have set your SkillPoints to " + Integer.parseInt(args[1]) + ".");
}
return;
}
if(args[0].equalsIgnoreCase("give")){
if(!sender.hasPermission("skilladmin.give")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, hst.getPlayerPoints(thero) + Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have given " +
Integer.parseInt(args[1]) + " SkillPoint(s) to " + args[2] + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, hst.getPlayerPoints(hero) + Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) to yourself.");
}
return;
}
if(args[0].equalsIgnoreCase("remove")){
if(sender.hasPermission("skilladmin.remove")) {
sender.sendMessage(ChatColor.RED + "You don't have enough permissions!");
return;
}
if(args.length > 2){
if(Bukkit.getPlayer(args[2]) != null){
Hero thero = HeroesSkillTree.heroes.getCharacterManager().getHero(Bukkit.getPlayer(args[2]));
hst.setPlayerPoints(thero, hst.getPlayerPoints(thero) - Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) from " + args[2] + ".");
} else {
sender.sendMessage(ChatColor.RED + "Sorry, " + args[2] + " is not online.");
}
} else {
if (!(sender instanceof Player)) {
sender.sendMessage(ChatColor.RED + "You must be in game to use this command");
return;
}
Hero hero = HeroesSkillTree.heroes.getCharacterManager().getHero((Player) sender);
hst.setPlayerPoints(hero, hst.getPlayerPoints(hero) - Integer.parseInt(args[1]));
sender.sendMessage(ChatColor.GOLD + "[HST] " + ChatColor.AQUA + "You have removed " +
Integer.parseInt(args[1]) + " SkillPoint(s) from yourself.");
}
}
}
|
diff --git a/src/edu/umn/cs/spatialHadoop/mapred/SpatialInputFormat.java b/src/edu/umn/cs/spatialHadoop/mapred/SpatialInputFormat.java
index 95c69d87..fac87390 100644
--- a/src/edu/umn/cs/spatialHadoop/mapred/SpatialInputFormat.java
+++ b/src/edu/umn/cs/spatialHadoop/mapred/SpatialInputFormat.java
@@ -1,266 +1,268 @@
/*
* 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 edu.umn.cs.spatialHadoop.mapred;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.io.compress.SplittableCompressionCodec;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileSplit;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.LineRecordReader;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;
import edu.umn.cs.spatialHadoop.core.GlobalIndex;
import edu.umn.cs.spatialHadoop.core.Partition;
import edu.umn.cs.spatialHadoop.core.ResultCollector;
import edu.umn.cs.spatialHadoop.core.SpatialSite;
import edu.umn.cs.spatialHadoop.nasa.HDFRecordReader;
import edu.umn.cs.spatialHadoop.nasa.HTTPFileSystem;
/**
* An input format used with spatial data. It filters generated splits before
* creating record readers.
* @author Ahmed Eldawy
*
*/
public abstract class SpatialInputFormat<K, V> extends FileInputFormat<K, V> {
/**
* Used to check whether files are compressed or not. Some compressed files
* (e.g., gz) are not splittable.
*/
private CompressionCodecFactory compressionCodecs = null;
/**
* We need to use this way of constructing readers to be able to pass it to
* CmobineFileRecordReader
**/
@SuppressWarnings("rawtypes")
static final Class[] constructorSignature = new Class[] {
Configuration.class, FileSplit.class };
@SuppressWarnings("rawtypes")
protected Class<? extends RecordReader> rrClass;
@SuppressWarnings("unchecked")
@Override
public RecordReader<K, V> getRecordReader(InputSplit split, JobConf job,
Reporter reporter) throws IOException {
// Create compressionCodecs to be used by isSplitable method
if (compressionCodecs == null)
compressionCodecs = new CompressionCodecFactory(job);
if (split instanceof FileSplit) {
FileSplit fsplit = (FileSplit) split;
if (fsplit.getPath().getName().matches("(?i:.*\\.hdf$)")) {
// HDF File. Create HDFRecordReader
return (RecordReader<K, V>) new HDFRecordReader(job, fsplit,
job.get(HDFRecordReader.DatasetName),
job.getBoolean(HDFRecordReader.SkipFillValue, true));
}
try {
@SuppressWarnings("rawtypes")
Constructor<? extends RecordReader> rrConstructor;
rrConstructor = rrClass.getDeclaredConstructor(constructorSignature);
rrConstructor.setAccessible(true);
return rrConstructor.newInstance(new Object [] {job, fsplit});
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
throw new RuntimeException("Cannot generate a record reader");
} else {
throw new RuntimeException("Cannot handle splits of type "+split.getClass());
}
}
protected void listStatus(final FileSystem fs, final Path dir,
final List<FileStatus> result, BlockFilter filter) throws IOException {
GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, dir);
if (gindex == null) {
FileStatus[] listStatus;
if (dir.toString().matches("\\*|\\?")) {
// Wild card
listStatus = fs.globStatus(dir);
} else {
listStatus = fs.listStatus(dir, SpatialSite.NonHiddenFileFilter);
}
// Special case for HDF files. Extract MBR from file name and use filter
if (filter != null && listStatus.length > 0 &&
listStatus[0].getPath().getName().matches("(?i:.*\\.hdf$)")) {
// Create a global index on the fly for these files based on their names
Partition[] partitions = new Partition[listStatus.length];
for (int i = 0; i < listStatus.length; i++) {
final Pattern cellRegex = Pattern.compile(".*(h\\d\\dv\\d\\d).*");
String filename = listStatus[i].getPath().getName();
Matcher matcher = cellRegex.matcher(filename);
if (matcher.matches()) {
String cellname = matcher.group(1);
int h = Integer.parseInt(cellname.substring(1, 3));
int v = Integer.parseInt(cellname.substring(4, 6));
Partition partition = new Partition();
partition.cellId = v * 36 + h;
partition.filename = filename;
// Calculate coordinates on MODIS Sinusoidal grid
partition.x1 = h * 10 - 180;
partition.y2 = (18 - v) * 10 - 90;
partition.x2 = partition.x1 + 10;
partition.y1 = partition.y2 - 10;
// Convert to Latitude Longitude
double lon1 = partition.x1 / Math.cos(partition.y1 * Math.PI / 180);
double lon2 = partition.x1 / Math.cos(partition.y2 * Math.PI / 180);
partition.x1 = Math.min(lon1, lon2);
lon1 = partition.x2 / Math.cos(partition.y1 * Math.PI / 180);
lon2 = partition.x2 / Math.cos(partition.y2 * Math.PI / 180);
partition.x2 = Math.max(lon1, lon2);
partitions[i] = partition;
}
}
gindex = new GlobalIndex<Partition>();
gindex.bulkLoad(partitions);
+ // The directory that contains the files (remove wildcard)
+ final Path indexDir = listStatus[0].getPath().getParent();
// Use the generated global index to limit files
filter.selectCells(gindex, new ResultCollector<Partition>() {
@Override
public void collect(Partition partition) {
try {
- Path cell_path = new Path(dir, partition.filename);
+ Path cell_path = new Path(indexDir, partition.filename);
if (!fs.exists(cell_path))
LOG.warn("Matched file not found: "+cell_path);
result.add(fs.getFileStatus(cell_path));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else {
// Add all files under this directory
for (FileStatus status : listStatus) {
if (status.isDir()) {
listStatus(fs, status.getPath(), result, filter);
} else if (status.getPath().getName().matches("(?i:.*\\.list$)")) {
LineRecordReader in = new LineRecordReader(fs.open(status.getPath()), 0, status.getLen(), Integer.MAX_VALUE);
LongWritable key = in.createKey();
Text value = in.createValue();
while (in.next(key, value)) {
result.add(fs.getFileStatus(new Path(status.getPath().getParent(), value.toString())));
}
in.close();
} else {
result.add(status);
}
}
}
} else {
// Use the global index to limit files
filter.selectCells(gindex, new ResultCollector<Partition>() {
@Override
public void collect(Partition partition) {
try {
Path cell_path = new Path(dir, partition.filename);
if (!fs.exists(cell_path))
LOG.warn("Matched file not found: "+cell_path);
result.add(fs.getFileStatus(cell_path));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
@Override
protected FileStatus[] listStatus(JobConf job) throws IOException {
try {
// Create the compressionCodecs to be used later by isSplitable
if (compressionCodecs == null)
compressionCodecs = new CompressionCodecFactory(job);
// Retrieve the BlockFilter set by the developers in the JobConf
Class<? extends BlockFilter> blockFilterClass =
job.getClass(SpatialSite.FilterClass, null, BlockFilter.class);
if (blockFilterClass == null) {
LOG.info("No block filter specified");
// No block filter specified by user
return super.listStatus(job);
}
// Get all blocks the user wants to process
BlockFilter blockFilter;
blockFilter = blockFilterClass.newInstance();
blockFilter.configure(job);
// Filter files based on user specified filter function
List<FileStatus> result = new ArrayList<FileStatus>();
Path[] inputDirs = getInputPaths(job);
for (Path dir : inputDirs) {
FileSystem fs = dir.getFileSystem(job);
listStatus(fs, dir, result, blockFilter);
}
LOG.info("Spatial filter function matched with "+result.size()+" cells");
return result.toArray(new FileStatus[result.size()]);
} catch (InstantiationException e) {
LOG.warn(e);
return super.listStatus(job);
} catch (IllegalAccessException e) {
LOG.warn(e);
return super.listStatus(job);
}
}
@Override
protected boolean isSplitable(FileSystem fs, Path file) {
// HDF files are not splittable
if (file.getName().matches("(?i:.*\\.hdf$)"))
return false;
final CompressionCodec codec = compressionCodecs.getCodec(file);
if (codec != null && !(codec instanceof SplittableCompressionCodec))
return false;
try {
// For performance reasons, skip checking isRTree if the file is on http
// isRTree needs to open the file and reads the first 8 bytes. Doing this
// in the input format means it will open all files in input which is
// very costly.
return !(fs instanceof HTTPFileSystem) && !SpatialSite.isRTree(fs, file);
} catch (IOException e) {
return super.isSplitable(fs, file);
}
}
}
| false | true | protected void listStatus(final FileSystem fs, final Path dir,
final List<FileStatus> result, BlockFilter filter) throws IOException {
GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, dir);
if (gindex == null) {
FileStatus[] listStatus;
if (dir.toString().matches("\\*|\\?")) {
// Wild card
listStatus = fs.globStatus(dir);
} else {
listStatus = fs.listStatus(dir, SpatialSite.NonHiddenFileFilter);
}
// Special case for HDF files. Extract MBR from file name and use filter
if (filter != null && listStatus.length > 0 &&
listStatus[0].getPath().getName().matches("(?i:.*\\.hdf$)")) {
// Create a global index on the fly for these files based on their names
Partition[] partitions = new Partition[listStatus.length];
for (int i = 0; i < listStatus.length; i++) {
final Pattern cellRegex = Pattern.compile(".*(h\\d\\dv\\d\\d).*");
String filename = listStatus[i].getPath().getName();
Matcher matcher = cellRegex.matcher(filename);
if (matcher.matches()) {
String cellname = matcher.group(1);
int h = Integer.parseInt(cellname.substring(1, 3));
int v = Integer.parseInt(cellname.substring(4, 6));
Partition partition = new Partition();
partition.cellId = v * 36 + h;
partition.filename = filename;
// Calculate coordinates on MODIS Sinusoidal grid
partition.x1 = h * 10 - 180;
partition.y2 = (18 - v) * 10 - 90;
partition.x2 = partition.x1 + 10;
partition.y1 = partition.y2 - 10;
// Convert to Latitude Longitude
double lon1 = partition.x1 / Math.cos(partition.y1 * Math.PI / 180);
double lon2 = partition.x1 / Math.cos(partition.y2 * Math.PI / 180);
partition.x1 = Math.min(lon1, lon2);
lon1 = partition.x2 / Math.cos(partition.y1 * Math.PI / 180);
lon2 = partition.x2 / Math.cos(partition.y2 * Math.PI / 180);
partition.x2 = Math.max(lon1, lon2);
partitions[i] = partition;
}
}
gindex = new GlobalIndex<Partition>();
gindex.bulkLoad(partitions);
// Use the generated global index to limit files
filter.selectCells(gindex, new ResultCollector<Partition>() {
@Override
public void collect(Partition partition) {
try {
Path cell_path = new Path(dir, partition.filename);
if (!fs.exists(cell_path))
LOG.warn("Matched file not found: "+cell_path);
result.add(fs.getFileStatus(cell_path));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else {
// Add all files under this directory
for (FileStatus status : listStatus) {
if (status.isDir()) {
listStatus(fs, status.getPath(), result, filter);
} else if (status.getPath().getName().matches("(?i:.*\\.list$)")) {
LineRecordReader in = new LineRecordReader(fs.open(status.getPath()), 0, status.getLen(), Integer.MAX_VALUE);
LongWritable key = in.createKey();
Text value = in.createValue();
while (in.next(key, value)) {
result.add(fs.getFileStatus(new Path(status.getPath().getParent(), value.toString())));
}
in.close();
} else {
result.add(status);
}
}
}
} else {
// Use the global index to limit files
filter.selectCells(gindex, new ResultCollector<Partition>() {
@Override
public void collect(Partition partition) {
try {
Path cell_path = new Path(dir, partition.filename);
if (!fs.exists(cell_path))
LOG.warn("Matched file not found: "+cell_path);
result.add(fs.getFileStatus(cell_path));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
| protected void listStatus(final FileSystem fs, final Path dir,
final List<FileStatus> result, BlockFilter filter) throws IOException {
GlobalIndex<Partition> gindex = SpatialSite.getGlobalIndex(fs, dir);
if (gindex == null) {
FileStatus[] listStatus;
if (dir.toString().matches("\\*|\\?")) {
// Wild card
listStatus = fs.globStatus(dir);
} else {
listStatus = fs.listStatus(dir, SpatialSite.NonHiddenFileFilter);
}
// Special case for HDF files. Extract MBR from file name and use filter
if (filter != null && listStatus.length > 0 &&
listStatus[0].getPath().getName().matches("(?i:.*\\.hdf$)")) {
// Create a global index on the fly for these files based on their names
Partition[] partitions = new Partition[listStatus.length];
for (int i = 0; i < listStatus.length; i++) {
final Pattern cellRegex = Pattern.compile(".*(h\\d\\dv\\d\\d).*");
String filename = listStatus[i].getPath().getName();
Matcher matcher = cellRegex.matcher(filename);
if (matcher.matches()) {
String cellname = matcher.group(1);
int h = Integer.parseInt(cellname.substring(1, 3));
int v = Integer.parseInt(cellname.substring(4, 6));
Partition partition = new Partition();
partition.cellId = v * 36 + h;
partition.filename = filename;
// Calculate coordinates on MODIS Sinusoidal grid
partition.x1 = h * 10 - 180;
partition.y2 = (18 - v) * 10 - 90;
partition.x2 = partition.x1 + 10;
partition.y1 = partition.y2 - 10;
// Convert to Latitude Longitude
double lon1 = partition.x1 / Math.cos(partition.y1 * Math.PI / 180);
double lon2 = partition.x1 / Math.cos(partition.y2 * Math.PI / 180);
partition.x1 = Math.min(lon1, lon2);
lon1 = partition.x2 / Math.cos(partition.y1 * Math.PI / 180);
lon2 = partition.x2 / Math.cos(partition.y2 * Math.PI / 180);
partition.x2 = Math.max(lon1, lon2);
partitions[i] = partition;
}
}
gindex = new GlobalIndex<Partition>();
gindex.bulkLoad(partitions);
// The directory that contains the files (remove wildcard)
final Path indexDir = listStatus[0].getPath().getParent();
// Use the generated global index to limit files
filter.selectCells(gindex, new ResultCollector<Partition>() {
@Override
public void collect(Partition partition) {
try {
Path cell_path = new Path(indexDir, partition.filename);
if (!fs.exists(cell_path))
LOG.warn("Matched file not found: "+cell_path);
result.add(fs.getFileStatus(cell_path));
} catch (IOException e) {
e.printStackTrace();
}
}
});
} else {
// Add all files under this directory
for (FileStatus status : listStatus) {
if (status.isDir()) {
listStatus(fs, status.getPath(), result, filter);
} else if (status.getPath().getName().matches("(?i:.*\\.list$)")) {
LineRecordReader in = new LineRecordReader(fs.open(status.getPath()), 0, status.getLen(), Integer.MAX_VALUE);
LongWritable key = in.createKey();
Text value = in.createValue();
while (in.next(key, value)) {
result.add(fs.getFileStatus(new Path(status.getPath().getParent(), value.toString())));
}
in.close();
} else {
result.add(status);
}
}
}
} else {
// Use the global index to limit files
filter.selectCells(gindex, new ResultCollector<Partition>() {
@Override
public void collect(Partition partition) {
try {
Path cell_path = new Path(dir, partition.filename);
if (!fs.exists(cell_path))
LOG.warn("Matched file not found: "+cell_path);
result.add(fs.getFileStatus(cell_path));
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
|
diff --git a/src/main/java/de/minestar/core/MinestarCore.java b/src/main/java/de/minestar/core/MinestarCore.java
index 9f22924..831c5f2 100644
--- a/src/main/java/de/minestar/core/MinestarCore.java
+++ b/src/main/java/de/minestar/core/MinestarCore.java
@@ -1,108 +1,108 @@
/*
* Copyright (C) 2012 MineStar.de
*
* This file is part of MinestarCore.
*
* MinestarCore 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 3 of the License.
*
* MinestarCore 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 MinestarCore. If not, see <http://www.gnu.org/licenses/>.
*/
package de.minestar.core;
import java.io.File;
import org.anjocaido.groupmanager.GroupManager;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import de.minestar.core.listener.ConnectionListener;
import de.minestar.core.manager.PlayerManager;
import de.minestar.core.units.MinestarPlayer;
import de.minestar.minestarlibrary.utils.ConsoleUtils;
public class MinestarCore extends JavaPlugin {
public static String pluginName = "MinestarCore";
public static File dataFolder;
public static GroupManager groupManager = null;
/**
* Manager
*/
private static PlayerManager playerManager;
/**
* Listener
*/
private ConnectionListener connectionListener;
@Override
public void onDisable() {
// SAVE PLAYERS
playerManager.savePlayers();
// PRINT INFO
ConsoleUtils.printInfo(pluginName, "Disabled v" + this.getDescription().getVersion() + "!");
}
@Override
public void onEnable() {
dataFolder = this.getDataFolder();
dataFolder.mkdirs();
// GET GROUPMANAGER
this.getGroupManager();
- File playerFolder = new File(dataFolder, "\\playerdata");
+ File playerFolder = new File(dataFolder, "playerdata");
playerFolder.mkdir();
// CREATE MANAGER, LISTENER, COMMANDS
this.createManager();
this.createListener();
// REGISTER EVENTS
this.registerEvents();
// PRINT INFO
ConsoleUtils.printInfo(pluginName, "Enabled v" + this.getDescription().getVersion() + "!");
}
private void getGroupManager() {
Plugin gm = Bukkit.getServer().getPluginManager().getPlugin("GroupManager");
if (gm != null && gm.isEnabled())
MinestarCore.groupManager = (GroupManager) gm;
else
ConsoleUtils.printError(MinestarCore.pluginName, "Can't find GroupManager was not found!");
}
private void createManager() {
playerManager = new PlayerManager();
}
private void createListener() {
this.connectionListener = new ConnectionListener(playerManager);
}
private void registerEvents() {
Bukkit.getPluginManager().registerEvents(this.connectionListener, this);
}
public static MinestarPlayer getPlayer(String playerName) {
return playerManager.getPlayer(playerName);
}
public static MinestarPlayer getPlayer(Player player) {
return MinestarCore.getPlayer(player.getName());
}
}
| true | true | public void onEnable() {
dataFolder = this.getDataFolder();
dataFolder.mkdirs();
// GET GROUPMANAGER
this.getGroupManager();
File playerFolder = new File(dataFolder, "\\playerdata");
playerFolder.mkdir();
// CREATE MANAGER, LISTENER, COMMANDS
this.createManager();
this.createListener();
// REGISTER EVENTS
this.registerEvents();
// PRINT INFO
ConsoleUtils.printInfo(pluginName, "Enabled v" + this.getDescription().getVersion() + "!");
}
| public void onEnable() {
dataFolder = this.getDataFolder();
dataFolder.mkdirs();
// GET GROUPMANAGER
this.getGroupManager();
File playerFolder = new File(dataFolder, "playerdata");
playerFolder.mkdir();
// CREATE MANAGER, LISTENER, COMMANDS
this.createManager();
this.createListener();
// REGISTER EVENTS
this.registerEvents();
// PRINT INFO
ConsoleUtils.printInfo(pluginName, "Enabled v" + this.getDescription().getVersion() + "!");
}
|
diff --git a/src/spatialcubeservice/src/main/java/org/vpac/web/controller/DatasetController.java b/src/spatialcubeservice/src/main/java/org/vpac/web/controller/DatasetController.java
index 5107ac0..e239731 100644
--- a/src/spatialcubeservice/src/main/java/org/vpac/web/controller/DatasetController.java
+++ b/src/spatialcubeservice/src/main/java/org/vpac/web/controller/DatasetController.java
@@ -1,149 +1,149 @@
/*
* This file is part of the Raster Storage Archive (RSA).
*
* The RSA 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.
*
* The RSA 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
* the RSA. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2013 CRCSI - Cooperative Research Centre for Spatial Information
* http://www.crcsi.com.au/
*/
package org.vpac.web.controller;
import java.io.IOException;
import java.util.List;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.vpac.ndg.Utils;
import org.vpac.ndg.common.datamodel.CellSize;
import org.vpac.ndg.storage.dao.DatasetDao;
import org.vpac.ndg.storage.model.Dataset;
import org.vpac.ndg.storage.util.DatasetUtil;
import org.vpac.web.exception.ResourceNotFoundException;
import org.vpac.web.model.request.DatasetRequest;
import org.vpac.web.model.request.PagingRequest;
import org.vpac.web.model.response.DatasetCollectionResponse;
import org.vpac.web.model.response.DatasetResponse;
import org.vpac.web.util.ControllerHelper;
@Controller
@RequestMapping("/Dataset")
public class DatasetController {
final private Logger log = LoggerFactory.getLogger(DatasetController.class);
@Autowired
ControllerHelper helper;
@Autowired
DatasetDao datasetDao;
@Autowired
DatasetUtil datasetUtil;
@InitBinder
public void binder(WebDataBinder binder) {
helper.BindDateTimeFormatter(binder);
helper.BindCellSizeFormatter(binder);
}
@RequestMapping(method = RequestMethod.GET)
public String getAllDataset(@RequestParam(required=false) String name, @Valid PagingRequest page, ModelMap model ) {
List<Dataset> list = datasetDao.search(name, page.getPage(), page.getPageSize());
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetCollectionResponse(list));
return "List";
}
@RequestMapping(value="/Search", method = RequestMethod.GET)
public String searchDataset(@RequestParam(required=false) String name, @RequestParam(required=false) String resolution, ModelMap model ) {
List<Dataset> list = datasetDao.search(name, CellSize.fromHumanString(resolution));
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetCollectionResponse(list));
return "List";
}
@RequestMapping(value="/{id}", method = RequestMethod.GET)
public String getDatasetById(@PathVariable String id, ModelMap model ) throws ResourceNotFoundException {
Dataset ds = datasetDao.retrieve(id);
if(ds == null) {
// Capture if dataset not exist
throw new ResourceNotFoundException(String.format("Dataset with ID = \"%s\" not found.", id));
}
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(ds));
return "List";
}
@RequestMapping(method = RequestMethod.POST)
public String createOrUpdateDataset(@Valid DatasetRequest dr, ModelMap model ) throws ResourceNotFoundException, IOException {
log.info("Create / Update Dataset");
log.debug("Id: {}", dr.getId());
log.debug("Name: {}", dr.getName());
log.debug("Resolution: {}", dr.getResolution());
log.debug("Precision: {}", dr.getPrecision());
log.debug("Abstract: {}", dr.getDataAbstract());
long precision = Utils.parseTemporalPrecision(dr.getPrecision());
- if(dr.getId() == null && dr.getId().isEmpty()) {
+ if(dr.getId() == null || dr.getId().isEmpty()) {
Dataset newDataset = new Dataset(dr.getName(), dr.getDataAbstract(), dr.getResolution(), precision);
datasetDao.create(newDataset);
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(newDataset));
} else {
Dataset ds = datasetDao.retrieve(dr.getId());
if(ds == null)
throw new ResourceNotFoundException(String.format("Dataset with ID = \"%s\" not found.", dr.getId()));
ds.setAbst(dr.getDataAbstract());
ds.setResolution(dr.getResolution());
ds.setPrecision(Long.parseLong(dr.getPrecision()));
if(ds.getName().equals(dr.getName()))
datasetDao.update(ds);
else {
ds.setName(dr.getName());
datasetUtil.update(ds);
}
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(ds));
}
return "Success";
}
@RequestMapping(value="/Delete/{id}", method = RequestMethod.POST)
public String deleteDataset(@PathVariable String id, ModelMap model ) throws ResourceNotFoundException, IOException {
Dataset ds = datasetDao.retrieve(id);
if(ds == null) {
// Capture if dataset not exist
throw new ResourceNotFoundException(String.format("Dataset with ID = \"%s\" not found.", id));
}
datasetUtil.deleteDataset(ds);
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(ds));
return "Success";
}
@RequestMapping(value="/Form", method = RequestMethod.GET)
public String createTestForm() {
return "DatasetForm";
}
}
| true | true | public String createOrUpdateDataset(@Valid DatasetRequest dr, ModelMap model ) throws ResourceNotFoundException, IOException {
log.info("Create / Update Dataset");
log.debug("Id: {}", dr.getId());
log.debug("Name: {}", dr.getName());
log.debug("Resolution: {}", dr.getResolution());
log.debug("Precision: {}", dr.getPrecision());
log.debug("Abstract: {}", dr.getDataAbstract());
long precision = Utils.parseTemporalPrecision(dr.getPrecision());
if(dr.getId() == null && dr.getId().isEmpty()) {
Dataset newDataset = new Dataset(dr.getName(), dr.getDataAbstract(), dr.getResolution(), precision);
datasetDao.create(newDataset);
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(newDataset));
} else {
Dataset ds = datasetDao.retrieve(dr.getId());
if(ds == null)
throw new ResourceNotFoundException(String.format("Dataset with ID = \"%s\" not found.", dr.getId()));
ds.setAbst(dr.getDataAbstract());
ds.setResolution(dr.getResolution());
ds.setPrecision(Long.parseLong(dr.getPrecision()));
if(ds.getName().equals(dr.getName()))
datasetDao.update(ds);
else {
ds.setName(dr.getName());
datasetUtil.update(ds);
}
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(ds));
}
return "Success";
}
| public String createOrUpdateDataset(@Valid DatasetRequest dr, ModelMap model ) throws ResourceNotFoundException, IOException {
log.info("Create / Update Dataset");
log.debug("Id: {}", dr.getId());
log.debug("Name: {}", dr.getName());
log.debug("Resolution: {}", dr.getResolution());
log.debug("Precision: {}", dr.getPrecision());
log.debug("Abstract: {}", dr.getDataAbstract());
long precision = Utils.parseTemporalPrecision(dr.getPrecision());
if(dr.getId() == null || dr.getId().isEmpty()) {
Dataset newDataset = new Dataset(dr.getName(), dr.getDataAbstract(), dr.getResolution(), precision);
datasetDao.create(newDataset);
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(newDataset));
} else {
Dataset ds = datasetDao.retrieve(dr.getId());
if(ds == null)
throw new ResourceNotFoundException(String.format("Dataset with ID = \"%s\" not found.", dr.getId()));
ds.setAbst(dr.getDataAbstract());
ds.setResolution(dr.getResolution());
ds.setPrecision(Long.parseLong(dr.getPrecision()));
if(ds.getName().equals(dr.getName()))
datasetDao.update(ds);
else {
ds.setName(dr.getName());
datasetUtil.update(ds);
}
model.addAttribute(ControllerHelper.RESPONSE_ROOT, new DatasetResponse(ds));
}
return "Success";
}
|
diff --git a/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/clipboard/DocumentListZipExporter.java b/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/clipboard/DocumentListZipExporter.java
index 277937ab..be69bede 100644
--- a/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/clipboard/DocumentListZipExporter.java
+++ b/nuxeo-platform-webapp-base/src/main/java/org/nuxeo/ecm/webapp/clipboard/DocumentListZipExporter.java
@@ -1,246 +1,250 @@
package org.nuxeo.ecm.webapp.clipboard;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipOutputStream;
import org.nuxeo.common.utils.StringUtils;
import org.nuxeo.ecm.core.api.Blob;
import org.nuxeo.ecm.core.api.ClientException;
import org.nuxeo.ecm.core.api.CoreSession;
import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.LifeCycleConstants;
import org.nuxeo.ecm.core.api.blobholder.BlobHolder;
import org.nuxeo.ecm.core.api.impl.blob.StringBlob;
import org.nuxeo.runtime.api.Framework;
public class DocumentListZipExporter {
public static final String ZIP_ENTRY_ENCODING_PROPERTY = "zip.entry.encoding";
public static enum ZIP_ENTRY_ENCODING_OPTIONS {
ascii
}
private static final int BUFFER = 2048;
private static final String SUMMARY_FILENAME = "INDEX.txt";
public File exportWorklistAsZip(List<DocumentModel> documents,
CoreSession documentManager, boolean exportAllBlobs)
throws ClientException, IOException {
StringBuilder blobList = new StringBuilder();
File tmpFile = File.createTempFile("NX-BigZipFile-", ".zip");
tmpFile.deleteOnExit(); // file is deleted after being downloaded in
// DownloadServlet
FileOutputStream fout = new FileOutputStream(tmpFile);
ZipOutputStream out = new ZipOutputStream(fout);
out.setMethod(ZipOutputStream.DEFLATED);
out.setLevel(9);
byte[] data = new byte[BUFFER];
for (DocumentModel doc : documents) {
// first check if DM is attached to the core
if (doc.getSessionId() == null) {
// refetch the doc from the core
doc = documentManager.getDocument(doc.getRef());
}
// NXP-2334 : skip deleted docs
if (LifeCycleConstants.DELETED_STATE.equals(doc.getCurrentLifeCycleState())) {
continue;
}
BlobHolder bh = doc.getAdapter(BlobHolder.class);
if (doc.isFolder() && !isEmptyFolder(doc, documentManager)) {
addFolderToZip("", out, doc, data, documentManager, blobList,
exportAllBlobs);
} else if (bh != null) {
addBlobHolderToZip("", out, doc, data, blobList, bh,
exportAllBlobs);
}
}
if (blobList.length() > 1) {
addSummaryToZip(out, data, blobList);
}
try {
out.close();
fout.close();
} catch (ZipException e) {
return null;
}
return tmpFile;
}
private void addFolderToZip(String path, ZipOutputStream out,
DocumentModel doc, byte[] data, CoreSession documentManager,
StringBuilder blobList, boolean exportAllBlobs)
throws ClientException, IOException {
String title = (String) doc.getProperty("dublincore", "title");
List<DocumentModel> docList = documentManager.getChildren(doc.getRef());
for (DocumentModel docChild : docList) {
// NXP-2334 : skip deleted docs
if (LifeCycleConstants.DELETED_STATE.equals(docChild.getCurrentLifeCycleState())) {
continue;
}
BlobHolder bh = docChild.getAdapter(BlobHolder.class);
String newPath = null;
if (path.length() == 0) {
newPath = title;
} else {
newPath = path + "/" + title;
}
if (docChild.isFolder()
&& !isEmptyFolder(docChild, documentManager)) {
addFolderToZip(newPath, out, docChild, data, documentManager,
blobList, exportAllBlobs);
} else if (bh != null) {
addBlobHolderToZip(newPath, out, docChild, data, blobList, bh,
exportAllBlobs);
}
}
}
private boolean isEmptyFolder(DocumentModel doc, CoreSession documentManager)
throws ClientException {
List<DocumentModel> docList = documentManager.getChildren(doc.getRef());
for (DocumentModel docChild : docList) {
// If there is a blob or a folder, it is not empty.
if (docChild.getAdapter(BlobHolder.class) != null
|| docChild.isFolder()) {
return false;
}
}
return true;
}
/**
* Writes a summary file and puts it in the archive.
*/
private void addSummaryToZip(ZipOutputStream out, byte[] data,
StringBuilder sb) throws IOException {
Blob content = new StringBlob(sb.toString());
BufferedInputStream buffi = new BufferedInputStream(
content.getStream(), BUFFER);
ZipEntry entry = new ZipEntry(SUMMARY_FILENAME);
out.putNextEntry(entry);
int count = buffi.read(data, 0, BUFFER);
while (count != -1) {
out.write(data, 0, count);
count = buffi.read(data, 0, BUFFER);
}
out.closeEntry();
buffi.close();
}
private void addBlobHolderToZip(String path, ZipOutputStream out,
DocumentModel doc, byte[] data, StringBuilder blobList,
BlobHolder bh, boolean exportAllBlobs) throws IOException,
ClientException {
List<Blob> blobs = new ArrayList<Blob>();
if (exportAllBlobs) {
if (bh.getBlobs() != null) {
blobs = bh.getBlobs();
}
} else {
Blob mainBlob = bh.getBlob();
if (mainBlob != null) {
blobs.add(mainBlob);
}
}
if (blobs.size() > 0) { // add document info
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
if (path.length() > 0) {
blobList.append(path).append('/');
}
blobList.append(doc.getTitle()).append(" ");
blobList.append(doc.getType()).append(" ");
Calendar c = (Calendar) doc.getPropertyValue("dc:modified");
if (c != null) {
blobList.append(format.format(c.getTime()));
}
blobList.append("\n");
}
for (Blob content : blobs) {
String fileName = content.getFilename();
+ if (fileName == null) {
+ // use a default value
+ fileName = "file.bin";
+ }
BufferedInputStream buffi = new BufferedInputStream(
content.getStream(), BUFFER);
// Workaround to deal with duplicate file names.
int tryCount = 0;
String entryPath = null;
String entryName = null;
while (true) {
try {
ZipEntry entry = null;
if (tryCount == 0) {
entryName = fileName;
} else {
entryName = formatFileName(fileName, "(" + tryCount
+ ")");
}
if (path.length() == 0) {
entryPath = entryName;
} else {
entryPath = path + "/" + entryName;
}
entryPath = escapeEntryPath(entryPath);
entry = new ZipEntry(entryPath);
out.putNextEntry(entry);
break;
} catch (ZipException e) {
tryCount++;
}
}
blobList.append(" - ").append(entryName).append("\n");
int count = buffi.read(data, 0, BUFFER);
while (count != -1) {
out.write(data, 0, count);
count = buffi.read(data, 0, BUFFER);
}
out.closeEntry();
buffi.close();
}
}
private String formatFileName(String filename, String count) {
StringBuilder sb = new StringBuilder();
CharSequence name = filename.subSequence(0, filename.lastIndexOf("."));
CharSequence extension = filename.subSequence(
filename.lastIndexOf("."), filename.length());
sb.append(name).append(count).append(extension);
return sb.toString();
}
protected String escapeEntryPath(String path) {
String zipEntryEncoding = Framework.getProperty(ZIP_ENTRY_ENCODING_PROPERTY);
if (zipEntryEncoding != null
&& zipEntryEncoding.equals(ZIP_ENTRY_ENCODING_OPTIONS.ascii.toString())) {
return StringUtils.toAscii(path);
}
return path;
}
}
| true | true | private void addBlobHolderToZip(String path, ZipOutputStream out,
DocumentModel doc, byte[] data, StringBuilder blobList,
BlobHolder bh, boolean exportAllBlobs) throws IOException,
ClientException {
List<Blob> blobs = new ArrayList<Blob>();
if (exportAllBlobs) {
if (bh.getBlobs() != null) {
blobs = bh.getBlobs();
}
} else {
Blob mainBlob = bh.getBlob();
if (mainBlob != null) {
blobs.add(mainBlob);
}
}
if (blobs.size() > 0) { // add document info
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
if (path.length() > 0) {
blobList.append(path).append('/');
}
blobList.append(doc.getTitle()).append(" ");
blobList.append(doc.getType()).append(" ");
Calendar c = (Calendar) doc.getPropertyValue("dc:modified");
if (c != null) {
blobList.append(format.format(c.getTime()));
}
blobList.append("\n");
}
for (Blob content : blobs) {
String fileName = content.getFilename();
BufferedInputStream buffi = new BufferedInputStream(
content.getStream(), BUFFER);
// Workaround to deal with duplicate file names.
int tryCount = 0;
String entryPath = null;
String entryName = null;
while (true) {
try {
ZipEntry entry = null;
if (tryCount == 0) {
entryName = fileName;
} else {
entryName = formatFileName(fileName, "(" + tryCount
+ ")");
}
if (path.length() == 0) {
entryPath = entryName;
} else {
entryPath = path + "/" + entryName;
}
entryPath = escapeEntryPath(entryPath);
entry = new ZipEntry(entryPath);
out.putNextEntry(entry);
break;
} catch (ZipException e) {
tryCount++;
}
}
blobList.append(" - ").append(entryName).append("\n");
int count = buffi.read(data, 0, BUFFER);
while (count != -1) {
out.write(data, 0, count);
count = buffi.read(data, 0, BUFFER);
}
out.closeEntry();
buffi.close();
}
}
| private void addBlobHolderToZip(String path, ZipOutputStream out,
DocumentModel doc, byte[] data, StringBuilder blobList,
BlobHolder bh, boolean exportAllBlobs) throws IOException,
ClientException {
List<Blob> blobs = new ArrayList<Blob>();
if (exportAllBlobs) {
if (bh.getBlobs() != null) {
blobs = bh.getBlobs();
}
} else {
Blob mainBlob = bh.getBlob();
if (mainBlob != null) {
blobs.add(mainBlob);
}
}
if (blobs.size() > 0) { // add document info
SimpleDateFormat format = new SimpleDateFormat(
"dd-MM-yyyy HH:mm:ss");
if (path.length() > 0) {
blobList.append(path).append('/');
}
blobList.append(doc.getTitle()).append(" ");
blobList.append(doc.getType()).append(" ");
Calendar c = (Calendar) doc.getPropertyValue("dc:modified");
if (c != null) {
blobList.append(format.format(c.getTime()));
}
blobList.append("\n");
}
for (Blob content : blobs) {
String fileName = content.getFilename();
if (fileName == null) {
// use a default value
fileName = "file.bin";
}
BufferedInputStream buffi = new BufferedInputStream(
content.getStream(), BUFFER);
// Workaround to deal with duplicate file names.
int tryCount = 0;
String entryPath = null;
String entryName = null;
while (true) {
try {
ZipEntry entry = null;
if (tryCount == 0) {
entryName = fileName;
} else {
entryName = formatFileName(fileName, "(" + tryCount
+ ")");
}
if (path.length() == 0) {
entryPath = entryName;
} else {
entryPath = path + "/" + entryName;
}
entryPath = escapeEntryPath(entryPath);
entry = new ZipEntry(entryPath);
out.putNextEntry(entry);
break;
} catch (ZipException e) {
tryCount++;
}
}
blobList.append(" - ").append(entryName).append("\n");
int count = buffi.read(data, 0, BUFFER);
while (count != -1) {
out.write(data, 0, count);
count = buffi.read(data, 0, BUFFER);
}
out.closeEntry();
buffi.close();
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/WorkspaceAwareContextStore.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/WorkspaceAwareContextStore.java
index b244677db..d72033f15 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/WorkspaceAwareContextStore.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/WorkspaceAwareContextStore.java
@@ -1,79 +1,80 @@
/*******************************************************************************
* 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.tasks.ui;
import java.io.File;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.mylyn.context.core.AbstractContextStore;
import org.eclipse.mylyn.monitor.core.StatusHandler;
import org.eclipse.mylyn.tasks.ui.TasksUiPlugin;
/**
* @author Mik Kersten
*/
public class WorkspaceAwareContextStore extends AbstractContextStore {
private static final String DIRECTORY_METADATA = ".metadata";
private static final String OLD_DATA_DIR = ".mylar";
public static final String CONTEXTS_DIRECTORY = "contexts";
private File rootDirectory;
private File contextDirectory;
@Override
public void init() {
// Migrate .mylar data folder to .metadata/.mylyn
String oldDefaultDataPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ OLD_DATA_DIR;
File newDefaultDataDir = new File(TasksUiPlugin.getDefault().getDefaultDataDirectory());
File oldDefaultDataDir = new File(oldDefaultDataPath);
- if (newDefaultDataDir.exists() && oldDefaultDataDir.exists()) {
- StatusHandler.log("Legacy data folder detected: " + oldDefaultDataDir.getAbsolutePath(), this);
- } else if (oldDefaultDataDir.exists() && !newDefaultDataDir.exists()) {
+// if (newDefaultDataDir.exists() && oldDefaultDataDir.exists()) {
+// StatusHandler.log("Legacy data folder detected: " + oldDefaultDataDir.getAbsolutePath(), this);
+// } else
+ if (oldDefaultDataDir.exists() && !newDefaultDataDir.exists()) {
File metadata = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ DIRECTORY_METADATA);
if (!metadata.exists()) {
if (!metadata.mkdirs()) {
StatusHandler.log("Unable to create metadata folder: " + metadata.getAbsolutePath(), this);
}
}
if (metadata.exists()) {
if (!oldDefaultDataDir.renameTo(new File(TasksUiPlugin.getDefault().getDefaultDataDirectory()))) {
StatusHandler.log("Failed to migrate legacy data from " + oldDefaultDataDir.getAbsolutePath()
+ " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this);
}
}
}
rootDirectory = new File(TasksUiPlugin.getDefault().getDataDirectory());
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
contextDirectory = new File(rootDirectory, CONTEXTS_DIRECTORY);
if (!contextDirectory.exists()) {
contextDirectory.mkdir();
}
}
@Override
public File getRootDirectory() {
return rootDirectory;
}
@Override
public File getContextDirectory() {
return contextDirectory;
}
}
| true | true | public void init() {
// Migrate .mylar data folder to .metadata/.mylyn
String oldDefaultDataPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ OLD_DATA_DIR;
File newDefaultDataDir = new File(TasksUiPlugin.getDefault().getDefaultDataDirectory());
File oldDefaultDataDir = new File(oldDefaultDataPath);
if (newDefaultDataDir.exists() && oldDefaultDataDir.exists()) {
StatusHandler.log("Legacy data folder detected: " + oldDefaultDataDir.getAbsolutePath(), this);
} else if (oldDefaultDataDir.exists() && !newDefaultDataDir.exists()) {
File metadata = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ DIRECTORY_METADATA);
if (!metadata.exists()) {
if (!metadata.mkdirs()) {
StatusHandler.log("Unable to create metadata folder: " + metadata.getAbsolutePath(), this);
}
}
if (metadata.exists()) {
if (!oldDefaultDataDir.renameTo(new File(TasksUiPlugin.getDefault().getDefaultDataDirectory()))) {
StatusHandler.log("Failed to migrate legacy data from " + oldDefaultDataDir.getAbsolutePath()
+ " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this);
}
}
}
rootDirectory = new File(TasksUiPlugin.getDefault().getDataDirectory());
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
contextDirectory = new File(rootDirectory, CONTEXTS_DIRECTORY);
if (!contextDirectory.exists()) {
contextDirectory.mkdir();
}
}
| public void init() {
// Migrate .mylar data folder to .metadata/.mylyn
String oldDefaultDataPath = ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ OLD_DATA_DIR;
File newDefaultDataDir = new File(TasksUiPlugin.getDefault().getDefaultDataDirectory());
File oldDefaultDataDir = new File(oldDefaultDataPath);
// if (newDefaultDataDir.exists() && oldDefaultDataDir.exists()) {
// StatusHandler.log("Legacy data folder detected: " + oldDefaultDataDir.getAbsolutePath(), this);
// } else
if (oldDefaultDataDir.exists() && !newDefaultDataDir.exists()) {
File metadata = new File(ResourcesPlugin.getWorkspace().getRoot().getLocation().toString() + '/'
+ DIRECTORY_METADATA);
if (!metadata.exists()) {
if (!metadata.mkdirs()) {
StatusHandler.log("Unable to create metadata folder: " + metadata.getAbsolutePath(), this);
}
}
if (metadata.exists()) {
if (!oldDefaultDataDir.renameTo(new File(TasksUiPlugin.getDefault().getDefaultDataDirectory()))) {
StatusHandler.log("Failed to migrate legacy data from " + oldDefaultDataDir.getAbsolutePath()
+ " to " + TasksUiPlugin.getDefault().getDefaultDataDirectory(), this);
}
}
}
rootDirectory = new File(TasksUiPlugin.getDefault().getDataDirectory());
if (!rootDirectory.exists()) {
rootDirectory.mkdir();
}
contextDirectory = new File(rootDirectory, CONTEXTS_DIRECTORY);
if (!contextDirectory.exists()) {
contextDirectory.mkdir();
}
}
|
diff --git a/Player.java b/Player.java
index 115ad17..9b8f25b 100644
--- a/Player.java
+++ b/Player.java
@@ -1,41 +1,35 @@
import greenfoot.*;
public abstract class Player extends Actor {
private int speed;
private int initialSpeed;
private Bag.BagType bagType;
protected Player(int speed) {
this.initialSpeed = speed;
this.speed = speed;
}
@Override
public void act() {
if (Greenfoot.isKeyDown("w")) move(0, -speed);
if (Greenfoot.isKeyDown("s")) move(0, +speed);
if (Greenfoot.isKeyDown("a")) move(-speed, 0);
if (Greenfoot.isKeyDown("d")) move(+speed, 0);
if(Greenfoot.mouseClicked(null)) {
- int x = -getImage().getWidth() * 4;
- int y = getImage().getHeight() * 4;
- Water water = (Water)getOneObjectAtOffset(x , y, Water.class);
- if(water != null) {
- water.delete();
- getWorld().addObject(new Sandbag(), x, y);
- Greenfoot.playSound("sandbag.wav");
- }
+ getWorld().addObject(new Sandbag(), getX(), getY());
+ Greenfoot.playSound("sandbag.wav");
}
}
private void move(int dx, int dy) {
setLocation(getX() + dx, getY() + dy);
}
public void carryBag(Bag bag) {
bag.getWorld().removeObject(bag);
speed = initialSpeed - bag.getWeight();
bagType = bag.getType();
}
}
| true | true | public void act() {
if (Greenfoot.isKeyDown("w")) move(0, -speed);
if (Greenfoot.isKeyDown("s")) move(0, +speed);
if (Greenfoot.isKeyDown("a")) move(-speed, 0);
if (Greenfoot.isKeyDown("d")) move(+speed, 0);
if(Greenfoot.mouseClicked(null)) {
int x = -getImage().getWidth() * 4;
int y = getImage().getHeight() * 4;
Water water = (Water)getOneObjectAtOffset(x , y, Water.class);
if(water != null) {
water.delete();
getWorld().addObject(new Sandbag(), x, y);
Greenfoot.playSound("sandbag.wav");
}
}
}
| public void act() {
if (Greenfoot.isKeyDown("w")) move(0, -speed);
if (Greenfoot.isKeyDown("s")) move(0, +speed);
if (Greenfoot.isKeyDown("a")) move(-speed, 0);
if (Greenfoot.isKeyDown("d")) move(+speed, 0);
if(Greenfoot.mouseClicked(null)) {
getWorld().addObject(new Sandbag(), getX(), getY());
Greenfoot.playSound("sandbag.wav");
}
}
|
diff --git a/src/main/java/hudson/plugins/warnings/WarningsPublisher.java b/src/main/java/hudson/plugins/warnings/WarningsPublisher.java
index 78c0c4a0..43c1dcf9 100644
--- a/src/main/java/hudson/plugins/warnings/WarningsPublisher.java
+++ b/src/main/java/hudson/plugins/warnings/WarningsPublisher.java
@@ -1,290 +1,290 @@
package hudson.plugins.warnings;
import hudson.Launcher;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixBuild;
import hudson.model.Action;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.plugins.analysis.core.AnnotationsClassifier;
import hudson.plugins.analysis.core.BuildResult;
import hudson.plugins.analysis.core.FilesParser;
import hudson.plugins.analysis.core.HealthAwarePublisher;
import hudson.plugins.analysis.core.ParserResult;
import hudson.plugins.analysis.util.ModuleDetector;
import hudson.plugins.analysis.util.NullModuleDetector;
import hudson.plugins.analysis.util.PluginLogger;
import hudson.plugins.analysis.util.model.FileAnnotation;
import hudson.plugins.warnings.parser.FileWarningsParser;
import hudson.plugins.warnings.parser.ParserRegistry;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kohsuke.stapler.DataBoundConstructor;
import com.google.common.collect.Sets;
/**
* Publishes the results of the warnings analysis (freestyle project type).
*
* @author Ulli Hafner
*/
// CHECKSTYLE:COUPLING-OFF
public class WarningsPublisher extends HealthAwarePublisher {
/** Unique ID of this class. */
private static final long serialVersionUID = -5936973521277401764L;
/** Ant file-set pattern of files to work with. */
private final String pattern;
/** Ant file-set pattern of files to include to report. */
private final String includePattern;
/** Ant file-set pattern of files to exclude from report. */
private final String excludePattern;
/** Name of parsers to use for scanning the logs. */
@edu.umd.cs.findbugs.annotations.SuppressWarnings("Se")
private Set<String> parserNames = new HashSet<String>();
/** Determines whether the console should be ignored. */
private final boolean ignoreConsole;
/**
* Creates a new instance of <code>WarningPublisher</code>.
*
* @param healthy
* Report health as 100% when the number of annotations is less
* than this value
* @param unHealthy
* Report health as 0% when the number of annotations is greater
* than this value
* @param thresholdLimit
* determines which warning priorities should be considered when
* evaluating the build stability and health
* @param defaultEncoding
* the default encoding to be used when reading and parsing files
* @param useDeltaValues
* determines whether the absolute annotations delta or the
* actual annotations set difference should be used to evaluate
* the build stability
* @param unstableTotalAll
* annotation threshold
* @param unstableTotalHigh
* annotation threshold
* @param unstableTotalNormal
* annotation threshold
* @param unstableTotalLow
* annotation threshold
* @param unstableNewAll
* annotation threshold
* @param unstableNewHigh
* annotation threshold
* @param unstableNewNormal
* annotation threshold
* @param unstableNewLow
* annotation threshold
* @param failedTotalAll
* annotation threshold
* @param failedTotalHigh
* annotation threshold
* @param failedTotalNormal
* annotation threshold
* @param failedTotalLow
* annotation threshold
* @param failedNewAll
* annotation threshold
* @param failedNewHigh
* annotation threshold
* @param failedNewNormal
* annotation threshold
* @param failedNewLow
* annotation threshold
* @param canRunOnFailed
* determines whether the plug-in can run for failed builds, too
* @param shouldDetectModules
* determines whether module names should be derived from Maven POM or Ant build files
* @param canScanConsole
* Determines whether the console should be scanned.
* @param pattern
* Ant file-set pattern that defines the files to scan for
* @param includePattern
* Ant file-set pattern of files to include in report
* @param excludePattern
* Ant file-set pattern of files to exclude from report
*/
// CHECKSTYLE:OFF
@SuppressWarnings("PMD.ExcessiveParameterList")
@DataBoundConstructor
public WarningsPublisher(final String healthy, final String unHealthy, final String thresholdLimit,
final String defaultEncoding, final boolean useDeltaValues,
final String unstableTotalAll, final String unstableTotalHigh, final String unstableTotalNormal, final String unstableTotalLow,
final String unstableNewAll, final String unstableNewHigh, final String unstableNewNormal, final String unstableNewLow,
final String failedTotalAll, final String failedTotalHigh, final String failedTotalNormal, final String failedTotalLow,
final String failedNewAll, final String failedNewHigh, final String failedNewNormal, final String failedNewLow,
final boolean canRunOnFailed, final boolean shouldDetectModules,
final boolean canScanConsole, final String pattern, final String includePattern, final String excludePattern) {
super(healthy, unHealthy, thresholdLimit, defaultEncoding, useDeltaValues,
unstableTotalAll, unstableTotalHigh, unstableTotalNormal, unstableTotalLow,
unstableNewAll, unstableNewHigh, unstableNewNormal, unstableNewLow,
failedTotalAll, failedTotalHigh, failedTotalNormal, failedTotalLow,
failedNewAll, failedNewHigh, failedNewNormal, failedNewLow,
canRunOnFailed, shouldDetectModules, "WARNINGS");
this.pattern = pattern;
ignoreConsole = !canScanConsole;
this.includePattern = StringUtils.stripToNull(includePattern);
this.excludePattern = StringUtils.stripToNull(excludePattern);
}
// CHECKSTYLE:ON
/**
* Returns the names of the configured parsers of this publisher.
*
* @return the parser names
*/
public List<String> getParserNames() {
return ParserRegistry.filterExistingParserNames(parserNames);
}
/**
* Returns whether this plug-in should scan the console or not.
*
* @return the can run on failed
*/
public boolean getCanScanConsole() {
return !ignoreConsole;
}
/**
* Adds the specified parsers to this publisher.
*
* @param parserNames
* the parsers to use when scanning the files
*/
public void setParserNames(final Set<String> parserNames) {
this.parserNames = parserNames;
}
/**
* Creates a new parser set for old versions of this class.
*
* @return this
*/
@Override
protected Object readResolve() {
super.readResolve();
if (parserNames == null) {
parserNames = new HashSet<String>();
}
return this;
}
/**
* Returns the Ant file-set pattern of files to work with.
*
* @return Ant file-set pattern of files to work with
*/
public String getPattern() {
return pattern;
}
/**
* Returns the Ant file-set pattern of files to include in report.
*
* @return Ant file-set pattern of files to include in report
*/
public String getIncludePattern() {
return includePattern;
}
/**
* Returns the Ant file-set pattern of files to exclude from report.
*
* @return Ant file-set pattern of files to exclude from report
*/
public String getExcludePattern() {
return excludePattern;
}
/** {@inheritDoc} */
@Override
public Action getProjectAction(final AbstractProject<?, ?> project) {
return new WarningsProjectAction(project);
}
/** {@inheritDoc} */
@Override
public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
File logFile = build.getLogFile();
Set<String> validParsers = Sets.newHashSet(getParserNames());
ParserResult project;
if (StringUtils.isNotBlank(getPattern())) {
logger.log("Parsing warnings in files: " + getPattern());
FilesParser parser;
if (shouldDetectModules()) {
parser = new FilesParser(logger, getPattern(), new FileWarningsParser(validParsers,
getDefaultEncoding(), getIncludePattern(), getExcludePattern()),
- isMavenBuild(build), isAntBuild(build));
+ isMavenBuild(build));
}
else {
parser = new FilesParser(logger, getPattern(), new FileWarningsParser(validParsers,
getDefaultEncoding(), getIncludePattern(), getExcludePattern()));
}
project = build.getWorkspace().act(parser);
}
else {
project = new ParserResult(build.getWorkspace());
}
if (!ignoreConsole || StringUtils.isBlank(getPattern())) {
logger.log("Parsing warnings in console log...");
ParserRegistry registry = new ParserRegistry(ParserRegistry.getParsers(validParsers),
getDefaultEncoding(), getIncludePattern(), getExcludePattern());
Collection<FileAnnotation> warnings = registry.parse(logFile, logger);
if (!build.getWorkspace().isRemote()) {
String workspace = build.getWorkspace().getRemote();
ModuleDetector detector = createModuleDetector(workspace);
for (FileAnnotation annotation : warnings) {
String module = detector.guessModuleName(annotation.getFileName());
annotation.setModuleName(module);
}
}
project.addAnnotations(warnings);
}
project = build.getWorkspace().act(new AnnotationsClassifier(project, getDefaultEncoding()));
for (FileAnnotation annotation : project.getAnnotations()) {
annotation.setPathName(build.getWorkspace().getRemote());
}
WarningsResult result = new WarningsResult(build, getDefaultEncoding(), project);
build.getActions().add(new WarningsResultAction(build, this, result));
return result;
}
private ModuleDetector createModuleDetector(final String workspace) {
if (shouldDetectModules()) {
return new ModuleDetector(new File(workspace));
}
else {
return new NullModuleDetector();
}
}
/** {@inheritDoc} */
@Override
public WarningsDescriptor getDescriptor() {
return (WarningsDescriptor)super.getDescriptor();
}
/** {@inheritDoc} */
public MatrixAggregator createAggregator(final MatrixBuild build, final Launcher launcher,
final BuildListener listener) {
return new WarningsAnnotationsAggregator(build, launcher, listener, this, getDefaultEncoding());
}
}
| true | true | public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
File logFile = build.getLogFile();
Set<String> validParsers = Sets.newHashSet(getParserNames());
ParserResult project;
if (StringUtils.isNotBlank(getPattern())) {
logger.log("Parsing warnings in files: " + getPattern());
FilesParser parser;
if (shouldDetectModules()) {
parser = new FilesParser(logger, getPattern(), new FileWarningsParser(validParsers,
getDefaultEncoding(), getIncludePattern(), getExcludePattern()),
isMavenBuild(build), isAntBuild(build));
}
else {
parser = new FilesParser(logger, getPattern(), new FileWarningsParser(validParsers,
getDefaultEncoding(), getIncludePattern(), getExcludePattern()));
}
project = build.getWorkspace().act(parser);
}
else {
project = new ParserResult(build.getWorkspace());
}
if (!ignoreConsole || StringUtils.isBlank(getPattern())) {
logger.log("Parsing warnings in console log...");
ParserRegistry registry = new ParserRegistry(ParserRegistry.getParsers(validParsers),
getDefaultEncoding(), getIncludePattern(), getExcludePattern());
Collection<FileAnnotation> warnings = registry.parse(logFile, logger);
if (!build.getWorkspace().isRemote()) {
String workspace = build.getWorkspace().getRemote();
ModuleDetector detector = createModuleDetector(workspace);
for (FileAnnotation annotation : warnings) {
String module = detector.guessModuleName(annotation.getFileName());
annotation.setModuleName(module);
}
}
project.addAnnotations(warnings);
}
project = build.getWorkspace().act(new AnnotationsClassifier(project, getDefaultEncoding()));
for (FileAnnotation annotation : project.getAnnotations()) {
annotation.setPathName(build.getWorkspace().getRemote());
}
WarningsResult result = new WarningsResult(build, getDefaultEncoding(), project);
build.getActions().add(new WarningsResultAction(build, this, result));
return result;
}
| public BuildResult perform(final AbstractBuild<?, ?> build, final PluginLogger logger) throws InterruptedException, IOException {
File logFile = build.getLogFile();
Set<String> validParsers = Sets.newHashSet(getParserNames());
ParserResult project;
if (StringUtils.isNotBlank(getPattern())) {
logger.log("Parsing warnings in files: " + getPattern());
FilesParser parser;
if (shouldDetectModules()) {
parser = new FilesParser(logger, getPattern(), new FileWarningsParser(validParsers,
getDefaultEncoding(), getIncludePattern(), getExcludePattern()),
isMavenBuild(build));
}
else {
parser = new FilesParser(logger, getPattern(), new FileWarningsParser(validParsers,
getDefaultEncoding(), getIncludePattern(), getExcludePattern()));
}
project = build.getWorkspace().act(parser);
}
else {
project = new ParserResult(build.getWorkspace());
}
if (!ignoreConsole || StringUtils.isBlank(getPattern())) {
logger.log("Parsing warnings in console log...");
ParserRegistry registry = new ParserRegistry(ParserRegistry.getParsers(validParsers),
getDefaultEncoding(), getIncludePattern(), getExcludePattern());
Collection<FileAnnotation> warnings = registry.parse(logFile, logger);
if (!build.getWorkspace().isRemote()) {
String workspace = build.getWorkspace().getRemote();
ModuleDetector detector = createModuleDetector(workspace);
for (FileAnnotation annotation : warnings) {
String module = detector.guessModuleName(annotation.getFileName());
annotation.setModuleName(module);
}
}
project.addAnnotations(warnings);
}
project = build.getWorkspace().act(new AnnotationsClassifier(project, getDefaultEncoding()));
for (FileAnnotation annotation : project.getAnnotations()) {
annotation.setPathName(build.getWorkspace().getRemote());
}
WarningsResult result = new WarningsResult(build, getDefaultEncoding(), project);
build.getActions().add(new WarningsResultAction(build, this, result));
return result;
}
|
diff --git a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java
index 1b0603a93..992b31e99 100644
--- a/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java
+++ b/opentripplanner-routing/src/main/java/org/opentripplanner/routing/impl/raptor/TargetBound.java
@@ -1,375 +1,375 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.routing.impl.raptor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import org.opentripplanner.common.geometry.DistanceLibrary;
import org.opentripplanner.common.geometry.SphericalDistanceLibrary;
import org.opentripplanner.routing.algorithm.strategies.RemainingWeightHeuristic;
import org.opentripplanner.routing.algorithm.strategies.SearchTerminationStrategy;
import org.opentripplanner.routing.algorithm.strategies.SkipTraverseResultStrategy;
import org.opentripplanner.routing.algorithm.strategies.TransitLocalStreetService;
import org.opentripplanner.routing.core.RoutingRequest;
import org.opentripplanner.routing.core.State;
import org.opentripplanner.routing.edgetype.PreAlightEdge;
import org.opentripplanner.routing.edgetype.PreBoardEdge;
import org.opentripplanner.routing.edgetype.StreetEdge;
import org.opentripplanner.routing.edgetype.TransitBoardAlight;
import org.opentripplanner.routing.graph.AbstractVertex;
import org.opentripplanner.routing.graph.Edge;
import org.opentripplanner.routing.graph.Vertex;
import org.opentripplanner.routing.spt.ArrayMultiShortestPathTree;
import org.opentripplanner.routing.spt.ShortestPathTree;
import org.opentripplanner.routing.spt.ShortestPathTreeFactory;
import org.opentripplanner.routing.vertextype.TransitStop;
import com.vividsolutions.jts.geom.Coordinate;
public class TargetBound implements SearchTerminationStrategy, SkipTraverseResultStrategy, RemainingWeightHeuristic, ShortestPathTreeFactory {
private static final long serialVersionUID = -5296036164138922096L;
private static final long WORST_TIME_DIFFERENCE = 3600;
private static final double WORST_WEIGHT_DIFFERENCE_FACTOR = 1.3;
List<State> bounders;
private Vertex realTarget;
private DistanceLibrary distanceLibrary = SphericalDistanceLibrary.getInstance();
private Coordinate realTargetCoordinate;
private double distanceToNearestTransitStop;
private TransitLocalStreetService transitLocalStreets;
private double speedUpperBound;
//this is saved so that it can be reused in various skipping functions
private double targetDistance;
private double speedWeight;
/**
* How much longer the worst path can be than the best in terms of time.
* Setting this lower will cut off some less-walking more-time paths.
* Setting it higher will slow down the search a lot.
*/
private double timeBoundFactor = 2;
private List<Integer> previousArrivalTime = new ArrayList<Integer>();
private RoutingRequest options;
public ShortestPathTree spt = new ArrayMultiShortestPathTree(options);
double[] distance = new double[AbstractVertex.getMaxIndex()];
public double bestTargetDistance = Double.POSITIVE_INFINITY;
public List<State> removedBoundingStates = new ArrayList<State>();
private List<State> transitStopsVisited = new ArrayList<State>();
public TargetBound(RoutingRequest options) {
this.options = options;
if (options.rctx.target != null) {
this.realTarget = options.rctx.target;
this.realTargetCoordinate = realTarget.getCoordinate();
this.distanceToNearestTransitStop = realTarget.getDistanceToNearestTransitStop();
bounders = new ArrayList<State>();
transitLocalStreets = options.rctx.graph.getService(TransitLocalStreetService.class);
speedUpperBound = options.getSpeedUpperBound();
this.speedWeight = options.getWalkReluctance() / speedUpperBound;
}
}
@Override
public boolean shouldSearchContinue(Vertex origin, Vertex target, State current,
ShortestPathTree spt, RoutingRequest traverseOptions) {
final Vertex vertex = current.getVertex();
if (vertex instanceof TransitStop) {
transitStopsVisited.add(current);
}
if (vertex == realTarget) {
addBounder(current);
}
return true;
}
public void addBounder(State bounder) {
for (Iterator<State> it = bounders.iterator(); it.hasNext(); ) {
State old = it.next();
if (bounder.dominates(old)) {
it.remove();
removedBoundingStates.add(old);
} else if (bounder.getNumBoardings() <= old.getNumBoardings() && options.arriveBy ? (
bounder.getTime() - WORST_TIME_DIFFERENCE > old.getTime())
: (bounder.getTime() + WORST_TIME_DIFFERENCE < old.getTime())) {
it.remove();
removedBoundingStates.add(old);
}
}
bounders.add(bounder);
RaptorState state = (RaptorState) bounder.getExtension("raptorParent");
if (state == null) {
previousArrivalTime.add(-1);
return;
}
RaptorStop stop = state.stop;
//get previous alight at stop
if (options.isArriveBy()) {
final int nextDepartTime = getNextDepartTime(options, (state.arrivalTime - options.getBoardSlack()) - 2, stop.stopVertex);
previousArrivalTime.add((int) ((nextDepartTime - options.getAlightSlack()) - bounder.getElapsedTime()));
} else {
final int previousArriveTime = getPreviousArriveTime(options, state.arrivalTime - options.getAlightSlack() + 2, stop.stopVertex);
previousArrivalTime.add((int) (previousArriveTime + options.getAlightSlack() + bounder.getElapsedTime()));
}
}
@Override
public boolean shouldSkipTraversalResult(Vertex origin, Vertex target, State parent,
State current, ShortestPathTree spt, RoutingRequest traverseOptions) {
if (realTarget == null)
return false;
final Vertex vertex = current.getVertex();
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
targetDistance = distance[vertexIndex];
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
distance[vertexIndex] = targetDistance;
if (vertex instanceof TransitStop && targetDistance < bestTargetDistance) {
bestTargetDistance = targetDistance;
}
}
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
final double remainingWalk = traverseOptions.maxWalkDistance
- current.getWalkDistance();
final double minWalk;
double minTime = 0;
if (targetDistance > remainingWalk) {
// then we must have some transit + some walk.
minWalk = this.distanceToNearestTransitStop + vertex.getDistanceToNearestTransitStop();
minTime = options.isArriveBy() ? traverseOptions.getAlightSlack() : traverseOptions.getBoardSlack();
- if (current.getBackEdge() instanceof StreetEdge && !transitLocalStreets.transferrable(vertex)) {
+ if (current.getBackEdge() instanceof StreetEdge && transitLocalStreets != null && !transitLocalStreets.transferrable(vertex)) {
return true;
}
} else {
// could walk directly to destination
- if (targetDistance < distanceToNearestTransitStop || !transitLocalStreets.transferrable(vertex))
+ if (targetDistance < distanceToNearestTransitStop || transitLocalStreets == null || !transitLocalStreets.transferrable(vertex))
minWalk = targetDistance;
else
minWalk = distanceToNearestTransitStop;
}
if (minWalk > remainingWalk)
return true;
final double optimisticDistance = current.getWalkDistance() + minWalk;
final double walkTime = minWalk
/ speedUpperBound;
minTime += (targetDistance - minWalk) / Raptor.MAX_TRANSIT_SPEED + walkTime;
double stateTime = current.getOptimizedElapsedTime() + minTime;
int i = 0;
boolean prevBounded = !bounders.isEmpty();
for (State bounder : bounders) {
if (current.getWeight() + minTime + walkTime * (options.getWalkReluctance() - 1) > bounder.getWeight() * WORST_WEIGHT_DIFFERENCE_FACTOR) {
return true;
}
int prevTime = previousArrivalTime.get(i++);
if (optimisticDistance * 1.1 > bounder.getWalkDistance()
&& current.getNumBoardings() >= bounder.getNumBoardings()) {
if (current.getElapsedTime() + minTime > bounder.getElapsedTime()) {
return true;
} else if (prevTime < 0 && (options.arriveBy ? (current.getTime() + minTime <= prevTime) : ((current.getTime() - minTime) >= prevTime))) {
prevBounded = false;
}
} else {
prevBounded = false;
}
//check that the new path is not much longer in time than the bounding path
if (bounder.getOptimizedElapsedTime() * timeBoundFactor < stateTime) {
return true;
}
}
return prevBounded;
}
public static int getNextDepartTime(RoutingRequest request, int departureTime, Vertex stopVertex) {
int bestArrivalTime = Integer.MAX_VALUE;
request.arriveBy = false;
// find the boards
for (Edge preboard : stopVertex.getOutgoing()) {
if (preboard instanceof PreBoardEdge) {
Vertex departure = preboard.getToVertex(); // this is the departure vertex
for (Edge board : departure.getOutgoing()) {
if (board instanceof TransitBoardAlight) {
State state = new State(board.getFromVertex(), departureTime, request);
State result = board.traverse(state);
if (result == null)
continue;
int time = (int) result.getTime();
if (time < bestArrivalTime) {
bestArrivalTime = time;
}
}
}
}
}
request.arriveBy = true;
return bestArrivalTime;
}
public static int getPreviousArriveTime(RoutingRequest request, int arrivalTime, Vertex stopVertex) {
int bestArrivalTime = -1;
request.arriveBy = true;
// find the alights
for (Edge prealight : stopVertex.getIncoming()) {
if (prealight instanceof PreAlightEdge) {
Vertex arrival = prealight.getFromVertex(); // this is the arrival vertex
for (Edge alight : arrival.getIncoming()) {
if (alight instanceof TransitBoardAlight) {
State state = new State(alight.getToVertex(), arrivalTime, request);
State result = alight.traverse(state);
if (result == null)
continue;
int time = (int) result.getTime();
if (time > bestArrivalTime) {
bestArrivalTime = time;
}
}
}
}
}
request.arriveBy = false;
return bestArrivalTime;
}
@Override
public double computeInitialWeight(State s, Vertex target) {
return computeForwardWeight(s, target);
}
/**
* This actually does have to be admissible, since when we find the target, it used to bound the rest of the search.
*/
@Override
public double computeForwardWeight(State s, Vertex target) {
return targetDistance * speedWeight;
}
@Override
public double computeReverseWeight(State s, Vertex target) {
return computeForwardWeight(s, target);
}
/** Reset the heuristic */
@Override
public void reset() {
}
public double getTimeBoundFactor() {
return timeBoundFactor;
}
public void setTimeBoundFactor(double timeBoundFactor) {
this.timeBoundFactor = timeBoundFactor;
}
@Override
public ShortestPathTree create(RoutingRequest options) {
return spt;
}
public void addSptStates(List<MaxWalkState> states) {
for (MaxWalkState state : states) {
if (state.getVertex() instanceof TransitStop) {
transitStopsVisited.add(state);
}
spt.add(state);
}
}
public double getTargetDistance(Vertex vertex) {
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
return distance[vertexIndex];
} else {
double d = distanceLibrary.fastDistance(realTargetCoordinate.y,
realTargetCoordinate.x, vertex.getY(), vertex.getX());
distance[vertexIndex] = d;
return d;
}
} else {
return distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
}
public List<State> getTransitStopsVisited() {
return transitStopsVisited;
}
public void prepareForSearch() {
transitStopsVisited.clear();
}
public void reset(RoutingRequest options) {
this.options = options;
if (realTarget != options.rctx.target) {
this.realTarget = options.rctx.target;
this.realTargetCoordinate = realTarget.getCoordinate();
this.distanceToNearestTransitStop = realTarget.getDistanceToNearestTransitStop();
bounders = new ArrayList<State>();
Arrays.fill(distance, -1);
}
spt = new ArrayMultiShortestPathTree(options);
transitLocalStreets = options.rctx.graph.getService(TransitLocalStreetService.class);
speedUpperBound = options.getSpeedUpperBound();
this.speedWeight = options.getWalkReluctance() / speedUpperBound;
}
}
| false | true | public boolean shouldSkipTraversalResult(Vertex origin, Vertex target, State parent,
State current, ShortestPathTree spt, RoutingRequest traverseOptions) {
if (realTarget == null)
return false;
final Vertex vertex = current.getVertex();
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
targetDistance = distance[vertexIndex];
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
distance[vertexIndex] = targetDistance;
if (vertex instanceof TransitStop && targetDistance < bestTargetDistance) {
bestTargetDistance = targetDistance;
}
}
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
final double remainingWalk = traverseOptions.maxWalkDistance
- current.getWalkDistance();
final double minWalk;
double minTime = 0;
if (targetDistance > remainingWalk) {
// then we must have some transit + some walk.
minWalk = this.distanceToNearestTransitStop + vertex.getDistanceToNearestTransitStop();
minTime = options.isArriveBy() ? traverseOptions.getAlightSlack() : traverseOptions.getBoardSlack();
if (current.getBackEdge() instanceof StreetEdge && !transitLocalStreets.transferrable(vertex)) {
return true;
}
} else {
// could walk directly to destination
if (targetDistance < distanceToNearestTransitStop || !transitLocalStreets.transferrable(vertex))
minWalk = targetDistance;
else
minWalk = distanceToNearestTransitStop;
}
if (minWalk > remainingWalk)
return true;
final double optimisticDistance = current.getWalkDistance() + minWalk;
final double walkTime = minWalk
/ speedUpperBound;
minTime += (targetDistance - minWalk) / Raptor.MAX_TRANSIT_SPEED + walkTime;
double stateTime = current.getOptimizedElapsedTime() + minTime;
int i = 0;
boolean prevBounded = !bounders.isEmpty();
for (State bounder : bounders) {
if (current.getWeight() + minTime + walkTime * (options.getWalkReluctance() - 1) > bounder.getWeight() * WORST_WEIGHT_DIFFERENCE_FACTOR) {
return true;
}
int prevTime = previousArrivalTime.get(i++);
if (optimisticDistance * 1.1 > bounder.getWalkDistance()
&& current.getNumBoardings() >= bounder.getNumBoardings()) {
if (current.getElapsedTime() + minTime > bounder.getElapsedTime()) {
return true;
} else if (prevTime < 0 && (options.arriveBy ? (current.getTime() + minTime <= prevTime) : ((current.getTime() - minTime) >= prevTime))) {
prevBounded = false;
}
} else {
prevBounded = false;
}
//check that the new path is not much longer in time than the bounding path
if (bounder.getOptimizedElapsedTime() * timeBoundFactor < stateTime) {
return true;
}
}
return prevBounded;
}
| public boolean shouldSkipTraversalResult(Vertex origin, Vertex target, State parent,
State current, ShortestPathTree spt, RoutingRequest traverseOptions) {
if (realTarget == null)
return false;
final Vertex vertex = current.getVertex();
int vertexIndex = vertex.getIndex();
if (vertexIndex < distance.length) {
if (distance[vertexIndex] > 0.0) {
targetDistance = distance[vertexIndex];
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
distance[vertexIndex] = targetDistance;
if (vertex instanceof TransitStop && targetDistance < bestTargetDistance) {
bestTargetDistance = targetDistance;
}
}
} else {
targetDistance = distanceLibrary.fastDistance(realTargetCoordinate.y, realTargetCoordinate.x,
vertex.getY(), vertex.getX());
}
final double remainingWalk = traverseOptions.maxWalkDistance
- current.getWalkDistance();
final double minWalk;
double minTime = 0;
if (targetDistance > remainingWalk) {
// then we must have some transit + some walk.
minWalk = this.distanceToNearestTransitStop + vertex.getDistanceToNearestTransitStop();
minTime = options.isArriveBy() ? traverseOptions.getAlightSlack() : traverseOptions.getBoardSlack();
if (current.getBackEdge() instanceof StreetEdge && transitLocalStreets != null && !transitLocalStreets.transferrable(vertex)) {
return true;
}
} else {
// could walk directly to destination
if (targetDistance < distanceToNearestTransitStop || transitLocalStreets == null || !transitLocalStreets.transferrable(vertex))
minWalk = targetDistance;
else
minWalk = distanceToNearestTransitStop;
}
if (minWalk > remainingWalk)
return true;
final double optimisticDistance = current.getWalkDistance() + minWalk;
final double walkTime = minWalk
/ speedUpperBound;
minTime += (targetDistance - minWalk) / Raptor.MAX_TRANSIT_SPEED + walkTime;
double stateTime = current.getOptimizedElapsedTime() + minTime;
int i = 0;
boolean prevBounded = !bounders.isEmpty();
for (State bounder : bounders) {
if (current.getWeight() + minTime + walkTime * (options.getWalkReluctance() - 1) > bounder.getWeight() * WORST_WEIGHT_DIFFERENCE_FACTOR) {
return true;
}
int prevTime = previousArrivalTime.get(i++);
if (optimisticDistance * 1.1 > bounder.getWalkDistance()
&& current.getNumBoardings() >= bounder.getNumBoardings()) {
if (current.getElapsedTime() + minTime > bounder.getElapsedTime()) {
return true;
} else if (prevTime < 0 && (options.arriveBy ? (current.getTime() + minTime <= prevTime) : ((current.getTime() - minTime) >= prevTime))) {
prevBounded = false;
}
} else {
prevBounded = false;
}
//check that the new path is not much longer in time than the bounding path
if (bounder.getOptimizedElapsedTime() * timeBoundFactor < stateTime) {
return true;
}
}
return prevBounded;
}
|
diff --git a/src/main/java/edu/isi/bmkeg/vpdmf/bin/BuildVpdmfModelMavenProject.java b/src/main/java/edu/isi/bmkeg/vpdmf/bin/BuildVpdmfModelMavenProject.java
index e71c4c3..ba4c7da 100644
--- a/src/main/java/edu/isi/bmkeg/vpdmf/bin/BuildVpdmfModelMavenProject.java
+++ b/src/main/java/edu/isi/bmkeg/vpdmf/bin/BuildVpdmfModelMavenProject.java
@@ -1,185 +1,183 @@
package edu.isi.bmkeg.vpdmf.bin;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.maven.model.DistributionManagement;
import org.apache.maven.model.Model;
import utils.VPDMfGeneratorConverters;
import com.google.common.io.Files;
import edu.isi.bmkeg.uml.interfaces.ActionscriptInterface;
import edu.isi.bmkeg.uml.interfaces.JavaUmlInterface;
import edu.isi.bmkeg.uml.interfaces.UimaUMLInterface;
import edu.isi.bmkeg.uml.model.UMLmodel;
import edu.isi.bmkeg.uml.sources.UMLModelSimpleParser;
import edu.isi.bmkeg.utils.Converters;
import edu.isi.bmkeg.utils.mvnRunner.LocalMavenInstall;
import edu.isi.bmkeg.vpdmf.model.definitions.VPDMf;
import edu.isi.bmkeg.vpdmf.model.definitions.specs.VpdmfSpec;
import edu.isi.bmkeg.vpdmf.utils.VPDMfConverters;
import edu.isi.bmkeg.vpdmf.utils.VPDMfParser;
public class BuildVpdmfModelMavenProject {
public static String USAGE = "arguments: [<proj1> <proj2> ... <projN>] <target-dir> <bmkeg-parent-version>";
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
if( args.length < 3 ) {
System.err.println(USAGE);
System.exit(-1);
}
List<File> viewFiles = new ArrayList<File>();
List<File> dataFiles = new ArrayList<File>();
List<String> solrViews = new ArrayList<String>();
UMLmodel model = null;
File firstPom = new File( args[0].replaceAll("\\/$", "") + "/pom.xml" );
Model firstPomModel = VPDMfGeneratorConverters.readModelFromPom(firstPom);
VpdmfSpec firstSpecs = VPDMfGeneratorConverters.readVpdmfSpecFromPom(firstPomModel);
List<File> pomFiles = new ArrayList<File>();
- List<String> pomPaths = new ArrayList<String>();
for (int i = 0; i < args.length - 2; i++) {
- pomPaths.add(args[i]);
- File specsFile = new File(args[i]);
- pomFiles.add(specsFile);
+ File pomFile = new File(args[i].replaceAll("\\/$", "") + "/pom.xml");
+ pomFiles.add(pomFile);
}
File dir = new File(args[args.length - 2]);
dir.mkdirs();
String bmkegParentVersion = args[args.length - 1];
Iterator<File> it = pomFiles.iterator();
while (it.hasNext()) {
File pomFile = it.next();
//
// parse the specs files
//
Model pomModel = VPDMfGeneratorConverters.readModelFromPom(pomFile);
VpdmfSpec vpdmfSpec = VPDMfGeneratorConverters.readVpdmfSpecFromPom(pomModel);
// Model file
String modelPath = vpdmfSpec.getModel().getPath();
String modelType = vpdmfSpec.getModel().getType();
File modelFile = new File(pomFile.getParent() + "/" + modelPath);
// View directory
String viewsPath = vpdmfSpec.getViewsPath();
File viewsDir = new File(pomFile.getParent() + "/" + viewsPath);
viewFiles.addAll(VPDMfParser.getAllSpecFiles(viewsDir));
// solr views
solrViews.addAll(vpdmfSpec.getSolrViews());
// Data file
File data = null;
if (vpdmfSpec.getData() != null) {
String dataPath = vpdmfSpec.getData().getPath();
- data = new File(dataPath);
+ data = new File(pomFile.getParent() + "/" + dataPath);
if (!data.exists())
data = null;
else
dataFiles.add(data);
}
if (data != null)
System.out.println("Data File: " + data.getPath());
UMLModelSimpleParser p = new UMLModelSimpleParser(
UMLmodel.XMI_MAGICDRAW);
p.parseUMLModelFile(modelFile);
UMLmodel m = p.getUmlModels().get(0);
if (model == null) {
model = m;
} else {
model.mergeModel(m);
}
}
VPDMfParser vpdmfP = new VPDMfParser();
VPDMf top = vpdmfP.buildAllViews(firstSpecs, model, viewFiles,
solrViews);
if( firstSpecs.getUimaPackagePattern() != null && firstSpecs.getUimaPackagePattern().length() > 0 ) {
top.setUimaPkgPattern(firstSpecs.getUimaPackagePattern());
}
String group = top.getGroupId();
String artifactId = top.getArtifactId();
String version = top.getVersion();
// ~~~~~~~~~~~~~~~~~~~~
// Java component build
// ~~~~~~~~~~~~~~~~~~~~
JavaUmlInterface java = new JavaUmlInterface();
if( top.getUimaPkgPattern() != null && top.getUimaPkgPattern().length() > 0 ) {
java = new UimaUMLInterface(top.getUimaPkgPattern());
}
java.setUmlModel(model);
java.setBuildQuestions(true);
File tempDir = Files.createTempDir();
tempDir.deleteOnExit();
String dAddr = tempDir.getAbsolutePath();
File zip = new File(dAddr + "/temp.zip");
java.buildJpaMavenProject(zip, null,
group, artifactId + "-jpa", version,
bmkegParentVersion);
File buildDir = new File(dAddr + "/jpaModel");
Converters.unzipIt(zip, buildDir);
String srcFileName = artifactId + "-jpa-" + version + "-src.jar";
String srcDirName = artifactId + "-jpa";
String srcFileAddr = dAddr + "/jpaModel/target/" + srcFileName;
File srcFile = new File(srcFileAddr);
Converters.copyFile(zip, new File(dir.getPath() + "/" + srcFileName));
Converters.unzipIt(zip, new File(dir.getPath() + "/" + srcDirName));
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Flex component build and deploy
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ActionscriptInterface as = new ActionscriptInterface();
as.setUmlModel(model);
zip = new File(dAddr + "/temp2.zip");
as.buildFlexMojoMavenProject(zip, null, group,
artifactId + "-as", version,
bmkegParentVersion);
Converters.unzipIt(zip, tempDir);
srcFileName = artifactId + "-as-" + version + "-src.zip";
srcDirName = artifactId + "-as-" + version + "-src";
srcFile = new File(dir.getPath() + "/" + srcFileName);
Converters.copyFile(zip, srcFile);
Converters.unzipIt(srcFile, new File(dir.getPath() ));
Converters.recursivelyDeleteFiles(tempDir);
System.out.println("Model libraries built:" + dir);
}
}
| false | true | public static void main(String[] args) throws Exception {
if( args.length < 3 ) {
System.err.println(USAGE);
System.exit(-1);
}
List<File> viewFiles = new ArrayList<File>();
List<File> dataFiles = new ArrayList<File>();
List<String> solrViews = new ArrayList<String>();
UMLmodel model = null;
File firstPom = new File( args[0].replaceAll("\\/$", "") + "/pom.xml" );
Model firstPomModel = VPDMfGeneratorConverters.readModelFromPom(firstPom);
VpdmfSpec firstSpecs = VPDMfGeneratorConverters.readVpdmfSpecFromPom(firstPomModel);
List<File> pomFiles = new ArrayList<File>();
List<String> pomPaths = new ArrayList<String>();
for (int i = 0; i < args.length - 2; i++) {
pomPaths.add(args[i]);
File specsFile = new File(args[i]);
pomFiles.add(specsFile);
}
File dir = new File(args[args.length - 2]);
dir.mkdirs();
String bmkegParentVersion = args[args.length - 1];
Iterator<File> it = pomFiles.iterator();
while (it.hasNext()) {
File pomFile = it.next();
//
// parse the specs files
//
Model pomModel = VPDMfGeneratorConverters.readModelFromPom(pomFile);
VpdmfSpec vpdmfSpec = VPDMfGeneratorConverters.readVpdmfSpecFromPom(pomModel);
// Model file
String modelPath = vpdmfSpec.getModel().getPath();
String modelType = vpdmfSpec.getModel().getType();
File modelFile = new File(pomFile.getParent() + "/" + modelPath);
// View directory
String viewsPath = vpdmfSpec.getViewsPath();
File viewsDir = new File(pomFile.getParent() + "/" + viewsPath);
viewFiles.addAll(VPDMfParser.getAllSpecFiles(viewsDir));
// solr views
solrViews.addAll(vpdmfSpec.getSolrViews());
// Data file
File data = null;
if (vpdmfSpec.getData() != null) {
String dataPath = vpdmfSpec.getData().getPath();
data = new File(dataPath);
if (!data.exists())
data = null;
else
dataFiles.add(data);
}
if (data != null)
System.out.println("Data File: " + data.getPath());
UMLModelSimpleParser p = new UMLModelSimpleParser(
UMLmodel.XMI_MAGICDRAW);
p.parseUMLModelFile(modelFile);
UMLmodel m = p.getUmlModels().get(0);
if (model == null) {
model = m;
} else {
model.mergeModel(m);
}
}
VPDMfParser vpdmfP = new VPDMfParser();
VPDMf top = vpdmfP.buildAllViews(firstSpecs, model, viewFiles,
solrViews);
if( firstSpecs.getUimaPackagePattern() != null && firstSpecs.getUimaPackagePattern().length() > 0 ) {
top.setUimaPkgPattern(firstSpecs.getUimaPackagePattern());
}
String group = top.getGroupId();
String artifactId = top.getArtifactId();
String version = top.getVersion();
// ~~~~~~~~~~~~~~~~~~~~
// Java component build
// ~~~~~~~~~~~~~~~~~~~~
JavaUmlInterface java = new JavaUmlInterface();
if( top.getUimaPkgPattern() != null && top.getUimaPkgPattern().length() > 0 ) {
java = new UimaUMLInterface(top.getUimaPkgPattern());
}
java.setUmlModel(model);
java.setBuildQuestions(true);
File tempDir = Files.createTempDir();
tempDir.deleteOnExit();
String dAddr = tempDir.getAbsolutePath();
File zip = new File(dAddr + "/temp.zip");
java.buildJpaMavenProject(zip, null,
group, artifactId + "-jpa", version,
bmkegParentVersion);
File buildDir = new File(dAddr + "/jpaModel");
Converters.unzipIt(zip, buildDir);
String srcFileName = artifactId + "-jpa-" + version + "-src.jar";
String srcDirName = artifactId + "-jpa";
String srcFileAddr = dAddr + "/jpaModel/target/" + srcFileName;
File srcFile = new File(srcFileAddr);
Converters.copyFile(zip, new File(dir.getPath() + "/" + srcFileName));
Converters.unzipIt(zip, new File(dir.getPath() + "/" + srcDirName));
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Flex component build and deploy
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ActionscriptInterface as = new ActionscriptInterface();
as.setUmlModel(model);
zip = new File(dAddr + "/temp2.zip");
as.buildFlexMojoMavenProject(zip, null, group,
artifactId + "-as", version,
bmkegParentVersion);
Converters.unzipIt(zip, tempDir);
srcFileName = artifactId + "-as-" + version + "-src.zip";
srcDirName = artifactId + "-as-" + version + "-src";
srcFile = new File(dir.getPath() + "/" + srcFileName);
Converters.copyFile(zip, srcFile);
Converters.unzipIt(srcFile, new File(dir.getPath() ));
Converters.recursivelyDeleteFiles(tempDir);
System.out.println("Model libraries built:" + dir);
}
| public static void main(String[] args) throws Exception {
if( args.length < 3 ) {
System.err.println(USAGE);
System.exit(-1);
}
List<File> viewFiles = new ArrayList<File>();
List<File> dataFiles = new ArrayList<File>();
List<String> solrViews = new ArrayList<String>();
UMLmodel model = null;
File firstPom = new File( args[0].replaceAll("\\/$", "") + "/pom.xml" );
Model firstPomModel = VPDMfGeneratorConverters.readModelFromPom(firstPom);
VpdmfSpec firstSpecs = VPDMfGeneratorConverters.readVpdmfSpecFromPom(firstPomModel);
List<File> pomFiles = new ArrayList<File>();
for (int i = 0; i < args.length - 2; i++) {
File pomFile = new File(args[i].replaceAll("\\/$", "") + "/pom.xml");
pomFiles.add(pomFile);
}
File dir = new File(args[args.length - 2]);
dir.mkdirs();
String bmkegParentVersion = args[args.length - 1];
Iterator<File> it = pomFiles.iterator();
while (it.hasNext()) {
File pomFile = it.next();
//
// parse the specs files
//
Model pomModel = VPDMfGeneratorConverters.readModelFromPom(pomFile);
VpdmfSpec vpdmfSpec = VPDMfGeneratorConverters.readVpdmfSpecFromPom(pomModel);
// Model file
String modelPath = vpdmfSpec.getModel().getPath();
String modelType = vpdmfSpec.getModel().getType();
File modelFile = new File(pomFile.getParent() + "/" + modelPath);
// View directory
String viewsPath = vpdmfSpec.getViewsPath();
File viewsDir = new File(pomFile.getParent() + "/" + viewsPath);
viewFiles.addAll(VPDMfParser.getAllSpecFiles(viewsDir));
// solr views
solrViews.addAll(vpdmfSpec.getSolrViews());
// Data file
File data = null;
if (vpdmfSpec.getData() != null) {
String dataPath = vpdmfSpec.getData().getPath();
data = new File(pomFile.getParent() + "/" + dataPath);
if (!data.exists())
data = null;
else
dataFiles.add(data);
}
if (data != null)
System.out.println("Data File: " + data.getPath());
UMLModelSimpleParser p = new UMLModelSimpleParser(
UMLmodel.XMI_MAGICDRAW);
p.parseUMLModelFile(modelFile);
UMLmodel m = p.getUmlModels().get(0);
if (model == null) {
model = m;
} else {
model.mergeModel(m);
}
}
VPDMfParser vpdmfP = new VPDMfParser();
VPDMf top = vpdmfP.buildAllViews(firstSpecs, model, viewFiles,
solrViews);
if( firstSpecs.getUimaPackagePattern() != null && firstSpecs.getUimaPackagePattern().length() > 0 ) {
top.setUimaPkgPattern(firstSpecs.getUimaPackagePattern());
}
String group = top.getGroupId();
String artifactId = top.getArtifactId();
String version = top.getVersion();
// ~~~~~~~~~~~~~~~~~~~~
// Java component build
// ~~~~~~~~~~~~~~~~~~~~
JavaUmlInterface java = new JavaUmlInterface();
if( top.getUimaPkgPattern() != null && top.getUimaPkgPattern().length() > 0 ) {
java = new UimaUMLInterface(top.getUimaPkgPattern());
}
java.setUmlModel(model);
java.setBuildQuestions(true);
File tempDir = Files.createTempDir();
tempDir.deleteOnExit();
String dAddr = tempDir.getAbsolutePath();
File zip = new File(dAddr + "/temp.zip");
java.buildJpaMavenProject(zip, null,
group, artifactId + "-jpa", version,
bmkegParentVersion);
File buildDir = new File(dAddr + "/jpaModel");
Converters.unzipIt(zip, buildDir);
String srcFileName = artifactId + "-jpa-" + version + "-src.jar";
String srcDirName = artifactId + "-jpa";
String srcFileAddr = dAddr + "/jpaModel/target/" + srcFileName;
File srcFile = new File(srcFileAddr);
Converters.copyFile(zip, new File(dir.getPath() + "/" + srcFileName));
Converters.unzipIt(zip, new File(dir.getPath() + "/" + srcDirName));
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Flex component build and deploy
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ActionscriptInterface as = new ActionscriptInterface();
as.setUmlModel(model);
zip = new File(dAddr + "/temp2.zip");
as.buildFlexMojoMavenProject(zip, null, group,
artifactId + "-as", version,
bmkegParentVersion);
Converters.unzipIt(zip, tempDir);
srcFileName = artifactId + "-as-" + version + "-src.zip";
srcDirName = artifactId + "-as-" + version + "-src";
srcFile = new File(dir.getPath() + "/" + srcFileName);
Converters.copyFile(zip, srcFile);
Converters.unzipIt(srcFile, new File(dir.getPath() ));
Converters.recursivelyDeleteFiles(tempDir);
System.out.println("Model libraries built:" + dir);
}
|
diff --git a/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/ContextHelpPart.java b/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/ContextHelpPart.java
index b28e0a9fe..31569207f 100644
--- a/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/ContextHelpPart.java
+++ b/org.eclipse.help.ui/src/org/eclipse/help/ui/internal/views/ContextHelpPart.java
@@ -1,615 +1,615 @@
/*******************************************************************************
* Copyright (c) 2000, 2007 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.help.ui.internal.views;
import org.eclipse.core.runtime.Platform;
import org.eclipse.help.HelpSystem;
import org.eclipse.help.ICommandLink;
import org.eclipse.help.IContext;
import org.eclipse.help.IContext2;
import org.eclipse.help.IContext3;
import org.eclipse.help.IContextProvider;
import org.eclipse.help.IHelpResource;
import org.eclipse.help.IToc;
import org.eclipse.help.ITopic;
import org.eclipse.help.UAContentFilter;
import org.eclipse.help.internal.HelpPlugin;
import org.eclipse.help.internal.base.HelpEvaluationContext;
import org.eclipse.help.ui.internal.ExecuteCommandAction;
import org.eclipse.help.ui.internal.HelpUIResources;
import org.eclipse.help.ui.internal.IHelpUIConstants;
import org.eclipse.help.ui.internal.Messages;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.dialogs.IDialogPage;
import org.eclipse.jface.dialogs.IPageChangeProvider;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.window.Window;
import org.eclipse.jface.wizard.IWizardContainer;
import org.eclipse.osgi.util.NLS;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.forms.IFormColors;
import org.eclipse.ui.forms.SectionPart;
import org.eclipse.ui.forms.events.ExpansionAdapter;
import org.eclipse.ui.forms.events.ExpansionEvent;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.events.IHyperlinkListener;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
public class ContextHelpPart extends SectionPart implements IHelpPart {
private ReusableHelpPart parent;
private static final String HELP_KEY = "org.eclipse.ui.help"; //$NON-NLS-1$
private FormText text;
private Control lastControl;
private IContextProvider lastProvider;
private IContext lastContext;
private IWorkbenchPart lastPart;
private String defaultText = ""; //$NON-NLS-1$
private String id;
private Font codeFont;
private String savedDescription;
/**
* @param parent
* @param toolkit
* @param style
*/
public ContextHelpPart(Composite parent, FormToolkit toolkit) {
super(parent, toolkit, Section.EXPANDED | Section.TWISTIE
| Section.TITLE_BAR);
Section section = getSection();
section.marginWidth = 5;
section.setText(Messages.ContextHelpPart_about);
Composite container = toolkit.createComposite(section);
section.setClient(container);
section.addExpansionListener(new ExpansionAdapter() {
public void expansionStateChanged(ExpansionEvent e) {
if (e.getState()) {
updateText(savedDescription);
}
}
});
TableWrapLayout layout = new TableWrapLayout();
layout.topMargin = layout.bottomMargin = 0;
layout.leftMargin = layout.rightMargin = 0;
layout.verticalSpacing = 10;
container.setLayout(layout);
text = toolkit.createFormText(container, false);
text.setWhitespaceNormalized(false);
text.setLayoutData(new TableWrapData(TableWrapData.FILL_GRAB));
text.setColor(IFormColors.TITLE, toolkit.getColors().getColor(
IFormColors.TITLE));
codeFont = createCodeFont(parent.getDisplay(), parent.getFont(), JFaceResources.getTextFont());
text.setFont("code", codeFont); //$NON-NLS-1$
String key = IHelpUIConstants.IMAGE_FILE_F1TOPIC;
text.setImage(key, HelpUIResources.getImage(key));
key = IHelpUIConstants.IMAGE_COMMAND_F1TOPIC;
text.setImage(key, HelpUIResources.getImage(key));
text.addHyperlinkListener(new IHyperlinkListener() {
public void linkActivated(HyperlinkEvent e) {
doOpenLink(e.getHref());
}
public void linkEntered(HyperlinkEvent e) {
ContextHelpPart.this.parent.handleLinkEntered(e);
}
public void linkExited(HyperlinkEvent e) {
ContextHelpPart.this.parent.handleLinkExited(e);
}
});
text.setText(defaultText, false, false);
}
private static Font createCodeFont(Display display, Font regularFont, Font textFont) {
FontData[] rfontData = regularFont.getFontData();
FontData[] tfontData = textFont.getFontData();
int height = 0;
for (int i=0; i<rfontData.length; i++) {
FontData data = rfontData[i];
height = Math.max(height, data.getHeight());
}
for (int i = 0; i < tfontData.length; i++) {
tfontData[i].setHeight(height);
}
return new Font(display, tfontData);
}
public void dispose() {
if (codeFont!=null)
codeFont.dispose();
codeFont = null;
super.dispose();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#getControl()
*/
public Control getControl() {
return getSection();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#init(org.eclipse.help.ui.internal.views.NewReusableHelpPart)
*/
public void init(ReusableHelpPart parent, String id, IMemento memento) {
this.parent = parent;
this.id = id;
parent.hookFormText(text);
}
public String getId() {
return id;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#setVisible(boolean)
*/
public void setVisible(boolean visible) {
getSection().setVisible(visible);
}
/**
* @return Returns the defaultText.
*/
public String getDefaultText() {
return defaultText;
}
/**
* @param defaultText
* The defaultText to set.
*/
public void setDefaultText(String defaultText) {
this.defaultText = defaultText;
if (text != null)
text.setText(defaultText, false, false);
}
private void doOpenLink(Object href) {
String sHref = (String)href;
if (sHref.startsWith("command://")) { //$NON-NLS-1$
doRunCommand(sHref.substring(10));
}
else {
parent.showURL(sHref);
}
}
private void doRunCommand(String serialization) {
ExecuteCommandAction action = new ExecuteCommandAction();
action.setInitializationString(serialization);
action.run();
}
public void handleActivation(Control c, IWorkbenchPart part) {
if (text.isDisposed())
return;
lastControl = c;
lastPart = part;
lastProvider = null;
String helpText = createContextHelp(c);
updateDescription(helpText);
updateDynamicHelp(false);
}
private void updateDescription(String helpText) {
if (getSection().isExpanded()) {
updateText(helpText);
}
savedDescription = helpText;
}
private void updateDynamicHelp(boolean explicitContext) {
if (explicitContext && lastContext instanceof IContext2) {
String title = ((IContext2)lastContext).getTitle();
if (title!=null) {
updateDynamicHelp(stripMnemonic(title), lastControl);
return;
}
}
if (lastProvider != null || lastControl != null)
updateDynamicHelp(lastProvider != null ? lastProvider
.getSearchExpression(lastControl) : null, lastControl);
}
public void handleActivation(IContextProvider provider, IContext context,
Control c,
IWorkbenchPart part) {
if (text.isDisposed())
return;
lastControl = c;
lastProvider = provider;
lastContext = context;
lastPart = part;
if (context==null && provider!=null) {
lastContext = provider.getContext(c);
}
String helpText;
if (lastContext!=null)
helpText = formatHelpContext(lastContext);
else
helpText = createContextHelp(c);
updateTitle();
updateDescription(helpText);
updateDynamicHelp(context!=null);
}
private void updateTitle() {
String title = null;
if (lastContext != null && lastContext instanceof IContext2) {
IContext2 c2 = (IContext2)lastContext;
title = c2.getTitle();
}
if (title==null && lastPart != null)
title = NLS.bind(Messages.ContextHelpPart_aboutP, lastPart
.getSite().getRegisteredName());
if (title==null)
title = Messages.ContextHelpPart_about;
getSection().setText(title);
}
private void updateText(String helpText) {
text.setText(helpText != null ? helpText : defaultText,
helpText != null,
false);
getSection().layout();
getManagedForm().reflow(true);
}
private void updateDynamicHelp(String expression, Control c) {
if (expression == null) {
expression = computeDefaultSearchExpression(c);
}
RelatedTopicsPart part = (RelatedTopicsPart) parent
.findPart(IHelpUIConstants.HV_RELATED_TOPICS);
if (part != null) {
if (expression != null) {
if (HelpPlugin.DEBUG_CONTEXT) {
System.out.println("Dynamic help - search for " + expression); //$NON-NLS-1$
}
part.startSearch(expression, lastContext);
}
}
}
private String computeDefaultSearchExpression(Control c) {
StringBuffer buff = new StringBuffer();
Composite parent = c.getParent();
while (parent != null) {
Object data = parent.getData();
if (data instanceof IWizardContainer) {
IWizardContainer wc = (IWizardContainer) data;
buff.append("\""); //$NON-NLS-1$
buff.append(wc.getCurrentPage().getTitle());
buff.append("\" OR \""); //$NON-NLS-1$
buff.append(wc.getCurrentPage().getWizard().getWindowTitle());
buff.append("\""); //$NON-NLS-1$
break;
} else if (data instanceof IWorkbenchWindow) {
IWorkbenchWindow window = (IWorkbenchWindow) data;
IWorkbenchPage page = window.getActivePage();
if (page != null) {
IWorkbenchPart part = lastPart;
if (part != null) {
buff.append("\""); //$NON-NLS-1$
if (part instanceof IViewPart)
buff.append(NLS.bind(
Messages.ContextHelpPart_query_view, part
.getSite().getRegisteredName()));
buff.append("\" "); //$NON-NLS-1$
}
IPerspectiveDescriptor persp = page.getPerspective();
if (persp != null) {
if (buff.length() > 0)
buff.append("OR "); //$NON-NLS-1$
buff.append("\""); //$NON-NLS-1$
buff.append(NLS.bind(
Messages.ContextHelpPart_query_perspective,
persp.getLabel()));
buff.append("\""); //$NON-NLS-1$
}
}
break;
} else if (data instanceof Window) {
Window w = (Window) data;
if (w instanceof IPageChangeProvider) {
Object page = ((IPageChangeProvider) w).getSelectedPage();
String pageName = getPageName(c, page);
if (pageName != null) {
buff.append("\""); //$NON-NLS-1$
buff.append(pageName);
buff.append("\" "); //$NON-NLS-1$
}
}
if (buff.length() > 0)
buff.append("OR "); //$NON-NLS-1$
buff.append("\""); //$NON-NLS-1$
buff.append(w.getShell().getText());
buff.append("\""); //$NON-NLS-1$
break;
}
parent = parent.getParent();
}
return buff.length() > 0 ? buff.toString().trim() : null;
}
private String getPageName(Control focusControl, Object page) {
if (page instanceof IDialogPage)
return ((IDialogPage) page).getTitle();
if (focusControl == null)
return null;
Composite parent = focusControl.getParent();
while (parent != null) {
if (parent instanceof TabFolder) {
TabItem[] selection = ((TabFolder) parent).getSelection();
if (selection.length == 1)
return stripMnemonic(selection[0].getText());
} else if (parent instanceof CTabFolder) {
CTabItem selection = ((CTabFolder) parent).getSelection();
return stripMnemonic(selection.getText());
}
parent = parent.getParent();
}
return null;
}
private String stripMnemonic(String name) {
int loc = name.indexOf('&');
if (loc!= -1)
return name.substring(0, loc)+name.substring(loc+1);
return name;
}
private String createContextHelp(Control page) {
String text = null;
lastContext = null;
if (page != null) {
if (page != null /* && page.isVisible() */&& !page.isDisposed()) {
IContext helpContext = findHelpContext(page);
if (helpContext != null) {
text = formatHelpContext(helpContext);
lastContext = helpContext;
}
}
}
return text;
}
public static IContext findHelpContext(Control c) {
String contextId = null;
Control node = c;
do {
contextId = (String) node.getData(HELP_KEY);
if (contextId != null)
break;
node = node.getParent();
} while (node != null);
if (contextId != null) {
return HelpSystem.getContext(contextId);
}
return null;
}
private String formatHelpContext(IContext context) {
String locale = Platform.getNL();
StringBuffer sbuf = new StringBuffer();
sbuf.append("<form>"); //$NON-NLS-1$
sbuf.append("<p>"); //$NON-NLS-1$
sbuf.append(decodeContextBoldTags(context));
sbuf.append("</p>"); //$NON-NLS-1$
ICommandLink[] commands = null;
if (context instanceof IContext3) {
commands = ((IContext3)context).getRelatedCommands();
}
String category = new String();
if (commands != null && commands.length > 0) {
for (int i=0;i<commands.length;++i) {
if (!UAContentFilter.isFiltered(commands[i], HelpEvaluationContext.getContext())) {
if (category != null) {
addCategory(sbuf, null);
}
category = null;
sbuf.append("<li style=\"image\" value=\""); //$NON-NLS-1$
sbuf.append(IHelpUIConstants.IMAGE_COMMAND_F1TOPIC);
sbuf.append("\" indent=\"21\">"); //$NON-NLS-1$
sbuf.append("<a href=\"command://"); //$NON-NLS-1$
sbuf.append(commands[i].getSerialization());
sbuf.append("\">"); //$NON-NLS-1$
sbuf.append(parent.escapeSpecialChars(commands[i].getLabel()));
sbuf.append("</a>"); //$NON-NLS-1$
sbuf.append("</li>"); //$NON-NLS-1$
}
}
}
IHelpResource[] links = context.getRelatedTopics();
if (links != null && context instanceof IContext2) {
ContextHelpSorter sorter = new ContextHelpSorter((IContext2)context);
sorter.sort(null, links);
}
if (links != null && links.length > 0) {
for (int i = 0; i < links.length; i++) {
IHelpResource link = links[i];
if (!UAContentFilter.isFiltered(link, HelpEvaluationContext.getContext())) {
String cat = null;
if (context instanceof IContext2) {
cat = ((IContext2)context).getCategory(link);
}
if (cat == null && category != null || cat != null
&& category == null || cat != null
&& category != null && !cat.equals(category)) {
addCategory(sbuf, cat);
}
category = cat;
sbuf.append("<li style=\"image\" value=\""); //$NON-NLS-1$
sbuf.append(IHelpUIConstants.IMAGE_FILE_F1TOPIC);
sbuf.append("\" indent=\"21\">"); //$NON-NLS-1$
sbuf.append("<a href=\""); //$NON-NLS-1$
sbuf.append(link.getHref());
String tcat = getTopicCategory(link.getHref(), locale);
if (tcat != null && !Platform.getWS().equals(Platform.WS_GTK)) {
sbuf.append("\" alt=\""); //$NON-NLS-1$
- sbuf.append(tcat);
+ sbuf.append(parent.escapeSpecialChars(tcat));
}
sbuf.append("\">"); //$NON-NLS-1$
sbuf.append(parent.escapeSpecialChars(link.getLabel()));
sbuf.append("</a>"); //$NON-NLS-1$
sbuf.append("</li>"); //$NON-NLS-1$
}
}
}
sbuf.append("</form>"); //$NON-NLS-1$
return sbuf.toString();
}
private void addCategory(StringBuffer sbuf, String category) {
if (category == null)
category = Messages.ContextHelpPart_seeAlso;
sbuf.append("<p><span color=\""); //$NON-NLS-1$
sbuf.append(IFormColors.TITLE);
sbuf.append("\">"); //$NON-NLS-1$
sbuf.append(category);
sbuf.append("</span></p>"); //$NON-NLS-1$
}
private String getTopicCategory(String href, String locale) {
IToc[] tocs = HelpPlugin.getTocManager().getTocs(locale);
for (int i = 0; i < tocs.length; i++) {
ITopic topic = tocs[i].getTopic(href);
if (topic != null)
return tocs[i].getLabel();
}
return null;
}
/**
* Make sure to support the Help system bold tag. Help systen returns a
* regular string for getText(). Use internal apis for now to get bold.
*
* @param context
* @return
*/
private String decodeContextBoldTags(IContext context) {
String styledText;
if (context instanceof IContext2) {
styledText = ((IContext2) context).getStyledText();
if (styledText == null) {
styledText = context.getText();
}
} else {
styledText = context.getText();
}
if (styledText == null) {
return Messages.ContextHelpPart_noDescription;
}
String decodedString = styledText.replaceAll("<@#\\$b>", "<b>"); //$NON-NLS-1$ //$NON-NLS-2$
decodedString = decodedString.replaceAll("</@#\\$b>", "</b>"); //$NON-NLS-1$ //$NON-NLS-2$
decodedString = parent.escapeSpecialChars(decodedString, true);
decodedString = decodedString.replaceAll("\r\n|\n|\r", "<br/>"); //$NON-NLS-1$ //$NON-NLS-2$
return decodedString;
}
public boolean setFormInput(Object input) {
if (input instanceof ContextHelpProviderInput) {
ContextHelpProviderInput chinput = (ContextHelpProviderInput) input;
//if (chinput.getContext() != null)
handleActivation(chinput.getProvider(), chinput.getContext(), chinput.getControl(),
chinput.getPart());
//else
//handleActivation(chinput.getProvider(), chinput.getControl(),
// chinput.getPart());
return true;
}
return false;
}
public void setFocus() {
if (text != null)
text.setFocus();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#fillContextMenu(org.eclipse.jface.action.IMenuManager)
*/
public boolean fillContextMenu(IMenuManager manager) {
return parent.fillFormContextMenu(text, manager);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.help.ui.internal.views.IHelpPart#hasFocusControl(org.eclipse.swt.widgets.Control)
*/
public boolean hasFocusControl(Control control) {
return text.equals(control);
}
public IAction getGlobalAction(String id) {
if (id.equals(ActionFactory.COPY.getId()))
return parent.getCopyAction();
return null;
}
public void stop() {
}
public void toggleRoleFilter() {
}
public void refilter() {
}
public void saveState(IMemento memento) {
}
}
| true | true | private String formatHelpContext(IContext context) {
String locale = Platform.getNL();
StringBuffer sbuf = new StringBuffer();
sbuf.append("<form>"); //$NON-NLS-1$
sbuf.append("<p>"); //$NON-NLS-1$
sbuf.append(decodeContextBoldTags(context));
sbuf.append("</p>"); //$NON-NLS-1$
ICommandLink[] commands = null;
if (context instanceof IContext3) {
commands = ((IContext3)context).getRelatedCommands();
}
String category = new String();
if (commands != null && commands.length > 0) {
for (int i=0;i<commands.length;++i) {
if (!UAContentFilter.isFiltered(commands[i], HelpEvaluationContext.getContext())) {
if (category != null) {
addCategory(sbuf, null);
}
category = null;
sbuf.append("<li style=\"image\" value=\""); //$NON-NLS-1$
sbuf.append(IHelpUIConstants.IMAGE_COMMAND_F1TOPIC);
sbuf.append("\" indent=\"21\">"); //$NON-NLS-1$
sbuf.append("<a href=\"command://"); //$NON-NLS-1$
sbuf.append(commands[i].getSerialization());
sbuf.append("\">"); //$NON-NLS-1$
sbuf.append(parent.escapeSpecialChars(commands[i].getLabel()));
sbuf.append("</a>"); //$NON-NLS-1$
sbuf.append("</li>"); //$NON-NLS-1$
}
}
}
IHelpResource[] links = context.getRelatedTopics();
if (links != null && context instanceof IContext2) {
ContextHelpSorter sorter = new ContextHelpSorter((IContext2)context);
sorter.sort(null, links);
}
if (links != null && links.length > 0) {
for (int i = 0; i < links.length; i++) {
IHelpResource link = links[i];
if (!UAContentFilter.isFiltered(link, HelpEvaluationContext.getContext())) {
String cat = null;
if (context instanceof IContext2) {
cat = ((IContext2)context).getCategory(link);
}
if (cat == null && category != null || cat != null
&& category == null || cat != null
&& category != null && !cat.equals(category)) {
addCategory(sbuf, cat);
}
category = cat;
sbuf.append("<li style=\"image\" value=\""); //$NON-NLS-1$
sbuf.append(IHelpUIConstants.IMAGE_FILE_F1TOPIC);
sbuf.append("\" indent=\"21\">"); //$NON-NLS-1$
sbuf.append("<a href=\""); //$NON-NLS-1$
sbuf.append(link.getHref());
String tcat = getTopicCategory(link.getHref(), locale);
if (tcat != null && !Platform.getWS().equals(Platform.WS_GTK)) {
sbuf.append("\" alt=\""); //$NON-NLS-1$
sbuf.append(tcat);
}
sbuf.append("\">"); //$NON-NLS-1$
sbuf.append(parent.escapeSpecialChars(link.getLabel()));
sbuf.append("</a>"); //$NON-NLS-1$
sbuf.append("</li>"); //$NON-NLS-1$
}
}
}
sbuf.append("</form>"); //$NON-NLS-1$
return sbuf.toString();
}
| private String formatHelpContext(IContext context) {
String locale = Platform.getNL();
StringBuffer sbuf = new StringBuffer();
sbuf.append("<form>"); //$NON-NLS-1$
sbuf.append("<p>"); //$NON-NLS-1$
sbuf.append(decodeContextBoldTags(context));
sbuf.append("</p>"); //$NON-NLS-1$
ICommandLink[] commands = null;
if (context instanceof IContext3) {
commands = ((IContext3)context).getRelatedCommands();
}
String category = new String();
if (commands != null && commands.length > 0) {
for (int i=0;i<commands.length;++i) {
if (!UAContentFilter.isFiltered(commands[i], HelpEvaluationContext.getContext())) {
if (category != null) {
addCategory(sbuf, null);
}
category = null;
sbuf.append("<li style=\"image\" value=\""); //$NON-NLS-1$
sbuf.append(IHelpUIConstants.IMAGE_COMMAND_F1TOPIC);
sbuf.append("\" indent=\"21\">"); //$NON-NLS-1$
sbuf.append("<a href=\"command://"); //$NON-NLS-1$
sbuf.append(commands[i].getSerialization());
sbuf.append("\">"); //$NON-NLS-1$
sbuf.append(parent.escapeSpecialChars(commands[i].getLabel()));
sbuf.append("</a>"); //$NON-NLS-1$
sbuf.append("</li>"); //$NON-NLS-1$
}
}
}
IHelpResource[] links = context.getRelatedTopics();
if (links != null && context instanceof IContext2) {
ContextHelpSorter sorter = new ContextHelpSorter((IContext2)context);
sorter.sort(null, links);
}
if (links != null && links.length > 0) {
for (int i = 0; i < links.length; i++) {
IHelpResource link = links[i];
if (!UAContentFilter.isFiltered(link, HelpEvaluationContext.getContext())) {
String cat = null;
if (context instanceof IContext2) {
cat = ((IContext2)context).getCategory(link);
}
if (cat == null && category != null || cat != null
&& category == null || cat != null
&& category != null && !cat.equals(category)) {
addCategory(sbuf, cat);
}
category = cat;
sbuf.append("<li style=\"image\" value=\""); //$NON-NLS-1$
sbuf.append(IHelpUIConstants.IMAGE_FILE_F1TOPIC);
sbuf.append("\" indent=\"21\">"); //$NON-NLS-1$
sbuf.append("<a href=\""); //$NON-NLS-1$
sbuf.append(link.getHref());
String tcat = getTopicCategory(link.getHref(), locale);
if (tcat != null && !Platform.getWS().equals(Platform.WS_GTK)) {
sbuf.append("\" alt=\""); //$NON-NLS-1$
sbuf.append(parent.escapeSpecialChars(tcat));
}
sbuf.append("\">"); //$NON-NLS-1$
sbuf.append(parent.escapeSpecialChars(link.getLabel()));
sbuf.append("</a>"); //$NON-NLS-1$
sbuf.append("</li>"); //$NON-NLS-1$
}
}
}
sbuf.append("</form>"); //$NON-NLS-1$
return sbuf.toString();
}
|
diff --git a/conpaas-services/src/conpaas/services/taskfarm/src/org/koala/runnersFramework/runners/bot/OpenNebulaOcaCluster.java b/conpaas-services/src/conpaas/services/taskfarm/src/org/koala/runnersFramework/runners/bot/OpenNebulaOcaCluster.java
index 8923a7c..e21614d 100644
--- a/conpaas-services/src/conpaas/services/taskfarm/src/org/koala/runnersFramework/runners/bot/OpenNebulaOcaCluster.java
+++ b/conpaas-services/src/conpaas/services/taskfarm/src/org/koala/runnersFramework/runners/bot/OpenNebulaOcaCluster.java
@@ -1,267 +1,267 @@
package org.koala.runnersFramework.runners.bot;
import ibis.ipl.Ibis;
import ibis.ipl.IbisIdentifier;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.opennebula.client.Client;
import org.opennebula.client.OneResponse;
import org.opennebula.client.vm.VirtualMachine;
public class OpenNebulaOcaCluster extends Cluster {
private static final long serialVersionUID = -3283811123364250109L;
public transient int currentNoNodes = 0;
public int image_id, network_id;
public String mem;
public String dns, gateway;
/*number of CPUs for the VM*/
public String speedFactor;
/**
* Map used for shutting down the machines from the managerial level.
* Maps location to VM id.
*/
public HashMap<String, String> map = new HashMap<String, String>();
/**
* Object used to execute ONE commands.
*/
public transient Client oneClient = null;
/**
* irrelevant dns and gateway default values.
*/
public static final String DNS = "130.73.79.13";
public static final String Gateway = "10.0.0.1";
public static final String DEF_MEM = "400";
public OpenNebulaOcaCluster(String hostname, int port, String alias, long timeUnit,
double costUnit, int maxNodes, String speedFactor,
int image_id, int network_id,
String mem, String dns, String gateway, String e) {
super(hostname, alias, timeUnit, costUnit, maxNodes);
this.image_id = image_id;
this.network_id = network_id;
this.speedFactor = speedFactor;
if((mem != null) && (!mem.equals(""))) {
this.mem = mem;
} else {
this.mem = DEF_MEM;
}
if((dns != null) && (!dns.equals(""))) {
this.dns = dns;
} else {
this.dns = DNS;
}
if((gateway != null) && (!gateway.equals(""))) {
this.gateway = dns;
} else {
this.gateway = Gateway;
}
}
public OpenNebulaOcaCluster(ClusterMetadata cm) {
super(cm.hostName, cm.alias, cm.timeUnit, cm.costUnit, cm.maxNodes);
this.image_id = cm.image_id;
this.network_id = cm.network_id;
this.speedFactor = cm.speedFactor;
this.mem = DEF_MEM;
if((cm.dns != null) && (!cm.dns.equals(""))) {
this.dns = cm.dns;
} else {
this.dns = DNS;
}
if(!"".equals(cm.gateway)) {
this.gateway = cm.gateway;
} else {
this.gateway = Gateway;
}
}
private void setOneClient() {
if (oneClient == null) {
try {
/*
* First of all, a Client object has to be created.
* Here the client will try to connect to OpenNebula using the default
* options: the auth file is assumed to be at $ONE_AUTH, and the
* endpoint will be set to the environment variable $ONE_XMLRPC.
*
* $ONE_AUTH=~/.one/one_auth
* $ONE_XMLRPC=http://localhost:2633/RPC2
*/
String auth, xmlrpc;
auth = System.getenv().get("ONE_AUTH");
xmlrpc = System.getenv().get("ONE_XMLRPC");
System.out.println("Initializing ONE client with one_auth=" + auth + " and one_xmlrpc=" + xmlrpc);
oneClient = new Client();
System.out.println("ONE client initialized...");
} catch (Exception ex) {
Logger.getLogger(OpenNebulaOcaCluster.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public Process startNodes(String time, int noWorkers,
String electionName, String poolName, String serverAddress) {
System.out.println("Starting " + noWorkers + " workers with ONE...");
// XXX: in ConPaaS, IP_PUBLIC is passed as an environment variable
// This needs to go upper in the call tree when all the bindings
// are supported by ConPaaS.
String newServerAddress = System.getenv().get("IP_PUBLIC");
if(newServerAddress != null)
{
- serverAddress = newServerAddress;
+ // serverAddress = newServerAddress;
}
- System.out.println("Ibis server address is " + serverAddress);
+ System.out.println("Ibis server address is: old: " + serverAddress + " new: " + newServerAddress);
// place here and not in constructor, because client is not serializable,
// so when the deserializing at the Executor occurs, oneClient will be null.
setOneClient();
String vmTemplate, vmId, location;
OneResponse rc;
/*
* I understand this caused you trouble, so I commented it out
if (noWorkers == 0 || (currentNoNodes + noWorkers >= maxNodes)) {
return null;
}
*/
int noWorkersNotStarted = 0, currentNo;
for (int i = 0; i < noWorkers; i++) {
currentNo = currentNoNodes + i - noWorkersNotStarted;
location = "node" + currentNo + "@" + alias;
// create a VM template
vmTemplate = createVMTemplate(electionName, poolName, serverAddress,
speedFactor, location);
rc = VirtualMachine.allocate(oneClient, vmTemplate);
if (rc.isError()) {
System.err.println("Failed starting the "
+ currentNo + "-th worker!\nError msg: "
+ rc.getErrorMessage()
+ "\nONE template:\n"
+ vmTemplate);
System.err.flush();
noWorkersNotStarted++;
continue;
}
// The response message is the new VM's ID
vmId = rc.getMessage();
System.out.println("ONE worker with id " + vmId + " started ...");
// Gather information about the virtual machines and place it in the hash map
map.put(location, vmId);
System.out.println("Ibis node with location " + location);
}
currentNoNodes += noWorkers - noWorkersNotStarted;
return null;
}
private String createVMTemplate(String electionName, String poolName,
String serverAddress, String speedFactor, String location) {
String vmTemplate =
"NAME = BoTSVM\n"
+ "CPU = " + speedFactor + "\n"
+ "MEMORY = " + mem + "\n\n"
+ "OS = [\n"
+ "arch = x86_64\n"
+ "]\n\n"
+ "DISK = [\n"
+ "IMAGE_ID = " + image_id + ",\n"
+ "target = \"sda\"\n"
+ "]\n\n"
+ "NIC = [\n"
+ "NETWORK_ID = " + network_id +"\n"
+ "]\n\n"
+ "GRAPHICS = [\n"
+ "TYPE = \"vnc\",\n"
+ "LISTEN = \"0.0.0.0\"\n"
+ "]\n\n"
+ "FEATURES = [\n"
+ "acpi=\"yes\"\n"
+ "]\n\n"
+ "RAW = [\n"
+ "type = \"kvm\",\n"
+ "data = \" <serial type='pty'> <source path='/dev/pts/3'/> <target port='1'/> </serial>\"\n"
+ "]\n\n"
+ "CONTEXT = [\n"
+ "hostname = \"$NAME\",\n"
/*+ "dns = \"$NETWORK[DNS, NAME=\\\"Small network\\\"]\",\n"*/
+ "nameserver = " + dns + ",\n"
/* + "gateway = \"$NETWORK[GATEWAY, NAME=\\\"Small network\\\"]\",\n"*/
+ "ip_gateway = " + gateway + ",\n"
// + "ip_public = \"$NIC[IP, NETWORK=\\\"Private LAN\\\"]\",\n"
+ "ip_public = \"$NIC[IP]\",\n"
/* variables required by a BoT worker */
+ "LOCATION=\"" + location + "\",\n"
+ "ELECTIONNAME=\"" + electionName + "\",\n"
+ "POOLNAME=\"" + poolName + "\",\n"
+ "SERVERADDRESS=\"" + serverAddress + "\",\n"
+ "SPEEDFACTOR=\"" + speedFactor + "\",\n"
+ "MOUNTURL=\"" + BoTRunner.filesLocationUrl + "\",\n"
/* end of vars req by a BoT worker */
/* variables required for calling the ONE service */
+ "ONE_XMLRPC=\"" + System.getenv().get("ONE_XMLRPC") + "\",\n"
+ "ONE_AUTH_CONTENT=\"" +
getOneAuthContent(System.getenv().get("ONE_AUTH")) + "\",\n"
+ "VM_ID = \"$VMID\",\n"
/* end - ONE service vars */
/*ISSUE: + "files = \"" + pathToInitSh + " " + pathToIdRsaPub + "\",\n"*/
/* PAY ATTENTION: this will work only if the worker's image is set to run $USERDATA*/
+ "USERDATA = \"" + getHexContent(System.getenv("HEX_FILE")) + "\",\n"
+ "target = \"sdb\"\n"
+ "]\n";
return vmTemplate;
}
private String getOneAuthContent(String oneAuthFile) {
try {
BufferedReader br = new BufferedReader(new FileReader(oneAuthFile));
String retVal = br.readLine();
br.close();
return retVal;
} catch (Exception ex) {
return "";
}
}
private String getHexContent(String hexFile) {
try {
BufferedReader br = new BufferedReader(new FileReader(hexFile));
StringBuilder retVal = new StringBuilder();
String line;
while( (line = br.readLine()) != null) {
retVal.append(line).append("\n");
}
br.close();
return retVal.toString();
} catch (Exception ex) {
return "";
}
}
@Override
public void terminateNode(IbisIdentifier node, Ibis myIbis)
throws IOException {
myIbis.registry().signal("die", node);
}
}
| false | true | public Process startNodes(String time, int noWorkers,
String electionName, String poolName, String serverAddress) {
System.out.println("Starting " + noWorkers + " workers with ONE...");
// XXX: in ConPaaS, IP_PUBLIC is passed as an environment variable
// This needs to go upper in the call tree when all the bindings
// are supported by ConPaaS.
String newServerAddress = System.getenv().get("IP_PUBLIC");
if(newServerAddress != null)
{
serverAddress = newServerAddress;
}
System.out.println("Ibis server address is " + serverAddress);
// place here and not in constructor, because client is not serializable,
// so when the deserializing at the Executor occurs, oneClient will be null.
setOneClient();
String vmTemplate, vmId, location;
OneResponse rc;
/*
* I understand this caused you trouble, so I commented it out
if (noWorkers == 0 || (currentNoNodes + noWorkers >= maxNodes)) {
return null;
}
*/
int noWorkersNotStarted = 0, currentNo;
for (int i = 0; i < noWorkers; i++) {
currentNo = currentNoNodes + i - noWorkersNotStarted;
location = "node" + currentNo + "@" + alias;
// create a VM template
vmTemplate = createVMTemplate(electionName, poolName, serverAddress,
speedFactor, location);
rc = VirtualMachine.allocate(oneClient, vmTemplate);
if (rc.isError()) {
System.err.println("Failed starting the "
+ currentNo + "-th worker!\nError msg: "
+ rc.getErrorMessage()
+ "\nONE template:\n"
+ vmTemplate);
System.err.flush();
noWorkersNotStarted++;
continue;
}
// The response message is the new VM's ID
vmId = rc.getMessage();
System.out.println("ONE worker with id " + vmId + " started ...");
// Gather information about the virtual machines and place it in the hash map
map.put(location, vmId);
System.out.println("Ibis node with location " + location);
}
currentNoNodes += noWorkers - noWorkersNotStarted;
return null;
}
| public Process startNodes(String time, int noWorkers,
String electionName, String poolName, String serverAddress) {
System.out.println("Starting " + noWorkers + " workers with ONE...");
// XXX: in ConPaaS, IP_PUBLIC is passed as an environment variable
// This needs to go upper in the call tree when all the bindings
// are supported by ConPaaS.
String newServerAddress = System.getenv().get("IP_PUBLIC");
if(newServerAddress != null)
{
// serverAddress = newServerAddress;
}
System.out.println("Ibis server address is: old: " + serverAddress + " new: " + newServerAddress);
// place here and not in constructor, because client is not serializable,
// so when the deserializing at the Executor occurs, oneClient will be null.
setOneClient();
String vmTemplate, vmId, location;
OneResponse rc;
/*
* I understand this caused you trouble, so I commented it out
if (noWorkers == 0 || (currentNoNodes + noWorkers >= maxNodes)) {
return null;
}
*/
int noWorkersNotStarted = 0, currentNo;
for (int i = 0; i < noWorkers; i++) {
currentNo = currentNoNodes + i - noWorkersNotStarted;
location = "node" + currentNo + "@" + alias;
// create a VM template
vmTemplate = createVMTemplate(electionName, poolName, serverAddress,
speedFactor, location);
rc = VirtualMachine.allocate(oneClient, vmTemplate);
if (rc.isError()) {
System.err.println("Failed starting the "
+ currentNo + "-th worker!\nError msg: "
+ rc.getErrorMessage()
+ "\nONE template:\n"
+ vmTemplate);
System.err.flush();
noWorkersNotStarted++;
continue;
}
// The response message is the new VM's ID
vmId = rc.getMessage();
System.out.println("ONE worker with id " + vmId + " started ...");
// Gather information about the virtual machines and place it in the hash map
map.put(location, vmId);
System.out.println("Ibis node with location " + location);
}
currentNoNodes += noWorkers - noWorkersNotStarted;
return null;
}
|
diff --git a/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/ast/check/UndocumentedApiCheck.java b/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/ast/check/UndocumentedApiCheck.java
index a14d42a382..221725b478 100644
--- a/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/ast/check/UndocumentedApiCheck.java
+++ b/plugins/sonar-squid-java-plugin/src/main/java/org/sonar/java/ast/check/UndocumentedApiCheck.java
@@ -1,85 +1,85 @@
/*
* Sonar, open source software quality management tool.
* Copyright (C) 2009 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* Sonar 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.
*
* Sonar 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 Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.java.ast.check;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.sonar.api.utils.WildcardPattern;
import org.sonar.check.IsoCategory;
import org.sonar.check.Priority;
import org.sonar.check.Rule;
import org.sonar.check.RuleProperty;
import org.sonar.java.PatternUtils;
import org.sonar.java.ast.visitor.PublicApiVisitor;
import org.sonar.squid.api.CheckMessage;
import org.sonar.squid.api.SourceClass;
import org.sonar.squid.api.SourceCode;
import org.sonar.squid.api.SourceFile;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
@Rule(key = "UndocumentedApi", name = "Undocumented API", isoCategory = IsoCategory.Usability, priority = Priority.MAJOR,
description = "<p>Check that each public class, interface, method and constructor has a Javadoc comment. "
+ "The following public methods/constructors are not concerned by this rule :</p>" + "<ul><li>Getter / Setter</li>"
+ "<li>Method with @Override annotation</li>" + "<li>Empty constructor</li></ul>")
public class UndocumentedApiCheck extends JavaAstCheck {
@RuleProperty(description = "Optional. If this property is not defined, all classes should adhere to this constraint. Ex : **.api.**")
private String forClasses = new String();
private WildcardPattern[] patterns;
@Override
public List<Integer> getWantedTokens() {
return PublicApiVisitor.TOKENS;
}
@Override
public void visitToken(DetailAST ast) {
SourceCode currentResource = peekSourceCode();
SourceClass sourceClass = peekParentClass();
if (WildcardPattern.match(getPatterns(), sourceClass.getKey())) {
if (PublicApiVisitor.isPublicApi(ast) && !PublicApiVisitor.isDocumentedApi(ast, getFileContents())) {
SourceFile sourceFile = currentResource.getParent(SourceFile.class);
- CheckMessage message = new CheckMessage(this, "Avoid undocumented API");
+ CheckMessage message = new CheckMessage(this, "Avoid undocumented API.");
message.setLine(ast.getLineNo());
sourceFile.log(message);
}
}
}
private WildcardPattern[] getPatterns() {
if (patterns == null) {
patterns = PatternUtils.createPatterns(StringUtils.defaultIfEmpty(forClasses, "**"));
}
return patterns;
}
public String getForClasses() {
return forClasses;
}
public void setForClasses(String forClasses) {
this.forClasses = forClasses;
}
}
| true | true | public void visitToken(DetailAST ast) {
SourceCode currentResource = peekSourceCode();
SourceClass sourceClass = peekParentClass();
if (WildcardPattern.match(getPatterns(), sourceClass.getKey())) {
if (PublicApiVisitor.isPublicApi(ast) && !PublicApiVisitor.isDocumentedApi(ast, getFileContents())) {
SourceFile sourceFile = currentResource.getParent(SourceFile.class);
CheckMessage message = new CheckMessage(this, "Avoid undocumented API");
message.setLine(ast.getLineNo());
sourceFile.log(message);
}
}
}
| public void visitToken(DetailAST ast) {
SourceCode currentResource = peekSourceCode();
SourceClass sourceClass = peekParentClass();
if (WildcardPattern.match(getPatterns(), sourceClass.getKey())) {
if (PublicApiVisitor.isPublicApi(ast) && !PublicApiVisitor.isDocumentedApi(ast, getFileContents())) {
SourceFile sourceFile = currentResource.getParent(SourceFile.class);
CheckMessage message = new CheckMessage(this, "Avoid undocumented API.");
message.setLine(ast.getLineNo());
sourceFile.log(message);
}
}
}
|
diff --git a/src/main/java/org/urish/gwtit/titanium/ui/events/RowClickEvent.java b/src/main/java/org/urish/gwtit/titanium/ui/events/RowClickEvent.java
index 3feeb69..6138da3 100644
--- a/src/main/java/org/urish/gwtit/titanium/ui/events/RowClickEvent.java
+++ b/src/main/java/org/urish/gwtit/titanium/ui/events/RowClickEvent.java
@@ -1,67 +1,67 @@
/*
* Copyright 2011 Uri Shaked
*
* 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.
*/
/* Automatically generated code, don't edit ! */
package org.urish.gwtit.titanium.ui.events;
import org.urish.gwtit.client.event.TouchEvent;
import com.google.gwt.core.client.JavaScriptObject;
/**
*
*/
public class RowClickEvent extends TouchEvent {
public final static String NATIVE_EVENT_NAME = "click";
protected RowClickEvent() {
}
/**
* table view row index
*/
- public final native float getIndex()
+ public final native int getIndex()
/*-{
return this.index;
}-*/;
/**
* table view section object
*/
public final native org.urish.gwtit.titanium.ui.TableViewSection getSection()
/*-{
return this.section;
}-*/;
/**
* table view row data object
*/
public final native JavaScriptObject getRowData()
/*-{
return this.rowData;
}-*/;
/**
* table view row that was clicked
*/
public final native org.urish.gwtit.titanium.ui.TableViewRow getRow()
/*-{
return this.row;
}-*/;
}
| true | true | public final native float getIndex()
/*-{
return this.index;
| public final native int getIndex()
/*-{
return this.index;
|
diff --git a/Dashboard/src/dashboard/servlet/LoginServlet.java b/Dashboard/src/dashboard/servlet/LoginServlet.java
index 68f6b02..101c83d 100644
--- a/Dashboard/src/dashboard/servlet/LoginServlet.java
+++ b/Dashboard/src/dashboard/servlet/LoginServlet.java
@@ -1,55 +1,55 @@
package dashboard.servlet;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dashboard.model.Student;
import dashboard.registry.StudentRegistry;
import dashboard.util.OwnOfy;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = -2516739187837047286L;
/**
* Called when a user tries to log in on the login.jsp page
* @param req
* @param resp
* @throws IOException
*/
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
HttpSession session = req.getSession();
//TODO
//DIT MOET ER LATER UIT
//ZEER BELANGERIJK
if(username.equals("delete") && password.equals("delete")){
OwnOfy.clearStudents();
//StudentRegistry.deleteAll();
StudentRegistry.addFakeUser();
resp.sendRedirect("/error.jsp?msg= Info erased");
}
//KIJK HIERBOVEN, DIT MOET ERUIT
//NIET OVERKIJKEN
else if(StudentRegistry.isValidlogIn(username, password)){//check whether username and password are correct
Student user = StudentRegistry.getUserByUserName(username);
session.setAttribute("student", user);//set the current student to the one who is trying to log in
resp.sendRedirect("/track");
} else {
- resp.sendRedirect("/login.jsp?msg=The combination of the given username and password is invalid.");
+ resp.sendRedirect("/login.jsp?msg=De opgegeven combinatie van gebruikersnaam en paswoord is niet geldig.");
}
}
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession();
if(session.getAttribute("student") != null)
resp.sendRedirect("/track");
else
resp.sendRedirect("/login.jsp");
}
}
| true | true | public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
HttpSession session = req.getSession();
//TODO
//DIT MOET ER LATER UIT
//ZEER BELANGERIJK
if(username.equals("delete") && password.equals("delete")){
OwnOfy.clearStudents();
//StudentRegistry.deleteAll();
StudentRegistry.addFakeUser();
resp.sendRedirect("/error.jsp?msg= Info erased");
}
//KIJK HIERBOVEN, DIT MOET ERUIT
//NIET OVERKIJKEN
else if(StudentRegistry.isValidlogIn(username, password)){//check whether username and password are correct
Student user = StudentRegistry.getUserByUserName(username);
session.setAttribute("student", user);//set the current student to the one who is trying to log in
resp.sendRedirect("/track");
} else {
resp.sendRedirect("/login.jsp?msg=The combination of the given username and password is invalid.");
}
}
| public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
HttpSession session = req.getSession();
//TODO
//DIT MOET ER LATER UIT
//ZEER BELANGERIJK
if(username.equals("delete") && password.equals("delete")){
OwnOfy.clearStudents();
//StudentRegistry.deleteAll();
StudentRegistry.addFakeUser();
resp.sendRedirect("/error.jsp?msg= Info erased");
}
//KIJK HIERBOVEN, DIT MOET ERUIT
//NIET OVERKIJKEN
else if(StudentRegistry.isValidlogIn(username, password)){//check whether username and password are correct
Student user = StudentRegistry.getUserByUserName(username);
session.setAttribute("student", user);//set the current student to the one who is trying to log in
resp.sendRedirect("/track");
} else {
resp.sendRedirect("/login.jsp?msg=De opgegeven combinatie van gebruikersnaam en paswoord is niet geldig.");
}
}
|
diff --git a/KitsuneChat/src/com/cyberkitsune/prefixchat/ChatListener.java b/KitsuneChat/src/com/cyberkitsune/prefixchat/ChatListener.java
index 500db76..1e8cfd0 100644
--- a/KitsuneChat/src/com/cyberkitsune/prefixchat/ChatListener.java
+++ b/KitsuneChat/src/com/cyberkitsune/prefixchat/ChatListener.java
@@ -1,89 +1,88 @@
package com.cyberkitsune.prefixchat;
import java.util.List;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerChatEvent;
public class ChatListener implements Listener {
private KitsuneChat plugin;
private KitsuneChatUtils util;
public ChatListener(KitsuneChat plugin) {
this.plugin = plugin;
util = new KitsuneChatUtils(plugin);
}
/**
* playerChat handles capturing the event and doing silly things with it.
*
* @param evt
* The event! :o
*/
@EventHandler
public void playerChat(PlayerChatEvent evt) {
evt.setCancelled(true);
String message = KitsuneChatUtils.colorizeString(evt.getMessage());
- String prefix = "<" + evt.getPlayer().getDisplayName() + ">";
/*
* So, first split the first char to see what channel it goes to. Then,
* colorize, Finally, send to just the group
*/
if (evt.getMessage().startsWith(plugin.getConfig().getString("global.prefix"))) {
Set<Player> everybody = evt.getRecipients();
for (Player plr : everybody) {
plr.sendMessage(
util.formatChatPrefixes(message, plugin.getConfig().getString("global.sayformat"), evt));
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("world.prefix"))) {
List<Player> worldPlayers = evt.getPlayer().getWorld().getPlayers();
for (Player plr : worldPlayers) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("world.sayformat"), evt));
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("admin.prefix"))) {
if (evt.getPlayer().hasPermission("kitsunechat.adminchat")) {
for (Player plr : plugin.getServer().getOnlinePlayers()) {
if (plr.hasPermission("kitsunechat.adminchat")) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("admin.sayformat"), evt));
}
}
} else {
evt.getPlayer()
.sendMessage(
ChatColor.RED
+ "You do not have permissions to use admin chat.");
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("party.prefix"))) {
if (plugin.party.isInAParty(evt.getPlayer())) {
Set<Player> channelPlayers = plugin.party
.getPartyMembers(plugin.party.getPartyName(evt
.getPlayer()));
for (Player plr : channelPlayers) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("party.sayformat"), evt));
}
} else {
evt.getPlayer()
.sendMessage(
ChatColor.YELLOW
+ "[KitsuneChat] You are not currently in a channel.");
}
} else {
Set<Player> local = KitsuneChatUtils.getNearbyPlayers(plugin
.getConfig().getInt("local.radius"), evt.getPlayer());
for (Player plr : local) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("local.sayformat"), evt));
}
}
}
}
| true | true | public void playerChat(PlayerChatEvent evt) {
evt.setCancelled(true);
String message = KitsuneChatUtils.colorizeString(evt.getMessage());
String prefix = "<" + evt.getPlayer().getDisplayName() + ">";
/*
* So, first split the first char to see what channel it goes to. Then,
* colorize, Finally, send to just the group
*/
if (evt.getMessage().startsWith(plugin.getConfig().getString("global.prefix"))) {
Set<Player> everybody = evt.getRecipients();
for (Player plr : everybody) {
plr.sendMessage(
util.formatChatPrefixes(message, plugin.getConfig().getString("global.sayformat"), evt));
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("world.prefix"))) {
List<Player> worldPlayers = evt.getPlayer().getWorld().getPlayers();
for (Player plr : worldPlayers) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("world.sayformat"), evt));
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("admin.prefix"))) {
if (evt.getPlayer().hasPermission("kitsunechat.adminchat")) {
for (Player plr : plugin.getServer().getOnlinePlayers()) {
if (plr.hasPermission("kitsunechat.adminchat")) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("admin.sayformat"), evt));
}
}
} else {
evt.getPlayer()
.sendMessage(
ChatColor.RED
+ "You do not have permissions to use admin chat.");
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("party.prefix"))) {
if (plugin.party.isInAParty(evt.getPlayer())) {
Set<Player> channelPlayers = plugin.party
.getPartyMembers(plugin.party.getPartyName(evt
.getPlayer()));
for (Player plr : channelPlayers) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("party.sayformat"), evt));
}
} else {
evt.getPlayer()
.sendMessage(
ChatColor.YELLOW
+ "[KitsuneChat] You are not currently in a channel.");
}
} else {
Set<Player> local = KitsuneChatUtils.getNearbyPlayers(plugin
.getConfig().getInt("local.radius"), evt.getPlayer());
for (Player plr : local) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("local.sayformat"), evt));
}
}
}
| public void playerChat(PlayerChatEvent evt) {
evt.setCancelled(true);
String message = KitsuneChatUtils.colorizeString(evt.getMessage());
/*
* So, first split the first char to see what channel it goes to. Then,
* colorize, Finally, send to just the group
*/
if (evt.getMessage().startsWith(plugin.getConfig().getString("global.prefix"))) {
Set<Player> everybody = evt.getRecipients();
for (Player plr : everybody) {
plr.sendMessage(
util.formatChatPrefixes(message, plugin.getConfig().getString("global.sayformat"), evt));
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("world.prefix"))) {
List<Player> worldPlayers = evt.getPlayer().getWorld().getPlayers();
for (Player plr : worldPlayers) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("world.sayformat"), evt));
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("admin.prefix"))) {
if (evt.getPlayer().hasPermission("kitsunechat.adminchat")) {
for (Player plr : plugin.getServer().getOnlinePlayers()) {
if (plr.hasPermission("kitsunechat.adminchat")) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("admin.sayformat"), evt));
}
}
} else {
evt.getPlayer()
.sendMessage(
ChatColor.RED
+ "You do not have permissions to use admin chat.");
}
} else if (evt.getMessage().startsWith(
plugin.getConfig().getString("party.prefix"))) {
if (plugin.party.isInAParty(evt.getPlayer())) {
Set<Player> channelPlayers = plugin.party
.getPartyMembers(plugin.party.getPartyName(evt
.getPlayer()));
for (Player plr : channelPlayers) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("party.sayformat"), evt));
}
} else {
evt.getPlayer()
.sendMessage(
ChatColor.YELLOW
+ "[KitsuneChat] You are not currently in a channel.");
}
} else {
Set<Player> local = KitsuneChatUtils.getNearbyPlayers(plugin
.getConfig().getInt("local.radius"), evt.getPlayer());
for (Player plr : local) {
plr.sendMessage(util.formatChatPrefixes(message, plugin.getConfig().getString("local.sayformat"), evt));
}
}
}
|
diff --git a/src/session/Controller.java b/src/session/Controller.java
index 6e2f030..a861718 100644
--- a/src/session/Controller.java
+++ b/src/session/Controller.java
@@ -1,90 +1,90 @@
package session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.Cookie;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class Controller
*/
@WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Controller() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
// Get Client IP & Message From The Text Box & Create a sesison object
try{
- out.println(request.getAttribute("message"));
+ out.println(request.getParameter("message"));
Session user = new Session("message",
request.getRemoteAddr());
String localSessionID = user.getSessionID();
localSessionID = localSessionID + "|" + user.getVersionNumber() + "|"
+ request.getLocalAddr().toString();
// Cookie Time!
Cookie[] cookies = request.getCookies();
if (cookies == null) {
out.println("No Cookies Found<br />");
// Make A New Cookie
Cookie cookie = new Cookie("CS5300PROJ1SESSION", localSessionID);
cookie.setMaxAge(615);
response.addCookie(cookie);
} else {
for (Cookie retrievedCookie : cookies) {
String name = retrievedCookie.getName();
String value = retrievedCookie.getValue();
if (name.equals("CS5300PROJ1SESSION")) {
out.println("<h1>" + name + " : " + value + "</h1><br />");
}
}
}
}catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
| true | true | protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
// Get Client IP & Message From The Text Box & Create a sesison object
try{
out.println(request.getAttribute("message"));
Session user = new Session("message",
request.getRemoteAddr());
String localSessionID = user.getSessionID();
localSessionID = localSessionID + "|" + user.getVersionNumber() + "|"
+ request.getLocalAddr().toString();
// Cookie Time!
Cookie[] cookies = request.getCookies();
if (cookies == null) {
out.println("No Cookies Found<br />");
// Make A New Cookie
Cookie cookie = new Cookie("CS5300PROJ1SESSION", localSessionID);
cookie.setMaxAge(615);
response.addCookie(cookie);
} else {
for (Cookie retrievedCookie : cookies) {
String name = retrievedCookie.getName();
String value = retrievedCookie.getValue();
if (name.equals("CS5300PROJ1SESSION")) {
out.println("<h1>" + name + " : " + value + "</h1><br />");
}
}
}
}catch (NullPointerException e) {
e.printStackTrace();
}
}
| protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
// Get Client IP & Message From The Text Box & Create a sesison object
try{
out.println(request.getParameter("message"));
Session user = new Session("message",
request.getRemoteAddr());
String localSessionID = user.getSessionID();
localSessionID = localSessionID + "|" + user.getVersionNumber() + "|"
+ request.getLocalAddr().toString();
// Cookie Time!
Cookie[] cookies = request.getCookies();
if (cookies == null) {
out.println("No Cookies Found<br />");
// Make A New Cookie
Cookie cookie = new Cookie("CS5300PROJ1SESSION", localSessionID);
cookie.setMaxAge(615);
response.addCookie(cookie);
} else {
for (Cookie retrievedCookie : cookies) {
String name = retrievedCookie.getName();
String value = retrievedCookie.getValue();
if (name.equals("CS5300PROJ1SESSION")) {
out.println("<h1>" + name + " : " + value + "</h1><br />");
}
}
}
}catch (NullPointerException e) {
e.printStackTrace();
}
}
|
diff --git a/mydlp-ui-service/src/main/java/com/mydlp/ui/service/EncryptionServiceImpl.java b/mydlp-ui-service/src/main/java/com/mydlp/ui/service/EncryptionServiceImpl.java
index 3219e1f1..77c9182a 100644
--- a/mydlp-ui-service/src/main/java/com/mydlp/ui/service/EncryptionServiceImpl.java
+++ b/mydlp-ui-service/src/main/java/com/mydlp/ui/service/EncryptionServiceImpl.java
@@ -1,62 +1,60 @@
package com.mydlp.ui.service;
import java.nio.ByteBuffer;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service("encryptionService")
public class EncryptionServiceImpl implements EncryptionService {
private static Logger logger = LoggerFactory.getLogger(EncryptionServiceImpl.class);
private static String ALGORITHM = "Blowfish";
private static String MODE = "/ECB/NoPadding";
private static String PROVIDER = "SunJCE";
@Override
public ByteBuffer decrypt(String secret, ByteBuffer data)
throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, IllegalBlockSizeException, BadPaddingException, ShortBufferException {
Cipher cipher = Cipher.getInstance(ALGORITHM + MODE, PROVIDER);
SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
ByteBuffer output = ByteBuffer.allocate(data.remaining());
int n = cipher.doFinal(data, output);
logger.error(output.position() + "");
logger.error(output.remaining() + "");
- output.position(0);
- output.limit(n);
- output.compact();
- return output;
+ output.rewind();
+ return output;
}
@Override
public ByteBuffer encrypt(String secret, ByteBuffer data)
throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, IllegalBlockSizeException, BadPaddingException, ShortBufferException {
Cipher cipher = Cipher.getInstance(ALGORITHM + MODE, PROVIDER);
SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
ByteBuffer output = ByteBuffer.allocate(data.remaining());
int n = cipher.doFinal(data, output);
output.position(0);
output.limit(n);
output.compact();
return output;
}
}
| true | true | public ByteBuffer decrypt(String secret, ByteBuffer data)
throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, IllegalBlockSizeException, BadPaddingException, ShortBufferException {
Cipher cipher = Cipher.getInstance(ALGORITHM + MODE, PROVIDER);
SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
ByteBuffer output = ByteBuffer.allocate(data.remaining());
int n = cipher.doFinal(data, output);
logger.error(output.position() + "");
logger.error(output.remaining() + "");
output.position(0);
output.limit(n);
output.compact();
return output;
}
| public ByteBuffer decrypt(String secret, ByteBuffer data)
throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException,
NoSuchProviderException, IllegalBlockSizeException, BadPaddingException, ShortBufferException {
Cipher cipher = Cipher.getInstance(ALGORITHM + MODE, PROVIDER);
SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
ByteBuffer output = ByteBuffer.allocate(data.remaining());
int n = cipher.doFinal(data, output);
logger.error(output.position() + "");
logger.error(output.remaining() + "");
output.rewind();
return output;
}
|
diff --git a/src/net/rptools/maptool/model/Token.java b/src/net/rptools/maptool/model/Token.java
index bfbaf337..42591f50 100644
--- a/src/net/rptools/maptool/model/Token.java
+++ b/src/net/rptools/maptool/model/Token.java
@@ -1,876 +1,877 @@
/* The MIT License
*
* Copyright (c) 2005 David Rice, Trevor Croft
*
* 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 net.rptools.maptool.model;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Point;
import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.ImageIcon;
import antlr.StringUtils;
import net.rptools.lib.MD5Key;
import net.rptools.lib.image.ImageUtil;
import net.rptools.lib.swing.SwingUtil;
import net.rptools.lib.transferable.TokenTransferData;
import net.rptools.maptool.util.ImageManager;
import net.rptools.maptool.util.StringUtil;
/**
* This object represents the placeable objects on a map. For example an icon
* that represents a character would exist as an {@link Asset} (the image
* itself) and a location and scale.
*/
public class Token {
private GUID id = new GUID();
public static final String NAME_USE_FILENAME = "Use Filename";
public static final String NAME_USE_CREATURE = "Use \"Creature\"";
public static final String NUM_INCREMENT = "Increment";
public static final String NUM_RANDOM = "Random 2-digit";
public static final String NUM_ON_NAME = "Name";
public static final String NUM_ON_GM = "GM Name";
public static final String NUM_ON_BOTH = "Both";
public enum TokenShape {
TOP_DOWN("Top down"),
CIRCLE("Circle"),
SQUARE("Square");
private String displayName;
private TokenShape(String displayName) {
this.displayName = displayName;
}
public String toString() {
return displayName;
}
}
public enum Type {
PC,
NPC
}
public static final Comparator<Token> NAME_COMPARATOR = new Comparator<Token>() {
public int compare(Token o1, Token o2) {
return o1.getName().compareToIgnoreCase(o2.getName());
}
};
private MD5Key assetID;
private int x;
private int y;
private int z;
private int lastX;
private int lastY;
private Path lastPath;
private boolean snapToScale = true; // Whether the scaleX and scaleY
// represent snap-to-grid measurements
private int width = 1; // Default to using exactly 1x1 grid cell
private int height = 1;
private int size = TokenSize.Size.Medium.value(); // Abstract size
private boolean snapToGrid = true; // Whether the token snaps to the
// current grid or is free floating
private boolean isVisible = true;
private String name;
private Set<String> ownerList;
private int ownerType;
private static final int OWNER_TYPE_ALL = 1;
private static final int OWNER_TYPE_LIST = 0;
private String tokenType; // TODO: 2.0 => change this to tokenShape
private String tokenMobType; // TODO: 2.0 => change this to tokenType
private String layer;
private String propertyType = Campaign.DEFAULT_TOKEN_PROPERTY_TYPE;
private Integer facing = null;
private Integer haloColorValue;
private transient Color haloColor;
private List<Vision> visionList;
private boolean isFlippedX;
private boolean isFlippedY;
/**
* The notes that are displayed for this token.
*/
private String notes;
private String gmNotes;
private String gmName;
/**
* A state properties for this token. This allows state to be added that can
* change appearance of the token.
*/
private Map<String, Object> state;
/**
* Properties
*/
private Map<String, Object> propertyMap;
private Map<String, String> macroMap;
private Map<String, String> speechMap;
// Transient so that it isn't transfered over the wire
private transient List<ModelChangeListener> listenerList = new CopyOnWriteArrayList<ModelChangeListener>();
public enum ChangeEvent {
name
}
public Token(Token token) {
id = new GUID();
assetID = token.assetID;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
size = token.size;
facing = token.facing;
tokenType = token.tokenType;
tokenMobType = token.tokenMobType;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
+ ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.visionList != null) {
visionList = new ArrayList<Vision>();
visionList.addAll(token.visionList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
}
public Token() {
}
public Token(MD5Key assetID) {
this("", assetID);
}
public Token(String name, MD5Key assetID) {
this.name = name;
this.assetID = assetID;
state = new HashMap<String, Object>();
}
public boolean isMarker() {
return (isStamp() || isBackground()) && (!StringUtil.isEmpty(notes) || !StringUtil.isEmpty(gmNotes));
}
public String getPropertyType() {
return propertyType;
}
public void setPropertyType(String propertyType) {
this.propertyType = propertyType;
}
public String getGMNotes() {
return gmNotes;
}
public void setGMNote(String notes) {
gmNotes = notes;
}
public String getGMName() {
return gmName;
}
public void setGMName(String name) {
gmName = name;
}
public boolean hasHalo() {
return haloColorValue != null;
}
public void setHaloColor(Color color) {
if (color != null) {
haloColorValue = color.getRGB();
} else {
haloColorValue = null;
}
haloColor = color;
}
public Color getHaloColor() {
if (haloColor == null && haloColorValue != null) {
haloColor = new Color(haloColorValue);
}
return haloColor;
}
public boolean isStamp() {
return getLayer() == Zone.Layer.OBJECT;
}
public boolean isBackground() {
return getLayer() == Zone.Layer.BACKGROUND;
}
public boolean isToken() {
return getLayer() == Zone.Layer.TOKEN;
}
public TokenShape getShape() {
try {
return tokenType != null ? TokenShape.valueOf(tokenType) : TokenShape.SQUARE; // TODO: make this a psf
} catch (IllegalArgumentException iae) {
return TokenShape.SQUARE;
}
}
public void setShape(TokenShape type) {
this.tokenType = type.name();
}
public Type getType() {
try {
return tokenMobType != null ? Type.valueOf(tokenMobType) : Type.NPC; // TODO: make this a psf
} catch (IllegalArgumentException iae) {
return Type.NPC;
}
}
public void setType(Type type) {
this.tokenMobType = type.name();
}
public Zone.Layer getLayer() {
try {
return layer != null ? Zone.Layer.valueOf(layer) : Zone.Layer.TOKEN;
} catch (IllegalArgumentException iae) {
return Zone.Layer.TOKEN;
}
}
public void setLayer(Zone.Layer layer) {
this.layer = layer.name();
}
public boolean hasFacing() {
return facing != null;
}
public void setFacing(Integer facing) {
this.facing = facing;
}
public Integer getFacing() {
return facing;
}
public boolean hasVision() {
return visionList != null && visionList.size() > 0;
}
public void addVision(Vision vision) {
if (visionList == null) {
visionList = new ArrayList<Vision>();
}
if (!visionList.contains(vision)) {
visionList.add(vision);
}
}
public void removeVision(Vision vision) {
if (visionList != null) {
visionList.remove(vision);
}
}
public List<Vision> getVisionList() {
return (List<Vision>)(visionList != null ? Collections.unmodifiableList(visionList) : Collections.emptyList());
}
public synchronized void addOwner(String playerId) {
ownerType = OWNER_TYPE_LIST;
if (ownerList == null) {
ownerList = new HashSet<String>();
}
ownerList.add(playerId);
}
public synchronized boolean hasOwners() {
return ownerType == OWNER_TYPE_ALL || (ownerList != null && !ownerList.isEmpty());
}
public synchronized void removeOwner(String playerId) {
ownerType = OWNER_TYPE_LIST;
if (ownerList == null) {
return;
}
ownerList.remove(playerId);
if (ownerList.size() == 0) {
ownerList = null;
}
}
public synchronized void setAllOwners() {
ownerType = OWNER_TYPE_ALL;
ownerList = null;
}
public Set<String> getOwners() {
return ownerList != null ? Collections.unmodifiableSet(ownerList) : new HashSet<String>();
}
public boolean isOwnedByAll() {
return ownerType == OWNER_TYPE_ALL;
}
public synchronized void clearAllOwners() {
ownerList = null;
ownerType = OWNER_TYPE_LIST;
}
public synchronized boolean isOwner(String playerId) {
return /*getType() == Type.PC && */(ownerType == OWNER_TYPE_ALL
|| (ownerList != null && ownerList.contains(playerId)));
}
public boolean equals(Object o) {
if (!(o instanceof Token)) {
return false;
}
return id.equals(((Token) o).id);
}
public void setZOrder(int z) {
this.z = z;
}
public int getZOrder() {
return z;
}
public void setName(String name) {
this.name = name;
fireModelChangeEvent(new ModelChangeEvent(this, ChangeEvent.name, name));
}
public MD5Key getAssetID() {
return assetID;
}
public void setAsset(MD5Key assetID) {
this.assetID = assetID;
}
public GUID getId() {
return id;
}
public void setId(GUID id) {
this.id = id;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
lastX = this.x;
this.x = x;
}
public void setY(int y) {
lastY = this.y;
this.y = y;
}
public void applyMove(int xOffset, int yOffset, Path path) {
setX(x + xOffset);
setY(y + yOffset);
lastPath = path;
}
public void setLastPath(Path path) {
lastPath = path;
}
public int getLastY() {
return lastY;
}
public int getLastX() {
return lastX;
}
public Path getLastPath() {
return lastPath;
}
/**
* @return Returns the scaleX.
*/
public int getWidth() {
return width;
}
/**
* @param scaleX
* The scaleX to set.
*/
public void setWidth(int width) {
this.width = width;
}
/**
* @return Returns the sizeY.
*/
public int getHeight() {
return height;
}
/**
* @param height
* The sizeY to set.
*/
public void setHeight(int height) {
this.height = height;
}
/**
* @return Returns the snapScale.
*/
public boolean isSnapToScale() {
return snapToScale;
}
/**
* @param snapScale
* The snapScale to set.
*/
public void setSnapToScale(boolean snapScale) {
this.snapToScale = snapScale;
}
public void setVisible(boolean visible) {
this.isVisible = visible;
}
public boolean isVisible() {
return isVisible;
}
public String getName() {
return name != null ? name : "";
}
/**
* @return Returns the size.
*/
public int getSize() {
return size;
}
/**
* @param size
* The size to set.
*/
public void setSize(int size) {
this.size = size;
}
public boolean isSnapToGrid() {
return snapToGrid;
}
public void setSnapToGrid(boolean snapToGrid) {
this.snapToGrid = snapToGrid;
}
public void addModelChangeListener(ModelChangeListener listener) {
listenerList.add(listener);
}
public void removeModelChangeListener(ModelChangeListener listener) {
listenerList.remove(listener);
}
protected void fireModelChangeEvent(ModelChangeEvent event) {
for (ModelChangeListener listener : listenerList) {
listener.modelChanged(event);
}
}
/**
* Get a particular state property for this Token.
*
* @param property
* The name of the property being read.
* @return Returns the current value of property.
*/
public Object getState(String property) {
return state.get(property);
}
/**
* Set the value of state for this Token.
*
* @param aState
* The property to set.
* @param aValue
* The new value for the property.
* @return The original vaoue of the property, if any.
*/
public Object setState(String aState, Object aValue) {
if (aValue == null)
return state.remove(aState);
return state.put(aState, aValue);
}
public void setProperty(String key, Object value) {
getPropertyMap().put(key, value);
}
public Object getProperty(String key) {
return getPropertyMap().get(key);
}
public Set<String> getPropertyNames() {
return getPropertyMap().keySet();
}
private Map<String, Object> getPropertyMap() {
if (propertyMap == null) {
propertyMap = new HashMap<String, Object>();
}
return propertyMap;
}
public void setMacroMap(Map<String, String> map) {
getMacroMap().clear();
getMacroMap().putAll(map);
}
public Set<String> getMacroNames() {
return getMacroMap().keySet();
}
public String getMacro(String key) {
return getMacroMap().get(key);
}
private Map<String, String> getMacroMap() {
if (macroMap == null) {
macroMap = new HashMap<String, String>();
}
return macroMap;
}
public void setSpeechMap(Map<String, String> map) {
getSpeechMap().clear();
getSpeechMap().putAll(map);
}
public Set<String> getSpeechNames() {
return getSpeechMap().keySet();
}
public String getSpeech(String key) {
return getSpeechMap().get(key);
}
private Map<String, String> getSpeechMap() {
if (speechMap == null) {
speechMap = new HashMap<String, String>();
}
return speechMap;
}
/**
* Get a set containing the names of all set properties on this token.
*
* @return The set of state property names that have a value associated with
* them.
*/
public Set<String> getStatePropertyNames() {
return state.keySet();
}
/** @return Getter for notes */
public String getNotes() {
return notes;
}
/**
* @param aNotes
* Setter for notes
*/
public void setNotes(String aNotes) {
notes = aNotes;
}
public boolean isFlippedY() {
return isFlippedY;
}
public void setFlippedY(boolean isFlippedY) {
this.isFlippedY = isFlippedY;
}
public boolean isFlippedX() {
return isFlippedX;
}
public void setFlippedX(boolean isFlippedX) {
this.isFlippedX = isFlippedX;
}
/**
* Convert the token into a hash map. This is used to ship all of the
* properties for the token to other apps that do need access to the
* <code>Token</code> class.
*
* @return A map containing the properties of the token.
*/
public TokenTransferData toTransferData() {
TokenTransferData td = new TokenTransferData();
td.setName(name);
td.setPlayers(ownerList);
td.setVisible(isVisible);
td.setLocation(new Point(x, y));
td.setFacing(facing);
// Set the properties
td.put(TokenTransferData.ID, id.toString());
td.put(TokenTransferData.ASSET_ID, assetID);
td.put(TokenTransferData.Z, z);
td.put(TokenTransferData.SNAP_TO_SCALE, snapToScale);
td.put(TokenTransferData.WIDTH, width);
td.put(TokenTransferData.HEIGHT, height);
td.put(TokenTransferData.SIZE, size);
td.put(TokenTransferData.SNAP_TO_GRID, snapToGrid);
td.put(TokenTransferData.OWNER_TYPE, ownerType);
td.put(TokenTransferData.TOKEN_TYPE, tokenType);
td.put(TokenTransferData.NOTES, notes);
td.put(TokenTransferData.GM_NOTES, gmNotes);
td.put(TokenTransferData.GM_NAME, gmName);
// Put all of the serializable state into the map
for (String key : getStatePropertyNames()) {
Object value = getState(key);
if (value instanceof Serializable)
td.put(key, value);
} // endfor
td.putAll(state);
// Create the image from the asset and add it to the map
Asset asset = AssetManager.getAsset(assetID);
Image image = ImageManager.getImageAndWait(asset);
if (image != null)
td.setToken(new ImageIcon(image)); // Image icon makes it serializable.
return td;
}
/**
* Constructor to create a new token from a transfer object containing its property
* values. This is used to read in a new token from other apps that don't
* have access to the <code>Token</code> class.
*
* @param td
* Read the values from this transfer object.
*/
public Token(TokenTransferData td) {
if (td.getLocation() != null) {
x = td.getLocation().x;
y = td.getLocation().y;
} // endif
snapToScale = getBoolean(td, TokenTransferData.SNAP_TO_SCALE, true);
width = getInt(td, TokenTransferData.WIDTH, 1);
height = getInt(td, TokenTransferData.HEIGHT, 1);
size = getInt(td, TokenTransferData.SIZE, TokenSize.Size.Medium.value());
snapToGrid = getBoolean(td, TokenTransferData.SNAP_TO_GRID, true);
isVisible = td.isVisible();
name = td.getName();
ownerList = td.getPlayers();
ownerType = getInt(td, TokenTransferData.OWNER_TYPE,
ownerList == null ? OWNER_TYPE_ALL : OWNER_TYPE_LIST);
tokenType = (String) td.get(TokenTransferData.TOKEN_TYPE);
facing = td.getFacing();
notes = (String) td.get(TokenTransferData.NOTES);
gmNotes = (String) td.get(TokenTransferData.GM_NOTES);
gmName = (String) td.get(TokenTransferData.GM_NAME);
// Get the image for the token
ImageIcon icon = td.getToken();
if (icon != null) {
// Make sure there is a buffered image for it
Image image = icon.getImage();
if (!(image instanceof BufferedImage)) {
image = new BufferedImage(icon.getIconWidth(), icon
.getIconHeight(), Transparency.TRANSLUCENT);
Graphics2D g = ((BufferedImage) image).createGraphics();
icon.paintIcon(null, g, 0, 0);
} // endif
// Create the asset
try {
Asset asset = new Asset(name, ImageUtil
.imageToBytes((BufferedImage) image));
if (!AssetManager.hasAsset(asset))
AssetManager.putAsset(asset);
assetID = asset.getId();
} catch (IOException e) {
e.printStackTrace();
} // endtry
} // endtry
// Get all of the non maptool state
state = new HashMap<String, Object>();
for (String key : td.keySet()) {
if (key.startsWith(TokenTransferData.MAPTOOL))
continue;
setState(key, td.get(key));
} // endfor
}
/**
* Get an integer value from the map or return the default value
*
* @param map
* Get the value from this map
* @param propName
* The name of the property being read.
* @param defaultValue
* The value for the property if it is not set in the map.
* @return The value for the passed property
*/
private static int getInt(Map<String, Object> map, String propName,
int defaultValue) {
Integer integer = (Integer) map.get(propName);
if (integer == null)
return defaultValue;
return integer.intValue();
}
/**
* Get a boolean value from the map or return the default value
*
* @param map
* Get the value from this map
* @param propName
* The name of the property being read.
* @param defaultValue
* The value for the property if it is not set in the map.
* @return The value for the passed property
*/
private static boolean getBoolean(Map<String, Object> map, String propName,
boolean defaultValue) {
Boolean bool = (Boolean) map.get(propName);
if (bool == null)
return defaultValue;
return bool.booleanValue();
}
}
| true | true | public Token(Token token) {
id = new GUID();
assetID = token.assetID;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
size = token.size;
facing = token.facing;
tokenType = token.tokenType;
tokenMobType = token.tokenMobType;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.visionList != null) {
visionList = new ArrayList<Vision>();
visionList.addAll(token.visionList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
}
| public Token(Token token) {
id = new GUID();
assetID = token.assetID;
x = token.x;
y = token.y;
// These properties shouldn't be transferred, they are more transient and relate to token history, not to new tokens
// lastX = token.lastX;
// lastY = token.lastY;
// lastPath = token.lastPath;
snapToScale = token.snapToScale;
width = token.width;
height = token.height;
size = token.size;
facing = token.facing;
tokenType = token.tokenType;
tokenMobType = token.tokenMobType;
snapToGrid = token.snapToGrid;
isVisible = token.isVisible;
name = token.name;
notes = token.notes;
gmName = token.gmName;
gmNotes = token.gmNotes;
isFlippedX = token.isFlippedX;
isFlippedY = token.isFlippedY;
layer = token.layer;
ownerType = token.ownerType;
if (token.ownerList != null) {
ownerList = new HashSet<String>();
ownerList.addAll(token.ownerList);
}
if (token.visionList != null) {
visionList = new ArrayList<Vision>();
visionList.addAll(token.visionList);
}
if (token.state != null) {
state = new HashMap<String, Object>(token.state);
}
if (token.propertyMap != null) {
propertyMap = new HashMap<String, Object>(token.propertyMap);
}
if (token.macroMap != null) {
macroMap = new HashMap<String, String>(token.macroMap);
}
if (token.speechMap != null) {
speechMap = new HashMap<String, String>(token.speechMap);
}
}
|
diff --git a/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java b/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java
index 6d0dceb75..3553725e5 100644
--- a/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java
+++ b/opentripplanner-graph-builder/src/test/java/org/opentripplanner/graph_builder/impl/shapefile/TestShapefileStreetGraphBuilderImpl.java
@@ -1,74 +1,73 @@
package org.opentripplanner.graph_builder.impl.shapefile;
import java.io.File;
import junit.framework.TestCase;
import org.opentripplanner.routing.core.Graph;
import org.opentripplanner.routing.core.Vertex;
import org.opentripplanner.routing.edgetype.StreetTraversalPermission;
public class TestShapefileStreetGraphBuilderImpl extends TestCase {
public void testBasic() throws Exception {
Graph gg = new Graph();
File file = new File("src/test/resources/nyc_streets/streets.shp");
- file = new File("/Users/bdferris/oba/data/opentripplanner-data/nyc/streets/nyc_streets/streets.shp");
if (!file.exists()) {
System.out.println("No New York City basemap; skipping; see comment here for details");
/*
* This test requires the New York City base map, available at:
* http://www.nyc.gov/html/dcp/html/bytes/dwnlion.shtml Download the MapInfo file. This
* must be converted to a ShapeFile. unzip nyc_lion09ami.zip ogr2ogr -f 'ESRI Shapefile'
* nyc_streets/streets.shp lion/MNLION1.tab ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/SILION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/QNLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BKLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BXLION1.tab -nln streets
*
* It also requires the NYC Subway data in GTFS: cd src/test/resources wget
* http://data.topplabs.org/data/mta_nyct_subway/subway.zip
*/
return;
}
ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file);
ShapefileStreetSchema schema = new ShapefileStreetSchema();
schema.setIdAttribute("StreetCode");
schema.setNameAttribute("Street");
CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
forward.addPermission("W", StreetTraversalPermission.ALL);
reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY);
forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY);
reverse.addPermission("A", StreetTraversalPermission.ALL);
forward.addPermission("T", StreetTraversalPermission.ALL);
reverse.addPermission("T", StreetTraversalPermission.ALL);
schema.setForwardPermissionConverter(forward);
schema.setReversePermissionConverter(reverse);
ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl();
loader.setFeatureSourceFactory(factory);
loader.setSchema(schema);
loader.buildGraph(gg);
assertEquals(104910,gg.getVertices().size());
Vertex start = gg.getVertex("PARK PL at VANDERBILT AV");
Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST");
assertNotNull(start);
assertNotNull(end);
}
}
| true | true | public void testBasic() throws Exception {
Graph gg = new Graph();
File file = new File("src/test/resources/nyc_streets/streets.shp");
file = new File("/Users/bdferris/oba/data/opentripplanner-data/nyc/streets/nyc_streets/streets.shp");
if (!file.exists()) {
System.out.println("No New York City basemap; skipping; see comment here for details");
/*
* This test requires the New York City base map, available at:
* http://www.nyc.gov/html/dcp/html/bytes/dwnlion.shtml Download the MapInfo file. This
* must be converted to a ShapeFile. unzip nyc_lion09ami.zip ogr2ogr -f 'ESRI Shapefile'
* nyc_streets/streets.shp lion/MNLION1.tab ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/SILION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/QNLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BKLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BXLION1.tab -nln streets
*
* It also requires the NYC Subway data in GTFS: cd src/test/resources wget
* http://data.topplabs.org/data/mta_nyct_subway/subway.zip
*/
return;
}
ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file);
ShapefileStreetSchema schema = new ShapefileStreetSchema();
schema.setIdAttribute("StreetCode");
schema.setNameAttribute("Street");
CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
forward.addPermission("W", StreetTraversalPermission.ALL);
reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY);
forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY);
reverse.addPermission("A", StreetTraversalPermission.ALL);
forward.addPermission("T", StreetTraversalPermission.ALL);
reverse.addPermission("T", StreetTraversalPermission.ALL);
schema.setForwardPermissionConverter(forward);
schema.setReversePermissionConverter(reverse);
ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl();
loader.setFeatureSourceFactory(factory);
loader.setSchema(schema);
loader.buildGraph(gg);
assertEquals(104910,gg.getVertices().size());
Vertex start = gg.getVertex("PARK PL at VANDERBILT AV");
Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST");
assertNotNull(start);
assertNotNull(end);
}
| public void testBasic() throws Exception {
Graph gg = new Graph();
File file = new File("src/test/resources/nyc_streets/streets.shp");
if (!file.exists()) {
System.out.println("No New York City basemap; skipping; see comment here for details");
/*
* This test requires the New York City base map, available at:
* http://www.nyc.gov/html/dcp/html/bytes/dwnlion.shtml Download the MapInfo file. This
* must be converted to a ShapeFile. unzip nyc_lion09ami.zip ogr2ogr -f 'ESRI Shapefile'
* nyc_streets/streets.shp lion/MNLION1.tab ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/SILION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/QNLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BKLION1.tab -nln streets ogr2ogr -update -append -f 'ESRI Shapefile'
* nyc_streets lion/BXLION1.tab -nln streets
*
* It also requires the NYC Subway data in GTFS: cd src/test/resources wget
* http://data.topplabs.org/data/mta_nyct_subway/subway.zip
*/
return;
}
ShapefileFeatureSourceFactoryImpl factory = new ShapefileFeatureSourceFactoryImpl(file);
ShapefileStreetSchema schema = new ShapefileStreetSchema();
schema.setIdAttribute("StreetCode");
schema.setNameAttribute("Street");
CaseBasedTraversalPermissionConverter reverse = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
CaseBasedTraversalPermissionConverter forward = new CaseBasedTraversalPermissionConverter(
"TrafDir", StreetTraversalPermission.PEDESTRIAN_AND_BICYCLE_ONLY);
forward.addPermission("W", StreetTraversalPermission.ALL);
reverse.addPermission("W", StreetTraversalPermission.PEDESTRIAN_ONLY);
forward.addPermission("A", StreetTraversalPermission.PEDESTRIAN_ONLY);
reverse.addPermission("A", StreetTraversalPermission.ALL);
forward.addPermission("T", StreetTraversalPermission.ALL);
reverse.addPermission("T", StreetTraversalPermission.ALL);
schema.setForwardPermissionConverter(forward);
schema.setReversePermissionConverter(reverse);
ShapefileStreetGraphBuilderImpl loader = new ShapefileStreetGraphBuilderImpl();
loader.setFeatureSourceFactory(factory);
loader.setSchema(schema);
loader.buildGraph(gg);
assertEquals(104910,gg.getVertices().size());
Vertex start = gg.getVertex("PARK PL at VANDERBILT AV");
Vertex end = gg.getVertex("GRAND ST at LAFAYETTE ST");
assertNotNull(start);
assertNotNull(end);
}
|
diff --git a/hw2/wci/frontend/java/tokens/JavaWordToken.java b/hw2/wci/frontend/java/tokens/JavaWordToken.java
index d70cbd5..d9312b7 100644
--- a/hw2/wci/frontend/java/tokens/JavaWordToken.java
+++ b/hw2/wci/frontend/java/tokens/JavaWordToken.java
@@ -1,53 +1,53 @@
package wci.frontend.java.tokens;
import wci.frontend.*;
import wci.frontend.java.*;
import static wci.frontend.java.JavaTokenType.*;
/**
* <h1>JavaWordToken</h1>
*
* <p> Java word tokens (identifiers and reserved words).</p>
*
* <p>Copyright (c) 2009 by Ronald Mak</p>
* <p>For instructional purposes only. No warranties.</p>
*/
public class JavaWordToken extends JavaToken
{
/**
* Constructor.
* @param source the source from where to fetch the token's characters.
* @throws Exception if an error occurred.
*/
public JavaWordToken(Source source)
throws Exception
{
super(source);
}
/**
* Extract a Java word token from the source.
* @throws Exception if an error occurred.
*/
protected void extract()
throws Exception
{
StringBuilder textBuffer = new StringBuilder();
char currentChar = currentChar();
// Get the word characters (letter or digit). The scanner has
// already determined that the first character is a letter.
while (Character.isLetterOrDigit(currentChar)) {
textBuffer.append(currentChar);
currentChar = nextChar(); // consume character
}
text = textBuffer.toString();
// Is it a reserved word or an identifier?
type = (RESERVED_WORDS.contains(text))
- ? JavaTokenType.valueOf(text.toUpperCase()) // reserved word
+ ? JavaTokenType.valueOf(JavaTokenType.class, text.toUpperCase()) // reserved word
: IDENTIFIER; // identifier
}
}
| true | true | protected void extract()
throws Exception
{
StringBuilder textBuffer = new StringBuilder();
char currentChar = currentChar();
// Get the word characters (letter or digit). The scanner has
// already determined that the first character is a letter.
while (Character.isLetterOrDigit(currentChar)) {
textBuffer.append(currentChar);
currentChar = nextChar(); // consume character
}
text = textBuffer.toString();
// Is it a reserved word or an identifier?
type = (RESERVED_WORDS.contains(text))
? JavaTokenType.valueOf(text.toUpperCase()) // reserved word
: IDENTIFIER; // identifier
}
| protected void extract()
throws Exception
{
StringBuilder textBuffer = new StringBuilder();
char currentChar = currentChar();
// Get the word characters (letter or digit). The scanner has
// already determined that the first character is a letter.
while (Character.isLetterOrDigit(currentChar)) {
textBuffer.append(currentChar);
currentChar = nextChar(); // consume character
}
text = textBuffer.toString();
// Is it a reserved word or an identifier?
type = (RESERVED_WORDS.contains(text))
? JavaTokenType.valueOf(JavaTokenType.class, text.toUpperCase()) // reserved word
: IDENTIFIER; // identifier
}
|
diff --git a/src/fr/iutvalence/java/projet/test/TestBoundingBox.java b/src/fr/iutvalence/java/projet/test/TestBoundingBox.java
index 2e4a0c6..a5e01c8 100644
--- a/src/fr/iutvalence/java/projet/test/TestBoundingBox.java
+++ b/src/fr/iutvalence/java/projet/test/TestBoundingBox.java
@@ -1,46 +1,46 @@
/**
*
*/
package fr.iutvalence.java.projet.test;
import fr.iutvalence.java.projet.spaceinvaders.BoundingBox;
import fr.iutvalence.java.projet.spaceinvaders.Coordinates;
import fr.iutvalence.java.projet.spaceinvaders.NegativeCoordinatesException;
/**
* @author alexandre
*
*/
public class TestBoundingBox
{
/**
* @param args
*/
public static void main(String[] args)
{
try
{
BoundingBox b1 = new BoundingBox(new Coordinates(0,0),
new Coordinates(10,10));
BoundingBox b2 = new BoundingBox(new Coordinates(5,5),
new Coordinates(5,5));
- System.out.println(b1 + "\n" + b2);
+ System.out.println("Avant : " + b1 + "\n\t" + b2);
b1.moveTo(new Coordinates(10,10));
b2.translate(new Coordinates(10,10));
- b2.reSize(new Coordinates(10,10));
+ //b2.reSize(new Coordinates(10,10));
- System.out.println(b1 + "\n" + b2);
+ System.out.println("Apres : " + b1 + "\n\t" + b2);
System.out.println("Intersection : " + b1.intersection(b2));
}
catch (NegativeCoordinatesException e)
{
}
}
}
| false | true | public static void main(String[] args)
{
try
{
BoundingBox b1 = new BoundingBox(new Coordinates(0,0),
new Coordinates(10,10));
BoundingBox b2 = new BoundingBox(new Coordinates(5,5),
new Coordinates(5,5));
System.out.println(b1 + "\n" + b2);
b1.moveTo(new Coordinates(10,10));
b2.translate(new Coordinates(10,10));
b2.reSize(new Coordinates(10,10));
System.out.println(b1 + "\n" + b2);
System.out.println("Intersection : " + b1.intersection(b2));
}
catch (NegativeCoordinatesException e)
{
}
}
| public static void main(String[] args)
{
try
{
BoundingBox b1 = new BoundingBox(new Coordinates(0,0),
new Coordinates(10,10));
BoundingBox b2 = new BoundingBox(new Coordinates(5,5),
new Coordinates(5,5));
System.out.println("Avant : " + b1 + "\n\t" + b2);
b1.moveTo(new Coordinates(10,10));
b2.translate(new Coordinates(10,10));
//b2.reSize(new Coordinates(10,10));
System.out.println("Apres : " + b1 + "\n\t" + b2);
System.out.println("Intersection : " + b1.intersection(b2));
}
catch (NegativeCoordinatesException e)
{
}
}
|
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesTemplateEngine.java b/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesTemplateEngine.java
index c4ad8dd5b..8333009a6 100644
--- a/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesTemplateEngine.java
+++ b/grails/src/web/org/codehaus/groovy/grails/web/pages/GroovyPagesTemplateEngine.java
@@ -1,511 +1,513 @@
/* 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.pages;
import groovy.lang.*;
import groovy.text.Template;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsServiceClass;
import org.codehaus.groovy.grails.web.metaclass.ControllerDynamicMethods;
import org.codehaus.groovy.grails.web.metaclass.GetParamsDynamicProperty;
import org.codehaus.groovy.grails.web.metaclass.GetSessionDynamicProperty;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.DefaultGrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsHttpSession;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsParameterMap;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.springframework.context.ApplicationContext;
/**
* A GroovyPagesTemplateEngine based on (but not extending) the existing TemplateEngine implementations
* within Groovy. It allows GSP pages to be re-used in different context using code like the below:
*
* <code>
* Template t = new GroovyPagesTemplateEngine()
* .createTemplate(context,request,response);
* t.make()
* .writeTo(out);
* </code>
*
* @author Graeme Rocher
* @since 0.1
*
* Created: 12-Jan-2006
*/
public class GroovyPagesTemplateEngine {
private static final Log LOG = LogFactory.getLog(GroovyPagesTemplateEngine.class);
private static Map pageCache = Collections.synchronizedMap(new HashMap());
private boolean showSource;
private GroovyClassLoader classLoader;
public void setClassLoader(GroovyClassLoader classLoader) {
this.classLoader = classLoader;
}
/**
* Set whether to show the compiled source in the response
* @param showSource Sets whether to show the generated Groovy source of the GSP
*/
public void setShowSource(boolean showSource) {
this.showSource = showSource;
}
/**
* Retrieves a line number matrix for the specified page that can be used
* to retrieve the actual line number within the GSP page if the line number within the
* compiled GSP is known
*
* @param context The ServletContext instance
* @param url The URL of the page
* @return An array where the index is the line number witin the compiled GSP and the value is the line number within the source
*/
public int[] getLineNumbersForPage(ServletContext context,String url) {
URL pageUrl;
try {
pageUrl = getPageUrl(context, url);
if(pageUrl != null) {
PageMeta pm = getPage(url,context,pageUrl,false);
if(pm != null) {
return pm.lineNumbers;
}
}
} catch (Exception e) {
// ignore, non critical method used for retrieving debug info
LOG.warn("Exception retrieving line numbers from GSP: " + url + ", message: " + e.getMessage());
LOG.debug("Full stack trace of error", e);
}
return new int[0]; //To change body of created methods use File | Settings | File Templates.
}
private static class PageMeta {
private Class servletScriptClass;
private long lastModified;
private Map dependencies = new HashMap();
private InputStream groovySource;
public String contentType;
public int[] lineNumbers;
} // PageMeta
/**
* Create a template for the current request
*
* @param context The ServletContext instance
* @param request The HttpServletRequest instance
* @param response The HttpServletResponse instance
* @return The created template or null if the page was not found
* @throws IOException
* @throws ServletException
*/
public Template createTemplate(ServletContext context, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
String uri = getPageId(request);
return createTemplate(uri,context,request,response);
}
/**
* Creates a template for the specified uri
*
* @param uri The URI of the template
* @param context The ServletContext instance
* @param request The HttpServletRequest instance
* @param response The HttpServletResponse instance
* @return The created template or null if the page was not found for the specified uri
* @throws IOException
* @throws ServletException
*/
public Template createTemplate(String uri, ServletContext context, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
URL pageUrl = getPageUrl(context,uri);
if (pageUrl == null) {
context.log("GroovyPagesServlet: \"" + pageUrl + "\" not found");
return null;
}
boolean spillGroovy = showSource && request.getParameter("showSource") != null;
PageMeta pageMeta = getPage(uri, context,pageUrl, spillGroovy);
return new GroovyPagesTemplate(context,request,response,pageMeta,spillGroovy);
}
/**
* Return the page identifier.
* @param request The HttpServletRequest instance
* @return The page id
*/
protected String getPageId(HttpServletRequest request) {
// Get the name of the Groovy script (intern the name so that we can
// lock on it)
Object includePath = request.getAttribute("javax.servlet.include.servlet_path");
if (includePath != null) {
return ((String) includePath).intern();
} else {
return request.getServletPath().intern();
}
} // getPageId()
/**
* Return the page URL from the request path.
* @param pageId The page URI as a string
* @return The java.net.URL of the page or null
* @throws java.net.MalformedURLException
* @param context The ServletContext instances
*/
protected URL getPageUrl(ServletContext context, String pageId) throws MalformedURLException {
// Check to make sure that the file exists in the web application
if(LOG.isDebugEnabled()) {
LOG.debug("Loading GSP for url ["+pageId+"]");
}
URL url = context.getResource(pageId);
if(url == null) {
StringBuffer buf = new StringBuffer();
String[] tokens;
if(pageId.startsWith("/"))
tokens = pageId.substring(1).split("/");
else
tokens = pageId.split("/");
buf.append(GrailsApplicationAttributes.PATH_TO_VIEWS);
buf.append('/');
if(tokens.length > 0) {
buf.append(tokens[0]);
buf.append('/');
}
if(tokens.length > 1) {
buf.append(tokens[1]);
}
buf.append(GrailsApplicationAttributes.GSP_FILE_EXTENSION);
String secondTry = buf.toString();
if(LOG.isDebugEnabled()) {
LOG.debug("Page ["+pageId+"] doesn't exist, trying ["+secondTry+"]");
}
url = context.getResource(secondTry);
}
return url;
} // getPageUrl()
/**
* Lookup page class or load new one if needed.
* @param uri The URI of the page as a String
* @param pageUrl The URL instance of the page
* @param spillGroovy Whether to show the generated source
* @return The PageMeta instance of the page with info about the last modified date, the class and so on
*
* @throws IOException Thrown when there were problems reading the page or writing to the response
* @throws javax.servlet.ServletException
* @param context The ServletContext instance
*
*/
protected PageMeta getPage(String uri, ServletContext context,URL pageUrl, boolean spillGroovy)
throws IOException, ServletException {
// Lock on the uri to ensure that only one compile occurs for any script
synchronized (uri) {
// Get the URLConnection
URLConnection groovyScriptConn = pageUrl.openConnection();
// URL last modified
long lastModified = groovyScriptConn.getLastModified();
// Check the cache for the script
PageMeta pageMeta = (PageMeta)pageCache.get(uri);
// If the pageMeta isn't null check all the dependencies
boolean dependencyOutOfDate = false;
if (pageMeta != null && !spillGroovy) {
isPageNew(pageMeta);
}
if (pageMeta == null || pageMeta.lastModified < lastModified || dependencyOutOfDate || spillGroovy) {
pageMeta = newPage(uri, context,groovyScriptConn, lastModified, spillGroovy);
}
return pageMeta;
}
} // getPage()
/**
* Creates a new PageMeta instance of the specified page URI
* @param uri The URI of the page as a String
* @param groovyScriptConn The URLConnection for the page
* @param lastModified The last time it was modified
* @param spillGroovy Whether to show the generated source
* @return The created PageMeta instance
* @throws IOException Thrown when an error occurs reading or writing the page
* @throws ServletException
* @param context The ServletContext instance
*/
private PageMeta newPage(String uri, ServletContext context,URLConnection groovyScriptConn, long lastModified,
boolean spillGroovy) throws IOException, ServletException {
Parse parse = new Parse(uri, groovyScriptConn.getInputStream());
InputStream in = parse.parse();
// Make a new pageMeta
PageMeta pageMeta = new PageMeta();
pageMeta.contentType = parse.getContentType();
pageMeta.lineNumbers = parse.getLineNumberMatrix();
// just return groovy and don't compile if asked
if (spillGroovy) {
if(LOG.isDebugEnabled()){
LOG.debug("Show source enabled, display generated GSP source...");
}
pageMeta.groovySource = in;
return pageMeta;
}
// Compile the script into an object
Loader loader = new Loader(classLoader, context, uri, pageMeta.dependencies);
Class scriptClass;
try {
scriptClass =
loader.parseClass(in, uri.substring(1));
} catch (CompilationFailedException e) {
LOG.error("Compilation error compiling GSP ["+uri+"]:" + e.getMessage(), e);
throw new ServletException("Could not parse script: " + uri, e);
}
pageMeta.servletScriptClass = scriptClass;
pageMeta.lastModified = lastModified;
pageCache.put(uri, pageMeta);
return pageMeta;
} // newPage()
/**
* Is page new or changed?
* @param pageMeta page data
* @return true if compile needed
*/
private boolean isPageNew(PageMeta pageMeta) {
for (Iterator i = pageMeta.dependencies.keySet().iterator(); i.hasNext(); ) {
URLConnection urlc;
URL url = (URL)i.next();
try {
urlc = url.openConnection();
urlc.setDoInput(false);
urlc.setDoOutput(false);
long dependentLastModified = urlc.getLastModified();
if (dependentLastModified > ((Long)pageMeta.dependencies.get(url)).longValue()) {
return true;
}
} catch (IOException ioe) {
LOG.debug("I/O exception checking last modified date of GSP: " + ioe.getMessage(),ioe);
return true;
}
}
return false;
} // isPageNew()
/**
* An instance of the groovy.text.Template interface that knows how to
* make in instance of GroovyPageTemplateWritable
*
* @author Graeme Rocher
* @since 12-Jan-2006
*/
protected static class GroovyPagesTemplate implements Template {
private HttpServletResponse response;
private HttpServletRequest request;
private ServletContext context;
private boolean showSource = false;
private PageMeta pageMeta;
public GroovyPagesTemplate(ServletContext context,
HttpServletRequest request,
HttpServletResponse response,
PageMeta pageMeta,
boolean showSource) {
this.request = request;
this.response = response;
this.context = context;
this.showSource = showSource;
this.pageMeta = pageMeta;
}
public Writable make() {
return new GroovyPageTemplateWritable(context,request,response,pageMeta,showSource);
}
public Writable make(Map binding) {
GroovyPageTemplateWritable gptw = new GroovyPageTemplateWritable(context,request,response,pageMeta,showSource);
gptw.setBinding(binding);
return gptw;
}
}
/**
* An instance of groovy.lang.Writable that writes itself to the specified
* writer, typically the response writer
*
* @author Graeme Rocher
* @since 12-Jan-2006
*/
protected static class GroovyPageTemplateWritable implements Writable {
private HttpServletResponse response;
private HttpServletRequest request;
private PageMeta pageMeta;
private boolean showSource;
private ServletContext context;
private Map additionalBinding = new HashMap();
public GroovyPageTemplateWritable(ServletContext context,
HttpServletRequest request,
HttpServletResponse response,
PageMeta pageMeta,
boolean showSource) {
this.request = request;
this.response = response;
this.pageMeta = pageMeta;
this.showSource = showSource;
this.context = context;
}
public void setBinding(Map binding) {
if(binding != null)
this.additionalBinding = binding;
}
public Writer writeTo(Writer out) throws IOException {
if (showSource) {
// Set it to TEXT
response.setContentType("text/plain"); // must come before response.getOutputStream()
send(pageMeta.groovySource, out);
pageMeta.groovySource = null;
} else {
// Set it to HTML by default
if(LOG.isDebugEnabled() && !response.isCommitted()) {
LOG.debug("Writing response with content type: " + pageMeta.contentType);
}
if(!response.isCommitted())
response.setContentType(pageMeta.contentType); // must come before response.getWriter()
Binding binding = getBinding(request, response, out);
Script page = InvokerHelper.createScript(pageMeta.servletScriptClass, binding);
page.run();
}
return out;
}
/**
* Copy all of input to output.
* @param in The input stream to send from
* @param out The output to write to
* @throws IOException
*/
public static void send(InputStream in, Writer out) throws IOException {
try {
Reader reader = new InputStreamReader(in);
char[] buf = new char[8192];
for (;;) {
int read = reader.read(buf);
if (read <= 0) break;
out.write(buf, 0, read);
}
} finally {
out.close();
in.close();
}
} // send()
/**
* Prepare Bindings before instantiating page.
* @param request The HttpServletRequest instance
* @param response The HttpServletResponse instance
* @param out The response out
* @return the Bindings
* @throws IOException
*/
protected Binding getBinding(HttpServletRequest request, HttpServletResponse response, Writer out)
throws IOException {
// Set up the script context
Binding binding = new Binding();
GroovyObject controller = (GroovyObject)request.getAttribute(GrailsApplicationAttributes.CONTROLLER);
boolean initialiseFromRequest = false;
if(controller!=null) {
try {
binding.setVariable(GroovyPage.REQUEST, controller.getProperty(ControllerDynamicMethods.REQUEST_PROPERTY));
binding.setVariable(GroovyPage.RESPONSE, controller.getProperty(ControllerDynamicMethods.RESPONSE_PROPERTY));
binding.setVariable(GroovyPage.FLASH, controller.getProperty(ControllerDynamicMethods.FLASH_SCOPE_PROPERTY));
binding.setVariable(GroovyPage.SERVLET_CONTEXT, context);
ApplicationContext appContext = (ApplicationContext)context.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
binding.setVariable(GroovyPage.APPLICATION_CONTEXT, appContext);
binding.setVariable(GrailsApplication.APPLICATION_ID, appContext.getBean(GrailsApplication.APPLICATION_ID));
binding.setVariable(GrailsApplicationAttributes.CONTROLLER, controller);
binding.setVariable(GroovyPage.SESSION, controller.getProperty(GetSessionDynamicProperty.PROPERTY_NAME));
binding.setVariable(GroovyPage.PARAMS, controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME));
binding.setVariable(GroovyPage.PLUGIN_CONTEXT_PATH, controller.getProperty(GroovyPage.PLUGIN_CONTEXT_PATH));
binding.setVariable(GroovyPage.OUT, out);
- initialiseFromRequest = true;
}
catch(MissingPropertyException mpe) {
initialiseFromRequest = true;
}
}
+ else {
+ initialiseFromRequest = true;
+ }
if(initialiseFromRequest) {
// if there is no controller in the request configure using existing attributes, creating objects where necessary
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)request.getAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID);
if(attrs == null) attrs = new DefaultGrailsApplicationAttributes(context);
binding.setVariable(GroovyPage.REQUEST, request);
binding.setVariable(GroovyPage.RESPONSE, response);
binding.setVariable(GroovyPage.FLASH, attrs.getFlashScope(request));
binding.setVariable(GroovyPage.SERVLET_CONTEXT, context);
ApplicationContext appContext = (ApplicationContext)context.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
binding.setVariable(GroovyPage.APPLICATION_CONTEXT, appContext);
binding.setVariable(GrailsApplication.APPLICATION_ID, appContext.getBean(GrailsApplication.APPLICATION_ID));
binding.setVariable(GroovyPage.SESSION, new GrailsHttpSession(request.getSession()));
binding.setVariable(GroovyPage.PARAMS, new GrailsParameterMap(request));
binding.setVariable(GroovyPage.OUT, out);
}
// Go through request attributes and add them to the binding as the model
for (Enumeration attributeEnum = request.getAttributeNames(); attributeEnum.hasMoreElements();) {
String key = (String) attributeEnum.nextElement();
if(!binding.getVariables().containsKey(key)) {
binding.setVariable( key, request.getAttribute(key) );
}
}
for (Iterator i = additionalBinding.keySet().iterator(); i.hasNext();) {
String key = (String)i.next();
binding.setVariable(key, additionalBinding.get(key));
}
return binding;
} // getBinding()
}
}
| false | true | protected Binding getBinding(HttpServletRequest request, HttpServletResponse response, Writer out)
throws IOException {
// Set up the script context
Binding binding = new Binding();
GroovyObject controller = (GroovyObject)request.getAttribute(GrailsApplicationAttributes.CONTROLLER);
boolean initialiseFromRequest = false;
if(controller!=null) {
try {
binding.setVariable(GroovyPage.REQUEST, controller.getProperty(ControllerDynamicMethods.REQUEST_PROPERTY));
binding.setVariable(GroovyPage.RESPONSE, controller.getProperty(ControllerDynamicMethods.RESPONSE_PROPERTY));
binding.setVariable(GroovyPage.FLASH, controller.getProperty(ControllerDynamicMethods.FLASH_SCOPE_PROPERTY));
binding.setVariable(GroovyPage.SERVLET_CONTEXT, context);
ApplicationContext appContext = (ApplicationContext)context.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
binding.setVariable(GroovyPage.APPLICATION_CONTEXT, appContext);
binding.setVariable(GrailsApplication.APPLICATION_ID, appContext.getBean(GrailsApplication.APPLICATION_ID));
binding.setVariable(GrailsApplicationAttributes.CONTROLLER, controller);
binding.setVariable(GroovyPage.SESSION, controller.getProperty(GetSessionDynamicProperty.PROPERTY_NAME));
binding.setVariable(GroovyPage.PARAMS, controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME));
binding.setVariable(GroovyPage.PLUGIN_CONTEXT_PATH, controller.getProperty(GroovyPage.PLUGIN_CONTEXT_PATH));
binding.setVariable(GroovyPage.OUT, out);
initialiseFromRequest = true;
}
catch(MissingPropertyException mpe) {
initialiseFromRequest = true;
}
}
if(initialiseFromRequest) {
// if there is no controller in the request configure using existing attributes, creating objects where necessary
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)request.getAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID);
if(attrs == null) attrs = new DefaultGrailsApplicationAttributes(context);
binding.setVariable(GroovyPage.REQUEST, request);
binding.setVariable(GroovyPage.RESPONSE, response);
binding.setVariable(GroovyPage.FLASH, attrs.getFlashScope(request));
binding.setVariable(GroovyPage.SERVLET_CONTEXT, context);
ApplicationContext appContext = (ApplicationContext)context.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
binding.setVariable(GroovyPage.APPLICATION_CONTEXT, appContext);
binding.setVariable(GrailsApplication.APPLICATION_ID, appContext.getBean(GrailsApplication.APPLICATION_ID));
binding.setVariable(GroovyPage.SESSION, new GrailsHttpSession(request.getSession()));
binding.setVariable(GroovyPage.PARAMS, new GrailsParameterMap(request));
binding.setVariable(GroovyPage.OUT, out);
}
// Go through request attributes and add them to the binding as the model
for (Enumeration attributeEnum = request.getAttributeNames(); attributeEnum.hasMoreElements();) {
String key = (String) attributeEnum.nextElement();
if(!binding.getVariables().containsKey(key)) {
binding.setVariable( key, request.getAttribute(key) );
}
}
for (Iterator i = additionalBinding.keySet().iterator(); i.hasNext();) {
String key = (String)i.next();
binding.setVariable(key, additionalBinding.get(key));
}
return binding;
} // getBinding()
| protected Binding getBinding(HttpServletRequest request, HttpServletResponse response, Writer out)
throws IOException {
// Set up the script context
Binding binding = new Binding();
GroovyObject controller = (GroovyObject)request.getAttribute(GrailsApplicationAttributes.CONTROLLER);
boolean initialiseFromRequest = false;
if(controller!=null) {
try {
binding.setVariable(GroovyPage.REQUEST, controller.getProperty(ControllerDynamicMethods.REQUEST_PROPERTY));
binding.setVariable(GroovyPage.RESPONSE, controller.getProperty(ControllerDynamicMethods.RESPONSE_PROPERTY));
binding.setVariable(GroovyPage.FLASH, controller.getProperty(ControllerDynamicMethods.FLASH_SCOPE_PROPERTY));
binding.setVariable(GroovyPage.SERVLET_CONTEXT, context);
ApplicationContext appContext = (ApplicationContext)context.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
binding.setVariable(GroovyPage.APPLICATION_CONTEXT, appContext);
binding.setVariable(GrailsApplication.APPLICATION_ID, appContext.getBean(GrailsApplication.APPLICATION_ID));
binding.setVariable(GrailsApplicationAttributes.CONTROLLER, controller);
binding.setVariable(GroovyPage.SESSION, controller.getProperty(GetSessionDynamicProperty.PROPERTY_NAME));
binding.setVariable(GroovyPage.PARAMS, controller.getProperty(GetParamsDynamicProperty.PROPERTY_NAME));
binding.setVariable(GroovyPage.PLUGIN_CONTEXT_PATH, controller.getProperty(GroovyPage.PLUGIN_CONTEXT_PATH));
binding.setVariable(GroovyPage.OUT, out);
}
catch(MissingPropertyException mpe) {
initialiseFromRequest = true;
}
}
else {
initialiseFromRequest = true;
}
if(initialiseFromRequest) {
// if there is no controller in the request configure using existing attributes, creating objects where necessary
GrailsApplicationAttributes attrs = (GrailsApplicationAttributes)request.getAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID);
if(attrs == null) attrs = new DefaultGrailsApplicationAttributes(context);
binding.setVariable(GroovyPage.REQUEST, request);
binding.setVariable(GroovyPage.RESPONSE, response);
binding.setVariable(GroovyPage.FLASH, attrs.getFlashScope(request));
binding.setVariable(GroovyPage.SERVLET_CONTEXT, context);
ApplicationContext appContext = (ApplicationContext)context.getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT);
binding.setVariable(GroovyPage.APPLICATION_CONTEXT, appContext);
binding.setVariable(GrailsApplication.APPLICATION_ID, appContext.getBean(GrailsApplication.APPLICATION_ID));
binding.setVariable(GroovyPage.SESSION, new GrailsHttpSession(request.getSession()));
binding.setVariable(GroovyPage.PARAMS, new GrailsParameterMap(request));
binding.setVariable(GroovyPage.OUT, out);
}
// Go through request attributes and add them to the binding as the model
for (Enumeration attributeEnum = request.getAttributeNames(); attributeEnum.hasMoreElements();) {
String key = (String) attributeEnum.nextElement();
if(!binding.getVariables().containsKey(key)) {
binding.setVariable( key, request.getAttribute(key) );
}
}
for (Iterator i = additionalBinding.keySet().iterator(); i.hasNext();) {
String key = (String)i.next();
binding.setVariable(key, additionalBinding.get(key));
}
return binding;
} // getBinding()
|
diff --git a/src/main/java/gov/usgs/cida/geoutils/geoserver/servlet/ShapefileUploadServlet.java b/src/main/java/gov/usgs/cida/geoutils/geoserver/servlet/ShapefileUploadServlet.java
index d48cac9..9c80fb3 100644
--- a/src/main/java/gov/usgs/cida/geoutils/geoserver/servlet/ShapefileUploadServlet.java
+++ b/src/main/java/gov/usgs/cida/geoutils/geoserver/servlet/ShapefileUploadServlet.java
@@ -1,534 +1,534 @@
package gov.usgs.cida.geoutils.geoserver.servlet;
import gov.usgs.cida.config.DynamicReadOnlyProperties;
import gov.usgs.cida.owsutils.commons.communication.RequestResponse;
import gov.usgs.cida.owsutils.commons.io.FileHelper;
import gov.usgs.cida.owsutils.commons.properties.JNDISingleton;
import gov.usgs.cida.owsutils.commons.shapefile.ProjectionUtils;
import it.geosolutions.geoserver.rest.GeoServerRESTManager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder.ProjectionPolicy;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.jxpath.JXPathContext;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
public class ShapefileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final org.slf4j.Logger LOG = LoggerFactory.getLogger(ShapefileUploadServlet.class);
private static DynamicReadOnlyProperties props = null;
private static String applicationName;
private static Integer maxFileSize;
private static String geoserverEndpoint;
private static URL geoserverEndpointURL;
private static String geoserverUsername;
private static String geoserverPassword;
private static GeoServerRESTManager gsRestManager;
// Defaults
private static String defaultWorkspaceName;
private static String defaultStoreName;
private static String defaultSRS;
private static String defaultFilenameParam = "qqfile"; // Legacy to handle jquery fineuploader
private static Integer defaultMaxFileSize = Integer.MAX_VALUE;
private static boolean defaultUseBaseCRSFallback = true;
private static boolean defaultOverwriteExistingLayer = false;
private static ProjectionPolicy defaultProjectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
private static ServletConfig servletConfig;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
super.init();
ShapefileUploadServlet.servletConfig = servletConfig;
props = JNDISingleton.getInstance();
applicationName = servletConfig.getInitParameter("application.name");
Enumeration<String> initParameterNames = servletConfig.getInitParameterNames();
while (initParameterNames.hasMoreElements()) {
String initPKey = initParameterNames.nextElement();
if (StringUtils.isBlank(props.getProperty(applicationName + "." + initPKey))) {
String initPVal = servletConfig.getInitParameter(initPKey);
if (StringUtils.isNotBlank(initPVal)) {
LOG.debug("Could not find JNDI property for " + applicationName + "." + initPKey + ". Substituting the value from web.xml");
props.setProperty(applicationName + "." + initPKey, initPVal);
}
}
}
// The maximum upload file size allowd by this server, 0 = Integer.MAX_VALUE
String mfsJndiProp = props.getProperty(applicationName + ".max.upload.file.size");
if (StringUtils.isNotBlank(mfsJndiProp)) {
maxFileSize = Integer.parseInt(mfsJndiProp);
} else {
maxFileSize = defaultMaxFileSize;
}
if (maxFileSize == 0) {
maxFileSize = defaultMaxFileSize;
}
LOG.debug("Maximum allowable file size set to: " + maxFileSize + " bytes");
String gsepJndiProp = props.getProperty(applicationName + ".geoserver.endpoint");
if (StringUtils.isNotBlank(gsepJndiProp)) {
geoserverEndpoint = gsepJndiProp;
if (geoserverEndpoint.endsWith("/")) {
geoserverEndpoint = geoserverEndpoint.substring(0, geoserverEndpoint.length() - 1);
}
} else {
throw new ServletException("Geoserver endpoint is not defined.");
}
LOG.debug("Geoserver endpoint set to: " + geoserverEndpoint);
try {
geoserverEndpointURL = new URL(geoserverEndpoint);
} catch (MalformedURLException ex) {
throw new ServletException("Geoserver endpoint (" + geoserverEndpoint + ") could not be parsed into a valid URL.");
}
String gsuserJndiProp = props.getProperty(applicationName + ".geoserver.username");
if (StringUtils.isNotBlank(gsuserJndiProp)) {
geoserverUsername = gsuserJndiProp;
} else {
throw new ServletException("Geoserver username is not defined.");
}
LOG.debug("Geoserver username set to: " + geoserverUsername);
// This should only be coming from JNDI or JVM properties
String gspassJndiProp = props.getProperty(applicationName + ".geoserver.password");
if (StringUtils.isNotBlank(gspassJndiProp)) {
geoserverPassword = gspassJndiProp;
} else {
throw new ServletException("Geoserver password is not defined.");
}
LOG.debug("Geoserver password is set");
try {
gsRestManager = new GeoServerRESTManager(geoserverEndpointURL, geoserverUsername, geoserverPassword);
} catch (IllegalArgumentException ex) {
throw new ServletException("Geoserver manager count not be built", ex);
} catch (MalformedURLException ex) {
// This should not happen since we take care of it above - we can probably move this into the try block above
throw new ServletException("Geoserver endpoint (" + geoserverEndpoint + ") could not be parsed into a valid URL.");
}
String dwJndiProp = props.getProperty(applicationName + ".default.upload.workspace");
if (StringUtils.isNotBlank(dwJndiProp)) {
defaultWorkspaceName = dwJndiProp;
} else {
defaultWorkspaceName = "";
LOG.warn("Default workspace is not defined. If a workspace is not passed to during the request, the request will fail.");
}
LOG.debug("Default workspace set to: " + defaultWorkspaceName);
String dsnJndiProp = props.getProperty(applicationName + ".default.upload.storename");
if (StringUtils.isNotBlank(dsnJndiProp)) {
defaultStoreName = dsnJndiProp;
} else {
defaultStoreName = "";
LOG.warn("Default store name is not defined. If a store name is not passed to during the request, the name of the layer will be used as the name of the store");
}
LOG.debug("Default store name set to: " + defaultStoreName);
String dsrsJndiProp = props.getProperty(applicationName + ".default.srs");
if (StringUtils.isNotBlank(dsrsJndiProp)) {
defaultSRS = dsrsJndiProp;
} else {
defaultSRS = "";
LOG.warn("Default SRS is not defined. If a SRS name is not passed to during the request, the request will fail");
}
LOG.debug("Default SRS set to: " + defaultSRS);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException {
String filenameParam;
boolean useBaseCRSFailover;
boolean overwriteExistingLayer;
// "reproject" (default), "force", "none"
ProjectionPolicy projectionPolicy;
Map<String, String> responseMap = new HashMap<String, String>();
RequestResponse.ResponseType responseType = RequestResponse.ResponseType.XML;
String responseEncoding = request.getParameter("response.encoding");
if (StringUtils.isBlank(responseEncoding) || responseEncoding.toLowerCase().contains("json")) {
responseType = RequestResponse.ResponseType.JSON;
}
LOG.debug("Response type set to " + responseType.toString());
int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
if (fileSize > maxFileSize) {
responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
// The key to search for in the upload form post to find the file
String fnInitParam = servletConfig.getInitParameter("filename.param");
String fnJndiProp = props.getProperty(applicationName + ".filename.param");
String fnReqParam = request.getParameter("filename.param");
if (StringUtils.isNotBlank(fnReqParam)) {
filenameParam = fnReqParam;
} else if (StringUtils.isNotBlank(fnInitParam)) {
filenameParam = fnInitParam;
} else if (StringUtils.isNotBlank(fnJndiProp)) {
filenameParam = fnJndiProp;
} else {
filenameParam = defaultFilenameParam;
}
LOG.debug("Filename parameter set to: " + filenameParam);
String oelInitParam = servletConfig.getInitParameter("overwrite.existing.layer");
String oelJndiProp = props.getProperty(applicationName + ".overwrite.existing.layer");
String oelReqParam = request.getParameter("overwrite.existing.layer");
if (StringUtils.isNotBlank(oelReqParam)) {
overwriteExistingLayer = Boolean.parseBoolean(oelReqParam);
} else if (StringUtils.isNotBlank(oelInitParam)) {
overwriteExistingLayer = Boolean.parseBoolean(oelInitParam);
} else if (StringUtils.isNotBlank(oelJndiProp)) {
overwriteExistingLayer = Boolean.parseBoolean(oelJndiProp);
} else {
overwriteExistingLayer = defaultOverwriteExistingLayer;
}
LOG.debug("Overwrite existing layer set to: " + overwriteExistingLayer);
LOG.debug("Cleaning file name.\nWas: " + filenameParam);
String filename = cleanFileName(request.getParameter(filenameParam));
LOG.debug("Is: " + filename);
if (filenameParam.equals(filename)) {
LOG.debug("(No change)");
}
String tempDir = System.getProperty("java.io.tmpdir");
File shapeZipFile = new File(tempDir + File.separator + filename);
LOG.debug("Temporary file set to " + shapeZipFile.getPath());
String layerName = request.getParameter("layer");
if (StringUtils.isBlank(layerName)) {
layerName = filename.split("\\.")[0];
}
layerName = layerName.trim().replaceAll("\\.", "_").replaceAll(" ", "_");
LOG.debug("Layer name set to " + layerName);
String workspaceName = request.getParameter("workspace");
if (StringUtils.isBlank(workspaceName)) {
workspaceName = defaultWorkspaceName;
}
if (StringUtils.isBlank(workspaceName)) {
responseMap.put("error", "Parameter \"workspace\" is mandatory");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
LOG.debug("Workspace name set to " + workspaceName);
String storeName = request.getParameter("store");
if (StringUtils.isBlank(storeName)) {
storeName = defaultStoreName;
}
if (StringUtils.isBlank(storeName)) {
storeName = layerName;
}
LOG.debug("Store name set to " + storeName);
String srsName = request.getParameter("srs");
if (StringUtils.isBlank(srsName)) {
srsName = defaultSRS;
}
if (StringUtils.isBlank(srsName)) {
responseMap.put("error", "Parameter \"srs\" is mandatory");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
LOG.debug("SRS name set to " + srsName);
String bCRSfoInitParam = servletConfig.getInitParameter("use.crs.failover");
String bCRSfoJndiProp = props.getProperty(applicationName + ".use.crs.failover");
String bCRSfoReqParam = request.getParameter("use.crs.failover");
if (StringUtils.isNotBlank(bCRSfoReqParam)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoReqParam);
} else if (StringUtils.isNotBlank(bCRSfoInitParam)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoInitParam);
} else if (StringUtils.isNotBlank(bCRSfoJndiProp)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoJndiProp);
} else {
useBaseCRSFailover = defaultUseBaseCRSFallback;
}
LOG.debug("Use base CRS failover set to: " + useBaseCRSFailover);
String projectionPolicyReqParam = request.getParameter("projection.policy");
String ppInitParam = servletConfig.getInitParameter("projection.policy");
String ppJndiProp = props.getProperty(applicationName + ".projection.policy");
if (StringUtils.isNotBlank(projectionPolicyReqParam)) {
if (projectionPolicyReqParam.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (projectionPolicyReqParam.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = defaultProjectionPolicy;
}
} else if (StringUtils.isNotBlank(ppInitParam)) {
if (ppInitParam.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (ppInitParam.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = ProjectionPolicy.NONE;
}
} else if (StringUtils.isNotBlank(ppJndiProp)) {
if (ppJndiProp.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (ppJndiProp.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = ProjectionPolicy.NONE;
}
} else {
projectionPolicy = defaultProjectionPolicy;
}
LOG.debug("Projection policy set to: " + projectionPolicy.name());
LOG.debug("Projection policy re-set to: " + projectionPolicy);
try {
RequestResponse.saveFileFromRequest(request, shapeZipFile, filenameParam);
LOG.debug("File saved to " + shapeZipFile.getPath());
FileHelper.flattenZipFile(shapeZipFile.getPath());
LOG.debug("Zip file directory structure flattened");
FileHelper.validateShapefileZip(shapeZipFile);
LOG.debug("Zip file seems to be a valid shapefile");
} catch (Exception ex) {
LOG.warn(ex.getMessage());
responseMap.put("error", "Unable to upload file");
responseMap.put("exception", ex.getMessage());
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
try {
- ProjectionUtils.getProjectionFromShapefileZip(shapeZipFile, false);
+ srsName = ProjectionUtils.getProjectionFromShapefileZip(shapeZipFile, false);
} catch (Exception ex) {
responseMap.put("warning", "WARNING: Could not find EPSG code for prj definition. The geographic coordinate system '"+srsName+"' will be used ");
}
String importResponse;
try {
GeoServerRESTPublisher gsPublisher = gsRestManager.getPublisher();
if (overwriteExistingLayer) {
// TODO- Using this library, I am unable to rename a layer. If publishing the layer
// fails, we will have lost this layer due to removal here.
if (gsPublisher.unpublishFeatureType(workspaceName, storeName, layerName)) {
gsPublisher.unpublishCoverage(workspaceName, storeName, layerName);
gsPublisher.reloadStore(workspaceName, storeName, GeoServerRESTPublisher.StoreType.DATASTORES);
}
}
importResponse = importUsingWPS(workspaceName, storeName, layerName, shapeZipFile.toURI(), srsName, projectionPolicy, null);
if (importResponse.toLowerCase().contains("exception")) {
String error = parseWPSErrorText(importResponse);
LOG.debug("Shapefile could not be imported successfully");
responseMap.put("error", error);
RequestResponse.sendErrorResponse(response, responseMap, responseType);
} else {
LOG.debug("Shapefile has been imported successfully");
responseMap.put("name", importResponse);
responseMap.put("workspace", workspaceName);
responseMap.put("store", storeName);
RequestResponse.sendSuccessResponse(response, responseMap, responseType);
}
} catch (Exception ex) {
LOG.warn(ex.getMessage());
responseMap.put("error", "Unable to upload file");
responseMap.put("exception", ex.getMessage());
RequestResponse.sendErrorResponse(response, responseMap, responseType);
} finally {
FileUtils.deleteQuietly(shapeZipFile);
}
}
private String importUsingWPS(String workspaceName, String storeName, String layerName, URI shapefile, String srsName, ProjectionPolicy projectionPolicy, String styleName) throws IOException {
FileOutputStream wpsRequestOutputStream = null;
FileInputStream uploadedInputStream = null;
File wpsRequestFile = File.createTempFile("wps.upload.", ".xml");
wpsRequestFile.deleteOnExit();
try {
wpsRequestOutputStream = new FileOutputStream(wpsRequestFile);
uploadedInputStream = new FileInputStream(new File(shapefile));
wpsRequestOutputStream.write(new String(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<wps:Execute service=\"WPS\" version=\"1.0.0\" "
+ "xmlns:wps=\"http://www.opengis.net/wps/1.0.0\" "
+ "xmlns:ows=\"http://www.opengis.net/ows/1.1\" "
+ "xmlns:xlink=\"http://www.w3.org/1999/xlink\" "
+ "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" "
+ "xsi:schemaLocation=\"http://www.opengis.net/wps/1.0.0 "
+ "http://schemas.opengis.net/wps/1.0.0/wpsExecute_request.xsd\">"
+ "<ows:Identifier>gs:Import</ows:Identifier>"
+ "<wps:DataInputs>"
+ "<wps:Input>"
+ "<ows:Identifier>features</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:ComplexData mimeType=\"application/zip\"><![CDATA[").getBytes());
IOUtils.copy(uploadedInputStream, new Base64OutputStream(wpsRequestOutputStream, true, 0, null));
wpsRequestOutputStream.write(new String(
"]]></wps:ComplexData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>workspace</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + workspaceName + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>store</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + storeName + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>name</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + layerName + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>srs</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + srsName + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>"
+ "<wps:Input>"
+ "<ows:Identifier>srsHandling</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + projectionPolicy + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>").getBytes());
// TODO- Not yet implemented
if (StringUtils.isNotBlank(styleName)) {
wpsRequestOutputStream.write(new String(
"<wps:Input>"
+ "<ows:Identifier>styleName</ows:Identifier>"
+ "<wps:Data>"
+ "<wps:LiteralData>" + styleName + "</wps:LiteralData>"
+ "</wps:Data>"
+ "</wps:Input>").getBytes());
}
wpsRequestOutputStream.write(new String(
"</wps:DataInputs>"
+ "<wps:ResponseForm>"
+ "<wps:RawDataOutput>"
+ "<ows:Identifier>layerName</ows:Identifier>"
+ "</wps:RawDataOutput>"
+ "</wps:ResponseForm>"
+ "</wps:Execute>").getBytes());
} finally {
IOUtils.closeQuietly(wpsRequestOutputStream);
IOUtils.closeQuietly(uploadedInputStream);
}
String url = geoserverEndpointURL.toString();
return postToWPS(url + (url.endsWith("/") ? "" : "/") + "wps/WebProcessingService?Service=WPS&Request=execute&identifier=gs:Import", wpsRequestFile);
}
private String postToWPS(String url, File wpsRequestFile) throws IOException {
HttpPost post;
HttpClient httpClient = new DefaultHttpClient();
post = new HttpPost(url);
FileInputStream wpsRequestInputStream = null;
try {
wpsRequestInputStream = new FileInputStream(wpsRequestFile);
AbstractHttpEntity entity = new InputStreamEntity(wpsRequestInputStream, wpsRequestFile.length());
post.setEntity(entity);
HttpResponse response = httpClient.execute(post);
return EntityUtils.toString(response.getEntity());
} finally {
IOUtils.closeQuietly(wpsRequestInputStream);
FileUtils.deleteQuietly(wpsRequestFile);
}
}
private String parseWPSErrorText(String xml) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
dbFactory.setValidating(false);
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(new ByteArrayInputStream(xml.getBytes()));
doc.getDocumentElement().normalize();
JXPathContext ctx = JXPathContext.newContext(doc);
Node errorNode = (Node) ctx.selectSingleNode("//ows:ExceptionReport/ows:Exception/ows:ExceptionText");
return errorNode.getChildNodes().item(0).getTextContent();
}
private String cleanFileName(String input) {
String updated = input;
// Test the first character and if numeric, prepend with underscore
if (input.substring(0, 1).matches("[0-9]")) {
updated = "_" + input;
}
// Test the rest of the characters and replace anything that's not a
// letter, digit or period with an underscore
char[] inputArr = updated.toCharArray();
for (int cInd = 0; cInd < inputArr.length; cInd++) {
if (!Character.isLetterOrDigit(inputArr[cInd]) && !(inputArr[cInd] == '.')) {
inputArr[cInd] = '_';
}
}
return String.valueOf(inputArr);
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException {
String filenameParam;
boolean useBaseCRSFailover;
boolean overwriteExistingLayer;
// "reproject" (default), "force", "none"
ProjectionPolicy projectionPolicy;
Map<String, String> responseMap = new HashMap<String, String>();
RequestResponse.ResponseType responseType = RequestResponse.ResponseType.XML;
String responseEncoding = request.getParameter("response.encoding");
if (StringUtils.isBlank(responseEncoding) || responseEncoding.toLowerCase().contains("json")) {
responseType = RequestResponse.ResponseType.JSON;
}
LOG.debug("Response type set to " + responseType.toString());
int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
if (fileSize > maxFileSize) {
responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
// The key to search for in the upload form post to find the file
String fnInitParam = servletConfig.getInitParameter("filename.param");
String fnJndiProp = props.getProperty(applicationName + ".filename.param");
String fnReqParam = request.getParameter("filename.param");
if (StringUtils.isNotBlank(fnReqParam)) {
filenameParam = fnReqParam;
} else if (StringUtils.isNotBlank(fnInitParam)) {
filenameParam = fnInitParam;
} else if (StringUtils.isNotBlank(fnJndiProp)) {
filenameParam = fnJndiProp;
} else {
filenameParam = defaultFilenameParam;
}
LOG.debug("Filename parameter set to: " + filenameParam);
String oelInitParam = servletConfig.getInitParameter("overwrite.existing.layer");
String oelJndiProp = props.getProperty(applicationName + ".overwrite.existing.layer");
String oelReqParam = request.getParameter("overwrite.existing.layer");
if (StringUtils.isNotBlank(oelReqParam)) {
overwriteExistingLayer = Boolean.parseBoolean(oelReqParam);
} else if (StringUtils.isNotBlank(oelInitParam)) {
overwriteExistingLayer = Boolean.parseBoolean(oelInitParam);
} else if (StringUtils.isNotBlank(oelJndiProp)) {
overwriteExistingLayer = Boolean.parseBoolean(oelJndiProp);
} else {
overwriteExistingLayer = defaultOverwriteExistingLayer;
}
LOG.debug("Overwrite existing layer set to: " + overwriteExistingLayer);
LOG.debug("Cleaning file name.\nWas: " + filenameParam);
String filename = cleanFileName(request.getParameter(filenameParam));
LOG.debug("Is: " + filename);
if (filenameParam.equals(filename)) {
LOG.debug("(No change)");
}
String tempDir = System.getProperty("java.io.tmpdir");
File shapeZipFile = new File(tempDir + File.separator + filename);
LOG.debug("Temporary file set to " + shapeZipFile.getPath());
String layerName = request.getParameter("layer");
if (StringUtils.isBlank(layerName)) {
layerName = filename.split("\\.")[0];
}
layerName = layerName.trim().replaceAll("\\.", "_").replaceAll(" ", "_");
LOG.debug("Layer name set to " + layerName);
String workspaceName = request.getParameter("workspace");
if (StringUtils.isBlank(workspaceName)) {
workspaceName = defaultWorkspaceName;
}
if (StringUtils.isBlank(workspaceName)) {
responseMap.put("error", "Parameter \"workspace\" is mandatory");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
LOG.debug("Workspace name set to " + workspaceName);
String storeName = request.getParameter("store");
if (StringUtils.isBlank(storeName)) {
storeName = defaultStoreName;
}
if (StringUtils.isBlank(storeName)) {
storeName = layerName;
}
LOG.debug("Store name set to " + storeName);
String srsName = request.getParameter("srs");
if (StringUtils.isBlank(srsName)) {
srsName = defaultSRS;
}
if (StringUtils.isBlank(srsName)) {
responseMap.put("error", "Parameter \"srs\" is mandatory");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
LOG.debug("SRS name set to " + srsName);
String bCRSfoInitParam = servletConfig.getInitParameter("use.crs.failover");
String bCRSfoJndiProp = props.getProperty(applicationName + ".use.crs.failover");
String bCRSfoReqParam = request.getParameter("use.crs.failover");
if (StringUtils.isNotBlank(bCRSfoReqParam)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoReqParam);
} else if (StringUtils.isNotBlank(bCRSfoInitParam)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoInitParam);
} else if (StringUtils.isNotBlank(bCRSfoJndiProp)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoJndiProp);
} else {
useBaseCRSFailover = defaultUseBaseCRSFallback;
}
LOG.debug("Use base CRS failover set to: " + useBaseCRSFailover);
String projectionPolicyReqParam = request.getParameter("projection.policy");
String ppInitParam = servletConfig.getInitParameter("projection.policy");
String ppJndiProp = props.getProperty(applicationName + ".projection.policy");
if (StringUtils.isNotBlank(projectionPolicyReqParam)) {
if (projectionPolicyReqParam.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (projectionPolicyReqParam.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = defaultProjectionPolicy;
}
} else if (StringUtils.isNotBlank(ppInitParam)) {
if (ppInitParam.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (ppInitParam.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = ProjectionPolicy.NONE;
}
} else if (StringUtils.isNotBlank(ppJndiProp)) {
if (ppJndiProp.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (ppJndiProp.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = ProjectionPolicy.NONE;
}
} else {
projectionPolicy = defaultProjectionPolicy;
}
LOG.debug("Projection policy set to: " + projectionPolicy.name());
LOG.debug("Projection policy re-set to: " + projectionPolicy);
try {
RequestResponse.saveFileFromRequest(request, shapeZipFile, filenameParam);
LOG.debug("File saved to " + shapeZipFile.getPath());
FileHelper.flattenZipFile(shapeZipFile.getPath());
LOG.debug("Zip file directory structure flattened");
FileHelper.validateShapefileZip(shapeZipFile);
LOG.debug("Zip file seems to be a valid shapefile");
} catch (Exception ex) {
LOG.warn(ex.getMessage());
responseMap.put("error", "Unable to upload file");
responseMap.put("exception", ex.getMessage());
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
try {
ProjectionUtils.getProjectionFromShapefileZip(shapeZipFile, false);
} catch (Exception ex) {
responseMap.put("warning", "WARNING: Could not find EPSG code for prj definition. The geographic coordinate system '"+srsName+"' will be used ");
}
String importResponse;
try {
GeoServerRESTPublisher gsPublisher = gsRestManager.getPublisher();
if (overwriteExistingLayer) {
// TODO- Using this library, I am unable to rename a layer. If publishing the layer
// fails, we will have lost this layer due to removal here.
if (gsPublisher.unpublishFeatureType(workspaceName, storeName, layerName)) {
gsPublisher.unpublishCoverage(workspaceName, storeName, layerName);
gsPublisher.reloadStore(workspaceName, storeName, GeoServerRESTPublisher.StoreType.DATASTORES);
}
}
importResponse = importUsingWPS(workspaceName, storeName, layerName, shapeZipFile.toURI(), srsName, projectionPolicy, null);
if (importResponse.toLowerCase().contains("exception")) {
String error = parseWPSErrorText(importResponse);
LOG.debug("Shapefile could not be imported successfully");
responseMap.put("error", error);
RequestResponse.sendErrorResponse(response, responseMap, responseType);
} else {
LOG.debug("Shapefile has been imported successfully");
responseMap.put("name", importResponse);
responseMap.put("workspace", workspaceName);
responseMap.put("store", storeName);
RequestResponse.sendSuccessResponse(response, responseMap, responseType);
}
} catch (Exception ex) {
LOG.warn(ex.getMessage());
responseMap.put("error", "Unable to upload file");
responseMap.put("exception", ex.getMessage());
RequestResponse.sendErrorResponse(response, responseMap, responseType);
} finally {
FileUtils.deleteQuietly(shapeZipFile);
}
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, FileNotFoundException {
String filenameParam;
boolean useBaseCRSFailover;
boolean overwriteExistingLayer;
// "reproject" (default), "force", "none"
ProjectionPolicy projectionPolicy;
Map<String, String> responseMap = new HashMap<String, String>();
RequestResponse.ResponseType responseType = RequestResponse.ResponseType.XML;
String responseEncoding = request.getParameter("response.encoding");
if (StringUtils.isBlank(responseEncoding) || responseEncoding.toLowerCase().contains("json")) {
responseType = RequestResponse.ResponseType.JSON;
}
LOG.debug("Response type set to " + responseType.toString());
int fileSize = Integer.parseInt(request.getHeader("Content-Length"));
if (fileSize > maxFileSize) {
responseMap.put("error", "Upload exceeds max file size of " + maxFileSize + " bytes");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
// The key to search for in the upload form post to find the file
String fnInitParam = servletConfig.getInitParameter("filename.param");
String fnJndiProp = props.getProperty(applicationName + ".filename.param");
String fnReqParam = request.getParameter("filename.param");
if (StringUtils.isNotBlank(fnReqParam)) {
filenameParam = fnReqParam;
} else if (StringUtils.isNotBlank(fnInitParam)) {
filenameParam = fnInitParam;
} else if (StringUtils.isNotBlank(fnJndiProp)) {
filenameParam = fnJndiProp;
} else {
filenameParam = defaultFilenameParam;
}
LOG.debug("Filename parameter set to: " + filenameParam);
String oelInitParam = servletConfig.getInitParameter("overwrite.existing.layer");
String oelJndiProp = props.getProperty(applicationName + ".overwrite.existing.layer");
String oelReqParam = request.getParameter("overwrite.existing.layer");
if (StringUtils.isNotBlank(oelReqParam)) {
overwriteExistingLayer = Boolean.parseBoolean(oelReqParam);
} else if (StringUtils.isNotBlank(oelInitParam)) {
overwriteExistingLayer = Boolean.parseBoolean(oelInitParam);
} else if (StringUtils.isNotBlank(oelJndiProp)) {
overwriteExistingLayer = Boolean.parseBoolean(oelJndiProp);
} else {
overwriteExistingLayer = defaultOverwriteExistingLayer;
}
LOG.debug("Overwrite existing layer set to: " + overwriteExistingLayer);
LOG.debug("Cleaning file name.\nWas: " + filenameParam);
String filename = cleanFileName(request.getParameter(filenameParam));
LOG.debug("Is: " + filename);
if (filenameParam.equals(filename)) {
LOG.debug("(No change)");
}
String tempDir = System.getProperty("java.io.tmpdir");
File shapeZipFile = new File(tempDir + File.separator + filename);
LOG.debug("Temporary file set to " + shapeZipFile.getPath());
String layerName = request.getParameter("layer");
if (StringUtils.isBlank(layerName)) {
layerName = filename.split("\\.")[0];
}
layerName = layerName.trim().replaceAll("\\.", "_").replaceAll(" ", "_");
LOG.debug("Layer name set to " + layerName);
String workspaceName = request.getParameter("workspace");
if (StringUtils.isBlank(workspaceName)) {
workspaceName = defaultWorkspaceName;
}
if (StringUtils.isBlank(workspaceName)) {
responseMap.put("error", "Parameter \"workspace\" is mandatory");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
LOG.debug("Workspace name set to " + workspaceName);
String storeName = request.getParameter("store");
if (StringUtils.isBlank(storeName)) {
storeName = defaultStoreName;
}
if (StringUtils.isBlank(storeName)) {
storeName = layerName;
}
LOG.debug("Store name set to " + storeName);
String srsName = request.getParameter("srs");
if (StringUtils.isBlank(srsName)) {
srsName = defaultSRS;
}
if (StringUtils.isBlank(srsName)) {
responseMap.put("error", "Parameter \"srs\" is mandatory");
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
LOG.debug("SRS name set to " + srsName);
String bCRSfoInitParam = servletConfig.getInitParameter("use.crs.failover");
String bCRSfoJndiProp = props.getProperty(applicationName + ".use.crs.failover");
String bCRSfoReqParam = request.getParameter("use.crs.failover");
if (StringUtils.isNotBlank(bCRSfoReqParam)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoReqParam);
} else if (StringUtils.isNotBlank(bCRSfoInitParam)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoInitParam);
} else if (StringUtils.isNotBlank(bCRSfoJndiProp)) {
useBaseCRSFailover = Boolean.parseBoolean(bCRSfoJndiProp);
} else {
useBaseCRSFailover = defaultUseBaseCRSFallback;
}
LOG.debug("Use base CRS failover set to: " + useBaseCRSFailover);
String projectionPolicyReqParam = request.getParameter("projection.policy");
String ppInitParam = servletConfig.getInitParameter("projection.policy");
String ppJndiProp = props.getProperty(applicationName + ".projection.policy");
if (StringUtils.isNotBlank(projectionPolicyReqParam)) {
if (projectionPolicyReqParam.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (projectionPolicyReqParam.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = defaultProjectionPolicy;
}
} else if (StringUtils.isNotBlank(ppInitParam)) {
if (ppInitParam.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (ppInitParam.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = ProjectionPolicy.NONE;
}
} else if (StringUtils.isNotBlank(ppJndiProp)) {
if (ppJndiProp.equalsIgnoreCase("reproject")) {
projectionPolicy = ProjectionPolicy.REPROJECT_TO_DECLARED;
} else if (ppJndiProp.equalsIgnoreCase("force")) {
projectionPolicy = ProjectionPolicy.FORCE_DECLARED;
} else {
projectionPolicy = ProjectionPolicy.NONE;
}
} else {
projectionPolicy = defaultProjectionPolicy;
}
LOG.debug("Projection policy set to: " + projectionPolicy.name());
LOG.debug("Projection policy re-set to: " + projectionPolicy);
try {
RequestResponse.saveFileFromRequest(request, shapeZipFile, filenameParam);
LOG.debug("File saved to " + shapeZipFile.getPath());
FileHelper.flattenZipFile(shapeZipFile.getPath());
LOG.debug("Zip file directory structure flattened");
FileHelper.validateShapefileZip(shapeZipFile);
LOG.debug("Zip file seems to be a valid shapefile");
} catch (Exception ex) {
LOG.warn(ex.getMessage());
responseMap.put("error", "Unable to upload file");
responseMap.put("exception", ex.getMessage());
RequestResponse.sendErrorResponse(response, responseMap, responseType);
return;
}
try {
srsName = ProjectionUtils.getProjectionFromShapefileZip(shapeZipFile, false);
} catch (Exception ex) {
responseMap.put("warning", "WARNING: Could not find EPSG code for prj definition. The geographic coordinate system '"+srsName+"' will be used ");
}
String importResponse;
try {
GeoServerRESTPublisher gsPublisher = gsRestManager.getPublisher();
if (overwriteExistingLayer) {
// TODO- Using this library, I am unable to rename a layer. If publishing the layer
// fails, we will have lost this layer due to removal here.
if (gsPublisher.unpublishFeatureType(workspaceName, storeName, layerName)) {
gsPublisher.unpublishCoverage(workspaceName, storeName, layerName);
gsPublisher.reloadStore(workspaceName, storeName, GeoServerRESTPublisher.StoreType.DATASTORES);
}
}
importResponse = importUsingWPS(workspaceName, storeName, layerName, shapeZipFile.toURI(), srsName, projectionPolicy, null);
if (importResponse.toLowerCase().contains("exception")) {
String error = parseWPSErrorText(importResponse);
LOG.debug("Shapefile could not be imported successfully");
responseMap.put("error", error);
RequestResponse.sendErrorResponse(response, responseMap, responseType);
} else {
LOG.debug("Shapefile has been imported successfully");
responseMap.put("name", importResponse);
responseMap.put("workspace", workspaceName);
responseMap.put("store", storeName);
RequestResponse.sendSuccessResponse(response, responseMap, responseType);
}
} catch (Exception ex) {
LOG.warn(ex.getMessage());
responseMap.put("error", "Unable to upload file");
responseMap.put("exception", ex.getMessage());
RequestResponse.sendErrorResponse(response, responseMap, responseType);
} finally {
FileUtils.deleteQuietly(shapeZipFile);
}
}
|
diff --git a/martus-android/src/org/martus/android/dialog/CreateAccountDialog.java b/martus-android/src/org/martus/android/dialog/CreateAccountDialog.java
index b4bc72e..4d2dd5e 100644
--- a/martus-android/src/org/martus/android/dialog/CreateAccountDialog.java
+++ b/martus-android/src/org/martus/android/dialog/CreateAccountDialog.java
@@ -1,106 +1,107 @@
package org.martus.android.dialog;
import java.util.Arrays;
import org.martus.android.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
/**
* @author roms
* Date: 12/22/12
*/
public class CreateAccountDialog extends DialogFragment implements DialogInterface.OnClickListener, TextWatcher,
TextView.OnEditorActionListener {
public static final int MIN_PASSWORD_SIZE = 8;
private EditText newPasswordText;
private EditText confirmPasswordText;
private TextView error;
public interface CreateAccountDialogListener {
void onFinishNewAccountDialog(TextView passwordText, TextView confirmPasswordText);
void onCancelNewAccountDialog();
}
public CreateAccountDialog() {
// Empty constructor required for DialogFragment
}
public static CreateAccountDialog newInstance() {
CreateAccountDialog frag = new CreateAccountDialog();
Bundle args = new Bundle();
frag.setArguments(args);
frag.setCancelable(false);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater factory = LayoutInflater.from(getActivity());
final View createAccountDialog = factory.inflate(R.layout.create_account, null);
newPasswordText = (EditText) createAccountDialog.findViewById(R.id.new_password_field);
confirmPasswordText = (EditText) createAccountDialog.findViewById(R.id.confirm_password_field);
confirmPasswordText.setOnEditorActionListener(this);
error = (TextView) createAccountDialog.findViewById(R.id.password_problem_text);
confirmPasswordText.addTextChangedListener(this);
+ newPasswordText.addTextChangedListener(this);
return new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.create_account_dialog_title)
.setView(createAccountDialog)
.setPositiveButton(R.string.alert_dialog_ok, this)
.setNegativeButton(R.string.create_account_dialog_cancel,this)
.create();
}
public void onClick(DialogInterface dialog, int whichButton) {
switch (whichButton) {
case -1: ((CreateAccountDialogListener) getActivity()).onFinishNewAccountDialog(newPasswordText, confirmPasswordText);
break;
case -2: ((CreateAccountDialogListener) getActivity()).onCancelNewAccountDialog();
break;
}
}
@Override
public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
((CreateAccountDialogListener) getActivity()).onFinishNewAccountDialog(newPasswordText, confirmPasswordText);
this.dismiss();
return true;
}
return false;
}
public void afterTextChanged(Editable s) {
char[] password = newPasswordText.getText().toString().trim().toCharArray();
char[] confirmPassword = confirmPasswordText.getText().toString().trim().toCharArray();
if (password.length < MIN_PASSWORD_SIZE) {
error.setText(R.string.invalid_password);
return;
}
if (Arrays.equals(password, confirmPassword)) {
error.setText(R.string.settings_pwd_equal);
} else {
error.setText(R.string.settings_pwd_not_equal);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
}
| true | true | public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater factory = LayoutInflater.from(getActivity());
final View createAccountDialog = factory.inflate(R.layout.create_account, null);
newPasswordText = (EditText) createAccountDialog.findViewById(R.id.new_password_field);
confirmPasswordText = (EditText) createAccountDialog.findViewById(R.id.confirm_password_field);
confirmPasswordText.setOnEditorActionListener(this);
error = (TextView) createAccountDialog.findViewById(R.id.password_problem_text);
confirmPasswordText.addTextChangedListener(this);
return new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.create_account_dialog_title)
.setView(createAccountDialog)
.setPositiveButton(R.string.alert_dialog_ok, this)
.setNegativeButton(R.string.create_account_dialog_cancel,this)
.create();
}
| public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater factory = LayoutInflater.from(getActivity());
final View createAccountDialog = factory.inflate(R.layout.create_account, null);
newPasswordText = (EditText) createAccountDialog.findViewById(R.id.new_password_field);
confirmPasswordText = (EditText) createAccountDialog.findViewById(R.id.confirm_password_field);
confirmPasswordText.setOnEditorActionListener(this);
error = (TextView) createAccountDialog.findViewById(R.id.password_problem_text);
confirmPasswordText.addTextChangedListener(this);
newPasswordText.addTextChangedListener(this);
return new AlertDialog.Builder(getActivity())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.create_account_dialog_title)
.setView(createAccountDialog)
.setPositiveButton(R.string.alert_dialog_ok, this)
.setNegativeButton(R.string.create_account_dialog_cancel,this)
.create();
}
|
diff --git a/src/test/java/mock/VoteActionHandlerMockTest.java b/src/test/java/mock/VoteActionHandlerMockTest.java
index edafb74..5c8e7d7 100644
--- a/src/test/java/mock/VoteActionHandlerMockTest.java
+++ b/src/test/java/mock/VoteActionHandlerMockTest.java
@@ -1,107 +1,108 @@
package mock;
import junit.framework.TestCase;
import org.drools.runtime.StatefulKnowledgeSession;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.Test;
import org.junit.runner.RunWith;
import services.NomicService;
import uk.ac.imperial.presage2.core.Action;
import uk.ac.imperial.presage2.core.environment.ActionHandlingException;
import uk.ac.imperial.presage2.core.environment.EnvironmentServiceProvider;
import uk.ac.imperial.presage2.core.environment.EnvironmentSharedStateAccess;
import uk.ac.imperial.presage2.core.environment.UnavailableServiceException;
import uk.ac.imperial.presage2.core.event.EventBus;
import uk.ac.imperial.presage2.core.util.random.Random;
import actionHandlers.VoteActionHandler;
import actions.Vote;
import agents.NomicAgent;
import enums.VoteType;
@RunWith(JMock.class)
public class VoteActionHandlerMockTest extends TestCase {
Mockery context = new JUnit4Mockery();
final StatefulKnowledgeSession session = context.mock(StatefulKnowledgeSession.class);
final EnvironmentServiceProvider serviceProvider = context.mock(EnvironmentServiceProvider.class);
final EventBus e = context.mock(EventBus.class);
final EnvironmentSharedStateAccess sharedState = context.mock(EnvironmentSharedStateAccess.class);
@Test
public void canHandleTest() {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
Vote yes = new Vote(mockAgent, VoteType.YES);
Vote no = new Vote(mockAgent, VoteType.NO);
Action genericAction = context.mock(Action.class);
assertTrue(handler.canHandle(yes));
assertTrue(handler.canHandle(no));
assertFalse(handler.canHandle(genericAction));
}
@Test
public void handleTest() throws UnavailableServiceException {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
final NomicService service = context.mock(NomicService.class);
final Vote yes = new Vote(mockAgent, VoteType.YES);
final Vote no = new Vote(mockAgent, VoteType.NO);
final Action genericAction = context.mock(Action.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
context.checking(new Expectations() {{
oneOf(serviceProvider).getEnvironmentService(with(NomicService.class));
will(returnValue(service));
oneOf(service).Vote(yes);
oneOf(service).getTurnNumber();
+ oneOf(service).getSimTime();
oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(yes);
}});
try {
handler.handle(yes, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle yes vote");
}
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(service).Vote(no);
oneOf(service).getTurnNumber();
oneOf(session).insert(no);
}});
try {
handler.handle(no, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle no vote");
}
context.assertIsSatisfied();
try {
handler.handle(genericAction, Random.randomUUID());
fail("Ate exception for invalid action");
} catch (ActionHandlingException e) {
}
}
}
| true | true | public void handleTest() throws UnavailableServiceException {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
final NomicService service = context.mock(NomicService.class);
final Vote yes = new Vote(mockAgent, VoteType.YES);
final Vote no = new Vote(mockAgent, VoteType.NO);
final Action genericAction = context.mock(Action.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
context.checking(new Expectations() {{
oneOf(serviceProvider).getEnvironmentService(with(NomicService.class));
will(returnValue(service));
oneOf(service).Vote(yes);
oneOf(service).getTurnNumber();
oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(yes);
}});
try {
handler.handle(yes, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle yes vote");
}
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(service).Vote(no);
oneOf(service).getTurnNumber();
oneOf(session).insert(no);
}});
try {
handler.handle(no, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle no vote");
}
context.assertIsSatisfied();
try {
handler.handle(genericAction, Random.randomUUID());
fail("Ate exception for invalid action");
} catch (ActionHandlingException e) {
}
}
| public void handleTest() throws UnavailableServiceException {
context.setImposteriser(ClassImposteriser.INSTANCE);
final NomicAgent mockAgent = context.mock(NomicAgent.class);
final NomicService service = context.mock(NomicService.class);
final Vote yes = new Vote(mockAgent, VoteType.YES);
final Vote no = new Vote(mockAgent, VoteType.NO);
final Action genericAction = context.mock(Action.class);
VoteActionHandler handler = new VoteActionHandler(serviceProvider);
context.checking(new Expectations() {{
oneOf(serviceProvider).getEnvironmentService(with(NomicService.class));
will(returnValue(service));
oneOf(service).Vote(yes);
oneOf(service).getTurnNumber();
oneOf(service).getSimTime();
oneOf(service).getActiveStatefulKnowledgeSession(); will(returnValue(session));
oneOf(session).insert(yes);
}});
try {
handler.handle(yes, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle yes vote");
}
context.assertIsSatisfied();
context.checking(new Expectations() {{
oneOf(service).Vote(no);
oneOf(service).getTurnNumber();
oneOf(session).insert(no);
}});
try {
handler.handle(no, Random.randomUUID());
} catch (ActionHandlingException e) {
fail("Failed to handle no vote");
}
context.assertIsSatisfied();
try {
handler.handle(genericAction, Random.randomUUID());
fail("Ate exception for invalid action");
} catch (ActionHandlingException e) {
}
}
|
diff --git a/src/skittles/g6/CompulsiveEater.java b/src/skittles/g6/CompulsiveEater.java
index 4dd6c31..7596cfb 100644
--- a/src/skittles/g6/CompulsiveEater.java
+++ b/src/skittles/g6/CompulsiveEater.java
@@ -1,419 +1,419 @@
package skittles.g6;
import java.util.ArrayList;
import java.util.Collections;
import skittles.g6.strategy.CompulsiveOfferEvaluator;
import skittles.g6.strategy.InventoryLowerBound;
import skittles.g6.strategy.InventoryLowerBoundImpl;
import skittles.g6.strategy.OfferEvaluator;
import skittles.g6.strategy.OfferGenerator;
import skittles.g6.strategy.OfferGeneratorImplementer;
import skittles.g6.strategy.Pair;
import skittles.g6.strategy.Parameters;
import skittles.g6.strategy.PreferenceEvaluator;
import skittles.g6.strategy.PreferenceEvaluatorImpl;
import skittles.sim.*;
public class CompulsiveEater extends Player
{
private PreferenceEvaluator prefEval;
private OfferEvaluator offerEval;
private OfferGenerator offerGen;
private InventoryLowerBound inventoryLowerBound;
private int turnCounter;
private boolean discovery;
private int turnsEatenSame;
private int turnsSinceLastTrade;
private int colorsRemaining;
private int target;
private int totalSkittles;
private int initialTargetInventory;
private int discoveryIndex;
private boolean negativesRemain;
private ArrayList<Pair<Integer, Integer>> piles = new ArrayList<Pair<Integer, Integer>>();
private ArrayList<Pair<Integer, Integer>> pilesBelowSecondaryThreshold = new ArrayList<Pair<Integer, Integer>>();
//===== EVERYTHING BELOW CAME FROM DumpPlayer ====
private int[] aintInHand;
private int intColorNum;
double dblHappiness;
String strClassName;
int intPlayerIndex;
int playerNum;
//
private double[] adblTastes;
private int intLastEatIndex;
private int intLastEatNum;
@Override
public void eat( int[] aintTempEat )
{
//printInHand();
turnCounter++;
int eatIndex = scanForLeastValuable();
//self-destruct if nothing remaining under secondary threshold
//TODO: set threshold for turnsSinceLastTrade or for only positives left
- if(!negativesRemain && turnsSinceLastTrade > pilesBelowSecondaryThreshold.size()){
+ if((eatIndex == -1 || !negativesRemain) && turnsSinceLastTrade > pilesBelowSecondaryThreshold.size()){
for (int i = 0; i < aintInHand.length; i++) {
if(aintInHand[i] > 0){
aintTempEat[ i ] = aintInHand[ i ];
aintInHand[ i ] = 0;
return;
}
}
}
//eat all of last color if positive taste
if(colorsRemaining == 1 && adblTastes[eatIndex] >= 0){
aintTempEat[ eatIndex ] = aintInHand[ eatIndex ];
aintInHand[ eatIndex ] = 0;
return;
}
//try to eat one of every color
while(discovery && discoveryIndex < intColorNum - 1){
discoveryIndex++;
refreshDiscoveryOrdering();
if(piles.get(discoveryIndex).getFront() == 0){
discoveryIndex++;
continue;
}
aintInHand[piles.get(discoveryIndex).getBack()]--;
aintTempEat[piles.get(discoveryIndex).getBack()] = 1;
intLastEatNum = 1;
intLastEatIndex = piles.get(discoveryIndex).getBack();
return;
}
discovery = false;
//TODO: Test threshold
aintTempEat[ eatIndex ] = 1;
aintInHand[ eatIndex ]--;
intLastEatIndex = eatIndex;
intLastEatNum = aintTempEat[ eatIndex ];
if(eatIndex == intLastEatIndex)
turnsEatenSame++;
else
turnsEatenSame = 1;
turnsSinceLastTrade++;
}
/*
* Returns the index of the color whose score is closest to zero
*/
private int scanForLeastValuable(){
double minDistanceFromZero = 2;
int minTasteIndex = -1;
colorsRemaining = intColorNum;
for(int i = 0; i < intColorNum; i++){
if(aintInHand[i] == 0){
colorsRemaining--;
continue;
}
if(Math.abs(adblTastes[i]) < minDistanceFromZero && adblTastes[i] <= 0){
minDistanceFromZero = Math.abs(adblTastes[i]);
minTasteIndex = i;
}
}
if(minDistanceFromZero == 2){
negativesRemain = false;
for(int i = 0; i < intColorNum; i++){
if(aintInHand[i] == 0){
continue;
}
if(Math.abs(adblTastes[i]) < minDistanceFromZero && adblTastes[i] < Parameters.SECONDARY_THRESHOLD){
minDistanceFromZero = Math.abs(adblTastes[i]);
minTasteIndex = i;
}
}
}
return minTasteIndex;
}
private void createDiscoveryOrdering(){
for (int i = 0; i < aintInHand.length; i++) {
piles.add(new Pair<Integer, Integer>(aintInHand[i], i));
}
Collections.sort(piles);
}
private void refreshDiscoveryOrdering(){
for (int i = 0; i < piles.size(); i++) {
if(aintInHand[piles.get(i).getBack()] != piles.get(i).getFront())
piles.set(i, new Pair<Integer, Integer>(aintInHand[piles.get(i).getBack()], piles.get(i).getBack()));
}
}
private void refreshBelowSecondaryOrdering(){
for (int i = 0; i < pilesBelowSecondaryThreshold.size(); i++) {
if(aintInHand[pilesBelowSecondaryThreshold.get(i).getBack()] != pilesBelowSecondaryThreshold.get(i).getFront())
pilesBelowSecondaryThreshold.set(i, new Pair<Integer, Integer>(aintInHand[piles.get(i).getBack()],
pilesBelowSecondaryThreshold.get(i).getBack()));
}
Collections.sort(pilesBelowSecondaryThreshold);
}
/*private void createBelowSecondaryOrdering(){
for (int i = 0; i < pilesBelowSecondaryThreshold.size(); i++) {
if(adblTastes[i] < Parameters.SECONDARY_THRESHOLD && adblTastes[i] != Parameters.UNKNOWN_TASTE)
pilesBelowSecondaryThreshold.add(new Pair<Integer, Integer>(aintInHand[i], i));
}
Collections.sort(pilesBelowSecondaryThreshold);
}*/
private void refreshCreateBelowSecondaryOrdering(){
if(adblTastes[intLastEatIndex] < Parameters.SECONDARY_THRESHOLD)
pilesBelowSecondaryThreshold.add(new Pair<Integer, Integer>(aintInHand[intLastEatIndex], intLastEatIndex));
Collections.sort(pilesBelowSecondaryThreshold);
}
private void refreshTargetColor(){
int back = piles.get(discoveryIndex).getBack();
if(target == -1){
if(adblTastes[back] >= Parameters.PRIMARY_THRESHOLD){
target = back;
initialTargetInventory = piles.get(discoveryIndex).getFront();
}
return;
}
double tasteDiff;
//TODO: Tweak these params
if((tasteDiff = adblTastes[back] - adblTastes[target]) > 0){
double inventoryDiff = 5.0 * (aintInHand[target] - aintInHand[back]) / totalSkittles;
double liquidity = 1.0 * (aintInHand[target] - initialTargetInventory) / aintInHand[target];
if((tasteDiff - inventoryDiff + liquidity) / 3 > .5){
target = back;
initialTargetInventory = piles.get(discoveryIndex).getFront();
}
}
}
//used if none above secondary threshold. sets greatest positive as max
public void setTargetAsMax(){
double maxScore = 0;
int targetIndex = 0;
for (int i = 0; i < aintInHand.length; i++) {
if(adblTastes[i] > maxScore){
maxScore = adblTastes[i] * Math.pow(aintInHand[i], 2);
targetIndex = i;
}
}
target = targetIndex;
}
@Override
public void offer( Offer offTemp )
{
Offer ourOffer = new Offer(intPlayerIndex, intColorNum);
if(discovery){
refreshTargetColor();
refreshBelowSecondaryOrdering();
refreshCreateBelowSecondaryOrdering();
}
else if(target == -1){
setTargetAsMax();
refreshBelowSecondaryOrdering();
}
else
refreshBelowSecondaryOrdering();
ourOffer = offerGen.getOffer();
offTemp.setOffer(ourOffer.getOffer(), ourOffer.getDesire());
}
@Override
public void syncInHand(int[] aintInHand)
{
// TODO Auto-generated method stub
for (int i = 0; i < this.aintInHand.length; i++) {
this.aintInHand[i] = aintInHand[i];
}
}
@Override
public void happier(double dblHappinessUp)
{
double dblHappinessPerCandy = dblHappinessUp / Math.pow( intLastEatNum, 2 );
if ( adblTastes[ intLastEatIndex ] == Parameters.UNKNOWN_TASTE )
{
adblTastes[ intLastEatIndex ] = dblHappinessPerCandy;
}
else
{
if ( adblTastes[ intLastEatIndex ] != dblHappinessPerCandy )
{
//System.out.println( "Error: Inconsistent color happiness!" );
}
}
}
@Override
public Offer pickOffer(Offer[] aoffCurrentOffers)
{
inventoryLowerBound.setCurrentOffers(aoffCurrentOffers);
prefEval.examineIncomeOffers(aoffCurrentOffers);
offerGen.setCurrentOffers(aoffCurrentOffers);
Offer gonnaPick = offerEval.getBestOffer(aoffCurrentOffers);
if(gonnaPick == null)
return null;
int[] aintOffer = gonnaPick.getOffer();
int[] aintDesire = gonnaPick.getDesire();
for ( int intColorIndex = 0; intColorIndex < intColorNum; intColorIndex ++ )
{
aintInHand[ intColorIndex ] += aintOffer[ intColorIndex ] - aintDesire[ intColorIndex ];
}
turnsSinceLastTrade = 0;
return gonnaPick;
}
@Override
public void offerExecuted(Offer offPicked)
{
turnsSinceLastTrade = 0;
int[] aintOffer = offPicked.getOffer();
int[] aintDesire = offPicked.getDesire();
for ( int intColorIndex = 0; intColorIndex < intColorNum; intColorIndex ++ )
{
aintInHand[ intColorIndex ] += aintDesire[ intColorIndex ] - aintOffer[ intColorIndex ];
}
}
@Override
public void updateOfferExe(Offer[] aoffCurrentOffers)
{
prefEval.examineAcceptedOffers(aoffCurrentOffers);
}
@Override
public void initialize(int intPlayerNum, int intPlayerIndex, String strClassName, int[] aintInHand)
{
this.intPlayerIndex = intPlayerIndex;
this.strClassName = strClassName;
this.aintInHand = aintInHand;
this.playerNum = intPlayerNum;
intColorNum = aintInHand.length;
turnsEatenSame = 0;
turnCounter = -1;
target = -1;
negativesRemain = true;
intLastEatIndex = -1;
discoveryIndex = -1;
turnsSinceLastTrade = 0;
dblHappiness = 0;
discovery = true;
adblTastes = new double[ intColorNum ];
offerGen = new OfferGeneratorImplementer(intColorNum);
offerGen.setPlayer(this);
prefEval = new PreferenceEvaluatorImpl(intColorNum);
prefEval.setPlayer(this);
offerEval = new CompulsiveOfferEvaluator();
offerEval.setPlayer(this);
inventoryLowerBound = new InventoryLowerBoundImpl();
inventoryLowerBound.setPlayer(this);
totalSkittles = 0;
for ( int intColorIndex = 0; intColorIndex < intColorNum; intColorIndex ++ )
{
adblTastes[ intColorIndex ] = Parameters.UNKNOWN_TASTE;
totalSkittles += this.aintInHand[intColorIndex];
}
createDiscoveryOrdering();
}
private boolean checkEnoughInHand( int[] aintTryToUse )
{
for ( int intColorIndex = 0; intColorIndex < intColorNum; intColorIndex ++ )
{
if ( aintTryToUse[ intColorIndex ] > aintInHand[ intColorIndex ] )
{
return false;
}
}
return true;
}
public void printInHand(){
System.out.print("InHand: ");
for (int i = 0; i < aintInHand.length; i++) {
System.out.print(aintInHand[i] + " ");
}
System.out.println();
}
@Override
public String getClassName()
{
return "CompulsiveEater";
}
@Override
public int getPlayerIndex()
{
return intPlayerIndex;
}
public OfferGenerator getOfferGenerator() {
return offerGen;
}
public OfferEvaluator getOfferEvaluator() {
return offerEval;
}
public PreferenceEvaluator getPreferenceEavluator() {
return prefEval;
}
public InventoryLowerBound getInventoryLowerBound() {
return inventoryLowerBound;
}
public int getTurnCounter() {
return turnCounter;
}
public int getPlayerNum() {
return playerNum;
}
public double[] getPreferences() {
return adblTastes;
}
public int[] getAIntInHand() {
return aintInHand;
}
public int getIntLastEatIndex() {
return intLastEatIndex;
}
public int getTarget() {
return target;
}
public ArrayList<Pair<Integer, Integer>> getPiles() {
return piles;
}
public ArrayList<Pair<Integer, Integer>> getPilesBelowSecondaryThreshold() {
return pilesBelowSecondaryThreshold;
}
}
| true | true | public void eat( int[] aintTempEat )
{
//printInHand();
turnCounter++;
int eatIndex = scanForLeastValuable();
//self-destruct if nothing remaining under secondary threshold
//TODO: set threshold for turnsSinceLastTrade or for only positives left
if(!negativesRemain && turnsSinceLastTrade > pilesBelowSecondaryThreshold.size()){
for (int i = 0; i < aintInHand.length; i++) {
if(aintInHand[i] > 0){
aintTempEat[ i ] = aintInHand[ i ];
aintInHand[ i ] = 0;
return;
}
}
}
//eat all of last color if positive taste
if(colorsRemaining == 1 && adblTastes[eatIndex] >= 0){
aintTempEat[ eatIndex ] = aintInHand[ eatIndex ];
aintInHand[ eatIndex ] = 0;
return;
}
//try to eat one of every color
while(discovery && discoveryIndex < intColorNum - 1){
discoveryIndex++;
refreshDiscoveryOrdering();
if(piles.get(discoveryIndex).getFront() == 0){
discoveryIndex++;
continue;
}
aintInHand[piles.get(discoveryIndex).getBack()]--;
aintTempEat[piles.get(discoveryIndex).getBack()] = 1;
intLastEatNum = 1;
intLastEatIndex = piles.get(discoveryIndex).getBack();
return;
}
discovery = false;
//TODO: Test threshold
aintTempEat[ eatIndex ] = 1;
aintInHand[ eatIndex ]--;
intLastEatIndex = eatIndex;
intLastEatNum = aintTempEat[ eatIndex ];
if(eatIndex == intLastEatIndex)
turnsEatenSame++;
else
turnsEatenSame = 1;
turnsSinceLastTrade++;
}
| public void eat( int[] aintTempEat )
{
//printInHand();
turnCounter++;
int eatIndex = scanForLeastValuable();
//self-destruct if nothing remaining under secondary threshold
//TODO: set threshold for turnsSinceLastTrade or for only positives left
if((eatIndex == -1 || !negativesRemain) && turnsSinceLastTrade > pilesBelowSecondaryThreshold.size()){
for (int i = 0; i < aintInHand.length; i++) {
if(aintInHand[i] > 0){
aintTempEat[ i ] = aintInHand[ i ];
aintInHand[ i ] = 0;
return;
}
}
}
//eat all of last color if positive taste
if(colorsRemaining == 1 && adblTastes[eatIndex] >= 0){
aintTempEat[ eatIndex ] = aintInHand[ eatIndex ];
aintInHand[ eatIndex ] = 0;
return;
}
//try to eat one of every color
while(discovery && discoveryIndex < intColorNum - 1){
discoveryIndex++;
refreshDiscoveryOrdering();
if(piles.get(discoveryIndex).getFront() == 0){
discoveryIndex++;
continue;
}
aintInHand[piles.get(discoveryIndex).getBack()]--;
aintTempEat[piles.get(discoveryIndex).getBack()] = 1;
intLastEatNum = 1;
intLastEatIndex = piles.get(discoveryIndex).getBack();
return;
}
discovery = false;
//TODO: Test threshold
aintTempEat[ eatIndex ] = 1;
aintInHand[ eatIndex ]--;
intLastEatIndex = eatIndex;
intLastEatNum = aintTempEat[ eatIndex ];
if(eatIndex == intLastEatIndex)
turnsEatenSame++;
else
turnsEatenSame = 1;
turnsSinceLastTrade++;
}
|
diff --git a/src/test/java/tool/email/sender/SendJobTest.java b/src/test/java/tool/email/sender/SendJobTest.java
index fd30884..d89fecb 100644
--- a/src/test/java/tool/email/sender/SendJobTest.java
+++ b/src/test/java/tool/email/sender/SendJobTest.java
@@ -1,60 +1,60 @@
package tool.email.sender;
import static org.junit.Assert.assertTrue;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import org.junit.Before;
import org.junit.Test;
/**
* @author dhf
*/
public class SendJobTest {
private String username = "";
private String password = "";
private String smtpHost = "";
private int smtpPort = 25;
private String heloName = "";
private String mailto = "";
@Before
public void init() {
this.username = "";
this.password = "";
this.smtpHost = "";
this.smtpPort = 25;
this.heloName = "";
this.mailto = "";
}
@Test
public void testSend() throws AddressException {
SendJob job = new SendJob();
Connection conn = new Connection();
ConnectionParams params = new ConnectionParams();
params.setConnectTimeout(15000).setDebug(true).setDebugOut(System.out)
.setEnvelopeFrom(username).setHeloName(heloName)
.setHost(smtpHost).setKeepAlive(false).setNeedAuth(true)
.setPassword(password).setPort(smtpPort).setProtocol("smtp")
.setSocketTimeout(15000);
conn.setConnectionParams(params);
job.setConnection(conn);
job.setContentEncoding("utf-8");
job.setHtmlContent(false);
job.setMailContent("<script>alert(\"content\");</script>");
job.setMailFrom(new InternetAddress("[email protected]"));
job.setSubject("<script>alert(\"subject\");</script>");
job.addMailTo(new InternetAddress(mailto));
boolean success = job.send();
- assertTrue(success);
+ assertTrue(!success);
}
}
| true | true | public void testSend() throws AddressException {
SendJob job = new SendJob();
Connection conn = new Connection();
ConnectionParams params = new ConnectionParams();
params.setConnectTimeout(15000).setDebug(true).setDebugOut(System.out)
.setEnvelopeFrom(username).setHeloName(heloName)
.setHost(smtpHost).setKeepAlive(false).setNeedAuth(true)
.setPassword(password).setPort(smtpPort).setProtocol("smtp")
.setSocketTimeout(15000);
conn.setConnectionParams(params);
job.setConnection(conn);
job.setContentEncoding("utf-8");
job.setHtmlContent(false);
job.setMailContent("<script>alert(\"content\");</script>");
job.setMailFrom(new InternetAddress("[email protected]"));
job.setSubject("<script>alert(\"subject\");</script>");
job.addMailTo(new InternetAddress(mailto));
boolean success = job.send();
assertTrue(success);
}
| public void testSend() throws AddressException {
SendJob job = new SendJob();
Connection conn = new Connection();
ConnectionParams params = new ConnectionParams();
params.setConnectTimeout(15000).setDebug(true).setDebugOut(System.out)
.setEnvelopeFrom(username).setHeloName(heloName)
.setHost(smtpHost).setKeepAlive(false).setNeedAuth(true)
.setPassword(password).setPort(smtpPort).setProtocol("smtp")
.setSocketTimeout(15000);
conn.setConnectionParams(params);
job.setConnection(conn);
job.setContentEncoding("utf-8");
job.setHtmlContent(false);
job.setMailContent("<script>alert(\"content\");</script>");
job.setMailFrom(new InternetAddress("[email protected]"));
job.setSubject("<script>alert(\"subject\");</script>");
job.addMailTo(new InternetAddress(mailto));
boolean success = job.send();
assertTrue(!success);
}
|
diff --git a/core/queryalgebra/evaluation/src/main/java/org/openrdf/query/algebra/evaluation/iterator/ExtensionIterator.java b/core/queryalgebra/evaluation/src/main/java/org/openrdf/query/algebra/evaluation/iterator/ExtensionIterator.java
index 8d860a7a4..5f2730752 100644
--- a/core/queryalgebra/evaluation/src/main/java/org/openrdf/query/algebra/evaluation/iterator/ExtensionIterator.java
+++ b/core/queryalgebra/evaluation/src/main/java/org/openrdf/query/algebra/evaluation/iterator/ExtensionIterator.java
@@ -1,63 +1,66 @@
/*
* Copyright Aduna (http://www.aduna-software.com/) (c) 1997-2007.
*
* Licensed under the Aduna BSD-style license.
*/
package org.openrdf.query.algebra.evaluation.iterator;
import info.aduna.iteration.CloseableIteration;
import info.aduna.iteration.ConvertingIteration;
import org.openrdf.model.Value;
import org.openrdf.query.BindingSet;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.query.algebra.AggregateOperator;
import org.openrdf.query.algebra.Extension;
import org.openrdf.query.algebra.ExtensionElem;
import org.openrdf.query.algebra.ValueExpr;
import org.openrdf.query.algebra.evaluation.EvaluationStrategy;
import org.openrdf.query.algebra.evaluation.QueryBindingSet;
import org.openrdf.query.algebra.evaluation.ValueExprEvaluationException;
public class ExtensionIterator extends ConvertingIteration<BindingSet, BindingSet, QueryEvaluationException> {
private final Extension extension;
private final EvaluationStrategy strategy;
public ExtensionIterator(Extension extension,
CloseableIteration<BindingSet, QueryEvaluationException> iter, EvaluationStrategy strategy)
throws QueryEvaluationException
{
super(iter);
this.extension = extension;
this.strategy = strategy;
}
@Override
public BindingSet convert(BindingSet sourceBindings)
throws QueryEvaluationException
{
QueryBindingSet targetBindings = new QueryBindingSet(sourceBindings);
for (ExtensionElem extElem : extension.getElements()) {
ValueExpr expr = extElem.getExpr();
if (!(expr instanceof AggregateOperator)) {
try {
- Value targetValue = strategy.evaluate(extElem.getExpr(), sourceBindings);
+ // we evaluate each extension element over the targetbindings, so that bindings from
+ // a previous extension element in this same extension can be used by other extension elements.
+ // e.g. if a projection contains (?a + ?b as ?c) (?c * 2 as ?d)
+ Value targetValue = strategy.evaluate(extElem.getExpr(), targetBindings);
if (targetValue != null) {
// Potentially overwrites bindings from super
targetBindings.setBinding(extElem.getName(), targetValue);
}
}
catch (ValueExprEvaluationException e) {
// silently ignore type errors in extension arguments. They should not cause the
// query to fail but just result in no additional binding.
}
}
}
return targetBindings;
}
}
| true | true | public BindingSet convert(BindingSet sourceBindings)
throws QueryEvaluationException
{
QueryBindingSet targetBindings = new QueryBindingSet(sourceBindings);
for (ExtensionElem extElem : extension.getElements()) {
ValueExpr expr = extElem.getExpr();
if (!(expr instanceof AggregateOperator)) {
try {
Value targetValue = strategy.evaluate(extElem.getExpr(), sourceBindings);
if (targetValue != null) {
// Potentially overwrites bindings from super
targetBindings.setBinding(extElem.getName(), targetValue);
}
}
catch (ValueExprEvaluationException e) {
// silently ignore type errors in extension arguments. They should not cause the
// query to fail but just result in no additional binding.
}
}
}
return targetBindings;
}
| public BindingSet convert(BindingSet sourceBindings)
throws QueryEvaluationException
{
QueryBindingSet targetBindings = new QueryBindingSet(sourceBindings);
for (ExtensionElem extElem : extension.getElements()) {
ValueExpr expr = extElem.getExpr();
if (!(expr instanceof AggregateOperator)) {
try {
// we evaluate each extension element over the targetbindings, so that bindings from
// a previous extension element in this same extension can be used by other extension elements.
// e.g. if a projection contains (?a + ?b as ?c) (?c * 2 as ?d)
Value targetValue = strategy.evaluate(extElem.getExpr(), targetBindings);
if (targetValue != null) {
// Potentially overwrites bindings from super
targetBindings.setBinding(extElem.getName(), targetValue);
}
}
catch (ValueExprEvaluationException e) {
// silently ignore type errors in extension arguments. They should not cause the
// query to fail but just result in no additional binding.
}
}
}
return targetBindings;
}
|
diff --git a/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/editor/ReplicationDetailsPage.java b/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/editor/ReplicationDetailsPage.java
index 930e671fb..7acb726f8 100644
--- a/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/editor/ReplicationDetailsPage.java
+++ b/plugins/apacheds.configuration.v2/src/main/java/org/apache/directory/studio/apacheds/configuration/v2/editor/ReplicationDetailsPage.java
@@ -1,1068 +1,1074 @@
/*
* 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.studio.apacheds.configuration.v2.editor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.apache.directory.server.config.beans.ReplConsumerBean;
import org.apache.directory.shared.ldap.model.exception.LdapInvalidDnException;
import org.apache.directory.shared.ldap.model.message.AliasDerefMode;
import org.apache.directory.shared.ldap.model.message.SearchScope;
import org.apache.directory.shared.ldap.model.name.Dn;
import org.apache.directory.shared.ldap.model.schema.AttributeType;
import org.apache.directory.studio.apacheds.configuration.v2.dialogs.AttributeDialog;
import org.apache.directory.studio.ldapbrowser.common.widgets.WidgetModifyEvent;
import org.apache.directory.studio.ldapbrowser.common.widgets.WidgetModifyListener;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.EntryWidget;
import org.apache.directory.studio.ldapbrowser.common.widgets.search.FilterWidget;
import org.apache.directory.studio.ldapbrowser.core.BrowserCorePlugin;
import org.apache.directory.studio.ldapbrowser.core.model.IBrowserConnection;
import org.apache.directory.studio.ldapbrowser.core.model.schema.Schema;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.IDetailsPage;
import org.eclipse.ui.forms.IFormPart;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.eclipse.ui.forms.widgets.TableWrapData;
import org.eclipse.ui.forms.widgets.TableWrapLayout;
/**
* This class represents the Details Page of the Server Configuration Editor for the Replication type
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
*/
public class ReplicationDetailsPage implements IDetailsPage
{
/** The associated Master Details Block */
private ReplicationMasterDetailsBlock masterDetailsBlock;
/** The Managed Form */
private IManagedForm mform;
/** The input consumer */
private ReplConsumerBean input;
/** The browser connection */
private IBrowserConnection browserConnection;
/** The array of attributes names and OIDs */
private String[] attributeNamesAndOids;
/** The list of attributes */
private List<String> attributesList;
// UI Widgets
private Button enabledCheckbox;
private Text idText;
private Text descriptionText;
private Text remoteHostText;
private Text remotePortText;
private Text bindDnText;
private Text bindPasswordText;
private Button showPasswordCheckbox;
private Text sizeLimitText;
private Text timeLimitText;
private EntryWidget entryWidget;
private FilterWidget filterWidget;
private Button subtreeScopeButton;
private Button oneLevelScopeButton;
private Button objectScopeButton;
private TableViewer attributesTableViewer;
private Button addAttributeButton;
private Button editAttributeButton;
private Button deleteAttributeButton;
private Button findingBaseDnAliasesDereferencingButton;
private Button searchAliasesDereferencingButton;
// Listeners
/** The Text Modify Listener */
private ModifyListener textModifyListener = new ModifyListener()
{
public void modifyText( ModifyEvent e )
{
commit( true );
masterDetailsBlock.setEditorDirty();
}
};
/** The button Selection Listener */
private SelectionListener buttonSelectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
commit( true );
masterDetailsBlock.setEditorDirty();
}
};
/** The widget Modify Listener */
private WidgetModifyListener widgetModifyListener = new WidgetModifyListener()
{
public void widgetModified( WidgetModifyEvent event )
{
commit( true );
masterDetailsBlock.setEditorDirty();
}
};
private VerifyListener integerVerifyListener = new VerifyListener()
{
public void verifyText( VerifyEvent e )
{
if ( !e.text.matches( "[0-9]*" ) ) //$NON-NLS-1$
{
e.doit = false;
}
}
};
private SelectionListener showPasswordCheckboxSelectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
if ( showPasswordCheckbox.getSelection() )
{
bindPasswordText.setEchoChar( '\0' );
}
else
{
bindPasswordText.setEchoChar( '\u2022' );
}
}
};
private ISelectionChangedListener attributesTableViewerSelectionListener = new ISelectionChangedListener()
{
public void selectionChanged( SelectionChangedEvent event )
{
updateAttributesButtonsEnableState();
}
};
/** The Double Click Listener for the Indexed Attributes Table Viewer */
private IDoubleClickListener attributesTableViewerDoubleClickListener = new IDoubleClickListener()
{
public void doubleClick( DoubleClickEvent event )
{
editSelectedAttribute();
}
};
private SelectionListener addAttributeButtonSelectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
addNewAttribute();
}
};
private SelectionListener editAttributeButtonSelectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
editSelectedAttribute();
}
};
private SelectionListener deleteAttributeButtonSelectionListener = new SelectionAdapter()
{
public void widgetSelected( SelectionEvent e )
{
deleteSelectedAttribute();
}
};
/**
* Creates a new instance of ReplicationDetailsPage.
*
* @param pmdb
* the associated Master Details Block
*/
public ReplicationDetailsPage( ReplicationMasterDetailsBlock pmdb )
{
masterDetailsBlock = pmdb;
// Getting the browser connection associated with the connection in the configuration
browserConnection = BrowserCorePlugin.getDefault().getConnectionManager()
.getBrowserConnection( masterDetailsBlock.getPage().getConnection() );
}
/**
* {@inheritDoc}
*/
public void createContents( Composite parent )
{
FormToolkit toolkit = mform.getToolkit();
TableWrapLayout layout = new TableWrapLayout();
layout.topMargin = 5;
layout.leftMargin = 5;
layout.rightMargin = 2;
layout.bottomMargin = 2;
parent.setLayout( layout );
createDetailsSection( parent, toolkit );
createConnectionSection( parent, toolkit );
createConfigurationSection( parent, toolkit );
}
/**
* Creates the Details Section
*
* @param parent
* the parent composite
* @param toolkit
* the toolkit to use
*/
private void createDetailsSection( Composite parent, FormToolkit toolkit )
{
Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR );
section.marginWidth = 10;
section.setText( "Replication Consumer Details" );
section.setDescription( "Set the properties of the replication consumer." );
TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP );
td.grabHorizontal = true;
section.setLayoutData( td );
Composite client = toolkit.createComposite( section );
toolkit.paintBordersFor( client );
GridLayout glayout = new GridLayout( 2, false );
client.setLayout( glayout );
section.setClient( client );
// Enabled Checkbox
enabledCheckbox = toolkit.createButton( client, "Enabled", SWT.CHECK );
enabledCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false, 2, 1 ) );
// ID Text
toolkit.createLabel( client, "ID:" );
idText = toolkit.createText( client, "" );
idText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Description Text
toolkit.createLabel( client, "Description:" );
descriptionText = toolkit.createText( client, "" );
descriptionText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
}
/**
* Creates the Details Section
*
* @param parent
* the parent composite
* @param toolkit
* the toolkit to use
*/
private void createConnectionSection( Composite parent, FormToolkit toolkit )
{
Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR );
section.marginWidth = 10;
section.setText( "Connection" );
section.setDescription( "Set the properties of the connection." );
TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP );
td.grabHorizontal = true;
section.setLayoutData( td );
Composite composite = toolkit.createComposite( section );
toolkit.paintBordersFor( composite );
GridLayout glayout = new GridLayout( 2, false );
composite.setLayout( glayout );
section.setClient( composite );
// Remote Host Text
toolkit.createLabel( composite, "Remote Host:" );
remoteHostText = toolkit.createText( composite, "" );
remoteHostText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Remote Port Text
toolkit.createLabel( composite, "Remote Port:" );
remotePortText = toolkit.createText( composite, "" );
remotePortText.addVerifyListener( integerVerifyListener );
remotePortText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Bind DN Text
toolkit.createLabel( composite, "Bind DN:" );
bindDnText = toolkit.createText( composite, "" );
bindDnText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Bind Password Text
toolkit.createLabel( composite, "Bind Password:" );
bindPasswordText = toolkit.createText( composite, "" );
bindPasswordText.setEchoChar( '\u2022' );
bindPasswordText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Show Password Checkbox
toolkit.createLabel( composite, "" ); //$NON-NLS-1$
showPasswordCheckbox = toolkit.createButton( composite, "Show password", SWT.CHECK );
showPasswordCheckbox.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false ) );
showPasswordCheckbox.setSelection( false );
// Size Limit Text
toolkit.createLabel( composite, "Size Limit:" );
sizeLimitText = toolkit.createText( composite, "" );
sizeLimitText.addVerifyListener( integerVerifyListener );
sizeLimitText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
// Time Limit Text
toolkit.createLabel( composite, "Time Limit:" );
timeLimitText = toolkit.createText( composite, "" );
timeLimitText.addVerifyListener( integerVerifyListener );
timeLimitText.setLayoutData( new GridData( SWT.FILL, SWT.NONE, true, false ) );
}
/**
* Creates the Details Section
*
* @param parent
* the parent composite
* @param toolkit
* the toolkit to use
*/
private void createConfigurationSection( Composite parent, FormToolkit toolkit )
{
Section section = toolkit.createSection( parent, Section.DESCRIPTION | Section.TITLE_BAR );
section.marginWidth = 10;
section.setText( "Replication Consumer Details" );
section.setDescription( "Set the properties of the configuration." );
TableWrapData td = new TableWrapData( TableWrapData.FILL, TableWrapData.TOP );
td.grabHorizontal = true;
section.setLayoutData( td );
Composite composite = toolkit.createComposite( section );
toolkit.paintBordersFor( composite );
GridLayout glayout = new GridLayout( 3, false );
composite.setLayout( glayout );
section.setClient( composite );
// Base DN Text
toolkit.createLabel( composite, "Base DN:" );
entryWidget = new EntryWidget( browserConnection, Dn.EMPTY_DN );
entryWidget.createWidget( composite );
// Filter Text
toolkit.createLabel( composite, "Filter:" );
filterWidget = new FilterWidget();
filterWidget.setBrowserConnection( browserConnection );
filterWidget.createWidget( composite );
// Scope
Label scopeLabel = toolkit.createLabel( composite, "Scope:" );
scopeLabel.setLayoutData( new GridData( SWT.BEGINNING, SWT.TOP, false, false, 1, 3 ) );
// Subtree Scope Button
subtreeScopeButton = toolkit.createButton( composite, "Subtree", SWT.RADIO );
subtreeScopeButton.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, false, false, 2, 1 ) );
// One Level Scope Button
oneLevelScopeButton = toolkit.createButton( composite, "One Level", SWT.RADIO );
oneLevelScopeButton.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, false, false, 2, 1 ) );
// Object Scope Button
objectScopeButton = toolkit.createButton( composite, "Object", SWT.RADIO );
objectScopeButton.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, false, false, 2, 1 ) );
// Attributes Label
Label attributesLabel = toolkit.createLabel( composite, "Attributes:" );
attributesLabel.setLayoutData( new GridData( SWT.FILL, SWT.CENTER, true, false, 3, 1 ) );
// Attributes Table Viewer
Composite attributesTableComposite = toolkit.createComposite( composite );
GridLayout gl = new GridLayout( 2, false );
gl.marginWidth = gl.marginHeight = 0;
attributesTableComposite.setLayout( gl );
attributesTableComposite.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 3, 1 ) );
Table attributesTable = toolkit.createTable( attributesTableComposite, SWT.BORDER );
attributesTable.setLayoutData( new GridData( SWT.FILL, SWT.FILL, true, true, 1, 3 ) );
attributesTableViewer = new TableViewer( attributesTable );
attributesTableViewer.setContentProvider( new ArrayContentProvider() );
addAttributeButton = toolkit.createButton( attributesTableComposite, "Add...", SWT.PUSH );
addAttributeButton.setLayoutData( createNewButtonGridData() );
editAttributeButton = toolkit.createButton( attributesTableComposite, "Edit...", SWT.PUSH );
editAttributeButton.setEnabled( false );
editAttributeButton.setLayoutData( createNewButtonGridData() );
deleteAttributeButton = toolkit.createButton( attributesTableComposite, "Delete", SWT.PUSH );
deleteAttributeButton.setEnabled( false );
deleteAttributeButton.setLayoutData( createNewButtonGridData() );
// Aliases Dereferencing Text
Label aliasesDereferencingLable = toolkit.createLabel( composite, "Aliases\nDereferencing:" );
aliasesDereferencingLable.setLayoutData( new GridData( SWT.BEGINNING, SWT.TOP, false, false, 1, 2 ) );
// Finding Base DN Aliases Dereferencing Button
findingBaseDnAliasesDereferencingButton = toolkit.createButton( composite, "Finding Base DN", SWT.CHECK );
findingBaseDnAliasesDereferencingButton
.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, false, false, 2, 1 ) );
// Search Aliases Dereferencing Button
searchAliasesDereferencingButton = toolkit.createButton( composite, "Search", SWT.CHECK );
searchAliasesDereferencingButton.setLayoutData( new GridData( SWT.LEFT, SWT.CENTER, false, false, 2, 1 ) );
}
/**
* Updates the attributes buttons enable state.
*/
private void updateAttributesButtonsEnableState()
{
ISelection selection = attributesTableViewer.getSelection();
editAttributeButton.setEnabled( !selection.isEmpty() );
deleteAttributeButton.setEnabled( !selection.isEmpty() );
}
/**
* Adds a new attribute and opens the attribute dialog.
*/
private void addNewAttribute()
{
AttributeDialog dialog = new AttributeDialog( addAttributeButton.getShell(), null, getAttributeNamesAndOids() );
if ( AttributeDialog.OK == dialog.open() )
{
String newAttribute = dialog.getAttribute();
if ( !attributesList.contains( newAttribute ) )
{
attributesList.add( newAttribute );
}
attributesTableViewer.refresh();
attributesTableViewer.setSelection( new StructuredSelection( newAttribute ) );
masterDetailsBlock.setEditorDirty();
}
}
/**
* Opens an attribute dialog with the selected attribute in the attributes table viewer.
*/
private void editSelectedAttribute()
{
StructuredSelection selection = ( StructuredSelection ) attributesTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String attribute = ( String ) selection.getFirstElement();
AttributeDialog dialog = new AttributeDialog( addAttributeButton.getShell(), attribute,
getAttributeNamesAndOids() );
if ( AttributeDialog.OK == dialog.open() )
{
attributesList.remove( attribute );
String newAttribute = dialog.getAttribute();
if ( !attributesList.contains( newAttribute ) )
{
attributesList.add( newAttribute );
}
attributesTableViewer.refresh();
attributesTableViewer.setSelection( new StructuredSelection( newAttribute ) );
masterDetailsBlock.setEditorDirty();
}
}
}
/**
* Deletes the selected index in the indexes table viewer.
*/
private void deleteSelectedAttribute()
{
StructuredSelection selection = ( StructuredSelection ) attributesTableViewer.getSelection();
if ( !selection.isEmpty() )
{
String attribute = ( String ) selection.getFirstElement();
attributesList.remove( attribute );
attributesTableViewer.refresh();
masterDetailsBlock.setEditorDirty();
}
}
/**
* Gets the array containing the attribute names and OIDs.
*
* @return the array containing the attribute names and OIDs
*/
private String[] getAttributeNamesAndOids()
{
// Checking if the array has already be generated
if ( ( attributeNamesAndOids == null ) || ( attributeNamesAndOids.length == 0 ) )
{
List<String> attributeNamesList = new ArrayList<String>();
List<String> oidsList = new ArrayList<String>();
if ( browserConnection == null )
{
// Getting all connections in the case where no connection is found
IBrowserConnection[] connections = BrowserCorePlugin.getDefault().getConnectionManager()
.getBrowserConnections();
for ( IBrowserConnection connection : connections )
{
addAttributeNamesAndOids( connection.getSchema(), attributeNamesList, oidsList );
}
}
else
{
// Only adding attribute names and OIDs from the associated connection
addAttributeNamesAndOids( browserConnection.getSchema(), attributeNamesList, oidsList );
}
// Also adding attribute names and OIDs from the default schema
addAttributeNamesAndOids( Schema.DEFAULT_SCHEMA, attributeNamesList, oidsList );
// Sorting the set
Collections.sort( attributeNamesList );
Collections.sort( oidsList );
attributeNamesAndOids = new String[attributeNamesList.size() + oidsList.size()];
System.arraycopy( attributeNamesList.toArray(), 0, attributeNamesAndOids, 0, attributeNamesList
.size() );
System.arraycopy( oidsList.toArray(), 0, attributeNamesAndOids, attributeNamesList
.size(), oidsList.size() );
}
return attributeNamesAndOids;
}
/**
* Adds the attribute names and OIDs to the given set.
*
* @param schema the schema
* @param attributeNamesList the attribute names list
* @param oidsList the OIDs name list
*/
private void addAttributeNamesAndOids( Schema schema, List<String> attributeNamesList, List<String> oidsList )
{
if ( schema != null )
{
Collection<AttributeType> atds = schema.getAttributeTypeDescriptions();
for ( AttributeType atd : atds )
{
// OID
if ( !oidsList.contains( atd.getOid() ) )
{
oidsList.add( atd.getOid() );
}
// Names
for ( String name : atd.getNames() )
{
if ( !attributeNamesList.contains( name ) )
{
attributeNamesList.add( name );
}
}
}
}
}
/**
* Create a new button grid data.
*
* @return the new button grid data
*/
private GridData createNewButtonGridData()
{
GridData gd = new GridData( SWT.FILL, SWT.BEGINNING, false, false );
gd.widthHint = IDialogConstants.BUTTON_WIDTH;
return gd;
}
/**
* Adds listeners to UI fields.
*/
private void addListeners()
{
enabledCheckbox.addSelectionListener( buttonSelectionListener );
idText.addModifyListener( textModifyListener );
descriptionText.addModifyListener( textModifyListener );
remoteHostText.addModifyListener( textModifyListener );
remotePortText.addModifyListener( textModifyListener );
bindDnText.addModifyListener( textModifyListener );
bindPasswordText.addModifyListener( textModifyListener );
showPasswordCheckbox.addSelectionListener( showPasswordCheckboxSelectionListener );
sizeLimitText.addModifyListener( textModifyListener );
timeLimitText.addModifyListener( textModifyListener );
entryWidget.addWidgetModifyListener( widgetModifyListener );
filterWidget.addWidgetModifyListener( widgetModifyListener );
subtreeScopeButton.addSelectionListener( buttonSelectionListener );
oneLevelScopeButton.addSelectionListener( buttonSelectionListener );
objectScopeButton.addSelectionListener( buttonSelectionListener );
attributesTableViewer.addDoubleClickListener( attributesTableViewerDoubleClickListener );
attributesTableViewer.addSelectionChangedListener( attributesTableViewerSelectionListener );
addAttributeButton.addSelectionListener( addAttributeButtonSelectionListener );
editAttributeButton.addSelectionListener( editAttributeButtonSelectionListener );
deleteAttributeButton.addSelectionListener( deleteAttributeButtonSelectionListener );
findingBaseDnAliasesDereferencingButton.addSelectionListener( buttonSelectionListener );
searchAliasesDereferencingButton.addSelectionListener( buttonSelectionListener );
}
/**
* Removes listeners to UI fields.
*/
private void removeListeners()
{
enabledCheckbox.removeSelectionListener( buttonSelectionListener );
idText.removeModifyListener( textModifyListener );
descriptionText.removeModifyListener( textModifyListener );
remoteHostText.removeModifyListener( textModifyListener );
remotePortText.removeModifyListener( textModifyListener );
bindDnText.removeModifyListener( textModifyListener );
bindPasswordText.removeModifyListener( textModifyListener );
showPasswordCheckbox.removeSelectionListener( showPasswordCheckboxSelectionListener );
sizeLimitText.removeModifyListener( textModifyListener );
timeLimitText.removeModifyListener( textModifyListener );
entryWidget.removeWidgetModifyListener( widgetModifyListener );
filterWidget.removeWidgetModifyListener( widgetModifyListener );
subtreeScopeButton.removeSelectionListener( buttonSelectionListener );
oneLevelScopeButton.removeSelectionListener( buttonSelectionListener );
objectScopeButton.removeSelectionListener( buttonSelectionListener );
attributesTableViewer.removeDoubleClickListener( attributesTableViewerDoubleClickListener );
attributesTableViewer.removeSelectionChangedListener( attributesTableViewerSelectionListener );
addAttributeButton.removeSelectionListener( addAttributeButtonSelectionListener );
editAttributeButton.removeSelectionListener( editAttributeButtonSelectionListener );
deleteAttributeButton.removeSelectionListener( deleteAttributeButtonSelectionListener );
findingBaseDnAliasesDereferencingButton.removeSelectionListener( buttonSelectionListener );
searchAliasesDereferencingButton.removeSelectionListener( buttonSelectionListener );
}
/**
* {@inheritDoc}
*/
public void selectionChanged( IFormPart part, ISelection selection )
{
IStructuredSelection ssel = ( IStructuredSelection ) selection;
if ( ssel.size() == 1 )
{
input = ( ReplConsumerBean ) ssel.getFirstElement();
}
else
{
input = null;
}
refresh();
}
/**
* {@inheritDoc}
*/
public void commit( boolean onSave )
{
if ( input != null )
{
// Enabled
input.setEnabled( enabledCheckbox.getSelection() );
// ID
input.setReplConsumerId( checkEmptyString( idText.getText() ) );
// Description
input.setDescription( checkEmptyString( descriptionText.getText() ) );
// Remote Host
input.setReplProvHostName( checkEmptyString( remoteHostText.getText() ) );
// Remote Port
try
{
input.setReplProvPort( Integer.parseInt( remotePortText.getText() ) );
}
catch ( NumberFormatException e )
{
input.setReplProvPort( 0 );
}
// Bind DN
input.setReplUserDn( checkEmptyString( bindDnText.getText() ) );
// Bind Password
String password = checkEmptyString( bindPasswordText.getText() );
if ( password != null )
{
input.setReplUserPassword( password.getBytes() );
}
else
{
input.setReplUserPassword( null );
}
// Size Limit
try
{
input.setReplSearchSizeLimit( Integer.parseInt( sizeLimitText.getText() ) );
}
catch ( NumberFormatException e )
{
input.setReplSearchSizeLimit( 0 );
}
// Time Limit
try
{
input.setReplSearchTimeout( Integer.parseInt( timeLimitText.getText() ) );
}
catch ( NumberFormatException e )
{
input.setReplSearchTimeout( 0 );
}
// Search Base DN
input.setSearchBaseDn( checkEmptyString( entryWidget.getDn().toString() ) );;
// Search Filter
input.setReplSearchFilter( checkEmptyString( filterWidget.getFilter() ) );
// Search Scope
SearchScope scope = getSearchScope();
if ( scope != null )
{
input.setReplSearchScope( scope.getLdapUrlValue() );
}
else
{
input.setReplSearchScope( null );
}
// Aliases Dereferencing
input.setReplAliasDerefMode( getAliasDerefMode().getJndiValue() );
}
}
/**
* Gets the search scope.
*
* @return the search scope
*/
private SearchScope getSearchScope()
{
if ( subtreeScopeButton.getSelection() )
{
return SearchScope.SUBTREE;
}
else if ( oneLevelScopeButton.getSelection() )
{
return SearchScope.ONELEVEL;
}
else if ( objectScopeButton.getSelection() )
{
return SearchScope.OBJECT;
}
return null;
}
/**
* Gets the aliases dereferencing mode.
*
* @return the aliases dereferencing mode
*/
private AliasDerefMode getAliasDerefMode()
{
if ( findingBaseDnAliasesDereferencingButton.getSelection() && searchAliasesDereferencingButton.getSelection() )
{
return AliasDerefMode.DEREF_ALWAYS;
}
else if ( !findingBaseDnAliasesDereferencingButton.getSelection()
&& searchAliasesDereferencingButton.getSelection() )
{
return AliasDerefMode.DEREF_IN_SEARCHING;
}
else if ( findingBaseDnAliasesDereferencingButton.getSelection()
&& !searchAliasesDereferencingButton.getSelection() )
{
return AliasDerefMode.DEREF_FINDING_BASE_OBJ;
}
else if ( !findingBaseDnAliasesDereferencingButton.getSelection()
&& !searchAliasesDereferencingButton.getSelection() )
{
return AliasDerefMode.NEVER_DEREF_ALIASES;
}
return AliasDerefMode.NEVER_DEREF_ALIASES;
}
/**
* Checks if the string is <code>null</code>
* and returns an empty string in that case.
*
* @param s the string
* @return a non-<code>null</code> string
*/
private String checkEmptyString( String s )
{
if ( "".equals( s ) )
{
return null;
}
return s;
}
/**
* {@inheritDoc}
*/
public void dispose()
{
}
/**
* {@inheritDoc}
*/
public void initialize( IManagedForm form )
{
this.mform = form;
}
/**
* {@inheritDoc}
*/
public boolean isDirty()
{
return false;
}
/**
* {@inheritDoc}
*/
public boolean isStale()
{
return false;
}
/**
* {@inheritDoc}
*/
public void refresh()
{
removeListeners();
if ( input != null )
{
// Enabled
enabledCheckbox.setSelection( input.isEnabled() );
// ID
idText.setText( checkNull( input.getReplConsumerId() ) );
// Description
descriptionText.setText( checkNull( input.getDescription() ) );
// Remote Host
remoteHostText.setText( checkNull( input.getReplProvHostName() ) );
// Remote Port
remotePortText.setText( checkNull( String.valueOf( input.getReplProvPort() ) ) );
// Bind DN
bindDnText.setText( checkNull( input.getReplUserDn() ) );
// Bind Password
bindPasswordText.setText( checkNull( String.valueOf( new String( input.getReplUserPassword() ) ) ) );
// Size Limit
sizeLimitText.setText( checkNull( String.valueOf( input.getReplSearchSizeLimit() ) ) );
// Time Limit
timeLimitText.setText( checkNull( String.valueOf( input.getReplSearchTimeout() ) ) );
// Search Base DN
try
{
entryWidget.setInput( browserConnection, new Dn( input.getSearchBaseDn() ) );
}
catch ( LdapInvalidDnException e )
{
entryWidget.setInput( browserConnection, Dn.EMPTY_DN );
}
// Search Filter
filterWidget.setFilter( checkNull( input.getReplSearchFilter() ) );
// Search Scope
SearchScope scope = null;
try
{
scope = SearchScope.getSearchScope( SearchScope.getSearchScope( input.getReplSearchScope() ) );
}
catch ( IllegalArgumentException e )
{
scope = null;
}
if ( scope != null )
{
switch ( scope )
{
case SUBTREE:
subtreeScopeButton.setSelection( true );
+ oneLevelScopeButton.setSelection( false );
+ objectScopeButton.setSelection( false );
break;
case ONELEVEL:
+ subtreeScopeButton.setSelection( false );
oneLevelScopeButton.setSelection( true );
+ objectScopeButton.setSelection( false );
break;
case OBJECT:
+ subtreeScopeButton.setSelection( false );
+ oneLevelScopeButton.setSelection( false );
objectScopeButton.setSelection( true );
break;
}
}
else
{
subtreeScopeButton.setSelection( true );
}
// Aliases Dereferencing
AliasDerefMode aliasDerefMode = null;
try
{
aliasDerefMode = AliasDerefMode.getDerefMode( input.getReplAliasDerefMode() );
}
catch ( IllegalArgumentException e )
{
aliasDerefMode = null;
}
if ( aliasDerefMode != null )
{
switch ( aliasDerefMode )
{
case DEREF_ALWAYS:
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( true );
break;
case DEREF_FINDING_BASE_OBJ:
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( false );
break;
case DEREF_IN_SEARCHING:
findingBaseDnAliasesDereferencingButton.setSelection( false );
searchAliasesDereferencingButton.setSelection( true );
break;
case NEVER_DEREF_ALIASES:
findingBaseDnAliasesDereferencingButton.setSelection( false );
searchAliasesDereferencingButton.setSelection( false );
break;
}
}
else
{
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( true );
}
// Attributes
attributesList = input.getReplAttributes();
attributesTableViewer.setInput( attributesList );
}
addListeners();
}
/**
* Checks if the string is <code>null</code>
* and returns an empty string in that case.
*
* @param s the string
* @return a non-<code>null</code> string
*/
private String checkNull( String s )
{
if ( s == null )
{
return "";
}
return s;
}
/**
* {@inheritDoc}
*/
public void setFocus()
{
idText.setFocus();
}
/**
* {@inheritDoc}
*/
public boolean setFormInput( Object input )
{
return false;
}
}
| false | true | public void refresh()
{
removeListeners();
if ( input != null )
{
// Enabled
enabledCheckbox.setSelection( input.isEnabled() );
// ID
idText.setText( checkNull( input.getReplConsumerId() ) );
// Description
descriptionText.setText( checkNull( input.getDescription() ) );
// Remote Host
remoteHostText.setText( checkNull( input.getReplProvHostName() ) );
// Remote Port
remotePortText.setText( checkNull( String.valueOf( input.getReplProvPort() ) ) );
// Bind DN
bindDnText.setText( checkNull( input.getReplUserDn() ) );
// Bind Password
bindPasswordText.setText( checkNull( String.valueOf( new String( input.getReplUserPassword() ) ) ) );
// Size Limit
sizeLimitText.setText( checkNull( String.valueOf( input.getReplSearchSizeLimit() ) ) );
// Time Limit
timeLimitText.setText( checkNull( String.valueOf( input.getReplSearchTimeout() ) ) );
// Search Base DN
try
{
entryWidget.setInput( browserConnection, new Dn( input.getSearchBaseDn() ) );
}
catch ( LdapInvalidDnException e )
{
entryWidget.setInput( browserConnection, Dn.EMPTY_DN );
}
// Search Filter
filterWidget.setFilter( checkNull( input.getReplSearchFilter() ) );
// Search Scope
SearchScope scope = null;
try
{
scope = SearchScope.getSearchScope( SearchScope.getSearchScope( input.getReplSearchScope() ) );
}
catch ( IllegalArgumentException e )
{
scope = null;
}
if ( scope != null )
{
switch ( scope )
{
case SUBTREE:
subtreeScopeButton.setSelection( true );
break;
case ONELEVEL:
oneLevelScopeButton.setSelection( true );
break;
case OBJECT:
objectScopeButton.setSelection( true );
break;
}
}
else
{
subtreeScopeButton.setSelection( true );
}
// Aliases Dereferencing
AliasDerefMode aliasDerefMode = null;
try
{
aliasDerefMode = AliasDerefMode.getDerefMode( input.getReplAliasDerefMode() );
}
catch ( IllegalArgumentException e )
{
aliasDerefMode = null;
}
if ( aliasDerefMode != null )
{
switch ( aliasDerefMode )
{
case DEREF_ALWAYS:
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( true );
break;
case DEREF_FINDING_BASE_OBJ:
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( false );
break;
case DEREF_IN_SEARCHING:
findingBaseDnAliasesDereferencingButton.setSelection( false );
searchAliasesDereferencingButton.setSelection( true );
break;
case NEVER_DEREF_ALIASES:
findingBaseDnAliasesDereferencingButton.setSelection( false );
searchAliasesDereferencingButton.setSelection( false );
break;
}
}
else
{
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( true );
}
// Attributes
attributesList = input.getReplAttributes();
attributesTableViewer.setInput( attributesList );
}
addListeners();
}
| public void refresh()
{
removeListeners();
if ( input != null )
{
// Enabled
enabledCheckbox.setSelection( input.isEnabled() );
// ID
idText.setText( checkNull( input.getReplConsumerId() ) );
// Description
descriptionText.setText( checkNull( input.getDescription() ) );
// Remote Host
remoteHostText.setText( checkNull( input.getReplProvHostName() ) );
// Remote Port
remotePortText.setText( checkNull( String.valueOf( input.getReplProvPort() ) ) );
// Bind DN
bindDnText.setText( checkNull( input.getReplUserDn() ) );
// Bind Password
bindPasswordText.setText( checkNull( String.valueOf( new String( input.getReplUserPassword() ) ) ) );
// Size Limit
sizeLimitText.setText( checkNull( String.valueOf( input.getReplSearchSizeLimit() ) ) );
// Time Limit
timeLimitText.setText( checkNull( String.valueOf( input.getReplSearchTimeout() ) ) );
// Search Base DN
try
{
entryWidget.setInput( browserConnection, new Dn( input.getSearchBaseDn() ) );
}
catch ( LdapInvalidDnException e )
{
entryWidget.setInput( browserConnection, Dn.EMPTY_DN );
}
// Search Filter
filterWidget.setFilter( checkNull( input.getReplSearchFilter() ) );
// Search Scope
SearchScope scope = null;
try
{
scope = SearchScope.getSearchScope( SearchScope.getSearchScope( input.getReplSearchScope() ) );
}
catch ( IllegalArgumentException e )
{
scope = null;
}
if ( scope != null )
{
switch ( scope )
{
case SUBTREE:
subtreeScopeButton.setSelection( true );
oneLevelScopeButton.setSelection( false );
objectScopeButton.setSelection( false );
break;
case ONELEVEL:
subtreeScopeButton.setSelection( false );
oneLevelScopeButton.setSelection( true );
objectScopeButton.setSelection( false );
break;
case OBJECT:
subtreeScopeButton.setSelection( false );
oneLevelScopeButton.setSelection( false );
objectScopeButton.setSelection( true );
break;
}
}
else
{
subtreeScopeButton.setSelection( true );
}
// Aliases Dereferencing
AliasDerefMode aliasDerefMode = null;
try
{
aliasDerefMode = AliasDerefMode.getDerefMode( input.getReplAliasDerefMode() );
}
catch ( IllegalArgumentException e )
{
aliasDerefMode = null;
}
if ( aliasDerefMode != null )
{
switch ( aliasDerefMode )
{
case DEREF_ALWAYS:
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( true );
break;
case DEREF_FINDING_BASE_OBJ:
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( false );
break;
case DEREF_IN_SEARCHING:
findingBaseDnAliasesDereferencingButton.setSelection( false );
searchAliasesDereferencingButton.setSelection( true );
break;
case NEVER_DEREF_ALIASES:
findingBaseDnAliasesDereferencingButton.setSelection( false );
searchAliasesDereferencingButton.setSelection( false );
break;
}
}
else
{
findingBaseDnAliasesDereferencingButton.setSelection( true );
searchAliasesDereferencingButton.setSelection( true );
}
// Attributes
attributesList = input.getReplAttributes();
attributesTableViewer.setInput( attributesList );
}
addListeners();
}
|
diff --git a/src/com/example/myfirstapp/MainActivity.java b/src/com/example/myfirstapp/MainActivity.java
index f0489a3..b0d4bd2 100644
--- a/src/com/example/myfirstapp/MainActivity.java
+++ b/src/com/example/myfirstapp/MainActivity.java
@@ -1,37 +1,37 @@
package com.example.myfirstapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void sendMessage(View view) {
- Intent intent = new Intent (this, DisplayMessageActibity.class);
+ Intent intent = new Intent (this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
| true | true | public void sendMessage(View view) {
Intent intent = new Intent (this, DisplayMessageActibity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
| public void sendMessage(View view) {
Intent intent = new Intent (this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
|
diff --git a/geotools2/geotools-src/defaultcore/src/org/geotools/styling/DefaultStroke.java b/geotools2/geotools-src/defaultcore/src/org/geotools/styling/DefaultStroke.java
index e26299109..cd7b1496f 100644
--- a/geotools2/geotools-src/defaultcore/src/org/geotools/styling/DefaultStroke.java
+++ b/geotools2/geotools-src/defaultcore/src/org/geotools/styling/DefaultStroke.java
@@ -1,263 +1,264 @@
/*
* DefaultStroke.java
* TODO:This is unfinised as it currently reutrns fixed values with no way to change them.
* Created on April 11, 2002, 2:08 PM
*/
package org.geotools.styling;
/**
* Geotools - OpenSource mapping toolkit
* (C) 2002, Center for Computational Geography
*
* 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;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*
* Contacts:
* UNITED KINDOM: James Macgill [email protected]
*
*
* @author jamesm
*/
public class DefaultStroke implements org.geotools.styling.Stroke {
private String color = "#000000";
private float[] dashArray = null;//HACK: is this an aceptable return?
private float dashOffset = 0;
private Graphic fillGraphic = null;
private Graphic strokeGraphic = null;
private String lineCap = "butt";
private String lineJoin = "miter";
private double opacity = 1;
private double width = 1;
/** Creates a new instance of DefaultStroke */
public DefaultStroke() {
}
/**
* This parameter gives the solid color that will be used for a stroke.<br>
* The color value is RGB-encoded using two hexidecimal digits per primary-color component in the
* order Red, Green, Blue, prefixed wih the hash (#) sign. The hexidecimal digits between A and F
* may be in either upper or lower case. For example, full red is encoded as "#ff0000" (with no
* quotation marks). The default color is defined to be black ("#000000").
*
* Note: in CSS this parameter is just called Stroke and not Color.
*
* @return The color of the stroke encoded as a hexidecimal RGB value.
*/
public String getColor() {
return color;
}
/**
* This parameter sets the solid color that will be used for a stroke.<br>
* The color value is RGB-encoded using two hexidecimal digits per primary-color component in the
* order Red, Green, Blue, prefixed wih the hash (#) sign. The hexidecimal digits between A and F
* may be in either upper or lower case. For example, full red is encoded as "#ff0000" (with no
* quotation marks). The default color is defined to be black ("#000000").
*
* Note: in CSS this parameter is just called Stroke and not Color.
*
* @param c The color of the stroke encoded as a hexidecimal RGB value.
*/
public void setColor(String c) {
color = c;
}
/**
* This parameter encodes the dash pattern as a series of floats.<br>
* The first number gives the length in pixels of the dash to draw, the second gives the amount of space to leave, and this pattern repeats.<br>
* If an odd number of values is given, then the pattern is expanded by repeating it twice to give an even number of values.
* The default is to draw an unbroken line.<br>
*
* For example, "2 1 3 2" would produce:<br>
* <code>-- --- -- --- -- --- -- --- -- --- --</code>
*
* @return The dash pattern as an array of float values in the form "dashlength gaplength ..."
*/
public float[] getDashArray() {
+ if(dashArray == null) return new float[0];
float[] newArray = new float[dashArray.length];
System.arraycopy(dashArray,0,newArray,0,dashArray.length);
return newArray;
}
/**
* This parameter encodes the dash pattern as a series of floats.<br>
* The first number gives the length in pixels of the dash to draw, the
* second gives the amount of space to leave, and this pattern repeats.<br>
* If an odd number of values is given, then the pattern is expanded by
* repeating it twice to give an even number of values.
* The default is to draw an unbroken line.<br>
*
* For example, "2 1 3 2" would produce:<br>
* <code>-- --- -- ---
* -- --- -- --- --
* --- --</code>
*
* @param dashPattern The dash pattern as an array of float values in the form
* "dashlength gaplength ..."
*/
public void setDashArray(float[] dashPattern) {
dashArray = dashPattern;
}
/**
* This param determins where the dash pattern should start from.
* @param offset The distance into the dash pattern that should act as the start.
*/
public double getDashOffset() {
return dashOffset;
}
/**
* This param determins where the dash pattern should start from.
* @param offset The distance into the dash pattern that should act as the start.
*/
public void setDashOffset(float offset){
dashOffset = offset;
}
/**
* This parameter indicates that a stipple-fill repeated graphic will be used and specifies the fill graphic to use.
*
* @return The graphic to use as a stipple fill. If null, then no Stipple fill should be used.
*/
public Graphic getGraphicFill() {
return fillGraphic;
}
/**
* This parameter indicates that a stipple-fill repeated graphic will be used and specifies the fill graphic to use.
*
* @param graphic The graphic to use as a stipple fill. If null, then no Stipple fill should be used.
*/
public void setGraphicFill(Graphic graphic) {
fillGraphic = graphic;
}
/**
* This parameter indicates that a repeated-linear-graphic graphic stroke type will be used and specifies the graphic to use.
*
* Proper stroking with a linear graphic requires two "hot-spot" points within the space of the graphic to indicate where the rendering line starts and stops.
* In the case of raster images with no special mark-up, this line will be assumed to be the middle pixel row of the image, starting from the first pixel column and
* ending at the last pixel column.
*
* @return The graphic to use as a linear graphic. If null, then no graphic stroke should be used.
*/
public Graphic getGraphicStroke() {
return strokeGraphic;
}
/**
* This parameter indicates that a repeated-linear-graphic graphic stroke type will be used and specifies the graphic to use.
*
* Proper stroking with a linear graphic requires two "hot-spot" points within the space of the graphic to indicate where the rendering line starts and stops.
* In the case of raster images with no special mark-up, this line will be assumed to be the middle pixel row of the image, starting from the first pixel column and
* ending at the last pixel column.
*
* @param graphic The graphic to use as a linear graphic. If null, then no graphic stroke should be used.
*/
public void setGraphicStroke(Graphic graphic) {
strokeGraphic = graphic;
}
/**
* This parameter controls how line strings should be capped.
*
* @return The cap style. This will be one of "butt", "round" and "square". There is no defined default.
*/
public String getLineCap() {
return lineCap;
}
/**
* This parameter controls how line strings should be capped.
*
* @param cap The cap style. This can be one of "butt", "round" and "square". There is no defined default.
*/
public void setLineCap(String cap) {
lineCap = cap;
}
/**
* This parameter controls how line strings should be joined together.
*
* @return The join style. This will be one of "miter", "round" and
* "bevel". There is no defined default.
*/
public String getLineJoin() {
return lineJoin;
}
/**
* This parameter controls how line strings should be joined together.
*
* @param join The join style. This will be one of "miter", "round" and
* "bevel". There is no defined default.
*/
public void setLineJoin(String join) {
lineJoin = join;
}
/**
* This specifies the level of translucency to use when rendering the stroke.<br>
* The value is encoded as a floating-point value between 0.0 and 1.0 with 0.0
* representing totally transparent and 1.0 representing totally opaque. A linear scale of
* translucency is used for intermediate values.<br>
* For example, "0.65" would represent 65% opacity. The default value is 1.0 (opaque).
*
* @return The opacity of the stroke, where 0.0 is completely transparent and 1.0 is completely opaque.
*/
public double getOpacity() {
return opacity;
}
/**
* This specifies the level of translucency to use when rendering the stroke.<br>
* The value is encoded as a floating-point value between 0.0 and 1.0 with 0.0
* representing totally transparent and 1.0 representing totally opaque. A linear scale of
* translucency is used for intermediate values.<br>
* For example, "0.65" would represent 65% opacity. The default value is 1.0 (opaque).
*
* @param level The opacity of the stroke, where 0.0 is completely transparent and 1.0 is completely opaque.
*/
public void setOpacity(double level) {
opacity = level;
}
/**
* This parameter gives the absolute width (thickness) of a stroke in pixels encoded as a float.
* The default is 1.0. Fractional numbers are allowed but negative numbers are not.
*
* @return The width of the stroke in pixels. This may be fractional but not negative.
*/
public double getWidth() {
return width;
}
/**
* This parameter sets the absolute width (thickness) of a stroke in pixels encoded as a float.
* The default is 1.0. Fractional numbers are allowed but negative numbers are not.
*
* @param pixels The width of the stroke in pixels. This may be fractional but not negative.
*/
public void setWidth(double pixels) {
width = pixels;
}
}
| true | true | public float[] getDashArray() {
float[] newArray = new float[dashArray.length];
System.arraycopy(dashArray,0,newArray,0,dashArray.length);
return newArray;
}
| public float[] getDashArray() {
if(dashArray == null) return new float[0];
float[] newArray = new float[dashArray.length];
System.arraycopy(dashArray,0,newArray,0,dashArray.length);
return newArray;
}
|
diff --git a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TextColumnDescriptor.java b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TextColumnDescriptor.java
index f85c92805..e285fb016 100644
--- a/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TextColumnDescriptor.java
+++ b/pmd-eclipse-plugin/plugins/net.sourceforge.pmd.eclipse.plugin/src/net/sourceforge/pmd/eclipse/ui/preferences/br/TextColumnDescriptor.java
@@ -1,138 +1,138 @@
package net.sourceforge.pmd.eclipse.ui.preferences.br;
import java.util.List;
import java.util.Map;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.eclipse.ui.PMDUiConstants;
import net.sourceforge.pmd.eclipse.util.AbstractCellPainterBuilder;
import net.sourceforge.pmd.eclipse.util.ResourceManager;
import net.sourceforge.pmd.eclipse.util.Util;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.swt.widgets.TreeItem;
/**
*
* @author Brian Remedios
*/
public class TextColumnDescriptor extends SimpleColumnDescriptor {
public static final RuleFieldAccessor ruleSetNameAcc = new BasicRuleFieldAccessor() {
public Comparable<?> valueFor(Rule rule) {
return RuleUIUtil.ruleSetNameFrom(rule);
}
};
public static final RuleFieldAccessor propertiesAcc = new BasicRuleFieldAccessor() {
public Comparable<?> valueFor(Rule rule) {
return RuleUIUtil.propertyStringFrom(rule, "*");
}
};
private static final int ImgOffset = 14;
/**
* @param theId String
* @param theLabel String
* @param theAlignment int
* @param theWidth int
* @param theAccessor RuleFieldAccessor
* @param resizableFlag boolean
* @param theImagePath String
*/
public TextColumnDescriptor(String theId, String theLabel, int theAlignment, int theWidth, RuleFieldAccessor theAccessor, boolean resizableFlag, String theImagePath) {
super(theId, theLabel, theAlignment,theWidth,theAccessor,resizableFlag, theImagePath);
}
private static boolean isCheckboxTree(Tree tree) {
return (tree.getStyle() | SWT.CHECK) > 0;
}
/* (non-Javadoc)
* @see net.sourceforge.pmd.eclipse.ui.preferences.br.IRuleColumnDescriptor#newTreeColumnFor(org.eclipse.swt.widgets.Tree, int, net.sourceforge.pmd.eclipse.ui.preferences.br.RuleSortListener, java.util.Map)
*/
public TreeColumn newTreeColumnFor(Tree parent, int columnIndex, SortListener sortListener, Map<Integer, List<Listener>> paintListeners) {
TreeColumn tc = super.newTreeColumnFor(parent, columnIndex, sortListener, paintListeners);
if (isCheckboxTree(parent) && columnIndex != 0) { // can't owner-draw the check or expansion toggles
addPainterFor(tc.getParent(), columnIndex, accessor(), paintListeners);
}
return tc;
}
public String stringValueFor(Rule rule) {
return ""; // we draw it ourselves
}
public String stringValueFor(RuleCollection collection) {
return ""; // we draw it ourselves
}
public Image imageFor(Rule rule) {
boolean hasIssues = rule.dysfunctionReason() != null;
return hasIssues ? ResourceManager.imageFor(PMDUiConstants.ICON_WARN) : null;
}
public void addPainterFor(final Tree tree, final int columnIndex, final RuleFieldAccessor getter, Map<Integer, List<Listener>> thePaintListeners) {
CellPainterBuilder cpl = new AbstractCellPainterBuilder() {
public void addPainterFor(final Tree tree, final int columnIndex, final RuleFieldAccessor getter, Map<Integer, List<Listener>> paintListeners) {
Listener paintListener = new Listener() {
public void handleEvent(Event event) {
if (event.index != columnIndex) return;
Object value = ((TreeItem)event.item).getData();
- if (value instanceof RuleCollection) return;
+ if (value == null || value instanceof RuleCollection) return;
GC gc = event.gc;
int imgOffset = 0;
Rule rule = (Rule)value;
gc.setFont( fontFor(tree, rule) );
imgOffset = rule.dysfunctionReason() != null ? ImgOffset : 0;
String text = textFor((TreeItem)event.item, getter);
int descent = gc.getFontMetrics().getDescent();
gc.drawString(text, event.x+imgOffset, event.y+descent, true);
}
};
Listener measureListener = new Listener() {
public void handleEvent(Event event) {
if (event.index != columnIndex) return;
String text = textFor((TreeItem)event.item, getter);
if (text == null) text = "";
Point size = event.gc.textExtent(text);
event.width = size.x + 2 * (3);
// event.height = Math.max(event.height, size.y + (3));
}
};
Util.addListener(tree, SWT.PaintItem, paintListener, paintListeners);
Util.addListener(tree, SWT.MeasureItem, measureListener, paintListeners);
}
};
cpl.addPainterFor(tree, columnIndex, getter, thePaintListeners);
}
}
| true | true | public void addPainterFor(final Tree tree, final int columnIndex, final RuleFieldAccessor getter, Map<Integer, List<Listener>> thePaintListeners) {
CellPainterBuilder cpl = new AbstractCellPainterBuilder() {
public void addPainterFor(final Tree tree, final int columnIndex, final RuleFieldAccessor getter, Map<Integer, List<Listener>> paintListeners) {
Listener paintListener = new Listener() {
public void handleEvent(Event event) {
if (event.index != columnIndex) return;
Object value = ((TreeItem)event.item).getData();
if (value instanceof RuleCollection) return;
GC gc = event.gc;
int imgOffset = 0;
Rule rule = (Rule)value;
gc.setFont( fontFor(tree, rule) );
imgOffset = rule.dysfunctionReason() != null ? ImgOffset : 0;
String text = textFor((TreeItem)event.item, getter);
int descent = gc.getFontMetrics().getDescent();
gc.drawString(text, event.x+imgOffset, event.y+descent, true);
}
};
Listener measureListener = new Listener() {
public void handleEvent(Event event) {
if (event.index != columnIndex) return;
String text = textFor((TreeItem)event.item, getter);
if (text == null) text = "";
Point size = event.gc.textExtent(text);
event.width = size.x + 2 * (3);
// event.height = Math.max(event.height, size.y + (3));
}
};
Util.addListener(tree, SWT.PaintItem, paintListener, paintListeners);
Util.addListener(tree, SWT.MeasureItem, measureListener, paintListeners);
}
};
cpl.addPainterFor(tree, columnIndex, getter, thePaintListeners);
}
| public void addPainterFor(final Tree tree, final int columnIndex, final RuleFieldAccessor getter, Map<Integer, List<Listener>> thePaintListeners) {
CellPainterBuilder cpl = new AbstractCellPainterBuilder() {
public void addPainterFor(final Tree tree, final int columnIndex, final RuleFieldAccessor getter, Map<Integer, List<Listener>> paintListeners) {
Listener paintListener = new Listener() {
public void handleEvent(Event event) {
if (event.index != columnIndex) return;
Object value = ((TreeItem)event.item).getData();
if (value == null || value instanceof RuleCollection) return;
GC gc = event.gc;
int imgOffset = 0;
Rule rule = (Rule)value;
gc.setFont( fontFor(tree, rule) );
imgOffset = rule.dysfunctionReason() != null ? ImgOffset : 0;
String text = textFor((TreeItem)event.item, getter);
int descent = gc.getFontMetrics().getDescent();
gc.drawString(text, event.x+imgOffset, event.y+descent, true);
}
};
Listener measureListener = new Listener() {
public void handleEvent(Event event) {
if (event.index != columnIndex) return;
String text = textFor((TreeItem)event.item, getter);
if (text == null) text = "";
Point size = event.gc.textExtent(text);
event.width = size.x + 2 * (3);
// event.height = Math.max(event.height, size.y + (3));
}
};
Util.addListener(tree, SWT.PaintItem, paintListener, paintListeners);
Util.addListener(tree, SWT.MeasureItem, measureListener, paintListeners);
}
};
cpl.addPainterFor(tree, columnIndex, getter, thePaintListeners);
}
|
diff --git a/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java b/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java
index ca4b104a..a849dcce 100644
--- a/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java
+++ b/core/src/net/sf/openrocket/gui/plot/SimulationPlotDialog.java
@@ -1,200 +1,201 @@
package net.sf.openrocket.gui.plot;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import net.sf.openrocket.document.Simulation;
import net.sf.openrocket.gui.components.StyledLabel;
import net.sf.openrocket.gui.util.GUIUtil;
import net.sf.openrocket.gui.util.Icons;
import net.sf.openrocket.l10n.Translator;
import net.sf.openrocket.simulation.FlightDataBranch;
import net.sf.openrocket.simulation.FlightDataType;
import net.sf.openrocket.simulation.FlightEvent;
import net.sf.openrocket.startup.Application;
import net.sf.openrocket.startup.Preferences;
import net.sf.openrocket.unit.Unit;
import net.sf.openrocket.unit.UnitGroup;
import net.sf.openrocket.util.BugException;
import net.sf.openrocket.util.MathUtil;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.annotations.XYImageAnnotation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.Marker;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.Range;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.text.TextUtilities;
import org.jfree.ui.LengthAdjustmentType;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.TextAnchor;
/**
* Dialog that shows a plot of a simulation results based on user options.
*
* @author Sampo Niskanen <[email protected]>
*/
public class SimulationPlotDialog extends JDialog {
private static final Translator trans = Application.getTranslator();
private SimulationPlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
//// Flight data plot
super(parent, simulation.getName());
this.setModalityType(ModalityType.DOCUMENT_MODAL);
final boolean initialShowPoints = Application.getPreferences().getBoolean(Preferences.PLOT_SHOW_POINTS, false);
final SimulationPlot myPlot = new SimulationPlot(simulation, config, initialShowPoints );
// Create the dialog
JPanel panel = new JPanel(new MigLayout("fill"));
this.add(panel);
final ChartPanel chartPanel = new SimulationChart(myPlot.getJFreeChart());
panel.add(chartPanel, "grow, wrap 20lp");
//// Description text
JLabel label = new StyledLabel(trans.get("PlotDialog.lbl.Chart"), -2);
panel.add(label, "wrap");
//// Show data points
final JCheckBox check = new JCheckBox(trans.get("PlotDialog.CheckBox.Showdatapoints"));
check.setSelected(initialShowPoints);
check.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean show = check.isSelected();
Application.getPreferences().putBoolean(Preferences.PLOT_SHOW_POINTS, show);
myPlot.setShowPoints(show);
}
});
panel.add(check, "split, left");
//// Zoom out button
JButton button = new JButton(Icons.ZOOM_OUT);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ( (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK ) {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_OUT_DOMAIN_COMMAND));
} else {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_OUT_BOTH_COMMAND));
}
}
});
panel.add(button, "gapleft rel");
//// Zoom in button
button = new JButton(Icons.ZOOM_IN);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ( (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK ) {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_IN_DOMAIN_COMMAND));
} else {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_IN_BOTH_COMMAND));
}
}
});
panel.add(button, "gapleft rel");
//// Add series selection box
//// FIXME
List<String> stages = new ArrayList<String>();
stages.add("All");
for ( int i=0; i< simulation.getSimulatedData().getBranchCount(); i++ ) {
stages.add( simulation.getSimulatedData().getBranch(i).getBranchName() + " (" + i + ")");
}
final JComboBox<String> stageSelection = new JComboBox<String>(stages.toArray(new String[0]));
stageSelection.addItemListener( new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int selectedStage = stageSelection.getSelectedIndex() -1;
myPlot.setShowBranch(selectedStage);
}
});
- if ( stages.size() > 1 ) {
+ if ( stages.size() > 2 ) {
+ // Only show the combo box if there are at least 3 entries (ie, "All", "Main", and one other one
panel.add(stageSelection, "gapleft rel");
panel.add(new JPanel(), "growx");
}
//// Close button
button = new JButton(trans.get("dlg.but.close"));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SimulationPlotDialog.this.dispose();
}
});
panel.add(button, "right");
this.setLocationByPlatform(true);
this.pack();
GUIUtil.setDisposableDialogOptions(this, button);
GUIUtil.rememberWindowSize(this);
}
/**
* Static method that shows a plot with the specified parameters.
*
* @param parent the parent window, which will be blocked.
* @param simulation the simulation to plot.
* @param config the configuration of the plot.
*/
public static void showPlot(Window parent, Simulation simulation, PlotConfiguration config) {
new SimulationPlotDialog(parent, simulation, config).setVisible(true);
}
}
| true | true | private SimulationPlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
//// Flight data plot
super(parent, simulation.getName());
this.setModalityType(ModalityType.DOCUMENT_MODAL);
final boolean initialShowPoints = Application.getPreferences().getBoolean(Preferences.PLOT_SHOW_POINTS, false);
final SimulationPlot myPlot = new SimulationPlot(simulation, config, initialShowPoints );
// Create the dialog
JPanel panel = new JPanel(new MigLayout("fill"));
this.add(panel);
final ChartPanel chartPanel = new SimulationChart(myPlot.getJFreeChart());
panel.add(chartPanel, "grow, wrap 20lp");
//// Description text
JLabel label = new StyledLabel(trans.get("PlotDialog.lbl.Chart"), -2);
panel.add(label, "wrap");
//// Show data points
final JCheckBox check = new JCheckBox(trans.get("PlotDialog.CheckBox.Showdatapoints"));
check.setSelected(initialShowPoints);
check.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean show = check.isSelected();
Application.getPreferences().putBoolean(Preferences.PLOT_SHOW_POINTS, show);
myPlot.setShowPoints(show);
}
});
panel.add(check, "split, left");
//// Zoom out button
JButton button = new JButton(Icons.ZOOM_OUT);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ( (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK ) {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_OUT_DOMAIN_COMMAND));
} else {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_OUT_BOTH_COMMAND));
}
}
});
panel.add(button, "gapleft rel");
//// Zoom in button
button = new JButton(Icons.ZOOM_IN);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ( (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK ) {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_IN_DOMAIN_COMMAND));
} else {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_IN_BOTH_COMMAND));
}
}
});
panel.add(button, "gapleft rel");
//// Add series selection box
//// FIXME
List<String> stages = new ArrayList<String>();
stages.add("All");
for ( int i=0; i< simulation.getSimulatedData().getBranchCount(); i++ ) {
stages.add( simulation.getSimulatedData().getBranch(i).getBranchName() + " (" + i + ")");
}
final JComboBox<String> stageSelection = new JComboBox<String>(stages.toArray(new String[0]));
stageSelection.addItemListener( new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int selectedStage = stageSelection.getSelectedIndex() -1;
myPlot.setShowBranch(selectedStage);
}
});
if ( stages.size() > 1 ) {
panel.add(stageSelection, "gapleft rel");
panel.add(new JPanel(), "growx");
}
//// Close button
button = new JButton(trans.get("dlg.but.close"));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SimulationPlotDialog.this.dispose();
}
});
panel.add(button, "right");
this.setLocationByPlatform(true);
this.pack();
GUIUtil.setDisposableDialogOptions(this, button);
GUIUtil.rememberWindowSize(this);
}
| private SimulationPlotDialog(Window parent, Simulation simulation, PlotConfiguration config) {
//// Flight data plot
super(parent, simulation.getName());
this.setModalityType(ModalityType.DOCUMENT_MODAL);
final boolean initialShowPoints = Application.getPreferences().getBoolean(Preferences.PLOT_SHOW_POINTS, false);
final SimulationPlot myPlot = new SimulationPlot(simulation, config, initialShowPoints );
// Create the dialog
JPanel panel = new JPanel(new MigLayout("fill"));
this.add(panel);
final ChartPanel chartPanel = new SimulationChart(myPlot.getJFreeChart());
panel.add(chartPanel, "grow, wrap 20lp");
//// Description text
JLabel label = new StyledLabel(trans.get("PlotDialog.lbl.Chart"), -2);
panel.add(label, "wrap");
//// Show data points
final JCheckBox check = new JCheckBox(trans.get("PlotDialog.CheckBox.Showdatapoints"));
check.setSelected(initialShowPoints);
check.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean show = check.isSelected();
Application.getPreferences().putBoolean(Preferences.PLOT_SHOW_POINTS, show);
myPlot.setShowPoints(show);
}
});
panel.add(check, "split, left");
//// Zoom out button
JButton button = new JButton(Icons.ZOOM_OUT);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ( (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK ) {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_OUT_DOMAIN_COMMAND));
} else {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_OUT_BOTH_COMMAND));
}
}
});
panel.add(button, "gapleft rel");
//// Zoom in button
button = new JButton(Icons.ZOOM_IN);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if ( (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK ) {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_IN_DOMAIN_COMMAND));
} else {
chartPanel.actionPerformed( new ActionEvent( chartPanel, ActionEvent.ACTION_FIRST, ChartPanel.ZOOM_IN_BOTH_COMMAND));
}
}
});
panel.add(button, "gapleft rel");
//// Add series selection box
//// FIXME
List<String> stages = new ArrayList<String>();
stages.add("All");
for ( int i=0; i< simulation.getSimulatedData().getBranchCount(); i++ ) {
stages.add( simulation.getSimulatedData().getBranch(i).getBranchName() + " (" + i + ")");
}
final JComboBox<String> stageSelection = new JComboBox<String>(stages.toArray(new String[0]));
stageSelection.addItemListener( new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
int selectedStage = stageSelection.getSelectedIndex() -1;
myPlot.setShowBranch(selectedStage);
}
});
if ( stages.size() > 2 ) {
// Only show the combo box if there are at least 3 entries (ie, "All", "Main", and one other one
panel.add(stageSelection, "gapleft rel");
panel.add(new JPanel(), "growx");
}
//// Close button
button = new JButton(trans.get("dlg.but.close"));
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
SimulationPlotDialog.this.dispose();
}
});
panel.add(button, "right");
this.setLocationByPlatform(true);
this.pack();
GUIUtil.setDisposableDialogOptions(this, button);
GUIUtil.rememberWindowSize(this);
}
|
diff --git a/EclipseWurstPlugin/src/de/peeeq/eclipsewurstplugin/editor/WurstTextHover.java b/EclipseWurstPlugin/src/de/peeeq/eclipsewurstplugin/editor/WurstTextHover.java
index 0b5c9408..2c9f27c3 100644
--- a/EclipseWurstPlugin/src/de/peeeq/eclipsewurstplugin/editor/WurstTextHover.java
+++ b/EclipseWurstPlugin/src/de/peeeq/eclipsewurstplugin/editor/WurstTextHover.java
@@ -1,116 +1,116 @@
package de.peeeq.eclipsewurstplugin.editor;
import java.util.Iterator;
import org.eclipse.jface.text.IRegion;
import org.eclipse.jface.text.ITextHover;
import org.eclipse.jface.text.ITextHoverExtension2;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.Position;
import org.eclipse.jface.text.Region;
import org.eclipse.jface.text.source.Annotation;
import org.eclipse.jface.text.source.IAnnotationModel;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.text.source.ISourceViewerExtension2;
import org.eclipse.ui.texteditor.SimpleMarkerAnnotation;
import de.peeeq.eclipsewurstplugin.builder.WurstBuilder;
import de.peeeq.eclipsewurstplugin.editor.autocomplete.WurstCompletionProcessor;
import de.peeeq.wurstscript.ast.AstElement;
import de.peeeq.wurstscript.ast.CompilationUnit;
import de.peeeq.wurstscript.ast.Documentable;
import de.peeeq.wurstscript.ast.ExprVarAccess;
import de.peeeq.wurstscript.ast.ExprVarArrayAccess;
import de.peeeq.wurstscript.ast.FuncRef;
import de.peeeq.wurstscript.ast.FunctionDefinition;
import de.peeeq.wurstscript.ast.NameDef;
import de.peeeq.wurstscript.ast.NameRef;
import de.peeeq.wurstscript.ast.VarDef;
import de.peeeq.wurstscript.utils.Utils;
public class WurstTextHover implements ITextHover,
// ITextHoverExtension,
ITextHoverExtension2 {
private ISourceViewer sourceViewer;
private WurstEditor editor;
public WurstTextHover(ISourceViewer sourceViewer, WurstEditor editor) {
this.sourceViewer = sourceViewer;
this.editor = editor;
}
@Override
public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
String annotationHover = getAnnotationHover(hoverRegion);
if (annotationHover != null) {
return annotationHover;
}
return getAstHover(textViewer, hoverRegion);
}
private String getAstHover(ITextViewer textViewer, IRegion hoverRegion) {
CompilationUnit cu = editor.getCompilationUnit();
if (cu == null) {
return null;
}
AstElement elem = Utils.getAstElementAtPosIgnoringLists(cu, hoverRegion.getOffset(), true);
try {
return elem.descriptionHtml();
} catch (Throwable t) {
// t.printStackTrace();
return null;
}
}
public String getAnnotationHover(IRegion hoverRegion) {
IAnnotationModel model= getAnnotationModel(sourceViewer);
if (model == null)
return null;
Iterator<?> e= model.getAnnotationIterator();
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (isIncluded(a)) {
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
String msg= a.getText();
if (msg != null && msg.trim().length() > 0)
- return msg;
+ return Utils.escapeHtml(msg);
}
}
}
return null;
}
private boolean isIncluded(Annotation annotation) {
if(annotation instanceof SimpleMarkerAnnotation){
SimpleMarkerAnnotation markerannotation = (SimpleMarkerAnnotation)annotation;
return markerannotation.getMarker().exists()
&& WurstBuilder.isWurstMarker(markerannotation.getMarker());
}
return false;
}
private IAnnotationModel getAnnotationModel(ISourceViewer viewer) {
if (viewer instanceof ISourceViewerExtension2) {
ISourceViewerExtension2 extension= (ISourceViewerExtension2) viewer;
return extension.getVisualAnnotationModel();
}
return viewer.getAnnotationModel();
}
@Override
public String getHoverInfo(ITextViewer textViewer, IRegion hoverRegion) {
return getHoverInfo2(textViewer, hoverRegion).toString();
}
@Override
public IRegion getHoverRegion(ITextViewer textViewer, int offset) {
// TODO smarter region
return new Region(offset,0);
}
}
| true | true | public String getAnnotationHover(IRegion hoverRegion) {
IAnnotationModel model= getAnnotationModel(sourceViewer);
if (model == null)
return null;
Iterator<?> e= model.getAnnotationIterator();
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (isIncluded(a)) {
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
String msg= a.getText();
if (msg != null && msg.trim().length() > 0)
return msg;
}
}
}
return null;
}
| public String getAnnotationHover(IRegion hoverRegion) {
IAnnotationModel model= getAnnotationModel(sourceViewer);
if (model == null)
return null;
Iterator<?> e= model.getAnnotationIterator();
while (e.hasNext()) {
Annotation a= (Annotation) e.next();
if (isIncluded(a)) {
Position p= model.getPosition(a);
if (p != null && p.overlapsWith(hoverRegion.getOffset(), hoverRegion.getLength())) {
String msg= a.getText();
if (msg != null && msg.trim().length() > 0)
return Utils.escapeHtml(msg);
}
}
}
return null;
}
|
diff --git a/src/com/android/browser/AddBookmarkPage.java b/src/com/android/browser/AddBookmarkPage.java
index 10c91f8d..f287e8e1 100644
--- a/src/com/android/browser/AddBookmarkPage.java
+++ b/src/com/android/browser/AddBookmarkPage.java
@@ -1,284 +1,284 @@
/*
* Copyright (C) 2006 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.browser;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.ParseException;
import android.net.WebAddress;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Browser;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
public class AddBookmarkPage extends Activity {
private final String LOGTAG = "Bookmarks";
private EditText mTitle;
private EditText mAddress;
private TextView mButton;
private View mCancelButton;
private boolean mEditingExisting;
private Bundle mMap;
private String mTouchIconUrl;
private Bitmap mThumbnail;
private String mOriginalUrl;
private boolean mIsUrlEditable = true;
// Message IDs
private static final int SAVE_BOOKMARK = 100;
private Handler mHandler;
private View.OnClickListener mSaveBookmark = new View.OnClickListener() {
public void onClick(View v) {
if (save()) {
finish();
}
}
};
private View.OnClickListener mCancel = new View.OnClickListener() {
public void onClick(View v) {
finish();
}
};
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
mMap = getIntent().getExtras();
if (mMap != null) {
mIsUrlEditable = mMap.getBoolean("url_editable", true);
}
if (mIsUrlEditable) {
setContentView(R.layout.browser_add_bookmark);
} else {
setContentView(R.layout.browser_add_bookmark_const_url);
}
setTitle(R.string.save_to_bookmarks);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ic_list_bookmark);
String title = null;
String url = null;
if (mMap != null) {
Bundle b = mMap.getBundle("bookmark");
if (b != null) {
mMap = b;
mEditingExisting = true;
setTitle(R.string.edit_bookmark);
}
title = mMap.getString("title");
url = mOriginalUrl = mMap.getString("url");
mTouchIconUrl = mMap.getString("touch_icon_url");
mThumbnail = (Bitmap) mMap.getParcelable("thumbnail");
}
mTitle = (EditText) findViewById(R.id.title);
mTitle.setText(title);
if (mIsUrlEditable) {
mAddress = (EditText) findViewById(R.id.address);
mAddress.setText(url);
}
View.OnClickListener accept = mSaveBookmark;
mButton = (TextView) findViewById(R.id.OK);
mButton.setOnClickListener(accept);
mCancelButton = findViewById(R.id.cancel);
mCancelButton.setOnClickListener(mCancel);
if (!getWindow().getDecorView().isInTouchMode()) {
mButton.requestFocus();
}
}
/**
* Runnable to save a bookmark, so it can be performed in its own thread.
*/
private class SaveBookmarkRunnable implements Runnable {
private Message mMessage;
public SaveBookmarkRunnable(Message msg) {
mMessage = msg;
}
public void run() {
// Unbundle bookmark data.
Bundle bundle = mMessage.getData();
String title = bundle.getString("title");
String url = bundle.getString("url");
boolean invalidateThumbnail = bundle.getBoolean(
"invalidateThumbnail");
Bitmap thumbnail = invalidateThumbnail ? null
: (Bitmap) bundle.getParcelable("thumbnail");
String touchIconUrl = bundle.getString("touchIconUrl");
// Save to the bookmarks DB.
try {
final ContentResolver cr = getContentResolver();
Bookmarks.addBookmark(null, cr, url, title, thumbnail, true);
if (touchIconUrl != null) {
new DownloadTouchIcon(AddBookmarkPage.this, cr, url).execute(mTouchIconUrl);
}
mMessage.arg1 = 1;
} catch (IllegalStateException e) {
mMessage.arg1 = 0;
}
mMessage.sendToTarget();
}
}
private void createHandler() {
if (mHandler == null) {
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SAVE_BOOKMARK:
if (1 == msg.arg1) {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_saved,
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_not_saved,
Toast.LENGTH_LONG).show();
}
break;
}
}
};
}
}
/**
* Parse the data entered in the dialog and post a message to update the bookmarks database.
*/
boolean save() {
createHandler();
String title = mTitle.getText().toString().trim();
String unfilteredUrl;
if (mIsUrlEditable) {
unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
} else {
unfilteredUrl = mOriginalUrl;
}
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_needs_url,
Toast.LENGTH_LONG).show();
}
- return false;
}
+ return false;
}
String url = unfilteredUrl.trim();
try {
// We allow bookmarks with a javascript: scheme, but these will in most cases
// fail URI parsing, so don't try it if that's the kind of bookmark we have.
if (!url.toLowerCase().startsWith("javascript:")) {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!Bookmarks.urlHasAcceptableScheme(url)) {
// If the scheme was non-null, let the user know that we
// can't save their bookmark. If it was null, we'll assume
// they meant http when we parse it in the WebAddress class.
if (scheme != null) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_cannot_save_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_cannot_save_url,
Toast.LENGTH_LONG).show();
}
return false;
}
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
}
} catch (URISyntaxException e) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_url_not_valid,
Toast.LENGTH_LONG).show();
}
return false;
}
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
mMap.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
// Post a message to write to the DB.
Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("url", url);
bundle.putParcelable("thumbnail", mThumbnail);
bundle.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
bundle.putString("touchIconUrl", mTouchIconUrl);
Message msg = Message.obtain(mHandler, SAVE_BOOKMARK);
msg.setData(bundle);
// Start a new thread so as to not slow down the UI
Thread t = new Thread(new SaveBookmarkRunnable(msg));
t.start();
setResult(RESULT_OK);
LogTag.logBookmarkAdded(url, "bookmarkview");
}
return true;
}
}
| false | true | boolean save() {
createHandler();
String title = mTitle.getText().toString().trim();
String unfilteredUrl;
if (mIsUrlEditable) {
unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
} else {
unfilteredUrl = mOriginalUrl;
}
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_needs_url,
Toast.LENGTH_LONG).show();
}
return false;
}
}
String url = unfilteredUrl.trim();
try {
// We allow bookmarks with a javascript: scheme, but these will in most cases
// fail URI parsing, so don't try it if that's the kind of bookmark we have.
if (!url.toLowerCase().startsWith("javascript:")) {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!Bookmarks.urlHasAcceptableScheme(url)) {
// If the scheme was non-null, let the user know that we
// can't save their bookmark. If it was null, we'll assume
// they meant http when we parse it in the WebAddress class.
if (scheme != null) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_cannot_save_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_cannot_save_url,
Toast.LENGTH_LONG).show();
}
return false;
}
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
}
} catch (URISyntaxException e) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_url_not_valid,
Toast.LENGTH_LONG).show();
}
return false;
}
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
mMap.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
// Post a message to write to the DB.
Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("url", url);
bundle.putParcelable("thumbnail", mThumbnail);
bundle.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
bundle.putString("touchIconUrl", mTouchIconUrl);
Message msg = Message.obtain(mHandler, SAVE_BOOKMARK);
msg.setData(bundle);
// Start a new thread so as to not slow down the UI
Thread t = new Thread(new SaveBookmarkRunnable(msg));
t.start();
setResult(RESULT_OK);
LogTag.logBookmarkAdded(url, "bookmarkview");
}
return true;
}
| boolean save() {
createHandler();
String title = mTitle.getText().toString().trim();
String unfilteredUrl;
if (mIsUrlEditable) {
unfilteredUrl =
BrowserActivity.fixUrl(mAddress.getText().toString());
} else {
unfilteredUrl = mOriginalUrl;
}
boolean emptyTitle = title.length() == 0;
boolean emptyUrl = unfilteredUrl.trim().length() == 0;
Resources r = getResources();
if (emptyTitle || emptyUrl) {
if (emptyTitle) {
mTitle.setError(r.getText(R.string.bookmark_needs_title));
}
if (emptyUrl) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_needs_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_needs_url,
Toast.LENGTH_LONG).show();
}
}
return false;
}
String url = unfilteredUrl.trim();
try {
// We allow bookmarks with a javascript: scheme, but these will in most cases
// fail URI parsing, so don't try it if that's the kind of bookmark we have.
if (!url.toLowerCase().startsWith("javascript:")) {
URI uriObj = new URI(url);
String scheme = uriObj.getScheme();
if (!Bookmarks.urlHasAcceptableScheme(url)) {
// If the scheme was non-null, let the user know that we
// can't save their bookmark. If it was null, we'll assume
// they meant http when we parse it in the WebAddress class.
if (scheme != null) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_cannot_save_url));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_cannot_save_url,
Toast.LENGTH_LONG).show();
}
return false;
}
WebAddress address;
try {
address = new WebAddress(unfilteredUrl);
} catch (ParseException e) {
throw new URISyntaxException("", "");
}
if (address.mHost.length() == 0) {
throw new URISyntaxException("", "");
}
url = address.toString();
}
}
} catch (URISyntaxException e) {
if (mIsUrlEditable) {
mAddress.setError(r.getText(R.string.bookmark_url_not_valid));
} else {
Toast.makeText(AddBookmarkPage.this, R.string.bookmark_url_not_valid,
Toast.LENGTH_LONG).show();
}
return false;
}
if (mEditingExisting) {
mMap.putString("title", title);
mMap.putString("url", url);
mMap.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
setResult(RESULT_OK, (new Intent()).setAction(
getIntent().toString()).putExtras(mMap));
} else {
// Post a message to write to the DB.
Bundle bundle = new Bundle();
bundle.putString("title", title);
bundle.putString("url", url);
bundle.putParcelable("thumbnail", mThumbnail);
bundle.putBoolean("invalidateThumbnail", !url.equals(mOriginalUrl));
bundle.putString("touchIconUrl", mTouchIconUrl);
Message msg = Message.obtain(mHandler, SAVE_BOOKMARK);
msg.setData(bundle);
// Start a new thread so as to not slow down the UI
Thread t = new Thread(new SaveBookmarkRunnable(msg));
t.start();
setResult(RESULT_OK);
LogTag.logBookmarkAdded(url, "bookmarkview");
}
return true;
}
|
diff --git a/srcj/com/sun/electric/tool/user/ui/SizeListener.java b/srcj/com/sun/electric/tool/user/ui/SizeListener.java
index 29270008d..0e7253f22 100755
--- a/srcj/com/sun/electric/tool/user/ui/SizeListener.java
+++ b/srcj/com/sun/electric/tool/user/ui/SizeListener.java
@@ -1,725 +1,727 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: SizeListener.java
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.user.ui;
import com.sun.electric.database.geometry.DBMath;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.geometry.Orientation;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.Geometric;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.Technology;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.user.CircuitChangeJobs;
import com.sun.electric.tool.user.Highlighter;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.EDialog;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.EventListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;
/**
* Class to interactively resize a node.
*/
public class SizeListener
implements MouseMotionListener, MouseListener, MouseWheelListener, KeyListener
{
private static final boolean NEWWAY = true;
private Geometric stretchGeom;
private EventListener oldListener;
private Cursor oldCursor;
private Point2D farthestCorner, farthestEdge, closestCorner, closestEdge;
private static Cursor sizeCursor = ToolBar.readCursor("CursorSize.gif", 14, 14);
private static SizeListener currentListener = null;
private SizeListener() {}
/**
* Method to do an interactive sizing of the currently selected object.
*/
public static void sizeObjects()
{
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<Geometric> geomList = highlighter.getHighlightedEObjs(true, true);
if (geomList == null) return;
if (geomList.size() != 1)
{
System.out.println("Select just one object to size");
return;
}
Geometric geom = geomList.get(0);
EventListener newListener = null;
// remember the listener that was there before
EventListener oldListener = WindowFrame.getListener();
Cursor oldCursor = TopLevel.getCurrentCursor();
System.out.println("Click to stretch " + geom);
newListener = oldListener;
if (newListener == null || !(newListener instanceof SizeListener))
{
currentListener = new SizeListener();
newListener = currentListener;
WindowFrame.setListener(newListener);
}
((SizeListener)newListener).stretchGeom = geom;
// Only store data when the previous event listener is not this one
if (!(oldListener instanceof SizeListener))
{
((SizeListener)newListener).oldListener = oldListener;
((SizeListener)newListener).oldCursor = oldCursor;
}
// change the cursor
TopLevel.setCurrentCursor(sizeCursor);
}
public static void restorePreviousListener(Object toDelete)
{
if (currentListener == null) return; // nothing to restore
if (currentListener.stretchGeom == toDelete)
currentListener.restoringOriginalSetup(null);
}
/**
* Method to present a dialog to resize all selected nodes.
*/
public static void sizeAllNodes()
{
new SizeObjects(TopLevel.getCurrentJFrame(), true, true);
}
/**
* Method to present a dialog to resize all selected arcs.
*/
public static void sizeAllArcs()
{
new SizeObjects(TopLevel.getCurrentJFrame(), true, false);
}
/**
* Class to handle the "Size all selected nodes/arcs" dialog.
*/
private static class SizeObjects extends EDialog
{
private JTextField xSize, ySize;
private boolean nodes;
/** Creates new form Size all selected nodes/arcs */
public SizeObjects(Frame parent, boolean modal, boolean nodes)
{
super(parent, modal);
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
getContentPane().setLayout(new GridBagLayout());
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt) { closeDialog(); }
});
String label = "Width:";
this.nodes = nodes;
if (nodes)
{
label = "X Size:";
setTitle("Set Node Size");
JLabel ySizeLabel = new JLabel("Y Size:");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(ySizeLabel, gbc);
ySize = new JTextField();
ySize.setColumns(6);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 1;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(ySize, gbc);
EDialog.makeTextFieldSelectAllOnTab(ySize);
} else
{
setTitle("Set Arc Size");
}
xSize = new JTextField();
xSize.setColumns(6);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(xSize, gbc);
EDialog.makeTextFieldSelectAllOnTab(xSize);
JLabel xSizeLabel = new JLabel(label);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(xSizeLabel, gbc);
// determine default size
double xS = 0, yS = 0;
Technology tech = null;
for(Geometric geom : highlighter.getHighlightedEObjs(true, true))
{
tech = geom.getParent().getTechnology();
if (geom instanceof NodeInst && nodes)
{
NodeInst ni = (NodeInst)geom;
xS = ni.getLambdaBaseXSize();
yS = ni.getLambdaBaseYSize();
} else if (geom instanceof ArcInst && !nodes)
{
ArcInst ai = (ArcInst)geom;
xS = ai.getLambdaBaseWidth();
}
}
xSize.setText(TextUtils.formatDistance(xS, tech));
if (nodes)
ySize.setText(TextUtils.formatDistance(yS, tech));
JButton ok = new JButton("OK");
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 2;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(ok, gbc);
ok.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt) { ok(evt); }
});
getRootPane().setDefaultButton(ok);
JButton cancel = new JButton("Cancel");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new java.awt.Insets(4, 4, 4, 4);
getContentPane().add(cancel, gbc);
cancel.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent evt) { cancel(evt); }
});
pack();
finishInitialization();
setVisible(true);
}
protected void escapePressed() { closeDialog(); }
private void cancel(ActionEvent evt) { closeDialog(); }
private void ok(ActionEvent evt)
{
// resize the objects
EditWindow wnd = EditWindow.needCurrent();
if (wnd == null) return;
Highlighter highlighter = wnd.getHighlighter();
List<Geometric> highlighted = highlighter.getHighlightedEObjs(true, true);
double xS = TextUtils.atofDistance(xSize.getText());
double yS = 0;
if (nodes)
yS = TextUtils.atofDistance(ySize.getText());
new ResizeStuff(wnd.getCell(), highlighted, xS, yS, nodes);
closeDialog();
}
}
/**
* Class to resize objects in a new thread.
*/
private static class ResizeStuff extends Job
{
private Cell cell;
private List<Geometric> highlighted;
private double xS, yS;
private boolean nodes;
protected ResizeStuff(Cell cell, List<Geometric> highlighted, double xS, double yS, boolean nodes)
{
super("Resize Objects", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.cell = cell;
this.highlighted = highlighted;
this.xS = xS;
this.yS = yS;
this.nodes = nodes;
startJob();
}
public boolean doIt() throws JobException
{
// make sure moving the node is allowed
if (CircuitChangeJobs.cantEdit(cell, null, true, false, true) != 0) return false;
boolean didSomething = false;
for(Geometric geom : highlighted)
{
if (geom instanceof NodeInst && nodes)
{
NodeInst ni = (NodeInst)geom;
double x = xS;
double y = yS;
if (!ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare())
{
if (y > x) x = y; else y = x;
}
ni.resize(x - ni.getLambdaBaseXSize(), y - ni.getLambdaBaseYSize());
didSomething = true;
} else if (geom instanceof ArcInst && !nodes)
{
ArcInst ai = (ArcInst)geom;
ai.setLambdaBaseWidth(xS);
didSomething = true;
}
}
if (!didSomething)
{
System.out.println("Could not find any " + (nodes?"nodes":"arcs") + " to resize");
}
return true;
}
}
public void mousePressed(MouseEvent evt)
{
farthestCorner = farthestEdge = null;
showHighlight(evt, (EditWindow)evt.getSource(), false);
}
public void mouseMoved(MouseEvent evt)
{
farthestCorner = farthestEdge = null;
showHighlight(evt, (EditWindow)evt.getSource(), true);
farthestCorner = farthestEdge = null;
}
public void mouseDragged(MouseEvent evt)
{
showHighlight(evt, (EditWindow)evt.getSource(), false);
}
public void mouseReleased(MouseEvent evt)
{
// restore the listener to the former state
EditWindow wnd = (EditWindow)evt.getSource();
restoringOriginalSetup(wnd);
// Checking the element hasn't been removed
assert(stretchGeom.isLinked());
// handle scaling the selected objects
if (stretchGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)stretchGeom;
Point2D newCenter = new Point2D.Double(ni.getAnchorCenterX(), ni.getAnchorCenterY());
Point2D newSize = getNewNodeSize(evt, newCenter);
new ScaleNode(ni, new EPoint(newCenter.getX(), newCenter.getY()), newSize.getX(), newSize.getY());
} else
{
ArcInst ai = (ArcInst)stretchGeom;
double newLambdaBaseWidth = getNewArcSize(evt);
new ScaleArc(ai, newLambdaBaseWidth);
}
wnd.repaint();
}
private void restoringOriginalSetup(EditWindow wnd)
{
// restore the listener to the former state
WindowFrame.setListener(oldListener);
TopLevel.setCurrentCursor(oldCursor);
if (wnd != null)
showHighlight(null, wnd, false);
}
public void keyPressed(KeyEvent evt)
{
int chr = evt.getKeyCode();
EditWindow wnd = (EditWindow)evt.getSource();
Cell cell = wnd.getCell();
if (cell == null) return;
// ESCAPE for abort
if (chr == KeyEvent.VK_ESCAPE)
{
restoringOriginalSetup(wnd);
System.out.println("Sizing aborted");
}
}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
public void mouseWheelMoved(MouseWheelEvent evt) {}
public void keyReleased(KeyEvent evt) {}
public void keyTyped(KeyEvent evt) {}
private void showHighlight(MouseEvent evt, EditWindow wnd, boolean stillUp)
{
Highlighter highlighter = wnd.getHighlighter();
Cell cell = stretchGeom.getParent();
highlighter.clear();
highlighter.addElectricObject(stretchGeom, cell);
if (evt != null)
{
double boxSize = 5 / wnd.getScale();
Color dotColor = new Color(User.getColor(User.ColorPrefType.GRID));
if (stretchGeom instanceof NodeInst)
{
NodeInst ni = (NodeInst)stretchGeom;
Point2D newCenter = new Point2D.Double(ni.getAnchorCenterX(), ni.getAnchorCenterY());
Point2D newSize = getNewNodeSize(evt, newCenter);
if (NEWWAY)
{
if (stillUp)
{
newSize.setLocation(ni.getLambdaBaseXSize(), ni.getLambdaBaseYSize());
newCenter.setLocation(ni.getAnchorCenterX(), ni.getAnchorCenterY());
}
}
Poly stretchedPoly = ni.getBaseShape(EPoint.snap(newCenter), newSize.getX(), newSize.getY());
Point2D [] stretchedPoints = stretchedPoly.getPoints();
for(int i=0; i<stretchedPoints.length; i++)
{
int lastI = i - 1;
if (lastI < 0) lastI = stretchedPoints.length - 1;
highlighter.addLine(stretchedPoints[lastI], stretchedPoints[i], cell);
if (NEWWAY)
{
double cX = (stretchedPoints[lastI].getX() + stretchedPoints[i].getX()) / 2;
double cY = (stretchedPoints[lastI].getY() + stretchedPoints[i].getY()) / 2;
Poly poly = new Poly(cX, cY, boxSize, boxSize);
poly.setStyle(Poly.Type.FILLED);
highlighter.addPoly(poly, cell, dotColor);
poly = new Poly(stretchedPoints[i].getX(), stretchedPoints[i].getY(), boxSize, boxSize);
poly.setStyle(Poly.Type.FILLED);
highlighter.addPoly(poly, cell, dotColor);
}
}
} else
{
// construct the polygons that describe the basic arc
long newGridWidth = DBMath.lambdaToSizeGrid(getNewArcSize(evt));
ArcInst ai = (ArcInst)stretchGeom;
Poly stretchedPoly = ai.makeLambdaPoly(newGridWidth, Poly.Type.CLOSED);
if (stretchedPoly == null) return;
Point2D [] stretchedPoints = stretchedPoly.getPoints();
for(int i=0; i<stretchedPoints.length; i++)
{
int lastI = i - 1;
if (lastI < 0) lastI = stretchedPoints.length - 1;
highlighter.addLine(stretchedPoints[lastI], stretchedPoints[i], cell);
}
}
}
highlighter.finished();
}
/**
* Method to determine the proper size for the NodeInst being stretched, given a cursor location.
* @param evt the event with the current cursor location.
*/
private Point2D getNewNodeSize(MouseEvent evt, Point2D newCenter)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the node being stretched
NodeInst ni = (NodeInst)stretchGeom;
if (ni.getProto() instanceof Cell) return EPoint.ORIGIN;
// setup outline of node with standard offset
Poly nodePoly = ni.getBaseShape();
AffineTransform transIn = ni.transformIn();
transIn.transform(pt, pt);
nodePoly.transform(transIn);
// determine the closest point on the outline
Point2D [] points = nodePoly.getPoints();
if (farthestCorner == null && farthestEdge == null)
{
double closestDist = Double.MAX_VALUE;
for(int i=0; i<points.length; i++)
{
double dist = pt.distance(points[i]);
if (dist < closestDist)
{
closestDist = dist;
closestCorner = points[i];
farthestCorner = points[(i + points.length/2) % points.length];
farthestEdge = closestEdge = null;
}
int lastI = i-1;
if (lastI < 0) lastI = points.length-1;
Point2D edge = new Point2D.Double((points[i].getX() + points[lastI].getX())/2,
(points[i].getY() + points[lastI].getY())/2);
dist = pt.distance(edge);
if (dist < closestDist)
{
closestDist = dist;
int oppI = (i + points.length/2) % points.length;
lastI = oppI-1;
if (lastI < 0) lastI = points.length-1;
farthestEdge = new Point2D.Double((points[oppI].getX() + points[lastI].getX())/2,
(points[oppI].getY() + points[lastI].getY())/2);
closestEdge = edge;
farthestCorner = closestCorner = null;
}
}
}
// if SHIFT and CONTROL is held, use center-based sizing
boolean centerBased = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
// if CONTROL is held, constrain to single-axis stretching
boolean singleAxis = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) == 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0 && farthestCorner != null;
// if SHIFT held (or if a square primitive) make growth the same in both axes
boolean square = !ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare();
if ((evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) == 0) square = true;
// determine the amount of growth of the node
double growthRatioX, growthRatioY;
Point2D closest = (closestCorner != null ? closestCorner : closestEdge);
Point2D farthest = (farthestCorner != null ? farthestCorner : farthestEdge);
if (centerBased)
{
double ptToCenterX = Math.abs(pt.getX());
double closestToCenterX = Math.abs(closest.getX());
double ptToCenterY = Math.abs(pt.getY());
double closestToCenterY = Math.abs(closest.getY());
growthRatioX = ptToCenterX / closestToCenterX;
growthRatioY = ptToCenterY / closestToCenterY;
} else
{
double ptToFarthestX = pt.getX() - farthest.getX();
double closestToFarthestX = closest.getX() - farthest.getX();
double ptToFarthestY = pt.getY() - farthest.getY();
double closestToFarthestY = closest.getY() - farthest.getY();
growthRatioX = closestToFarthestX == 0 ? 1 : (ptToFarthestX / closestToFarthestX);
growthRatioY = closestToFarthestY == 0 ? 1 : (ptToFarthestY / closestToFarthestY);
}
int direction = -1; // both X and Y
if (singleAxis)
{
// constrain to single-axis stretching
double grx = Math.abs(growthRatioX);
if (grx < 1)
{
if (grx == 0) grx = 9999; else grx = 1/grx;
}
double gry = Math.abs(growthRatioY);
if (gry < 1)
{
if (gry == 0) gry = 9999; else gry = 1/gry;
}
if (grx > gry)
{
growthRatioY = 1;
direction = 0; // Y
} else
{
growthRatioX = 1;
direction = 1; // X
}
}
if (square)
{
if (Math.abs(growthRatioX) > Math.abs(growthRatioY))
growthRatioY = growthRatioX;
else
growthRatioX = growthRatioY;
}
// compute the new node size
double newXSize = ni.getLambdaBaseXSize() * growthRatioX;
double newYSize = ni.getLambdaBaseYSize() * growthRatioY;
+ double signX = newXSize < 0 ? -1 : 1;
+ double signY = newYSize < 0 ? -1 : 1;
Point2D newSize = new Point2D.Double(Math.abs(newXSize), Math.abs(newYSize));
// grid align the new node size
EditWindow.gridAlignSize(newSize, direction);
// determine the new center point
if (!centerBased)
{
double closestX = closest.getX();
double closestY = closest.getY();
double farthestX = farthest.getX();
double farthestY = farthest.getY();
- double newClosestX = (closestX == farthestX ? closestX : farthestX + newXSize*(closestX > farthestX ? 1 : -1));
- double newClosestY = (closestY == farthestY ? closestY : farthestY + newYSize*(closestY > farthestY ? 1 : -1));
+ double newClosestX = (closestX == farthestX ? closestX : farthestX + newSize.getX()*signX*(closestX > farthestX ? 1 : -1));
+ double newClosestY = (closestY == farthestY ? closestY : farthestY + newSize.getY()*signY*(closestY > farthestY ? 1 : -1));
newCenter.setLocation((farthestX + newClosestX) / 2, (farthestY + newClosestY) / 2);
ni.transformOut().transform(newCenter, newCenter);
}
return newSize;
}
/**
* Method to determine the proper size for the ArcInst being stretched, given a cursor location.
* @param evt the event with the current cursor location.
* @return the new base size for the ArcInst in lambda units.
*/
private double getNewArcSize(MouseEvent evt)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the arc being stretched
ArcInst ai = (ArcInst)stretchGeom;
// determine point on arc that is closest to the cursor
Point2D ptOnLine = DBMath.closestPointToLine(ai.getHeadLocation(), ai.getTailLocation(), pt);
double newLambdaBaseWidth = ptOnLine.distance(pt)*2;
Point2D newLambdaBaseSize = new Point2D.Double(newLambdaBaseWidth, newLambdaBaseWidth);
EditWindow.gridAlignSize(newLambdaBaseSize, -1);
return newLambdaBaseSize.getX();
}
private static class ScaleNode extends Job
{
private NodeInst stretchNode;
private EPoint newCenter;
private double newWidth, newHeight;
protected ScaleNode(NodeInst stretchNode, EPoint newCenter, double newWidth, double newHeight)
{
super("Scale node", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.stretchNode = stretchNode;
this.newCenter = newCenter;
this.newWidth = newWidth;
this.newHeight = newHeight;
startJob();
}
public boolean doIt() throws JobException
{
// make sure scaling the node is allowed
if (CircuitChangeJobs.cantEdit(stretchNode.getParent(), null, true, false, true) != 0) return false;
Point2D [] points = stretchNode.getTrace();
if (points != null)
{
double percX = newWidth / stretchNode.getLambdaBaseXSize();
double percY = newHeight / stretchNode.getLambdaBaseYSize();
AffineTransform trans = stretchNode.pureRotateOut();
Point2D [] newPoints = new Point2D[points.length];
for(int i=0; i<points.length; i++)
{
if (points[i] == null) continue;
Point2D newPoint = new Point2D.Double(points[i].getX() * percX, points[i].getY() * percY);
trans.transform(newPoint, newPoint);
newPoint.setLocation(newPoint.getX() + newCenter.getX(), newPoint.getY() + newCenter.getY());
newPoints[i] = newPoint;
}
stretchNode.setTrace(newPoints);
return true;
}
double dWid = newWidth - stretchNode.getLambdaBaseXSize();
double dHei = newHeight - stretchNode.getLambdaBaseYSize();
stretchNode.modifyInstance(newCenter.getX() - stretchNode.getAnchorCenterX(),
newCenter.getY() - stretchNode.getAnchorCenterY(), dWid, dHei, Orientation.IDENT);
return true;
}
}
private static class ScaleArc extends Job
{
private ArcInst stretchArc;
private double newLambdaBaseWidth;
protected ScaleArc(ArcInst stretchArc, double newLambdaBaseWidth)
{
super("Scale arc", User.getUserTool(), Job.Type.CHANGE, null, null, Job.Priority.USER);
this.stretchArc = stretchArc;
this.newLambdaBaseWidth = newLambdaBaseWidth;
startJob();
}
public boolean doIt() throws JobException
{
// make sure scaling the arc is allowed
if (CircuitChangeJobs.cantEdit(stretchArc.getParent(), null, true, false, true) != 0) return false;
stretchArc.setLambdaBaseWidth(newLambdaBaseWidth);
return true;
}
}
}
| false | true | private Point2D getNewNodeSize(MouseEvent evt, Point2D newCenter)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the node being stretched
NodeInst ni = (NodeInst)stretchGeom;
if (ni.getProto() instanceof Cell) return EPoint.ORIGIN;
// setup outline of node with standard offset
Poly nodePoly = ni.getBaseShape();
AffineTransform transIn = ni.transformIn();
transIn.transform(pt, pt);
nodePoly.transform(transIn);
// determine the closest point on the outline
Point2D [] points = nodePoly.getPoints();
if (farthestCorner == null && farthestEdge == null)
{
double closestDist = Double.MAX_VALUE;
for(int i=0; i<points.length; i++)
{
double dist = pt.distance(points[i]);
if (dist < closestDist)
{
closestDist = dist;
closestCorner = points[i];
farthestCorner = points[(i + points.length/2) % points.length];
farthestEdge = closestEdge = null;
}
int lastI = i-1;
if (lastI < 0) lastI = points.length-1;
Point2D edge = new Point2D.Double((points[i].getX() + points[lastI].getX())/2,
(points[i].getY() + points[lastI].getY())/2);
dist = pt.distance(edge);
if (dist < closestDist)
{
closestDist = dist;
int oppI = (i + points.length/2) % points.length;
lastI = oppI-1;
if (lastI < 0) lastI = points.length-1;
farthestEdge = new Point2D.Double((points[oppI].getX() + points[lastI].getX())/2,
(points[oppI].getY() + points[lastI].getY())/2);
closestEdge = edge;
farthestCorner = closestCorner = null;
}
}
}
// if SHIFT and CONTROL is held, use center-based sizing
boolean centerBased = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
// if CONTROL is held, constrain to single-axis stretching
boolean singleAxis = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) == 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0 && farthestCorner != null;
// if SHIFT held (or if a square primitive) make growth the same in both axes
boolean square = !ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare();
if ((evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) == 0) square = true;
// determine the amount of growth of the node
double growthRatioX, growthRatioY;
Point2D closest = (closestCorner != null ? closestCorner : closestEdge);
Point2D farthest = (farthestCorner != null ? farthestCorner : farthestEdge);
if (centerBased)
{
double ptToCenterX = Math.abs(pt.getX());
double closestToCenterX = Math.abs(closest.getX());
double ptToCenterY = Math.abs(pt.getY());
double closestToCenterY = Math.abs(closest.getY());
growthRatioX = ptToCenterX / closestToCenterX;
growthRatioY = ptToCenterY / closestToCenterY;
} else
{
double ptToFarthestX = pt.getX() - farthest.getX();
double closestToFarthestX = closest.getX() - farthest.getX();
double ptToFarthestY = pt.getY() - farthest.getY();
double closestToFarthestY = closest.getY() - farthest.getY();
growthRatioX = closestToFarthestX == 0 ? 1 : (ptToFarthestX / closestToFarthestX);
growthRatioY = closestToFarthestY == 0 ? 1 : (ptToFarthestY / closestToFarthestY);
}
int direction = -1; // both X and Y
if (singleAxis)
{
// constrain to single-axis stretching
double grx = Math.abs(growthRatioX);
if (grx < 1)
{
if (grx == 0) grx = 9999; else grx = 1/grx;
}
double gry = Math.abs(growthRatioY);
if (gry < 1)
{
if (gry == 0) gry = 9999; else gry = 1/gry;
}
if (grx > gry)
{
growthRatioY = 1;
direction = 0; // Y
} else
{
growthRatioX = 1;
direction = 1; // X
}
}
if (square)
{
if (Math.abs(growthRatioX) > Math.abs(growthRatioY))
growthRatioY = growthRatioX;
else
growthRatioX = growthRatioY;
}
// compute the new node size
double newXSize = ni.getLambdaBaseXSize() * growthRatioX;
double newYSize = ni.getLambdaBaseYSize() * growthRatioY;
Point2D newSize = new Point2D.Double(Math.abs(newXSize), Math.abs(newYSize));
// grid align the new node size
EditWindow.gridAlignSize(newSize, direction);
// determine the new center point
if (!centerBased)
{
double closestX = closest.getX();
double closestY = closest.getY();
double farthestX = farthest.getX();
double farthestY = farthest.getY();
double newClosestX = (closestX == farthestX ? closestX : farthestX + newXSize*(closestX > farthestX ? 1 : -1));
double newClosestY = (closestY == farthestY ? closestY : farthestY + newYSize*(closestY > farthestY ? 1 : -1));
newCenter.setLocation((farthestX + newClosestX) / 2, (farthestY + newClosestY) / 2);
ni.transformOut().transform(newCenter, newCenter);
}
return newSize;
}
| private Point2D getNewNodeSize(MouseEvent evt, Point2D newCenter)
{
// get the coordinates of the cursor in database coordinates
EditWindow wnd = (EditWindow)evt.getSource();
int oldx = evt.getX();
int oldy = evt.getY();
Point2D pt = wnd.screenToDatabase(oldx, oldy);
// get information about the node being stretched
NodeInst ni = (NodeInst)stretchGeom;
if (ni.getProto() instanceof Cell) return EPoint.ORIGIN;
// setup outline of node with standard offset
Poly nodePoly = ni.getBaseShape();
AffineTransform transIn = ni.transformIn();
transIn.transform(pt, pt);
nodePoly.transform(transIn);
// determine the closest point on the outline
Point2D [] points = nodePoly.getPoints();
if (farthestCorner == null && farthestEdge == null)
{
double closestDist = Double.MAX_VALUE;
for(int i=0; i<points.length; i++)
{
double dist = pt.distance(points[i]);
if (dist < closestDist)
{
closestDist = dist;
closestCorner = points[i];
farthestCorner = points[(i + points.length/2) % points.length];
farthestEdge = closestEdge = null;
}
int lastI = i-1;
if (lastI < 0) lastI = points.length-1;
Point2D edge = new Point2D.Double((points[i].getX() + points[lastI].getX())/2,
(points[i].getY() + points[lastI].getY())/2);
dist = pt.distance(edge);
if (dist < closestDist)
{
closestDist = dist;
int oppI = (i + points.length/2) % points.length;
lastI = oppI-1;
if (lastI < 0) lastI = points.length-1;
farthestEdge = new Point2D.Double((points[oppI].getX() + points[lastI].getX())/2,
(points[oppI].getY() + points[lastI].getY())/2);
closestEdge = edge;
farthestCorner = closestCorner = null;
}
}
}
// if SHIFT and CONTROL is held, use center-based sizing
boolean centerBased = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0;
// if CONTROL is held, constrain to single-axis stretching
boolean singleAxis = (evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) == 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) != 0 && farthestCorner != null;
// if SHIFT held (or if a square primitive) make growth the same in both axes
boolean square = !ni.isCellInstance() && ((PrimitiveNode)ni.getProto()).isSquare();
if ((evt.getModifiersEx()&MouseEvent.SHIFT_DOWN_MASK) != 0 &&
(evt.getModifiersEx()&MouseEvent.CTRL_DOWN_MASK) == 0) square = true;
// determine the amount of growth of the node
double growthRatioX, growthRatioY;
Point2D closest = (closestCorner != null ? closestCorner : closestEdge);
Point2D farthest = (farthestCorner != null ? farthestCorner : farthestEdge);
if (centerBased)
{
double ptToCenterX = Math.abs(pt.getX());
double closestToCenterX = Math.abs(closest.getX());
double ptToCenterY = Math.abs(pt.getY());
double closestToCenterY = Math.abs(closest.getY());
growthRatioX = ptToCenterX / closestToCenterX;
growthRatioY = ptToCenterY / closestToCenterY;
} else
{
double ptToFarthestX = pt.getX() - farthest.getX();
double closestToFarthestX = closest.getX() - farthest.getX();
double ptToFarthestY = pt.getY() - farthest.getY();
double closestToFarthestY = closest.getY() - farthest.getY();
growthRatioX = closestToFarthestX == 0 ? 1 : (ptToFarthestX / closestToFarthestX);
growthRatioY = closestToFarthestY == 0 ? 1 : (ptToFarthestY / closestToFarthestY);
}
int direction = -1; // both X and Y
if (singleAxis)
{
// constrain to single-axis stretching
double grx = Math.abs(growthRatioX);
if (grx < 1)
{
if (grx == 0) grx = 9999; else grx = 1/grx;
}
double gry = Math.abs(growthRatioY);
if (gry < 1)
{
if (gry == 0) gry = 9999; else gry = 1/gry;
}
if (grx > gry)
{
growthRatioY = 1;
direction = 0; // Y
} else
{
growthRatioX = 1;
direction = 1; // X
}
}
if (square)
{
if (Math.abs(growthRatioX) > Math.abs(growthRatioY))
growthRatioY = growthRatioX;
else
growthRatioX = growthRatioY;
}
// compute the new node size
double newXSize = ni.getLambdaBaseXSize() * growthRatioX;
double newYSize = ni.getLambdaBaseYSize() * growthRatioY;
double signX = newXSize < 0 ? -1 : 1;
double signY = newYSize < 0 ? -1 : 1;
Point2D newSize = new Point2D.Double(Math.abs(newXSize), Math.abs(newYSize));
// grid align the new node size
EditWindow.gridAlignSize(newSize, direction);
// determine the new center point
if (!centerBased)
{
double closestX = closest.getX();
double closestY = closest.getY();
double farthestX = farthest.getX();
double farthestY = farthest.getY();
double newClosestX = (closestX == farthestX ? closestX : farthestX + newSize.getX()*signX*(closestX > farthestX ? 1 : -1));
double newClosestY = (closestY == farthestY ? closestY : farthestY + newSize.getY()*signY*(closestY > farthestY ? 1 : -1));
newCenter.setLocation((farthestX + newClosestX) / 2, (farthestY + newClosestY) / 2);
ni.transformOut().transform(newCenter, newCenter);
}
return newSize;
}
|
diff --git a/lilith/src/main/java/de/huxhorn/lilith/swing/TextPreprocessor.java b/lilith/src/main/java/de/huxhorn/lilith/swing/TextPreprocessor.java
index 1342bab2..91f3ce0c 100644
--- a/lilith/src/main/java/de/huxhorn/lilith/swing/TextPreprocessor.java
+++ b/lilith/src/main/java/de/huxhorn/lilith/swing/TextPreprocessor.java
@@ -1,287 +1,287 @@
/*
* Lilith - a log event viewer.
* Copyright (C) 2007-2013 Joern Huxhorn
*
* 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 de.huxhorn.lilith.swing;
import de.huxhorn.sulky.conditions.And;
import de.huxhorn.sulky.conditions.Condition;
import de.huxhorn.sulky.conditions.ConditionGroup;
import de.huxhorn.sulky.conditions.ConditionWrapper;
import de.huxhorn.sulky.conditions.Not;
import de.huxhorn.sulky.conditions.Or;
import de.huxhorn.sulky.formatting.SimpleXml;
import java.util.List;
public class TextPreprocessor
{
private static final int MAX_LINE_LENGTH = 100;
private static final int MAX_LINES = 40;
private static final String TAB_REPLACEMENT = " ";
private static final String LINE_TRUNCATION = "[..]";
private static final String INDENT = " ";
public static String cropLine(String text)
{
return cropLine(text, MAX_LINE_LENGTH, LINE_TRUNCATION);
}
public static String cropToSingleLine(String text)
{
return cropLine(text, 0, null);
}
private static String cropLine(String text, int maxLineLength, String lineTruncationMarker)
{
if(text == null)
{
return null;
}
StringBuilder result = new StringBuilder();
int newlineIndex = text.indexOf('\n');
if(newlineIndex > -1)
{
int newlineCounter = 0;
for(int i = 0; i < text.length(); i++)
{
if(text.charAt(i) == '\n')
{
newlineCounter++;
}
}
appendTruncated(text.subSequence(0, newlineIndex), result, maxLineLength, lineTruncationMarker);
newlineCounter--;
if(newlineCounter > 0)
{
result.append(" [+").append(newlineCounter).append(" lines]");
}
}
else
{
appendTruncated(text, result, maxLineLength, lineTruncationMarker);
}
return result.toString();
}
public static String cropTextBlock(String text)
{
return cropTextBlock(text, MAX_LINE_LENGTH, LINE_TRUNCATION, MAX_LINES, TAB_REPLACEMENT);
}
private static String cropTextBlock(String text, int maxLineLength, String lineTruncationMarker, int maxLines, String tabReplacement)
{
if(text == null)
{
return null;
}
// crop to a sane size, e.g. 80x25 characters
StringBuilder result=new StringBuilder();
StringBuilder lineBuilder=new StringBuilder();
int lineCounter = 0;
for(int i=0;i<text.length();i++)
{
char current = text.charAt(i);
if(current == '\t')
{
if(tabReplacement != null)
{
lineBuilder.append(tabReplacement);
}
else
{
lineBuilder.append('\t');
}
}
else if(current == '\n')
{
if(lineCounter < maxLines)
{
appendTruncated(lineBuilder, result, maxLineLength, lineTruncationMarker);
result.append('\n');
}
lineBuilder.setLength(0);
lineCounter++;
}
else if(current != '\r')
{
lineBuilder.append(current);
}
}
if(lineCounter >= maxLines)
{
int remaining = lineCounter - maxLines + 1;
result.append("[.. ").append(remaining).append(" more lines ..]");
}
else
{
appendTruncated(lineBuilder, result, maxLineLength, lineTruncationMarker);
}
return result.toString();
}
private static void appendTruncated(CharSequence sourceBuilder, StringBuilder targetBuilder, int maxLineLength, String lineTruncationMarker)
{
if(maxLineLength < 1 || sourceBuilder.length() <= maxLineLength)
{
targetBuilder.append(sourceBuilder);
return;
}
if(lineTruncationMarker == null)
{
targetBuilder.append(sourceBuilder.subSequence(0, maxLineLength));
}
else
{
targetBuilder.append(sourceBuilder.subSequence(0, maxLineLength - lineTruncationMarker.length()));
targetBuilder.append(lineTruncationMarker);
}
}
public static String wrapWithPre(String text)
{
if(text == null)
{
return null;
}
text = SimpleXml.escape(text);
text = text.replace("\n", "<br>");
return "<tt><pre>" + text + "</pre></tt>";
}
public static String preformattedTooltip(String text)
{
if(text == null)
{
return null;
}
return "<html>" + wrapWithPre(text) + "</html>";
}
public static String formatCondition(Condition condition)
{
if(condition == null)
{
return null;
}
StringBuilder result = new StringBuilder();
formatCondition(condition, result, 0);
return result.toString();
}
private static void formatCondition(Condition condition, StringBuilder result, int indent) {
if(condition == null)
{
appendIndent(result, indent);
result.append("null");
}
else if(condition instanceof ConditionWrapper)
{
ConditionWrapper wrapper = (ConditionWrapper)condition;
String operator;
if(wrapper instanceof Not)
{
operator = "!";
}
else
{
// Unknown wrapper. Improvise.
operator = wrapper.getClass().getSimpleName();
}
Condition c = wrapper.getCondition();
appendIndent(result, indent);
result.append(operator).append("(");
if(c == null)
{
result.append("null");
}
else
{
result.append("\n");
formatCondition(c, result, indent+1);
appendIndent(result, indent);
}
result.append(")");
}
else if(condition instanceof ConditionGroup)
{
ConditionGroup group = (ConditionGroup) condition;
String operator;
if(group instanceof And)
{
operator = "&&";
}
else if(group instanceof Or)
{
operator = "||";
}
else
{
// Unknown group. Improvise.
operator = group.getClass().getSimpleName();
}
List<Condition> conditions = group.getConditions();
appendIndent(result, indent);
result.append("(");
if(conditions == null || conditions.isEmpty())
{
result.append("[").append(operator).append(" without conditions.]");
}
else
{
result.append("\n");
boolean first = true;
for(Condition current : conditions)
{
if(first)
{
first = false;
}
else
{
- appendIndent(result, indent);
+ appendIndent(result, indent+1);
result.append(operator).append("\n");
}
formatCondition(current, result, indent+1);
}
appendIndent(result, indent);
}
result.append(")");
}
else
{
// an "ordinary" condition.
appendIndent(result, indent);
result.append(condition);
}
if(indent > 0)
{
result.append("\n");
}
}
private static void appendIndent(StringBuilder result, int indent)
{
for(int i=0;i<indent;i++)
{
result.append(INDENT);
}
}
}
| true | true | private static void formatCondition(Condition condition, StringBuilder result, int indent) {
if(condition == null)
{
appendIndent(result, indent);
result.append("null");
}
else if(condition instanceof ConditionWrapper)
{
ConditionWrapper wrapper = (ConditionWrapper)condition;
String operator;
if(wrapper instanceof Not)
{
operator = "!";
}
else
{
// Unknown wrapper. Improvise.
operator = wrapper.getClass().getSimpleName();
}
Condition c = wrapper.getCondition();
appendIndent(result, indent);
result.append(operator).append("(");
if(c == null)
{
result.append("null");
}
else
{
result.append("\n");
formatCondition(c, result, indent+1);
appendIndent(result, indent);
}
result.append(")");
}
else if(condition instanceof ConditionGroup)
{
ConditionGroup group = (ConditionGroup) condition;
String operator;
if(group instanceof And)
{
operator = "&&";
}
else if(group instanceof Or)
{
operator = "||";
}
else
{
// Unknown group. Improvise.
operator = group.getClass().getSimpleName();
}
List<Condition> conditions = group.getConditions();
appendIndent(result, indent);
result.append("(");
if(conditions == null || conditions.isEmpty())
{
result.append("[").append(operator).append(" without conditions.]");
}
else
{
result.append("\n");
boolean first = true;
for(Condition current : conditions)
{
if(first)
{
first = false;
}
else
{
appendIndent(result, indent);
result.append(operator).append("\n");
}
formatCondition(current, result, indent+1);
}
appendIndent(result, indent);
}
result.append(")");
}
else
{
// an "ordinary" condition.
appendIndent(result, indent);
result.append(condition);
}
if(indent > 0)
{
result.append("\n");
}
}
| private static void formatCondition(Condition condition, StringBuilder result, int indent) {
if(condition == null)
{
appendIndent(result, indent);
result.append("null");
}
else if(condition instanceof ConditionWrapper)
{
ConditionWrapper wrapper = (ConditionWrapper)condition;
String operator;
if(wrapper instanceof Not)
{
operator = "!";
}
else
{
// Unknown wrapper. Improvise.
operator = wrapper.getClass().getSimpleName();
}
Condition c = wrapper.getCondition();
appendIndent(result, indent);
result.append(operator).append("(");
if(c == null)
{
result.append("null");
}
else
{
result.append("\n");
formatCondition(c, result, indent+1);
appendIndent(result, indent);
}
result.append(")");
}
else if(condition instanceof ConditionGroup)
{
ConditionGroup group = (ConditionGroup) condition;
String operator;
if(group instanceof And)
{
operator = "&&";
}
else if(group instanceof Or)
{
operator = "||";
}
else
{
// Unknown group. Improvise.
operator = group.getClass().getSimpleName();
}
List<Condition> conditions = group.getConditions();
appendIndent(result, indent);
result.append("(");
if(conditions == null || conditions.isEmpty())
{
result.append("[").append(operator).append(" without conditions.]");
}
else
{
result.append("\n");
boolean first = true;
for(Condition current : conditions)
{
if(first)
{
first = false;
}
else
{
appendIndent(result, indent+1);
result.append(operator).append("\n");
}
formatCondition(current, result, indent+1);
}
appendIndent(result, indent);
}
result.append(")");
}
else
{
// an "ordinary" condition.
appendIndent(result, indent);
result.append(condition);
}
if(indent > 0)
{
result.append("\n");
}
}
|
diff --git a/src/tesla/app/command/Command.java b/src/tesla/app/command/Command.java
index 59ded9b..f523652 100644
--- a/src/tesla/app/command/Command.java
+++ b/src/tesla/app/command/Command.java
@@ -1,207 +1,208 @@
/* Copyright 2009 Sean Hodges <[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 tesla.app.command;
import java.util.ArrayList;
import java.util.Map;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
public final class Command implements Parcelable {
// Command key tokens
public static final String INIT = "init";
public static final String POWER = "power";
public static final String PLAY = "play";
public static final String PAUSE = "pause";
public static final String PREV = "prev";
public static final String NEXT = "next";
public static final String VOL_CHANGE = "vol_change";
public static final String VOL_MUTE = "vol_mute";
public static final String VOL_CURRENT = "vol_get_current";
public static final String GET_MEDIA_INFO = "get_media_info";
public static final String IS_PLAYING = "is_playing";
public static final String LAUNCH_PLAYER = "launch_player";
public static final String GET_MEDIA_POSITION = "get_media_position";
public static final String GET_MEDIA_LENGTH = "get_media_length";
public static final String SET_MEDIA_POSITION = "set_media_position";
public static final String GET_PLAYLIST = "get_playlist";
public static final String GET_PLAYLIST_SELECTION = "get_playlist_selection";
public static final String SET_PLAYLIST_SELECTION = "set_playlist_selection";
private String key;
private String commandString;
private Map<String, String> settings;
private ArrayList<Object> args;
private String output;
private String targetApp;
public static final Parcelable.Creator<Command> CREATOR = new Parcelable.Creator<Command>() {
public Command createFromParcel(Parcel in) {
return new Command(in);
}
public Command[] newArray(int size) {
return new Command[size];
}
};
public Command() {
args = new ArrayList<Object>();
}
public Command(Parcel in) {
readFromParcel(in);
}
public void setKey(String key) {
this.key = key;
}
public void setCommandString(String commandString) {
this.commandString = commandString;
}
public void addArg(Object arg) {
args.add(arg);
}
public String getKey() {
return key;
}
public String getCommandString() {
String out = "";
try {
out = parseArguments(commandString);
}
catch (IllegalArgumentException e) {
// function will return empty string
}
return out;
}
public void setSettings(Map<String, String> settings) {
this.settings = settings;
}
public Map<String, String> getSettings() {
return settings;
}
private String parseArguments(String out)
throws IllegalArgumentException {
// Add the arguments to the command
- boolean success = true;
- while (success && stillHasArgs(out)) {
+ boolean success = false;
+ do {
for (Object arg : args) {
+ success = false;
// !!! Remember to add new data types to stillHasArgs()
if (arg instanceof String) {
if (out.contains("%s")) {
out = out.replaceFirst("%s", (String)arg);
success = true;
}
}
else if (arg instanceof Float) {
if (out.contains("%f")) {
out = out.replaceFirst("%f", ((Float)arg).toString());
success = true;
}
}
else if (arg instanceof Integer) {
if (out.contains("%i")) {
out = out.replaceFirst("%i", ((Integer)arg).toString());
success = true;
}
else if (out.contains("%u16")) {
out = out.replaceFirst("%u16", ((Integer)arg).toString());
success = true;
}
else if (out.contains("%u32")) {
out = out.replaceFirst("%u32", ((Integer)arg).toString());
success = true;
}
}
else if (arg instanceof Boolean) {
if (out.contains("%b")) {
out = out.replaceFirst("%b", ((Boolean)arg).toString());
success = true;
}
}
}
- }
+ } while (success && stillHasArgs(out));
return out;
}
private boolean stillHasArgs(String data) {
String[] argList = {"%s", "%f", "%i", "%u16", "%u32", "%b"};
for (String argIt : argList) {
if (data.contains(argIt)) return true;
}
return false;
}
public int describeContents() {
return key.hashCode();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(key);
dest.writeList(args);
dest.writeString(commandString);
Bundle settingsBundle = new Bundle();
for (String key : settings.keySet()) {
settingsBundle.putString(key, settings.get(key));
}
dest.writeBundle(settingsBundle);
dest.writeString(output);
dest.writeString(targetApp);
}
@SuppressWarnings("unchecked")
public void readFromParcel(Parcel src) {
key = src.readString();
args = src.readArrayList(this.getClass().getClassLoader());
commandString = src.readString();
Bundle settingsBundle = src.readBundle(this.getClass().getClassLoader());
settings.clear();
for (String key : settingsBundle.keySet()) {
settings.put(key, settingsBundle.getString(key));
}
output = src.readString();
targetApp = src.readString();
}
public void setOutput(String output) {
this.output = output;
}
public String getOutput() {
return output;
}
public void setTargetApp(String appName) {
targetApp = appName;
}
public String getTargetApp() {
return targetApp;
}
}
| false | true | private String parseArguments(String out)
throws IllegalArgumentException {
// Add the arguments to the command
boolean success = true;
while (success && stillHasArgs(out)) {
for (Object arg : args) {
// !!! Remember to add new data types to stillHasArgs()
if (arg instanceof String) {
if (out.contains("%s")) {
out = out.replaceFirst("%s", (String)arg);
success = true;
}
}
else if (arg instanceof Float) {
if (out.contains("%f")) {
out = out.replaceFirst("%f", ((Float)arg).toString());
success = true;
}
}
else if (arg instanceof Integer) {
if (out.contains("%i")) {
out = out.replaceFirst("%i", ((Integer)arg).toString());
success = true;
}
else if (out.contains("%u16")) {
out = out.replaceFirst("%u16", ((Integer)arg).toString());
success = true;
}
else if (out.contains("%u32")) {
out = out.replaceFirst("%u32", ((Integer)arg).toString());
success = true;
}
}
else if (arg instanceof Boolean) {
if (out.contains("%b")) {
out = out.replaceFirst("%b", ((Boolean)arg).toString());
success = true;
}
}
}
}
return out;
}
| private String parseArguments(String out)
throws IllegalArgumentException {
// Add the arguments to the command
boolean success = false;
do {
for (Object arg : args) {
success = false;
// !!! Remember to add new data types to stillHasArgs()
if (arg instanceof String) {
if (out.contains("%s")) {
out = out.replaceFirst("%s", (String)arg);
success = true;
}
}
else if (arg instanceof Float) {
if (out.contains("%f")) {
out = out.replaceFirst("%f", ((Float)arg).toString());
success = true;
}
}
else if (arg instanceof Integer) {
if (out.contains("%i")) {
out = out.replaceFirst("%i", ((Integer)arg).toString());
success = true;
}
else if (out.contains("%u16")) {
out = out.replaceFirst("%u16", ((Integer)arg).toString());
success = true;
}
else if (out.contains("%u32")) {
out = out.replaceFirst("%u32", ((Integer)arg).toString());
success = true;
}
}
else if (arg instanceof Boolean) {
if (out.contains("%b")) {
out = out.replaceFirst("%b", ((Boolean)arg).toString());
success = true;
}
}
}
} while (success && stillHasArgs(out));
return out;
}
|
diff --git a/riot-hibernate/src/org/riotfamily/riot/hibernate/support/LongConversationTemplate.java b/riot-hibernate/src/org/riotfamily/riot/hibernate/support/LongConversationTemplate.java
index ab585694d..a43118fbf 100644
--- a/riot-hibernate/src/org/riotfamily/riot/hibernate/support/LongConversationTemplate.java
+++ b/riot-hibernate/src/org/riotfamily/riot/hibernate/support/LongConversationTemplate.java
@@ -1,96 +1,96 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
* 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 Riot.
*
* The Initial Developer of the Original Code is
* Neteye GmbH.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Felix Gnass [fgnass at neteye dot de]
*
* ***** END LICENSE BLOCK ***** */
package org.riotfamily.riot.hibernate.support;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateAccessor;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Class similar to Spring's HibernateTemplate that simplifies working with
* long conversations. This class can be considered as alternative to using
* an AOP HibernateInterceptor.
*
* @see <a href="http://www.hibernate.org/hib_docs/v3/reference/en/html/transactions.html#transactions-basics-apptx">Hibernate Reference - Long conversations</a>
* @author Felix Gnass [fgnass at neteye dot de]
* @since 8.0
*/
public class LongConversationTemplate extends HibernateAccessor {
public LongConversationTemplate(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
public final void execute(LongConversationCallback callback) throws Exception {
Session session = SessionFactoryUtils.getSession(getSessionFactory(),
getEntityInterceptor(), getJdbcExceptionTranslator());
SessionHolder sessionHolder = (SessionHolder)
TransactionSynchronizationManager.getResource(getSessionFactory());
boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
if (existingTransaction) {
logger.debug("Found thread-bound Session for HibernateInterceptor");
}
else {
if (sessionHolder != null) {
sessionHolder.addSession(session);
}
else {
TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
}
}
FlushMode previousFlushMode = null;
try {
previousFlushMode = applyFlushMode(session, existingTransaction);
enableFilters(session);
callback.doInHibernate(session);
flushIfNecessary(session, existingTransaction);
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
finally {
if (existingTransaction) {
logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
else {
- SessionFactoryUtils.releaseSession(session, getSessionFactory());
+ SessionFactoryUtils.closeSession(session);
if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
TransactionSynchronizationManager.unbindResource(getSessionFactory());
}
}
}
}
}
| true | true | public final void execute(LongConversationCallback callback) throws Exception {
Session session = SessionFactoryUtils.getSession(getSessionFactory(),
getEntityInterceptor(), getJdbcExceptionTranslator());
SessionHolder sessionHolder = (SessionHolder)
TransactionSynchronizationManager.getResource(getSessionFactory());
boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
if (existingTransaction) {
logger.debug("Found thread-bound Session for HibernateInterceptor");
}
else {
if (sessionHolder != null) {
sessionHolder.addSession(session);
}
else {
TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
}
}
FlushMode previousFlushMode = null;
try {
previousFlushMode = applyFlushMode(session, existingTransaction);
enableFilters(session);
callback.doInHibernate(session);
flushIfNecessary(session, existingTransaction);
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
finally {
if (existingTransaction) {
logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
else {
SessionFactoryUtils.releaseSession(session, getSessionFactory());
if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
TransactionSynchronizationManager.unbindResource(getSessionFactory());
}
}
}
}
| public final void execute(LongConversationCallback callback) throws Exception {
Session session = SessionFactoryUtils.getSession(getSessionFactory(),
getEntityInterceptor(), getJdbcExceptionTranslator());
SessionHolder sessionHolder = (SessionHolder)
TransactionSynchronizationManager.getResource(getSessionFactory());
boolean existingTransaction = (sessionHolder != null && sessionHolder.containsSession(session));
if (existingTransaction) {
logger.debug("Found thread-bound Session for HibernateInterceptor");
}
else {
if (sessionHolder != null) {
sessionHolder.addSession(session);
}
else {
TransactionSynchronizationManager.bindResource(getSessionFactory(), new SessionHolder(session));
}
}
FlushMode previousFlushMode = null;
try {
previousFlushMode = applyFlushMode(session, existingTransaction);
enableFilters(session);
callback.doInHibernate(session);
flushIfNecessary(session, existingTransaction);
}
catch (HibernateException ex) {
throw convertHibernateAccessException(ex);
}
finally {
if (existingTransaction) {
logger.debug("Not closing pre-bound Hibernate Session after HibernateInterceptor");
disableFilters(session);
if (previousFlushMode != null) {
session.setFlushMode(previousFlushMode);
}
}
else {
SessionFactoryUtils.closeSession(session);
if (sessionHolder == null || sessionHolder.doesNotHoldNonDefaultSession()) {
TransactionSynchronizationManager.unbindResource(getSessionFactory());
}
}
}
}
|
diff --git a/org.eclipse.help.base/src/org/eclipse/help/internal/search/WordTokenStream.java b/org.eclipse.help.base/src/org/eclipse/help/internal/search/WordTokenStream.java
index 28b431b65..136059964 100644
--- a/org.eclipse.help.base/src/org/eclipse/help/internal/search/WordTokenStream.java
+++ b/org.eclipse.help.base/src/org/eclipse/help/internal/search/WordTokenStream.java
@@ -1,112 +1,113 @@
/*******************************************************************************
* Copyright (c) 2000, 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.help.internal.search;
import com.ibm.icu.text.BreakIterator;
import java.io.IOException;
import java.io.Reader;
import java.util.Locale;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.Tokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
/**
* WordTokenStream obtains tokens containing words appropriate for use with
* Lucene search engine.
*/
public final class WordTokenStream extends Tokenizer {
private static final int BUF_LEN = 4096;
private final Reader reader;
private final BreakIterator boundary;
private StringBuffer strbuf;
private int start = 0;
private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);
/**
* Constructor
*/
public WordTokenStream(String fieldName, Reader reader, Locale locale) {
this.reader = reader;
boundary = BreakIterator.getWordInstance(locale);
}
/**
* @see TokenStream#incrementToken()
*/
@Override
public boolean incrementToken() throws IOException {
clearAttributes();
int length = 0;
char[] buffer = termAtt.buffer();
int end;
if(strbuf == null) {
int available;
char[] cbuf = new char[BUF_LEN];
while ((available = reader.read(cbuf)) <= 0) {
if (available < 0) {
reader.close();
return false;
}
}
strbuf = new StringBuffer(available + 80);
strbuf.append(cbuf, 0, available);
// read more until white space (or EOF)
int c;
while (0 <= (c = reader.read())) {
strbuf.append((char) c);
if (c == ' ' || c == '\r' || c == '\n' || c == '\t') {
break;
}
}
if (c < 0) {
reader.close();
}
boundary.setText(strbuf.toString());
start = boundary.first();
}
else {
start = boundary.next();
}
for (end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
// determine if it is a word
// any letter or digit between boundaries means it is a word
for (int i = start; i < end; i++) {
if (Character.isLetterOrDigit(strbuf.charAt(i))) {
// it is a word
length = end - start;
if (length >= buffer.length-1)
buffer = termAtt.resizeBuffer(2+length);
+ termAtt.setLength(length);
strbuf.getChars(start, end, buffer, 0);
return true;
}
}
}
return false;
}
public void reset() throws IOException {
super.reset();
clearAttributes();
}
public void close() throws IOException {
/// Unlikely to be called as this is a reused
if (this.reader != null) {
this.reader.close();
}
}
}
| true | true | public boolean incrementToken() throws IOException {
clearAttributes();
int length = 0;
char[] buffer = termAtt.buffer();
int end;
if(strbuf == null) {
int available;
char[] cbuf = new char[BUF_LEN];
while ((available = reader.read(cbuf)) <= 0) {
if (available < 0) {
reader.close();
return false;
}
}
strbuf = new StringBuffer(available + 80);
strbuf.append(cbuf, 0, available);
// read more until white space (or EOF)
int c;
while (0 <= (c = reader.read())) {
strbuf.append((char) c);
if (c == ' ' || c == '\r' || c == '\n' || c == '\t') {
break;
}
}
if (c < 0) {
reader.close();
}
boundary.setText(strbuf.toString());
start = boundary.first();
}
else {
start = boundary.next();
}
for (end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
// determine if it is a word
// any letter or digit between boundaries means it is a word
for (int i = start; i < end; i++) {
if (Character.isLetterOrDigit(strbuf.charAt(i))) {
// it is a word
length = end - start;
if (length >= buffer.length-1)
buffer = termAtt.resizeBuffer(2+length);
strbuf.getChars(start, end, buffer, 0);
return true;
}
}
}
return false;
}
| public boolean incrementToken() throws IOException {
clearAttributes();
int length = 0;
char[] buffer = termAtt.buffer();
int end;
if(strbuf == null) {
int available;
char[] cbuf = new char[BUF_LEN];
while ((available = reader.read(cbuf)) <= 0) {
if (available < 0) {
reader.close();
return false;
}
}
strbuf = new StringBuffer(available + 80);
strbuf.append(cbuf, 0, available);
// read more until white space (or EOF)
int c;
while (0 <= (c = reader.read())) {
strbuf.append((char) c);
if (c == ' ' || c == '\r' || c == '\n' || c == '\t') {
break;
}
}
if (c < 0) {
reader.close();
}
boundary.setText(strbuf.toString());
start = boundary.first();
}
else {
start = boundary.next();
}
for (end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
// determine if it is a word
// any letter or digit between boundaries means it is a word
for (int i = start; i < end; i++) {
if (Character.isLetterOrDigit(strbuf.charAt(i))) {
// it is a word
length = end - start;
if (length >= buffer.length-1)
buffer = termAtt.resizeBuffer(2+length);
termAtt.setLength(length);
strbuf.getChars(start, end, buffer, 0);
return true;
}
}
}
return false;
}
|
diff --git a/cobertura/src/net/sourceforge/cobertura/ant/InstrumentTask.java b/cobertura/src/net/sourceforge/cobertura/ant/InstrumentTask.java
index 9a1c02b..f307269 100644
--- a/cobertura/src/net/sourceforge/cobertura/ant/InstrumentTask.java
+++ b/cobertura/src/net/sourceforge/cobertura/ant/InstrumentTask.java
@@ -1,167 +1,167 @@
/*
* The Apache Software License, Version 1.1
*
* Copyright (C) 2000-2002 The Apache Software Foundation. All rights
* reserved.
* Copyright (C) 2003 jcoverage ltd.
* Copyright (C) 2005 Mark Doliner
* Copyright (C) 2005 Joakim Erdfelt
*
* 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. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Ant" and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``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 APACHE SOFTWARE FOUNDATION 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package net.sourceforge.cobertura.ant;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import net.sourceforge.cobertura.util.Header;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.types.FileSet;
public class InstrumentTask extends CommonMatchingTask
{
private String dataFile = null;
Ignore ignoreRegex = null;
public InstrumentTask()
{
super("net.sourceforge.cobertura.instrument.Main");
}
public Ignore createIgnore()
{
ignoreRegex = new Ignore();
return ignoreRegex;
}
private void addFilenames(String[] filenames)
{
if (filenames.length == 0)
{
return;
}
for (int i = 0; i < filenames.length; i++)
{
getProject().log("Adding " + filenames[i] + " to list",
Project.MSG_VERBOSE);
addArg(filenames[i]);
}
Header.print(System.out);
System.out.println("instrumenting " + filenames.length + " "
+ (filenames.length == 1 ? "class" : "classes")
+ (toDir != null ? " to " + toDir : ""));
}
public void execute() throws BuildException
{
initArgs();
if (dataFile != null)
{
addArg("--datafile");
addArg(dataFile);
}
if (toDir != null)
{
addArg("--destination");
addArg(toDir.toString());
}
// ignoreRegex.setRegex() is never called, but that's ok
// because ant sets it somehow, I think
if (ignoreRegex != null)
{
addArg("--ignore");
addArg(ignoreRegex.getRegex());
}
Set filenames = new HashSet();
Iterator iter = fileSets.iterator();
while (iter.hasNext())
{
FileSet fileSet = (FileSet)iter.next();
addArg("--basedir");
addArg(baseDir(fileSet));
filenames.addAll(Arrays.asList(getFilenames(fileSet)));
}
addFilenames((String[])filenames.toArray(new String[filenames.size()]));
saveArgs();
/**
* TODO: Do something here so that we can set System.in and System.out on
* getJava() to the one we're using now. So that when instrumentation calls
* System.out, it will show up as "[instrument] doing stuff" instead of
* "[java] doing stuff" in the ant output.
*/
if (getJava().executeJava() != 0)
{
- throw new BuildException();
+ throw new BuildException("Error instrumenting classes. See messages above.");
}
unInitArgs();
}
public void setDataFile(String dataFile)
{
this.dataFile = dataFile;
}
}
| true | true | public void execute() throws BuildException
{
initArgs();
if (dataFile != null)
{
addArg("--datafile");
addArg(dataFile);
}
if (toDir != null)
{
addArg("--destination");
addArg(toDir.toString());
}
// ignoreRegex.setRegex() is never called, but that's ok
// because ant sets it somehow, I think
if (ignoreRegex != null)
{
addArg("--ignore");
addArg(ignoreRegex.getRegex());
}
Set filenames = new HashSet();
Iterator iter = fileSets.iterator();
while (iter.hasNext())
{
FileSet fileSet = (FileSet)iter.next();
addArg("--basedir");
addArg(baseDir(fileSet));
filenames.addAll(Arrays.asList(getFilenames(fileSet)));
}
addFilenames((String[])filenames.toArray(new String[filenames.size()]));
saveArgs();
/**
* TODO: Do something here so that we can set System.in and System.out on
* getJava() to the one we're using now. So that when instrumentation calls
* System.out, it will show up as "[instrument] doing stuff" instead of
* "[java] doing stuff" in the ant output.
*/
if (getJava().executeJava() != 0)
{
throw new BuildException();
}
unInitArgs();
}
| public void execute() throws BuildException
{
initArgs();
if (dataFile != null)
{
addArg("--datafile");
addArg(dataFile);
}
if (toDir != null)
{
addArg("--destination");
addArg(toDir.toString());
}
// ignoreRegex.setRegex() is never called, but that's ok
// because ant sets it somehow, I think
if (ignoreRegex != null)
{
addArg("--ignore");
addArg(ignoreRegex.getRegex());
}
Set filenames = new HashSet();
Iterator iter = fileSets.iterator();
while (iter.hasNext())
{
FileSet fileSet = (FileSet)iter.next();
addArg("--basedir");
addArg(baseDir(fileSet));
filenames.addAll(Arrays.asList(getFilenames(fileSet)));
}
addFilenames((String[])filenames.toArray(new String[filenames.size()]));
saveArgs();
/**
* TODO: Do something here so that we can set System.in and System.out on
* getJava() to the one we're using now. So that when instrumentation calls
* System.out, it will show up as "[instrument] doing stuff" instead of
* "[java] doing stuff" in the ant output.
*/
if (getJava().executeJava() != 0)
{
throw new BuildException("Error instrumenting classes. See messages above.");
}
unInitArgs();
}
|
diff --git a/src/java-common/org/xins/common/servlet/container/ServletClassLoader.java b/src/java-common/org/xins/common/servlet/container/ServletClassLoader.java
index bbc6d683b..976ab1c29 100644
--- a/src/java-common/org/xins/common/servlet/container/ServletClassLoader.java
+++ b/src/java-common/org/xins/common/servlet/container/ServletClassLoader.java
@@ -1,274 +1,272 @@
/*
* ServletClassLoader.java
*
* Created on April 18, 2005, 1:32 PM
*/
package org.xins.common.servlet.container;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;
//import org.apache.tools.ant.loader.AntClassLoader2;
//import org.apache.tools.ant.BuildException;
/**
*
* @author anthonyg
*/
public class ServletClassLoader {
//-------------------------------------------------------------------------
// Class functions
//-------------------------------------------------------------------------
/**
* Get the class loader that will loader the servlet.
*
* @param warFile
* The WAR file containing the Servlet.
*
* @param mode
* the mode in which the servlet should be loaded. The possible values are
* <code>USE_CURRENT_CLASSPATH</code>, <code>USE_CLASSPATH_LIB</code>,
* <code>USE_XINS_LIB</code>, <code>USE_WAR_LIB</code>,
* <code>USE_WAR_EXTERNAL_LIB</code>.
*
* @return
* The Class loader to use to load the Servlet.
*
* @throws IOException
* if the file cannot be read or is incorrect.
*/
public static ClassLoader getServletClassLoader(File warFile, int mode) throws IOException {
if (mode == USE_CURRENT_CLASSPATH) {
return ServletClassLoader.class.getClassLoader();
}
List urlList = new ArrayList();
if (mode != USE_WAR_EXTERNAL_LIB) {
URL classesURL = new URL("jar:file:" + warFile.getAbsolutePath().replace(File.separatorChar, '/') + "!/WEB-INF/classes/");
urlList.add(classesURL);
}
List standardLibs = new ArrayList();
if (mode == USE_XINS_LIB) {
String classLocation = ServletClassLoader.class.getProtectionDomain().getCodeSource().getLocation().toString();
String commonJar = classLocation.substring(6).replace('/', File.separatorChar);
File baseDir = new File(commonJar).getParentFile();
File[] xinsFiles = baseDir.listFiles();
for (int i = 0; i < xinsFiles.length; i++) {
if (xinsFiles[i].getName().endsWith(".jar")) {
urlList.add(xinsFiles[i].toURL());
}
}
File libDir = new File(baseDir, ".." + File.separator + "lib");
File[] libFiles = libDir.listFiles();
for (int i = 0; i < libFiles.length; i++) {
if (libFiles[i].getName().endsWith(".jar")) {
urlList.add(libFiles[i].toURL());
}
}
}
if (mode == USE_CLASSPATH_LIB || mode == USE_WAR_EXTERNAL_LIB) {
String classPath = System.getProperty("java.class.path");
StringTokenizer stClassPath = new StringTokenizer(classPath, File.pathSeparator);
while (stClassPath.hasMoreTokens()) {
String nextPath = stClassPath.nextToken();
if (nextPath.toLowerCase().endsWith(".jar")) {
standardLibs.add(nextPath.substring(nextPath.lastIndexOf(File.separatorChar) + 1));
}
urlList.add(new File(nextPath).toURL());
}
}
if (mode == USE_WAR_LIB || mode == USE_WAR_EXTERNAL_LIB) {
JarInputStream jarStream = new JarInputStream(new FileInputStream(warFile));
JarEntry entry = jarStream.getNextJarEntry();
while(entry != null) {
String entryName = entry.getName();
if (entryName.startsWith("WEB-INF/lib/") && entryName.endsWith(".jar") && !standardLibs.contains(entryName.substring(12))) {
File tempJarFile = unpack(jarStream, entryName);
- System.err.println(":"+tempJarFile.toURL());
urlList.add(tempJarFile.toURL());
}
entry = jarStream.getNextJarEntry();
}
jarStream.close();
}
/*AntClassLoader2 loader = new AntClassLoader2();
loader.setParentFirst(false);
loader.setParent(null);
for (int i=0; i<urlList.size(); i++) {
try {
loader.addPathElement((String) urlList.get(i));
} catch (BuildException bex) {
bex.printStackTrace();
}
}*/
URL[] urls = new URL[urlList.size()];
for (int i=0; i<urlList.size(); i++) {
urls[i] = (URL) urlList.get(i);
- //System.err.println("adding " + urlList.get(i));
}
ClassLoader loader = new ChildFirstClassLoader(urls, ServletClassLoader.class.getClassLoader());
Thread.currentThread().setContextClassLoader(loader);
return loader;
}
/**
* Unpack the specified entry from the JAR file.
*
* @param jarStream
* The input stream of the JAR file positioned at the entry.
* @param entryName
* The name of the entry to extract.
*
* @return
* The extracted file. The created file is a temporary file in the
* temporary directory.
*
* @throws IOException
* if the JAR file cannot be read or is incorrect.
*/
private static File unpack(JarInputStream jarStream, String entryName) throws IOException {
String libName = entryName.substring(entryName.lastIndexOf('/') + 1, entryName.length() - 4);
File tempJarFile = File.createTempFile(libName, ".jar");
FileOutputStream out = new FileOutputStream(tempJarFile);
// Transfer bytes from the JAR file to the output file
byte[] buf = new byte[8192];
int len;
while ((len = jarStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
return tempJarFile;
}
//-------------------------------------------------------------------------
// Class fields
//-------------------------------------------------------------------------
/**
* Use the current class loader to load the servlet and the libraries.
*/
public final static int USE_CURRENT_CLASSPATH = 1;
/**
* Load the Servlet code from the WAR file and use the current
* classpath for the libraries.
*/
public final static int USE_CLASSPATH_LIB = 2;
/**
* Load the servlet code from the WAR file and try to find the libraries
* in the same directory as this xins-common.jar and <:parent>/lib
* directory.
*/
public final static int USE_XINS_LIB = 3;
/**
* Load the servlet code and the libraries from the WAR file.
* This may take some time as the libraries need to be extracted from the
* WAR file.
*/
public final static int USE_WAR_LIB = 4;
/**
* Load the servlet code and the standard libraries from the CLASSPATH.
* Load the included external libraries from the WAR file.
*/
public final static int USE_WAR_EXTERNAL_LIB = 5;
//-------------------------------------------------------------------------
// Inner classes
//-------------------------------------------------------------------------
/**
* An almost trivial no-fuss implementation of a class loader
* following the child-first delegation model.
*
* @author <a href="http://www.qos.ch/log4j/">Ceki Gulcu</a>
*/
private static class ChildFirstClassLoader extends URLClassLoader {
public ChildFirstClassLoader(URL[] urls) {
super(urls);
}
public ChildFirstClassLoader(URL[] urls, ClassLoader parent) {
super(urls, parent);
}
public void addURL(URL url) {
super.addURL(url);
}
public Class loadClass(String name) throws ClassNotFoundException {
return loadClass(name, false);
}
/**
* We override the parent-first behavior established by
* java.land.Classloader.
* <p>
* The implementation is surprisingly straightforward.
*/
protected Class loadClass(String name, boolean resolve)
throws ClassNotFoundException {
//System.out.println("ChildFirstClassLoader("+name+", "+resolve+")");
// First, check if the class has already been loaded
Class c = findLoadedClass(name);
// if not loaded, search the local (child) resources
if (c == null) {
try {
c = findClass(name);
} catch(ClassNotFoundException cnfe) {
// ignore
}
}
// if we could not find it, delegate to parent
// Note that we don't attempt to catch any ClassNotFoundException
if (c == null) {
if (getParent() != null) {
c = getParent().loadClass(name);
} else {
c = getSystemClassLoader().loadClass(name);
}
}
if (resolve) {
resolveClass(c);
}
return c;
}
/**
* Override the parent-first resource loading model established by
* java.land.Classloader with child-first behavior.
*/
public URL getResource(String name) {
URL url = findResource(name);
// if local search failed, delegate to parent
if(url == null) {
url = getParent().getResource(name);
}
return url;
}
}
}
| false | true | public static ClassLoader getServletClassLoader(File warFile, int mode) throws IOException {
if (mode == USE_CURRENT_CLASSPATH) {
return ServletClassLoader.class.getClassLoader();
}
List urlList = new ArrayList();
if (mode != USE_WAR_EXTERNAL_LIB) {
URL classesURL = new URL("jar:file:" + warFile.getAbsolutePath().replace(File.separatorChar, '/') + "!/WEB-INF/classes/");
urlList.add(classesURL);
}
List standardLibs = new ArrayList();
if (mode == USE_XINS_LIB) {
String classLocation = ServletClassLoader.class.getProtectionDomain().getCodeSource().getLocation().toString();
String commonJar = classLocation.substring(6).replace('/', File.separatorChar);
File baseDir = new File(commonJar).getParentFile();
File[] xinsFiles = baseDir.listFiles();
for (int i = 0; i < xinsFiles.length; i++) {
if (xinsFiles[i].getName().endsWith(".jar")) {
urlList.add(xinsFiles[i].toURL());
}
}
File libDir = new File(baseDir, ".." + File.separator + "lib");
File[] libFiles = libDir.listFiles();
for (int i = 0; i < libFiles.length; i++) {
if (libFiles[i].getName().endsWith(".jar")) {
urlList.add(libFiles[i].toURL());
}
}
}
if (mode == USE_CLASSPATH_LIB || mode == USE_WAR_EXTERNAL_LIB) {
String classPath = System.getProperty("java.class.path");
StringTokenizer stClassPath = new StringTokenizer(classPath, File.pathSeparator);
while (stClassPath.hasMoreTokens()) {
String nextPath = stClassPath.nextToken();
if (nextPath.toLowerCase().endsWith(".jar")) {
standardLibs.add(nextPath.substring(nextPath.lastIndexOf(File.separatorChar) + 1));
}
urlList.add(new File(nextPath).toURL());
}
}
if (mode == USE_WAR_LIB || mode == USE_WAR_EXTERNAL_LIB) {
JarInputStream jarStream = new JarInputStream(new FileInputStream(warFile));
JarEntry entry = jarStream.getNextJarEntry();
while(entry != null) {
String entryName = entry.getName();
if (entryName.startsWith("WEB-INF/lib/") && entryName.endsWith(".jar") && !standardLibs.contains(entryName.substring(12))) {
File tempJarFile = unpack(jarStream, entryName);
System.err.println(":"+tempJarFile.toURL());
urlList.add(tempJarFile.toURL());
}
entry = jarStream.getNextJarEntry();
}
jarStream.close();
}
/*AntClassLoader2 loader = new AntClassLoader2();
loader.setParentFirst(false);
loader.setParent(null);
for (int i=0; i<urlList.size(); i++) {
try {
loader.addPathElement((String) urlList.get(i));
} catch (BuildException bex) {
bex.printStackTrace();
}
}*/
URL[] urls = new URL[urlList.size()];
for (int i=0; i<urlList.size(); i++) {
urls[i] = (URL) urlList.get(i);
//System.err.println("adding " + urlList.get(i));
}
ClassLoader loader = new ChildFirstClassLoader(urls, ServletClassLoader.class.getClassLoader());
Thread.currentThread().setContextClassLoader(loader);
return loader;
}
| public static ClassLoader getServletClassLoader(File warFile, int mode) throws IOException {
if (mode == USE_CURRENT_CLASSPATH) {
return ServletClassLoader.class.getClassLoader();
}
List urlList = new ArrayList();
if (mode != USE_WAR_EXTERNAL_LIB) {
URL classesURL = new URL("jar:file:" + warFile.getAbsolutePath().replace(File.separatorChar, '/') + "!/WEB-INF/classes/");
urlList.add(classesURL);
}
List standardLibs = new ArrayList();
if (mode == USE_XINS_LIB) {
String classLocation = ServletClassLoader.class.getProtectionDomain().getCodeSource().getLocation().toString();
String commonJar = classLocation.substring(6).replace('/', File.separatorChar);
File baseDir = new File(commonJar).getParentFile();
File[] xinsFiles = baseDir.listFiles();
for (int i = 0; i < xinsFiles.length; i++) {
if (xinsFiles[i].getName().endsWith(".jar")) {
urlList.add(xinsFiles[i].toURL());
}
}
File libDir = new File(baseDir, ".." + File.separator + "lib");
File[] libFiles = libDir.listFiles();
for (int i = 0; i < libFiles.length; i++) {
if (libFiles[i].getName().endsWith(".jar")) {
urlList.add(libFiles[i].toURL());
}
}
}
if (mode == USE_CLASSPATH_LIB || mode == USE_WAR_EXTERNAL_LIB) {
String classPath = System.getProperty("java.class.path");
StringTokenizer stClassPath = new StringTokenizer(classPath, File.pathSeparator);
while (stClassPath.hasMoreTokens()) {
String nextPath = stClassPath.nextToken();
if (nextPath.toLowerCase().endsWith(".jar")) {
standardLibs.add(nextPath.substring(nextPath.lastIndexOf(File.separatorChar) + 1));
}
urlList.add(new File(nextPath).toURL());
}
}
if (mode == USE_WAR_LIB || mode == USE_WAR_EXTERNAL_LIB) {
JarInputStream jarStream = new JarInputStream(new FileInputStream(warFile));
JarEntry entry = jarStream.getNextJarEntry();
while(entry != null) {
String entryName = entry.getName();
if (entryName.startsWith("WEB-INF/lib/") && entryName.endsWith(".jar") && !standardLibs.contains(entryName.substring(12))) {
File tempJarFile = unpack(jarStream, entryName);
urlList.add(tempJarFile.toURL());
}
entry = jarStream.getNextJarEntry();
}
jarStream.close();
}
/*AntClassLoader2 loader = new AntClassLoader2();
loader.setParentFirst(false);
loader.setParent(null);
for (int i=0; i<urlList.size(); i++) {
try {
loader.addPathElement((String) urlList.get(i));
} catch (BuildException bex) {
bex.printStackTrace();
}
}*/
URL[] urls = new URL[urlList.size()];
for (int i=0; i<urlList.size(); i++) {
urls[i] = (URL) urlList.get(i);
}
ClassLoader loader = new ChildFirstClassLoader(urls, ServletClassLoader.class.getClassLoader());
Thread.currentThread().setContextClassLoader(loader);
return loader;
}
|
diff --git a/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java b/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java
index d0b1683c8..58971a446 100644
--- a/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java
+++ b/atlas-analytics/src/main/java/uk/ac/ebi/gxa/analytics/generator/service/ExperimentAnalyticsGeneratorService.java
@@ -1,455 +1,458 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.analytics.generator.service;
import uk.ac.ebi.gxa.analytics.compute.AtlasComputeService;
import uk.ac.ebi.gxa.analytics.compute.ComputeException;
import uk.ac.ebi.gxa.analytics.compute.ComputeTask;
import uk.ac.ebi.gxa.analytics.generator.AnalyticsGeneratorException;
import uk.ac.ebi.gxa.analytics.generator.listener.AnalyticsGeneratorListener;
import uk.ac.ebi.gxa.dao.AtlasDAO;
import uk.ac.ebi.gxa.dao.LoadStage;
import uk.ac.ebi.gxa.dao.LoadStatus;
import uk.ac.ebi.gxa.netcdf.reader.NetCDFProxy;
import uk.ac.ebi.microarray.atlas.model.Experiment;
import uk.ac.ebi.rcloud.server.RServices;
import uk.ac.ebi.rcloud.server.RType.RChar;
import uk.ac.ebi.rcloud.server.RType.RObject;
import java.io.*;
import java.rmi.RemoteException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.*;
/**
* Javadocs go here!
*
* @author Tony Burdett
* @date 28-Sep-2009
*/
public class ExperimentAnalyticsGeneratorService extends AnalyticsGeneratorService<File> {
private static final int NUM_THREADS = 32;
public ExperimentAnalyticsGeneratorService(AtlasDAO atlasDAO,
File repositoryLocation,
AtlasComputeService atlasComputeService) {
super(atlasDAO, repositoryLocation, atlasComputeService);
}
protected void createAnalytics() throws AnalyticsGeneratorException {
// do initial setup - build executor service
ExecutorService tpool = Executors.newFixedThreadPool(NUM_THREADS);
// fetch experiments - check if we want all or only the pending ones
List<Experiment> experiments = getPendingOnly()
? getAtlasDAO().getAllExperimentsPendingAnalytics()
: getAtlasDAO().getAllExperiments();
// if we're computing all analytics, some might not be pending, so reset them to pending up front
if (!getPendingOnly()) {
for (Experiment experiment : experiments) {
getAtlasDAO().writeLoadDetails(
experiment.getAccession(), LoadStage.RANKING, LoadStatus.PENDING);
}
}
// create a timer, so we can track time to generate analytics
final AnalyticsTimer timer = new AnalyticsTimer(experiments);
// the list of futures - we need these so we can block until completion
List<Future> tasks =
new ArrayList<Future>();
// start the timer
timer.start();
// call the start procedure with "null" parameter, as we're doing all
try {
// simply call start procedure
getAtlasDAO().startExpressionAnalytics(null);
}
catch (Exception e) {
getLog().error("Failing analytics run for all experiments: " +
"failed to run initialising management procedure.\n{}", e);
for (Experiment experiment : experiments) {
getAtlasDAO().writeLoadDetails(
experiment.getAccession(), LoadStage.RANKING, LoadStatus.FAILED);
}
return;
}
// the first error encountered whilst generating analytics, if any
Exception firstError = null;
try {
// process each experiment to build the netcdfs
for (final Experiment experiment : experiments) {
// run each experiment in parallel
tasks.add(tpool.submit(new Callable() {
public Void call() throws Exception {
long start = System.currentTimeMillis();
try {
generateExperimentAnalytics(experiment.getAccession(), null);
}
finally {
timer.completed(experiment.getExperimentID());
long end = System.currentTimeMillis();
String total = new DecimalFormat("#.##").format((end - start) / 1000);
String estimate = new DecimalFormat("#.##").format(timer.getCurrentEstimate() / 60000);
getLog().info("\n\tAnalytics for " + experiment.getAccession() +
" created in " + total + "s." +
"\n\tCompleted " + timer.getCompletedExperimentCount() + "/" +
timer.getTotalExperimentCount() + "." +
"\n\tEstimated time remaining: " + estimate + " mins.");
}
return null;
}
}));
}
// block until completion, and throw the first error we see
for (Future task : tasks) {
try {
task.get();
}
catch (Exception e) {
// print the stacktrace, but swallow this exception to rethrow at the very end
getLog().error("An error occurred whilst generating analytics:\n{}", e);
if (firstError == null) {
firstError = e;
}
}
}
// if we have encountered an exception, throw the first error
if (firstError != null) {
throw new AnalyticsGeneratorException("An error occurred whilst generating analytics", firstError);
}
}
finally {
// call the ending procedure
try {
// simply call start procedure
getAtlasDAO().finaliseExpressionAnalytics(null);
}
catch (Exception e) {
getLog().error("Failing analytics run for all experiments: " +
"failed to run finalising management procedure.\n{}", e);
for (Experiment experiment : experiments) {
getAtlasDAO().writeLoadDetails(
experiment.getAccession(), LoadStage.RANKING, LoadStatus.FAILED);
}
}
// shutdown the service
getLog().debug("Shutting down executor service in " + getClass().getSimpleName());
try {
tpool.shutdown();
tpool.awaitTermination(60, TimeUnit.SECONDS);
if (!tpool.isTerminated()) {
//noinspection ThrowFromFinallyBlock
throw new AnalyticsGeneratorException(
"Failed to terminate service for " + getClass().getSimpleName() +
" cleanly - suspended tasks were found");
}
else {
getLog().debug("Executor service exited cleanly");
}
}
catch (InterruptedException e) {
//noinspection ThrowFromFinallyBlock
throw new AnalyticsGeneratorException(
"Failed to terminate service for " + getClass().getSimpleName() +
" cleanly - suspended tasks were found", e);
}
}
}
protected void createAnalyticsForExperiment(String experimentAccession, AnalyticsGeneratorListener listener) throws AnalyticsGeneratorException {
try {
// simply call start procedure
getAtlasDAO().startExpressionAnalytics(experimentAccession);
}
catch (Exception e) {
getLog().error("Failing analytics for {}: failed to run initialising management procedure.\n{}",
experimentAccession, e);
getAtlasDAO().writeLoadDetails(
experimentAccession, LoadStage.RANKING, LoadStatus.FAILED);
return;
}
// then generateExperimentAnalytics
generateExperimentAnalytics(experimentAccession, listener);
try {
// finally call end procedure
getAtlasDAO().finaliseExpressionAnalytics(experimentAccession);
}
catch (Exception e) {
getLog().error("Failing analytics for {}: failed to run finalising management procedure.\n{}",
experimentAccession, e);
getAtlasDAO().writeLoadDetails(
experimentAccession, LoadStage.RANKING, LoadStatus.FAILED);
}
}
private void generateExperimentAnalytics(String experimentAccession, AnalyticsGeneratorListener listener)
throws AnalyticsGeneratorException {
getLog().info("Generating analytics for experiment " + experimentAccession);
// update loadmonitor - experiment is indexing
getAtlasDAO().writeLoadDetails(
experimentAccession, LoadStage.RANKING, LoadStatus.WORKING);
// first, delete old analytics for this experiment
getAtlasDAO().deleteExpressionAnalytics(experimentAccession);
// work out where the NetCDF(s) are located
final Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession);
File[] netCDFs = getRepositoryLocation().listFiles(new FilenameFilter() {
public boolean accept(File file, String name) {
return name.matches("^" + experiment.getExperimentID() + "_[0-9]+(_ratios)?\\.nc$");
}
});
if (netCDFs == null || netCDFs.length == 0) {
throw new AnalyticsGeneratorException("No NetCDF files present for " + experimentAccession);
}
final List<String> analysedEFs = new LinkedList<String>();
int count = 0;
for (final File netCDF : netCDFs) {
count++;
ComputeTask<Void> computeAnalytics = new ComputeTask<Void>() {
public Void compute(RServices rs) throws ComputeException {
try {
// first, make sure we load the R code that runs the analytics
rs.sourceFromBuffer(getRCodeFromResource("R/analytics.R"));
// note - the netCDF file MUST be on the same file system where the workers run
getLog().debug("Starting compute task for " + netCDF.getAbsolutePath());
RObject r = rs.getObject("computeAnalytics(\"" + netCDF.getAbsolutePath() + "\")");
getLog().debug("Completed compute task for " + netCDF.getAbsolutePath());
if(r instanceof RChar) {
String[] efs = ((RChar) r).getNames();
String[] analysedOK = ((RChar) r).getValue();
if(efs != null)
for(int i = 0; i < efs.length; i++) {
getLog().debug("Performed analytics computation for netcdf {}: {} was {}", new Object[] {netCDF.getAbsolutePath(), efs[i], analysedOK[i]});
if("OK".equals(analysedOK[i]))
analysedEFs.add(efs[i]);
}
for(String rc : analysedOK) {
if(rc.contains("Error"))
throw new ComputeException(rc);
}
} else
throw new ComputeException("Analytics returned unrecognized status of class " + r.getClass().getSimpleName() + ", string value: " + r.toString());
} catch (RemoteException e) {
throw new ComputeException("Problem communicating with R service", e);
} catch (IOException e) {
throw new ComputeException("Unable to load R source from R/analytics.R", e);
}
return null;
}
};
NetCDFProxy proxy = null;
// now run this compute task
try {
listener.buildProgress("Computing analytics for " + experimentAccession);
getAtlasComputeService().computeTask(computeAnalytics);
getLog().debug("Compute task " + count + "/" + netCDFs.length + " for " + experimentAccession +
" has completed.");
if(analysedEFs.size()==0) {
listener.buildWarning("No analytics were computed for this experiment!");
return;
}
// computeAnalytics writes analytics data back to NetCDF, so now read back from NetCDF to database
proxy = new NetCDFProxy(netCDF);
// get unique factor values for the expression value matrix
long[] designElements = proxy.getDesignElements();
String[] uefvs = proxy.getUniqueFactorValues();
listener.buildProgress("Writing analytics for " + experimentAccession + " to the database...");
// uefvs is list of unique EF||EFV pairs - separate by splitting on ||
getLog().debug("Writing analytics for " + experimentAccession + " to the database...");
int uefvIndex = 0;
for (String uefv : uefvs) {
String[] values = uefv.split("\\|\\|"); // sheesh, crazy java regexing!
String ef = values[0];
// only write to the database EFs that have been processed
if(!analysedEFs.contains(ef))
continue;
for (int i = 1; i < values.length; i++) {
String efv = values[i];
float[] pValues = proxy.getPValuesForUniqueFactorValue(uefvIndex);
float[] tStatistics = proxy.getTStatisticsForUniqueFactorValue(uefvIndex);
// write values
listener.buildProgress("Writing analytics for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv);
getLog().trace("Writing analytics for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv);
try {
getAtlasDAO().writeExpressionAnalytics(
experimentAccession, ef, efv, designElements, pValues, tStatistics);
}
catch (RuntimeException e) {
throw new AnalyticsGeneratorException("Writing analytics data for experiment: " + experimentAccession + "; " +
- "EF: " + ef + "; EFV: " + efv + " failed with errors: ", e);
+ "EF: " + ef + "; EFV: " + efv + " failed with errors: " + e.getMessage(), e);
}
}
// increment uefvIndex
uefvIndex++;
}
}
catch (IOException e) {
throw new AnalyticsGeneratorException("Unable to read from analytics at " + netCDF.getAbsolutePath(), e);
}
catch (ComputeException e) {
throw new AnalyticsGeneratorException("Computation of analytics for " + netCDF.getAbsolutePath() + " failed: " + e.getMessage(), e);
}
+ catch (AnalyticsGeneratorException e) {
+ throw e;
+ }
catch (Exception e) {
throw new AnalyticsGeneratorException("An error occurred while generating analytics for " + netCDF.getAbsolutePath(), e);
} finally {
if(proxy != null) {
try {
proxy.close();
} catch (IOException e) {
getLog().error("Failed to close NetCDF proxy for " + netCDF.getAbsolutePath());
}
}
}
}
}
private String getRCodeFromResource(String resourcePath) throws ComputeException {
// open a stream to the resource
InputStream in = getClass().getClassLoader().getResourceAsStream(resourcePath);
// create a reader to read in code
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
throw new ComputeException("Error while reading in R code from " + resourcePath, e);
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
getLog().error("Failed to close input stream", e);
}
}
}
return sb.toString();
}
private class AnalyticsTimer {
private long[] experimentIDs;
private boolean[] completions;
private int completedCount;
private long startTime;
private long lastEstimate;
public AnalyticsTimer(List<Experiment> experiments) {
experimentIDs = new long[experiments.size()];
completions = new boolean[experiments.size()];
int i = 0;
for (Experiment exp : experiments) {
experimentIDs[i] = exp.getExperimentID();
completions[i] = false;
i++;
}
}
public synchronized AnalyticsTimer start() {
startTime = System.currentTimeMillis();
return this;
}
public synchronized AnalyticsTimer completed(long experimentID) {
for (int i = 0; i < experimentIDs.length; i++) {
if (experimentIDs[i] == experimentID) {
if (!completions[i]) {
completions[i] = true;
completedCount++;
}
break;
}
}
// calculate estimate of time
long timeWorking = System.currentTimeMillis() - startTime;
lastEstimate = (timeWorking / completedCount) * (completions.length - completedCount);
return this;
}
public synchronized long getCurrentEstimate() {
return lastEstimate;
}
public synchronized int getCompletedExperimentCount() {
return completedCount;
}
public synchronized int getTotalExperimentCount() {
return completions.length;
}
}
}
| false | true | private void generateExperimentAnalytics(String experimentAccession, AnalyticsGeneratorListener listener)
throws AnalyticsGeneratorException {
getLog().info("Generating analytics for experiment " + experimentAccession);
// update loadmonitor - experiment is indexing
getAtlasDAO().writeLoadDetails(
experimentAccession, LoadStage.RANKING, LoadStatus.WORKING);
// first, delete old analytics for this experiment
getAtlasDAO().deleteExpressionAnalytics(experimentAccession);
// work out where the NetCDF(s) are located
final Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession);
File[] netCDFs = getRepositoryLocation().listFiles(new FilenameFilter() {
public boolean accept(File file, String name) {
return name.matches("^" + experiment.getExperimentID() + "_[0-9]+(_ratios)?\\.nc$");
}
});
if (netCDFs == null || netCDFs.length == 0) {
throw new AnalyticsGeneratorException("No NetCDF files present for " + experimentAccession);
}
final List<String> analysedEFs = new LinkedList<String>();
int count = 0;
for (final File netCDF : netCDFs) {
count++;
ComputeTask<Void> computeAnalytics = new ComputeTask<Void>() {
public Void compute(RServices rs) throws ComputeException {
try {
// first, make sure we load the R code that runs the analytics
rs.sourceFromBuffer(getRCodeFromResource("R/analytics.R"));
// note - the netCDF file MUST be on the same file system where the workers run
getLog().debug("Starting compute task for " + netCDF.getAbsolutePath());
RObject r = rs.getObject("computeAnalytics(\"" + netCDF.getAbsolutePath() + "\")");
getLog().debug("Completed compute task for " + netCDF.getAbsolutePath());
if(r instanceof RChar) {
String[] efs = ((RChar) r).getNames();
String[] analysedOK = ((RChar) r).getValue();
if(efs != null)
for(int i = 0; i < efs.length; i++) {
getLog().debug("Performed analytics computation for netcdf {}: {} was {}", new Object[] {netCDF.getAbsolutePath(), efs[i], analysedOK[i]});
if("OK".equals(analysedOK[i]))
analysedEFs.add(efs[i]);
}
for(String rc : analysedOK) {
if(rc.contains("Error"))
throw new ComputeException(rc);
}
} else
throw new ComputeException("Analytics returned unrecognized status of class " + r.getClass().getSimpleName() + ", string value: " + r.toString());
} catch (RemoteException e) {
throw new ComputeException("Problem communicating with R service", e);
} catch (IOException e) {
throw new ComputeException("Unable to load R source from R/analytics.R", e);
}
return null;
}
};
NetCDFProxy proxy = null;
// now run this compute task
try {
listener.buildProgress("Computing analytics for " + experimentAccession);
getAtlasComputeService().computeTask(computeAnalytics);
getLog().debug("Compute task " + count + "/" + netCDFs.length + " for " + experimentAccession +
" has completed.");
if(analysedEFs.size()==0) {
listener.buildWarning("No analytics were computed for this experiment!");
return;
}
// computeAnalytics writes analytics data back to NetCDF, so now read back from NetCDF to database
proxy = new NetCDFProxy(netCDF);
// get unique factor values for the expression value matrix
long[] designElements = proxy.getDesignElements();
String[] uefvs = proxy.getUniqueFactorValues();
listener.buildProgress("Writing analytics for " + experimentAccession + " to the database...");
// uefvs is list of unique EF||EFV pairs - separate by splitting on ||
getLog().debug("Writing analytics for " + experimentAccession + " to the database...");
int uefvIndex = 0;
for (String uefv : uefvs) {
String[] values = uefv.split("\\|\\|"); // sheesh, crazy java regexing!
String ef = values[0];
// only write to the database EFs that have been processed
if(!analysedEFs.contains(ef))
continue;
for (int i = 1; i < values.length; i++) {
String efv = values[i];
float[] pValues = proxy.getPValuesForUniqueFactorValue(uefvIndex);
float[] tStatistics = proxy.getTStatisticsForUniqueFactorValue(uefvIndex);
// write values
listener.buildProgress("Writing analytics for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv);
getLog().trace("Writing analytics for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv);
try {
getAtlasDAO().writeExpressionAnalytics(
experimentAccession, ef, efv, designElements, pValues, tStatistics);
}
catch (RuntimeException e) {
throw new AnalyticsGeneratorException("Writing analytics data for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv + " failed with errors: ", e);
}
}
// increment uefvIndex
uefvIndex++;
}
}
catch (IOException e) {
throw new AnalyticsGeneratorException("Unable to read from analytics at " + netCDF.getAbsolutePath(), e);
}
catch (ComputeException e) {
throw new AnalyticsGeneratorException("Computation of analytics for " + netCDF.getAbsolutePath() + " failed: " + e.getMessage(), e);
}
catch (Exception e) {
throw new AnalyticsGeneratorException("An error occurred while generating analytics for " + netCDF.getAbsolutePath(), e);
} finally {
if(proxy != null) {
try {
proxy.close();
} catch (IOException e) {
getLog().error("Failed to close NetCDF proxy for " + netCDF.getAbsolutePath());
}
}
}
}
}
| private void generateExperimentAnalytics(String experimentAccession, AnalyticsGeneratorListener listener)
throws AnalyticsGeneratorException {
getLog().info("Generating analytics for experiment " + experimentAccession);
// update loadmonitor - experiment is indexing
getAtlasDAO().writeLoadDetails(
experimentAccession, LoadStage.RANKING, LoadStatus.WORKING);
// first, delete old analytics for this experiment
getAtlasDAO().deleteExpressionAnalytics(experimentAccession);
// work out where the NetCDF(s) are located
final Experiment experiment = getAtlasDAO().getExperimentByAccession(experimentAccession);
File[] netCDFs = getRepositoryLocation().listFiles(new FilenameFilter() {
public boolean accept(File file, String name) {
return name.matches("^" + experiment.getExperimentID() + "_[0-9]+(_ratios)?\\.nc$");
}
});
if (netCDFs == null || netCDFs.length == 0) {
throw new AnalyticsGeneratorException("No NetCDF files present for " + experimentAccession);
}
final List<String> analysedEFs = new LinkedList<String>();
int count = 0;
for (final File netCDF : netCDFs) {
count++;
ComputeTask<Void> computeAnalytics = new ComputeTask<Void>() {
public Void compute(RServices rs) throws ComputeException {
try {
// first, make sure we load the R code that runs the analytics
rs.sourceFromBuffer(getRCodeFromResource("R/analytics.R"));
// note - the netCDF file MUST be on the same file system where the workers run
getLog().debug("Starting compute task for " + netCDF.getAbsolutePath());
RObject r = rs.getObject("computeAnalytics(\"" + netCDF.getAbsolutePath() + "\")");
getLog().debug("Completed compute task for " + netCDF.getAbsolutePath());
if(r instanceof RChar) {
String[] efs = ((RChar) r).getNames();
String[] analysedOK = ((RChar) r).getValue();
if(efs != null)
for(int i = 0; i < efs.length; i++) {
getLog().debug("Performed analytics computation for netcdf {}: {} was {}", new Object[] {netCDF.getAbsolutePath(), efs[i], analysedOK[i]});
if("OK".equals(analysedOK[i]))
analysedEFs.add(efs[i]);
}
for(String rc : analysedOK) {
if(rc.contains("Error"))
throw new ComputeException(rc);
}
} else
throw new ComputeException("Analytics returned unrecognized status of class " + r.getClass().getSimpleName() + ", string value: " + r.toString());
} catch (RemoteException e) {
throw new ComputeException("Problem communicating with R service", e);
} catch (IOException e) {
throw new ComputeException("Unable to load R source from R/analytics.R", e);
}
return null;
}
};
NetCDFProxy proxy = null;
// now run this compute task
try {
listener.buildProgress("Computing analytics for " + experimentAccession);
getAtlasComputeService().computeTask(computeAnalytics);
getLog().debug("Compute task " + count + "/" + netCDFs.length + " for " + experimentAccession +
" has completed.");
if(analysedEFs.size()==0) {
listener.buildWarning("No analytics were computed for this experiment!");
return;
}
// computeAnalytics writes analytics data back to NetCDF, so now read back from NetCDF to database
proxy = new NetCDFProxy(netCDF);
// get unique factor values for the expression value matrix
long[] designElements = proxy.getDesignElements();
String[] uefvs = proxy.getUniqueFactorValues();
listener.buildProgress("Writing analytics for " + experimentAccession + " to the database...");
// uefvs is list of unique EF||EFV pairs - separate by splitting on ||
getLog().debug("Writing analytics for " + experimentAccession + " to the database...");
int uefvIndex = 0;
for (String uefv : uefvs) {
String[] values = uefv.split("\\|\\|"); // sheesh, crazy java regexing!
String ef = values[0];
// only write to the database EFs that have been processed
if(!analysedEFs.contains(ef))
continue;
for (int i = 1; i < values.length; i++) {
String efv = values[i];
float[] pValues = proxy.getPValuesForUniqueFactorValue(uefvIndex);
float[] tStatistics = proxy.getTStatisticsForUniqueFactorValue(uefvIndex);
// write values
listener.buildProgress("Writing analytics for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv);
getLog().trace("Writing analytics for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv);
try {
getAtlasDAO().writeExpressionAnalytics(
experimentAccession, ef, efv, designElements, pValues, tStatistics);
}
catch (RuntimeException e) {
throw new AnalyticsGeneratorException("Writing analytics data for experiment: " + experimentAccession + "; " +
"EF: " + ef + "; EFV: " + efv + " failed with errors: " + e.getMessage(), e);
}
}
// increment uefvIndex
uefvIndex++;
}
}
catch (IOException e) {
throw new AnalyticsGeneratorException("Unable to read from analytics at " + netCDF.getAbsolutePath(), e);
}
catch (ComputeException e) {
throw new AnalyticsGeneratorException("Computation of analytics for " + netCDF.getAbsolutePath() + " failed: " + e.getMessage(), e);
}
catch (AnalyticsGeneratorException e) {
throw e;
}
catch (Exception e) {
throw new AnalyticsGeneratorException("An error occurred while generating analytics for " + netCDF.getAbsolutePath(), e);
} finally {
if(proxy != null) {
try {
proxy.close();
} catch (IOException e) {
getLog().error("Failed to close NetCDF proxy for " + netCDF.getAbsolutePath());
}
}
}
}
}
|
diff --git a/src/com/mpower/domain/model/paymentInfo/AbstractPaymentInfoEntity.java b/src/com/mpower/domain/model/paymentInfo/AbstractPaymentInfoEntity.java
index 4c44c24c..1ee64510 100644
--- a/src/com/mpower/domain/model/paymentInfo/AbstractPaymentInfoEntity.java
+++ b/src/com/mpower/domain/model/paymentInfo/AbstractPaymentInfoEntity.java
@@ -1,328 +1,333 @@
package com.mpower.domain.model.paymentInfo;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.collections.Factory;
import org.apache.commons.collections.list.LazyList;
import org.springframework.core.style.ToStringCreator;
import com.mpower.domain.model.AbstractCustomizableEntity;
import com.mpower.domain.model.AddressAware;
import com.mpower.domain.model.EmailAware;
import com.mpower.domain.model.PaymentSource;
import com.mpower.domain.model.PaymentSourceAware;
import com.mpower.domain.model.Person;
import com.mpower.domain.model.PhoneAware;
import com.mpower.domain.model.Site;
import com.mpower.domain.model.communication.Address;
import com.mpower.domain.model.communication.Email;
import com.mpower.domain.model.communication.Phone;
import com.mpower.type.FormBeanType;
import com.mpower.util.StringConstants;
@SuppressWarnings({ "serial", "unchecked" })
public abstract class AbstractPaymentInfoEntity extends AbstractCustomizableEntity implements PaymentSourceAware, AddressAware, PhoneAware, EmailAware {
protected String comments;
protected String currencyCode = StringConstants.USD;
protected String paymentType;
protected Integer checkNumber;
protected boolean sendAcknowledgment = false;
protected Date acknowledgmentDate;
protected Person person;
/** Form bean representation of the DistributionLines */
protected List<DistributionLine> mutableDistributionLines = LazyList.decorate(new ArrayList<DistributionLine>(), new Factory() {
public Object create() {
return new DistributionLine();
}
});
/** Domain object representation of the DistributionLines */
protected List<DistributionLine> distributionLines;
private FormBeanType addressType;
private FormBeanType phoneType;
private FormBeanType emailType;
private FormBeanType paymentSourceType;
protected Address address = new Address();
protected Phone phone = new Phone();
protected Email email = new Email();
protected PaymentSource paymentSource = new PaymentSource(person);
protected Address selectedAddress = new Address();
protected Phone selectedPhone = new Phone();
protected Email selectedEmail = new Email();
protected PaymentSource selectedPaymentSource = new PaymentSource(person);
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
if (person != null) {
if (paymentSource != null) {
paymentSource.setPerson(person);
}
if (selectedPaymentSource != null) {
selectedPaymentSource.setPerson(person);
}
}
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getCurrencyCode() {
if (currencyCode == null) {
currencyCode = StringConstants.USD;
}
return currencyCode;
}
public void setCurrencyCode(String currencyCode) {
this.currencyCode = currencyCode;
}
@Override
public void setPaymentType(String paymentType) {
this.paymentType = paymentType;
}
@Override
public String getPaymentType() {
return paymentType;
}
public void setCheckNumber(Integer checkNumber) {
this.checkNumber = checkNumber;
}
public Integer getCheckNumber() {
return checkNumber;
}
public boolean isSendAcknowledgment() {
return sendAcknowledgment;
}
public void setSendAcknowledgment(boolean sendAcknowledgment) {
this.sendAcknowledgment = sendAcknowledgment;
}
public Date getAcknowledgmentDate() {
return acknowledgmentDate;
}
public void setAcknowledgmentDate(Date acknowledgmentDate) {
this.acknowledgmentDate = acknowledgmentDate;
}
public List<DistributionLine> getDistributionLines() {
return distributionLines;
}
public void setDistributionLines(List<DistributionLine> distributionLines) {
this.distributionLines = distributionLines;
}
public List<DistributionLine> getMutableDistributionLines() {
return mutableDistributionLines;
}
public void setMutableDistributionLines(List<DistributionLine> mutableDistributionLines) {
this.mutableDistributionLines = mutableDistributionLines;
}
public void removeEmptyMutableDistributionLines() {
Iterator<DistributionLine> mutableLinesIter = mutableDistributionLines.iterator();
distributionLines = new ArrayList<DistributionLine>();
while (mutableLinesIter.hasNext()) {
DistributionLine line = mutableLinesIter.next();
- if (line != null && line.isFieldEntered() == false) {
- mutableLinesIter.remove();
- }
- else {
- distributionLines.add(line);
+ if (line != null) {
+ if (line.isFieldEntered() == false) {
+ mutableLinesIter.remove();
+ }
+ else {
+ distributionLines.add(line);
+ }
}
}
+ if (distributionLines.isEmpty()) {
+ distributionLines.add(new DistributionLine());
+ }
}
public void filterValidDistributionLines() {
distributionLines = new ArrayList<DistributionLine>();
Iterator<DistributionLine> mutableLinesIter = mutableDistributionLines.iterator();
while (mutableLinesIter.hasNext()) {
DistributionLine line = mutableLinesIter.next();
if (line != null && line.isValid()) {
distributionLines.add(line);
}
}
}
@Override
public FormBeanType getAddressType() {
return this.addressType;
}
@Override
public void setAddressType(FormBeanType type) {
this.addressType = type;
}
@Override
public FormBeanType getPhoneType() {
return this.phoneType;
}
@Override
public void setPhoneType(FormBeanType type) {
this.phoneType = type;
}
@Override
public FormBeanType getEmailType() {
return this.emailType;
}
@Override
public void setEmailType(FormBeanType type) {
this.emailType = type;
}
@Override
public FormBeanType getPaymentSourceType() {
return this.paymentSourceType;
}
@Override
public void setPaymentSourceType(FormBeanType type) {
this.paymentSourceType = type;
}
@Override
public PaymentSource getPaymentSource() {
return paymentSource;
}
@Override
public void setPaymentSource(PaymentSource paymentSource) {
this.paymentSource = paymentSource;
}
@Override
public Address getAddress() {
return address;
}
@Override
public void setAddress(Address address) {
this.address = address;
}
@Override
public Phone getPhone() {
return phone;
}
@Override
public void setPhone(Phone phone) {
this.phone = phone;
}
@Override
public Email getEmail() {
return email;
}
@Override
public void setEmail(Email email) {
this.email = email;
}
@Override
public PaymentSource getSelectedPaymentSource() {
if (selectedPaymentSource == null) {
selectedPaymentSource = new PaymentSource(); // created only because spring needs to bind to it
}
return selectedPaymentSource;
}
public void setSelectedPaymentSource(PaymentSource selectedPaymentSource) {
this.selectedPaymentSource = selectedPaymentSource;
}
@Override
public Address getSelectedAddress() {
if (selectedAddress == null) {
selectedAddress = new Address(); // created only because spring needs to bind to it
}
return selectedAddress;
}
public void setSelectedAddress(Address selectedAddress) {
this.selectedAddress = selectedAddress;
}
@Override
public Phone getSelectedPhone() {
if (selectedPhone == null) {
selectedPhone = new Phone(); // created only because spring needs to bind to it
}
return selectedPhone;
}
public void setSelectedPhone(Phone selectedPhone) {
this.selectedPhone = selectedPhone;
}
@Override
public Email getSelectedEmail() {
if (selectedEmail == null) {
selectedEmail = new Email(); // created only because spring needs to bind to it
}
return selectedEmail;
}
public void setSelectedEmail(Email selectedEmail) {
this.selectedEmail = selectedEmail;
}
public Site getSite() {
return person != null ? person.getSite() : null;
}
@Override
public void setPaymentSourcePaymentType() {
if (paymentSource != null) {
paymentSource.setPaymentType(getPaymentType());
}
}
@Override
public void setPaymentSourceAwarePaymentType() {
if (selectedPaymentSource != null) {
setPaymentType(selectedPaymentSource.getPaymentType());
}
}
@Override
public String toString() {
return new ToStringCreator(this).append(super.toString()).append("paymentType", paymentType).append("currencyCode", currencyCode).
append("checkNumber", checkNumber).append("sendAcknowledgment", sendAcknowledgment).append("acknowledgmentDate", acknowledgmentDate).append("comments", comments).
append("address", address).append("phone", phone).append("email", email).append("paymentSource", paymentSource).
append("paymentSourceType", paymentSourceType).
append("selectedAddress", selectedAddress).append("selectedPhone", selectedPhone).append("selectedEmail", selectedEmail).append("selectedPaymentSource", selectedPaymentSource).
append("emailType", emailType).append("phoneType", phoneType).append("addressType", addressType).append("person", person).
toString();
}
}
| false | true | public void removeEmptyMutableDistributionLines() {
Iterator<DistributionLine> mutableLinesIter = mutableDistributionLines.iterator();
distributionLines = new ArrayList<DistributionLine>();
while (mutableLinesIter.hasNext()) {
DistributionLine line = mutableLinesIter.next();
if (line != null && line.isFieldEntered() == false) {
mutableLinesIter.remove();
}
else {
distributionLines.add(line);
}
}
}
| public void removeEmptyMutableDistributionLines() {
Iterator<DistributionLine> mutableLinesIter = mutableDistributionLines.iterator();
distributionLines = new ArrayList<DistributionLine>();
while (mutableLinesIter.hasNext()) {
DistributionLine line = mutableLinesIter.next();
if (line != null) {
if (line.isFieldEntered() == false) {
mutableLinesIter.remove();
}
else {
distributionLines.add(line);
}
}
}
if (distributionLines.isEmpty()) {
distributionLines.add(new DistributionLine());
}
}
|
diff --git a/src/com/android/settings/Settings.java b/src/com/android/settings/Settings.java
index 02769e1..4763a2e 100644
--- a/src/com/android/settings/Settings.java
+++ b/src/com/android/settings/Settings.java
@@ -1,844 +1,844 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.settings;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.OnAccountsUpdateListener;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.RestrictionEntry;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.INetworkManagementService;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.UserHandle;
import android.os.UserManager;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.Switch;
import android.widget.TextView;
import com.android.internal.util.ArrayUtils;
import com.android.settings.AccessibilitySettings.ToggleAccessibilityServicePreferenceFragment;
import com.android.settings.accounts.AccountSyncSettings;
import com.android.settings.accounts.AuthenticatorHelper;
import com.android.settings.accounts.ManageAccountsSettings;
import com.android.settings.bluetooth.BluetoothEnabler;
import com.android.settings.bluetooth.BluetoothSettings;
import com.android.settings.wfd.WifiDisplaySettings;
import com.android.settings.wifi.WifiEnabler;
import com.android.settings.wifi.WifiSettings;
import com.android.settings.wifi.p2p.WifiP2pSettings;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
/**
* Top-level settings activity to handle single pane and double pane UI layout.
*/
public class Settings extends PreferenceActivity
implements ButtonBarHandler, OnAccountsUpdateListener {
private static final String LOG_TAG = "Settings";
private static final String META_DATA_KEY_HEADER_ID =
"com.android.settings.TOP_LEVEL_HEADER_ID";
private static final String META_DATA_KEY_FRAGMENT_CLASS =
"com.android.settings.FRAGMENT_CLASS";
private static final String META_DATA_KEY_PARENT_TITLE =
"com.android.settings.PARENT_FRAGMENT_TITLE";
private static final String META_DATA_KEY_PARENT_FRAGMENT_CLASS =
"com.android.settings.PARENT_FRAGMENT_CLASS";
private static final String EXTRA_UI_OPTIONS = "settings:ui_options";
private static final String SAVE_KEY_CURRENT_HEADER = "com.android.settings.CURRENT_HEADER";
private static final String SAVE_KEY_PARENT_HEADER = "com.android.settings.PARENT_HEADER";
private String mFragmentClass;
private int mTopLevelHeaderId;
private Header mFirstHeader;
private Header mCurrentHeader;
private Header mParentHeader;
private boolean mInLocalHeaderSwitch;
// Show only these settings for restricted users
private int[] SETTINGS_FOR_RESTRICTED = {
R.id.wireless_section,
R.id.wifi_settings,
R.id.bluetooth_settings,
R.id.data_usage_settings,
R.id.wireless_settings,
R.id.device_section,
R.id.sound_settings,
R.id.display_settings,
R.id.storage_settings,
R.id.application_settings,
R.id.battery_settings,
R.id.personal_section,
R.id.location_settings,
R.id.security_settings,
R.id.language_settings,
R.id.user_settings,
R.id.account_settings,
R.id.account_add,
R.id.system_section,
R.id.date_time_settings,
R.id.about_settings,
R.id.accessibility_settings
};
private SharedPreferences mDevelopmentPreferences;
private SharedPreferences.OnSharedPreferenceChangeListener mDevelopmentPreferencesListener;
// TODO: Update Call Settings based on airplane mode state.
protected HashMap<Integer, Integer> mHeaderIndexMap = new HashMap<Integer, Integer>();
private AuthenticatorHelper mAuthenticatorHelper;
private Header mLastHeader;
private boolean mListeningToAccountUpdates;
@Override
protected void onCreate(Bundle savedInstanceState) {
if (getIntent().hasExtra(EXTRA_UI_OPTIONS)) {
getWindow().setUiOptions(getIntent().getIntExtra(EXTRA_UI_OPTIONS, 0));
}
mAuthenticatorHelper = new AuthenticatorHelper();
mAuthenticatorHelper.updateAuthDescriptions(this);
mAuthenticatorHelper.onAccountsUpdated(this, null);
mDevelopmentPreferences = getSharedPreferences(DevelopmentSettings.PREF_FILE,
Context.MODE_PRIVATE);
getMetaData();
mInLocalHeaderSwitch = true;
super.onCreate(savedInstanceState);
mInLocalHeaderSwitch = false;
if (!onIsHidingHeaders() && onIsMultiPane()) {
highlightHeader(mTopLevelHeaderId);
// Force the title so that it doesn't get overridden by a direct launch of
// a specific settings screen.
setTitle(R.string.settings_label);
}
// Retrieve any saved state
if (savedInstanceState != null) {
mCurrentHeader = savedInstanceState.getParcelable(SAVE_KEY_CURRENT_HEADER);
mParentHeader = savedInstanceState.getParcelable(SAVE_KEY_PARENT_HEADER);
}
// If the current header was saved, switch to it
if (savedInstanceState != null && mCurrentHeader != null) {
//switchToHeaderLocal(mCurrentHeader);
showBreadCrumbs(mCurrentHeader.title, null);
}
if (mParentHeader != null) {
setParentTitle(mParentHeader.title, null, new OnClickListener() {
@Override
public void onClick(View v) {
switchToParent(mParentHeader.fragment);
}
});
}
// Override up navigation for multi-pane, since we handle it in the fragment breadcrumbs
if (onIsMultiPane()) {
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setHomeButtonEnabled(false);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the current fragment, if it is the same as originally launched
if (mCurrentHeader != null) {
outState.putParcelable(SAVE_KEY_CURRENT_HEADER, mCurrentHeader);
}
if (mParentHeader != null) {
outState.putParcelable(SAVE_KEY_PARENT_HEADER, mParentHeader);
}
}
@Override
public void onResume() {
super.onResume();
mDevelopmentPreferencesListener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
invalidateHeaders();
}
};
mDevelopmentPreferences.registerOnSharedPreferenceChangeListener(
mDevelopmentPreferencesListener);
ListAdapter listAdapter = getListAdapter();
if (listAdapter instanceof HeaderAdapter) {
((HeaderAdapter) listAdapter).resume();
}
invalidateHeaders();
}
@Override
public void onPause() {
super.onPause();
ListAdapter listAdapter = getListAdapter();
if (listAdapter instanceof HeaderAdapter) {
((HeaderAdapter) listAdapter).pause();
}
mDevelopmentPreferences.unregisterOnSharedPreferenceChangeListener(
mDevelopmentPreferencesListener);
mDevelopmentPreferencesListener = null;
}
@Override
public void onDestroy() {
super.onDestroy();
if (mListeningToAccountUpdates) {
AccountManager.get(this).removeOnAccountsUpdatedListener(this);
}
}
private void switchToHeaderLocal(Header header) {
mInLocalHeaderSwitch = true;
switchToHeader(header);
mInLocalHeaderSwitch = false;
}
@Override
public void switchToHeader(Header header) {
if (!mInLocalHeaderSwitch) {
mCurrentHeader = null;
mParentHeader = null;
}
super.switchToHeader(header);
}
/**
* Switch to parent fragment and store the grand parent's info
* @param className name of the activity wrapper for the parent fragment.
*/
private void switchToParent(String className) {
final ComponentName cn = new ComponentName(this, className);
try {
final PackageManager pm = getPackageManager();
final ActivityInfo parentInfo = pm.getActivityInfo(cn, PackageManager.GET_META_DATA);
if (parentInfo != null && parentInfo.metaData != null) {
String fragmentClass = parentInfo.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS);
CharSequence fragmentTitle = parentInfo.loadLabel(pm);
Header parentHeader = new Header();
parentHeader.fragment = fragmentClass;
parentHeader.title = fragmentTitle;
mCurrentHeader = parentHeader;
switchToHeaderLocal(parentHeader);
highlightHeader(mTopLevelHeaderId);
mParentHeader = new Header();
mParentHeader.fragment
= parentInfo.metaData.getString(META_DATA_KEY_PARENT_FRAGMENT_CLASS);
mParentHeader.title = parentInfo.metaData.getString(META_DATA_KEY_PARENT_TITLE);
}
} catch (NameNotFoundException nnfe) {
Log.w(LOG_TAG, "Could not find parent activity : " + className);
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// If it is not launched from history, then reset to top-level
if ((intent.getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY) == 0) {
if (mFirstHeader != null && !onIsHidingHeaders() && onIsMultiPane()) {
switchToHeaderLocal(mFirstHeader);
}
getListView().setSelectionFromTop(0, 0);
}
}
private void highlightHeader(int id) {
if (id != 0) {
Integer index = mHeaderIndexMap.get(id);
if (index != null) {
getListView().setItemChecked(index, true);
if (isMultiPane()) {
getListView().smoothScrollToPosition(index);
}
}
}
}
@Override
public Intent getIntent() {
Intent superIntent = super.getIntent();
String startingFragment = getStartingFragmentClass(superIntent);
// This is called from super.onCreate, isMultiPane() is not yet reliable
// Do not use onIsHidingHeaders either, which relies itself on this method
if (startingFragment != null && !onIsMultiPane()) {
Intent modIntent = new Intent(superIntent);
modIntent.putExtra(EXTRA_SHOW_FRAGMENT, startingFragment);
Bundle args = superIntent.getExtras();
if (args != null) {
args = new Bundle(args);
} else {
args = new Bundle();
}
args.putParcelable("intent", superIntent);
modIntent.putExtra(EXTRA_SHOW_FRAGMENT_ARGUMENTS, superIntent.getExtras());
return modIntent;
}
return superIntent;
}
/**
* Checks if the component name in the intent is different from the Settings class and
* returns the class name to load as a fragment.
*/
protected String getStartingFragmentClass(Intent intent) {
if (mFragmentClass != null) return mFragmentClass;
String intentClass = intent.getComponent().getClassName();
if (intentClass.equals(getClass().getName())) return null;
if ("com.android.settings.ManageApplications".equals(intentClass)
|| "com.android.settings.RunningServices".equals(intentClass)
|| "com.android.settings.applications.StorageUse".equals(intentClass)) {
// Old names of manage apps.
intentClass = com.android.settings.applications.ManageApplications.class.getName();
}
return intentClass;
}
/**
* Override initial header when an activity-alias is causing Settings to be launched
* for a specific fragment encoded in the android:name parameter.
*/
@Override
public Header onGetInitialHeader() {
String fragmentClass = getStartingFragmentClass(super.getIntent());
if (fragmentClass != null) {
Header header = new Header();
header.fragment = fragmentClass;
header.title = getTitle();
header.fragmentArguments = getIntent().getExtras();
mCurrentHeader = header;
return header;
}
return mFirstHeader;
}
@Override
public Intent onBuildStartFragmentIntent(String fragmentName, Bundle args,
int titleRes, int shortTitleRes) {
Intent intent = super.onBuildStartFragmentIntent(fragmentName, args,
titleRes, shortTitleRes);
// Some fragments want split ActionBar; these should stay in sync with
// uiOptions for fragments also defined as activities in manifest.
if (WifiSettings.class.getName().equals(fragmentName) ||
WifiP2pSettings.class.getName().equals(fragmentName) ||
WifiDisplaySettings.class.getName().equals(fragmentName) ||
BluetoothSettings.class.getName().equals(fragmentName) ||
DreamSettings.class.getName().equals(fragmentName) ||
ToggleAccessibilityServicePreferenceFragment.class.getName().equals(fragmentName)) {
intent.putExtra(EXTRA_UI_OPTIONS, ActivityInfo.UIOPTION_SPLIT_ACTION_BAR_WHEN_NARROW);
}
intent.setClass(this, SubSettings.class);
return intent;
}
/**
* Populate the activity with the top-level headers.
*/
@Override
public void onBuildHeaders(List<Header> headers) {
loadHeadersFromResource(R.xml.settings_headers, headers);
updateHeaderList(headers);
}
private void updateHeaderList(List<Header> target) {
final boolean showDev = mDevelopmentPreferences.getBoolean(
DevelopmentSettings.PREF_SHOW,
android.os.Build.TYPE.equals("eng"));
int i = 0;
final UserManager um = (UserManager) getSystemService(Context.USER_SERVICE);
mHeaderIndexMap.clear();
while (i < target.size()) {
Header header = target.get(i);
// Ids are integers, so downcasting
int id = (int) header.id;
if (id == R.id.operator_settings || id == R.id.manufacturer_settings) {
Utils.updateHeaderToSpecificActivityFromMetaDataOrRemove(this, target, header);
} else if (id == R.id.wifi_settings) {
// Remove WiFi Settings if WiFi service is not available.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI)) {
target.remove(i);
}
} else if (id == R.id.bluetooth_settings) {
// Remove Bluetooth Settings if Bluetooth service is not available.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {
target.remove(i);
}
} else if (id == R.id.data_usage_settings) {
// Remove data usage when kernel module not enabled
final INetworkManagementService netManager = INetworkManagementService.Stub
.asInterface(ServiceManager.getService(Context.NETWORKMANAGEMENT_SERVICE));
try {
if (!netManager.isBandwidthControlEnabled()) {
target.remove(i);
}
} catch (RemoteException e) {
// ignored
}
} else if (id == R.id.account_settings) {
int headerIndex = i + 1;
i = insertAccountsHeaders(target, headerIndex);
} else if (id == R.id.user_settings) {
if (!UserHandle.MU_ENABLED
|| !UserManager.supportsMultipleUsers()
|| Utils.isMonkeyRunning()) {
target.remove(i);
}
} else if (id == R.id.development_settings) {
if (!showDev) {
target.remove(i);
}
} else if (id == R.id.account_add) {
if (um.hasUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS)) {
target.remove(i);
}
}
if (i < target.size() && target.get(i) == header
&& UserHandle.MU_ENABLED && UserHandle.myUserId() != 0
&& !ArrayUtils.contains(SETTINGS_FOR_RESTRICTED, id)) {
target.remove(i);
}
// Increment if the current one wasn't removed by the Utils code.
if (i < target.size() && target.get(i) == header) {
// Hold on to the first header, when we need to reset to the top-level
if (mFirstHeader == null &&
HeaderAdapter.getHeaderType(header) != HeaderAdapter.HEADER_TYPE_CATEGORY) {
mFirstHeader = header;
}
mHeaderIndexMap.put(id, i);
i++;
}
}
}
private int insertAccountsHeaders(List<Header> target, int headerIndex) {
String[] accountTypes = mAuthenticatorHelper.getEnabledAccountTypes();
List<Header> accountHeaders = new ArrayList<Header>(accountTypes.length);
for (String accountType : accountTypes) {
CharSequence label = mAuthenticatorHelper.getLabelForType(this, accountType);
if (label == null) {
continue;
}
Account[] accounts = AccountManager.get(this).getAccountsByType(accountType);
boolean skipToAccount = accounts.length == 1
&& !mAuthenticatorHelper.hasAccountPreferences(accountType);
Header accHeader = new Header();
accHeader.title = label;
if (accHeader.extras == null) {
accHeader.extras = new Bundle();
}
if (skipToAccount) {
accHeader.breadCrumbTitleRes = R.string.account_sync_settings_title;
accHeader.breadCrumbShortTitleRes = R.string.account_sync_settings_title;
accHeader.fragment = AccountSyncSettings.class.getName();
accHeader.fragmentArguments = new Bundle();
// Need this for the icon
accHeader.extras.putString(ManageAccountsSettings.KEY_ACCOUNT_TYPE, accountType);
accHeader.extras.putParcelable(AccountSyncSettings.ACCOUNT_KEY, accounts[0]);
accHeader.fragmentArguments.putParcelable(AccountSyncSettings.ACCOUNT_KEY,
accounts[0]);
} else {
accHeader.breadCrumbTitle = label;
accHeader.breadCrumbShortTitle = label;
accHeader.fragment = ManageAccountsSettings.class.getName();
accHeader.fragmentArguments = new Bundle();
accHeader.extras.putString(ManageAccountsSettings.KEY_ACCOUNT_TYPE, accountType);
accHeader.fragmentArguments.putString(ManageAccountsSettings.KEY_ACCOUNT_TYPE,
accountType);
if (!isMultiPane()) {
accHeader.fragmentArguments.putString(ManageAccountsSettings.KEY_ACCOUNT_LABEL,
label.toString());
}
}
accountHeaders.add(accHeader);
}
// Sort by label
Collections.sort(accountHeaders, new Comparator<Header>() {
@Override
public int compare(Header h1, Header h2) {
return h1.title.toString().compareTo(h2.title.toString());
}
});
for (Header header : accountHeaders) {
target.add(headerIndex++, header);
}
if (!mListeningToAccountUpdates) {
AccountManager.get(this).addOnAccountsUpdatedListener(this, null, true);
mListeningToAccountUpdates = true;
}
return headerIndex;
}
private void getMetaData() {
try {
ActivityInfo ai = getPackageManager().getActivityInfo(getComponentName(),
PackageManager.GET_META_DATA);
if (ai == null || ai.metaData == null) return;
mTopLevelHeaderId = ai.metaData.getInt(META_DATA_KEY_HEADER_ID);
mFragmentClass = ai.metaData.getString(META_DATA_KEY_FRAGMENT_CLASS);
// Check if it has a parent specified and create a Header object
final int parentHeaderTitleRes = ai.metaData.getInt(META_DATA_KEY_PARENT_TITLE);
String parentFragmentClass = ai.metaData.getString(META_DATA_KEY_PARENT_FRAGMENT_CLASS);
if (parentFragmentClass != null) {
mParentHeader = new Header();
mParentHeader.fragment = parentFragmentClass;
if (parentHeaderTitleRes != 0) {
mParentHeader.title = getResources().getString(parentHeaderTitleRes);
}
}
} catch (NameNotFoundException nnfe) {
// No recovery
}
}
@Override
public boolean hasNextButton() {
return super.hasNextButton();
}
@Override
public Button getNextButton() {
return super.getNextButton();
}
private static class HeaderAdapter extends ArrayAdapter<Header> {
static final int HEADER_TYPE_CATEGORY = 0;
static final int HEADER_TYPE_NORMAL = 1;
static final int HEADER_TYPE_SWITCH = 2;
private static final int HEADER_TYPE_COUNT = HEADER_TYPE_SWITCH + 1;
private final WifiEnabler mWifiEnabler;
private final BluetoothEnabler mBluetoothEnabler;
private AuthenticatorHelper mAuthHelper;
private static class HeaderViewHolder {
ImageView icon;
TextView title;
TextView summary;
Switch switch_;
}
private LayoutInflater mInflater;
static int getHeaderType(Header header) {
if (header.fragment == null && header.intent == null) {
return HEADER_TYPE_CATEGORY;
} else if (header.id == R.id.wifi_settings || header.id == R.id.bluetooth_settings) {
return HEADER_TYPE_SWITCH;
} else {
return HEADER_TYPE_NORMAL;
}
}
@Override
public int getItemViewType(int position) {
Header header = getItem(position);
return getHeaderType(header);
}
@Override
public boolean areAllItemsEnabled() {
return false; // because of categories
}
@Override
public boolean isEnabled(int position) {
return getItemViewType(position) != HEADER_TYPE_CATEGORY;
}
@Override
public int getViewTypeCount() {
return HEADER_TYPE_COUNT;
}
@Override
public boolean hasStableIds() {
return true;
}
public HeaderAdapter(Context context, List<Header> objects,
AuthenticatorHelper authenticatorHelper) {
super(context, 0, objects);
mAuthHelper = authenticatorHelper;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Temp Switches provided as placeholder until the adapter replaces these with actual
// Switches inflated from their layouts. Must be done before adapter is set in super
mWifiEnabler = new WifiEnabler(context, new Switch(context));
mBluetoothEnabler = new BluetoothEnabler(context, new Switch(context));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
Header header = getItem(position);
int headerType = getHeaderType(header);
View view = null;
- if (convertView == null) {
+ if (convertView == null || headerType == HEADER_TYPE_SWITCH) {
holder = new HeaderViewHolder();
switch (headerType) {
case HEADER_TYPE_CATEGORY:
view = new TextView(getContext(), null,
android.R.attr.listSeparatorTextViewStyle);
holder.title = (TextView) view;
break;
case HEADER_TYPE_SWITCH:
view = mInflater.inflate(R.layout.preference_header_switch_item, parent,
false);
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.title = (TextView)
view.findViewById(com.android.internal.R.id.title);
holder.summary = (TextView)
view.findViewById(com.android.internal.R.id.summary);
holder.switch_ = (Switch) view.findViewById(R.id.switchWidget);
break;
case HEADER_TYPE_NORMAL:
view = mInflater.inflate(
R.layout.preference_header_item, parent,
false);
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.title = (TextView)
view.findViewById(com.android.internal.R.id.title);
holder.summary = (TextView)
view.findViewById(com.android.internal.R.id.summary);
break;
}
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
switch (headerType) {
case HEADER_TYPE_CATEGORY:
holder.title.setText(header.getTitle(getContext().getResources()));
break;
case HEADER_TYPE_SWITCH:
// Would need a different treatment if the main menu had more switches
if (header.id == R.id.wifi_settings) {
mWifiEnabler.setSwitch(holder.switch_);
} else {
mBluetoothEnabler.setSwitch(holder.switch_);
}
// No break, fall through on purpose to update common fields
//$FALL-THROUGH$
case HEADER_TYPE_NORMAL:
if (header.extras != null
&& header.extras.containsKey(ManageAccountsSettings.KEY_ACCOUNT_TYPE)) {
String accType = header.extras.getString(
ManageAccountsSettings.KEY_ACCOUNT_TYPE);
ViewGroup.LayoutParams lp = holder.icon.getLayoutParams();
lp.width = getContext().getResources().getDimensionPixelSize(
R.dimen.header_icon_width);
lp.height = lp.width;
holder.icon.setLayoutParams(lp);
Drawable icon = mAuthHelper.getDrawableForType(getContext(), accType);
holder.icon.setImageDrawable(icon);
} else {
holder.icon.setImageResource(header.iconRes);
}
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
break;
}
return view;
}
public void resume() {
mWifiEnabler.resume();
mBluetoothEnabler.resume();
}
public void pause() {
mWifiEnabler.pause();
mBluetoothEnabler.pause();
}
}
@Override
public void onHeaderClick(Header header, int position) {
boolean revert = false;
if (header.id == R.id.account_add) {
revert = true;
}
super.onHeaderClick(header, position);
if (revert && mLastHeader != null) {
highlightHeader((int) mLastHeader.id);
} else {
mLastHeader = header;
}
}
@Override
public boolean onPreferenceStartFragment(PreferenceFragment caller, Preference pref) {
// Override the fragment title for Wallpaper settings
int titleRes = pref.getTitleRes();
if (pref.getFragment().equals(WallpaperTypeSettings.class.getName())) {
titleRes = R.string.wallpaper_settings_fragment_title;
} else if (pref.getFragment().equals(OwnerInfoSettings.class.getName())
&& UserHandle.myUserId() != UserHandle.USER_OWNER) {
if (UserManager.get(this).isLinkedUser()) {
titleRes = R.string.profile_info_settings_title;
} else {
titleRes = R.string.user_info_settings_title;
}
}
startPreferencePanel(pref.getFragment(), pref.getExtras(), titleRes, pref.getTitle(),
null, 0);
return true;
}
@Override
public boolean shouldUpRecreateTask(Intent targetIntent) {
return super.shouldUpRecreateTask(new Intent(this, Settings.class));
}
@Override
public void setListAdapter(ListAdapter adapter) {
if (adapter == null) {
super.setListAdapter(null);
} else {
super.setListAdapter(new HeaderAdapter(this, getHeaders(), mAuthenticatorHelper));
}
}
@Override
public void onAccountsUpdated(Account[] accounts) {
// TODO: watch for package upgrades to invalidate cache; see 7206643
mAuthenticatorHelper.updateAuthDescriptions(this);
mAuthenticatorHelper.onAccountsUpdated(this, accounts);
invalidateHeaders();
}
/*
* Settings subclasses for launching independently.
*/
public static class BluetoothSettingsActivity extends Settings { /* empty */ }
public static class WirelessSettingsActivity extends Settings { /* empty */ }
public static class TetherSettingsActivity extends Settings { /* empty */ }
public static class VpnSettingsActivity extends Settings { /* empty */ }
public static class DateTimeSettingsActivity extends Settings { /* empty */ }
public static class StorageSettingsActivity extends Settings { /* empty */ }
public static class WifiSettingsActivity extends Settings { /* empty */ }
public static class WifiP2pSettingsActivity extends Settings { /* empty */ }
public static class InputMethodAndLanguageSettingsActivity extends Settings { /* empty */ }
public static class KeyboardLayoutPickerActivity extends Settings { /* empty */ }
public static class InputMethodAndSubtypeEnablerActivity extends Settings { /* empty */ }
public static class SpellCheckersSettingsActivity extends Settings { /* empty */ }
public static class LocalePickerActivity extends Settings { /* empty */ }
public static class UserDictionarySettingsActivity extends Settings { /* empty */ }
public static class SoundSettingsActivity extends Settings { /* empty */ }
public static class DisplaySettingsActivity extends Settings { /* empty */ }
public static class DeviceInfoSettingsActivity extends Settings { /* empty */ }
public static class ApplicationSettingsActivity extends Settings { /* empty */ }
public static class ManageApplicationsActivity extends Settings { /* empty */ }
public static class AppOpsSummaryActivity extends Settings { /* empty */ }
public static class StorageUseActivity extends Settings { /* empty */ }
public static class DevelopmentSettingsActivity extends Settings { /* empty */ }
public static class AccessibilitySettingsActivity extends Settings { /* empty */ }
public static class SecuritySettingsActivity extends Settings { /* empty */ }
public static class LocationSettingsActivity extends Settings { /* empty */ }
public static class PrivacySettingsActivity extends Settings { /* empty */ }
public static class RunningServicesActivity extends Settings { /* empty */ }
public static class ManageAccountsSettingsActivity extends Settings { /* empty */ }
public static class PowerUsageSummaryActivity extends Settings { /* empty */ }
public static class AccountSyncSettingsActivity extends Settings { /* empty */ }
public static class AccountSyncSettingsInAddAccountActivity extends Settings { /* empty */ }
public static class CryptKeeperSettingsActivity extends Settings { /* empty */ }
public static class DeviceAdminSettingsActivity extends Settings { /* empty */ }
public static class DataUsageSummaryActivity extends Settings { /* empty */ }
public static class AdvancedWifiSettingsActivity extends Settings { /* empty */ }
public static class TextToSpeechSettingsActivity extends Settings { /* empty */ }
public static class AndroidBeamSettingsActivity extends Settings { /* empty */ }
public static class WifiDisplaySettingsActivity extends Settings { /* empty */ }
public static class DreamSettingsActivity extends Settings { /* empty */ }
public static class NotificationStationActivity extends Settings { /* empty */ }
public static class UserSettingsActivity extends Settings { /* empty */ }
public static class NotificationAccessSettingsActivity extends Settings { /* empty */ }
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
Header header = getItem(position);
int headerType = getHeaderType(header);
View view = null;
if (convertView == null) {
holder = new HeaderViewHolder();
switch (headerType) {
case HEADER_TYPE_CATEGORY:
view = new TextView(getContext(), null,
android.R.attr.listSeparatorTextViewStyle);
holder.title = (TextView) view;
break;
case HEADER_TYPE_SWITCH:
view = mInflater.inflate(R.layout.preference_header_switch_item, parent,
false);
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.title = (TextView)
view.findViewById(com.android.internal.R.id.title);
holder.summary = (TextView)
view.findViewById(com.android.internal.R.id.summary);
holder.switch_ = (Switch) view.findViewById(R.id.switchWidget);
break;
case HEADER_TYPE_NORMAL:
view = mInflater.inflate(
R.layout.preference_header_item, parent,
false);
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.title = (TextView)
view.findViewById(com.android.internal.R.id.title);
holder.summary = (TextView)
view.findViewById(com.android.internal.R.id.summary);
break;
}
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
switch (headerType) {
case HEADER_TYPE_CATEGORY:
holder.title.setText(header.getTitle(getContext().getResources()));
break;
case HEADER_TYPE_SWITCH:
// Would need a different treatment if the main menu had more switches
if (header.id == R.id.wifi_settings) {
mWifiEnabler.setSwitch(holder.switch_);
} else {
mBluetoothEnabler.setSwitch(holder.switch_);
}
// No break, fall through on purpose to update common fields
//$FALL-THROUGH$
case HEADER_TYPE_NORMAL:
if (header.extras != null
&& header.extras.containsKey(ManageAccountsSettings.KEY_ACCOUNT_TYPE)) {
String accType = header.extras.getString(
ManageAccountsSettings.KEY_ACCOUNT_TYPE);
ViewGroup.LayoutParams lp = holder.icon.getLayoutParams();
lp.width = getContext().getResources().getDimensionPixelSize(
R.dimen.header_icon_width);
lp.height = lp.width;
holder.icon.setLayoutParams(lp);
Drawable icon = mAuthHelper.getDrawableForType(getContext(), accType);
holder.icon.setImageDrawable(icon);
} else {
holder.icon.setImageResource(header.iconRes);
}
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
break;
}
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder;
Header header = getItem(position);
int headerType = getHeaderType(header);
View view = null;
if (convertView == null || headerType == HEADER_TYPE_SWITCH) {
holder = new HeaderViewHolder();
switch (headerType) {
case HEADER_TYPE_CATEGORY:
view = new TextView(getContext(), null,
android.R.attr.listSeparatorTextViewStyle);
holder.title = (TextView) view;
break;
case HEADER_TYPE_SWITCH:
view = mInflater.inflate(R.layout.preference_header_switch_item, parent,
false);
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.title = (TextView)
view.findViewById(com.android.internal.R.id.title);
holder.summary = (TextView)
view.findViewById(com.android.internal.R.id.summary);
holder.switch_ = (Switch) view.findViewById(R.id.switchWidget);
break;
case HEADER_TYPE_NORMAL:
view = mInflater.inflate(
R.layout.preference_header_item, parent,
false);
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.title = (TextView)
view.findViewById(com.android.internal.R.id.title);
holder.summary = (TextView)
view.findViewById(com.android.internal.R.id.summary);
break;
}
view.setTag(holder);
} else {
view = convertView;
holder = (HeaderViewHolder) view.getTag();
}
// All view fields must be updated every time, because the view may be recycled
switch (headerType) {
case HEADER_TYPE_CATEGORY:
holder.title.setText(header.getTitle(getContext().getResources()));
break;
case HEADER_TYPE_SWITCH:
// Would need a different treatment if the main menu had more switches
if (header.id == R.id.wifi_settings) {
mWifiEnabler.setSwitch(holder.switch_);
} else {
mBluetoothEnabler.setSwitch(holder.switch_);
}
// No break, fall through on purpose to update common fields
//$FALL-THROUGH$
case HEADER_TYPE_NORMAL:
if (header.extras != null
&& header.extras.containsKey(ManageAccountsSettings.KEY_ACCOUNT_TYPE)) {
String accType = header.extras.getString(
ManageAccountsSettings.KEY_ACCOUNT_TYPE);
ViewGroup.LayoutParams lp = holder.icon.getLayoutParams();
lp.width = getContext().getResources().getDimensionPixelSize(
R.dimen.header_icon_width);
lp.height = lp.width;
holder.icon.setLayoutParams(lp);
Drawable icon = mAuthHelper.getDrawableForType(getContext(), accType);
holder.icon.setImageDrawable(icon);
} else {
holder.icon.setImageResource(header.iconRes);
}
holder.title.setText(header.getTitle(getContext().getResources()));
CharSequence summary = header.getSummary(getContext().getResources());
if (!TextUtils.isEmpty(summary)) {
holder.summary.setVisibility(View.VISIBLE);
holder.summary.setText(summary);
} else {
holder.summary.setVisibility(View.GONE);
}
break;
}
return view;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.